Просмотр исходного кода

Remove Razor SDK from repo (#29548)

* Remove Razor SDK from repo
* Use newer SDK version
* Delete mroe things

Co-authored-by: Pranav K <[email protected]>
Safia Abdalla 5 лет назад
Родитель
Сommit
2cd4f1f577
100 измененных файлов с 3 добавлено и 12548 удалено
  1. 0 81
      AspNetCore.sln
  2. 0 2
      eng/ProjectReferences.props
  3. 0 24
      eng/targets/CSharp.Common.props
  4. 0 5
      eng/targets/GetRazorSDKDirectory.props
  5. 2 2
      global.json
  6. 1 3
      src/Framework/Framework.slnf
  7. 0 1
      src/ProjectTemplates/BlazorTemplates.Tests/BlazorTemplates.Tests.csproj
  8. 0 12
      src/ProjectTemplates/TestInfrastructure/Directory.Build.targets.in
  9. 0 2
      src/ProjectTemplates/test/ProjectTemplates.Tests.csproj
  10. 0 116
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/Application.cs
  11. 0 70
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/BrotliCompressCommand.cs
  12. 0 32
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/CachingMetadataReference.cs
  13. 0 200
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/Client.cs
  14. 0 59
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/CommandBase.cs
  15. 0 134
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/CompilerHost.cs
  16. 0 51
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/CompositeRazorProjectFileSystem.cs
  17. 0 207
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ConcurrentLruCache.cs
  18. 0 28
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/Connection.cs
  19. 0 148
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ConnectionHost.cs
  20. 0 47
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ConnectionResult.cs
  21. 0 27
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/DebugMode.cs
  22. 0 241
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/DefaultExtensionAssemblyLoader.cs
  23. 0 158
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/DefaultExtensionDependencyChecker.cs
  24. 0 472
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/DefaultRequestDispatcher.cs
  25. 0 225
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/DiscoverCommand.cs
  26. 0 68
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/EventBus.cs
  27. 0 16
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ExtensionAssemblyLoader.cs
  28. 0 12
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ExtensionDependencyChecker.cs
  29. 0 425
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/GenerateCommand.cs
  30. 0 13
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/Memory.cs
  31. 0 86
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/MetadataCache.cs
  32. 0 94
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/MetadataReaderExtensions.cs
  33. 0 22
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/MutexName.cs
  34. 0 60
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/PipeName.cs
  35. 0 53
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/Program.cs
  36. 0 9
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/Properties/AssemblyInfo.cs
  37. 0 29
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/RequestDispatcher.cs
  38. 0 432
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/RewriteCssCommand.cs
  39. 0 189
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerCommand.cs
  40. 0 58
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/CompletedServerResponse.cs
  41. 0 17
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/MismatchedVersionServerResponse.cs
  42. 0 89
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/NativeMethods.cs
  43. 0 17
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/RejectedServerResponse.cs
  44. 0 72
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/RequestArgument.cs
  45. 0 390
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/ServerConnection.cs
  46. 0 146
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/ServerLogger.cs
  47. 0 33
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/ServerPaths.cs
  48. 0 70
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/ServerProtocol.cs
  49. 0 216
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/ServerRequest.cs
  50. 0 132
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/ServerResponse.cs
  51. 0 30
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/ShutdownServerResponse.cs
  52. 0 170
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ShadowCopyManager.cs
  53. 0 97
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ShutdownCommand.cs
  54. 0 3
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/runtimeconfig.template.json
  55. 0 49
      src/Razor/Microsoft.AspNetCore.Razor.Tools/src/rzc.csproj
  56. 0 81
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/CompositeRazorProjectFileSystemTest.cs
  57. 0 120
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/ConcurrentLruCacheTest.cs
  58. 0 128
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/DefaultExtensionAssemblyLoaderTest.cs
  59. 0 111
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/DefaultExtensionDependencyCheckerTest.cs
  60. 0 572
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/DefaultRequestDispatcherTest.cs
  61. 0 49
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/Infrastructure/ServerData.cs
  62. 0 17
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/Infrastructure/ServerStats.cs
  63. 0 156
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/Infrastructure/ServerUtilities.cs
  64. 0 64
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/Infrastructure/TestableEventBus.cs
  65. 0 146
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/LoaderTestResources.cs
  66. 0 103
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/MetadataCacheTest.cs
  67. 0 16
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/Microsoft.AspNetCore.Razor.Tools.Test.csproj
  68. 0 45
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/MvcShim.cs
  69. 0 6
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/Properties/AssemblyInfo.cs
  70. 0 391
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/RewriteCssCommandTest.cs
  71. 0 120
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/ServerCommandTest.cs
  72. 0 291
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/ServerLifecycleTest.cs
  73. 0 128
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/ServerProtocol/ServerProtocolTest.cs
  74. 0 30
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/TempDirectory.cs
  75. 0 25
      src/Razor/Microsoft.AspNetCore.Razor.Tools/test/TestDefaultExtensionAssemblyLoader.cs
  76. 0 193
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/ApplicationPartDiscoveryIntegrationTest.cs
  77. 0 416
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildIncrementalismTest.cs
  78. 0 745
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildIntegrationTest.cs
  79. 0 291
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildIntrospectionTest.cs
  80. 0 110
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildPerformanceTest.cs
  81. 0 274
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildServerIntegrationTest.cs
  82. 0 29
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildServerTestFixture.cs
  83. 0 65
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildServerTestFixtureBase.cs
  84. 0 38
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildWithComponents31IntegrationTest.cs
  85. 0 149
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildWithComponentsIntegrationTest.cs
  86. 0 102
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/ConfigurationMetadataIntegrationTest.cs
  87. 0 92
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/DesignTimeBuildIntegrationTest.cs
  88. 0 9
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/Directory.Build.props
  89. 0 53
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/InitializeTestProjectAttribute.cs
  90. 0 18
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/LegacyBuildServerTestFixture.cs
  91. 0 165
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/MSBuildIntegrationTestBase.cs
  92. 0 79
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/Microsoft.NET.Sdk.Razor.IntegrationTests.csproj
  93. 0 91
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/MvcBuildIntegrationTest21.cs
  94. 0 47
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/MvcBuildIntegrationTest22.cs
  95. 0 48
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/MvcBuildIntegrationTest31.cs
  96. 0 146
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/MvcBuildIntegrationTestLegacy.cs
  97. 0 403
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/PackIntegrationTest.cs
  98. 0 469
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/PublishIntegrationTest.cs
  99. 0 115
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/RazorCompileIntegrationTest.cs
  100. 0 358
      src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/RazorGenerateIntegrationTest.cs

+ 0 - 81
AspNetCore.sln

@@ -1033,12 +1033,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.
 EndProject
 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.Language.Test", "src\Razor\Microsoft.AspNetCore.Razor.Language\test\Microsoft.AspNetCore.Razor.Language.Test.csproj", "{313ADEF5-5A2D-4C11-8655-E227445144E2}"
 EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Microsoft.AspNetCore.Razor.Tools", "Microsoft.AspNetCore.Razor.Tools", "{B9704650-5360-416C-9393-FAF707766AA8}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "rzc", "src\Razor\Microsoft.AspNetCore.Razor.Tools\src\rzc.csproj", "{4C84173F-5C1F-49A1-895A-C0CA11DE84B1}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.Tools.Test", "src\Razor\Microsoft.AspNetCore.Razor.Tools\test\Microsoft.AspNetCore.Razor.Tools.Test.csproj", "{FE095F11-4CD2-406D-A2BB-1BE569603BF0}"
-EndProject
 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Microsoft.CodeAnalysis.Razor", "Microsoft.CodeAnalysis.Razor", "{3854EA4A-5530-4FEC-971E-B0CB45C5B19D}"
 EndProject
 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Razor", "src\Razor\Microsoft.CodeAnalysis.Razor\src\Microsoft.CodeAnalysis.Razor.csproj", "{AE06A841-F90D-486A-9DEF-70495DF4D28A}"
@@ -1055,12 +1049,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "perf", "perf", "{D510860C-B
 EndProject
 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.Performance", "src\Razor\perf\Microsoft.AspNetCore.Razor.Performance\Microsoft.AspNetCore.Razor.Performance.csproj", "{8ED505A5-A33A-401E-89BA-3AED7B73DD6A}"
 EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Microsoft.NET.Sdk.Razor", "Microsoft.NET.Sdk.Razor", "{DA9E1AB0-0094-4777-BF3F-BC5596C3CDA9}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.NET.Sdk.Razor", "src\Razor\Microsoft.NET.Sdk.Razor\src\Microsoft.NET.Sdk.Razor.csproj", "{44B3F6C4-0F65-4649-B4CF-6CDC2094E061}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.NET.Sdk.Razor.Test", "src\Razor\Microsoft.NET.Sdk.Razor\test\Microsoft.NET.Sdk.Razor.Test.csproj", "{7CB23DCD-B416-4293-9848-224077F9E71D}"
-EndProject
 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{06C916C7-67BF-45DC-9D0B-CEEF0C731451}"
 EndProject
 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.Test.Common", "src\Razor\test\Microsoft.AspNetCore.Razor.Test.Common\Microsoft.AspNetCore.Razor.Test.Common.csproj", "{69637901-CAD7-4335-81F4-92E03C4DA354}"
@@ -1075,8 +1063,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.
 EndProject
 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.Test.MvcShim.Version2_X", "src\Razor\test\Microsoft.AspNetCore.Razor.Test.MvcShim.Version2_X\Microsoft.AspNetCore.Razor.Test.MvcShim.Version2_X.csproj", "{2A3B2388-F9F3-4F28-B008-2CD7862A86C4}"
 EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.NET.Sdk.Razor.IntegrationTests", "src\Razor\Microsoft.NET.Sdk.Razor\integrationtests\Microsoft.NET.Sdk.Razor.IntegrationTests.csproj", "{930CB054-3E69-4721-9F7E-01FB911AAF6A}"
-EndProject
 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{CF9D35EC-CA9B-481D-BAAC-5D4654732AB9}"
 EndProject
 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AuthSamples.FunctionalTests", "src\Security\test\AuthSamples.FunctionalTests\AuthSamples.FunctionalTests.csproj", "{31B7D2B1-47AF-432B-BF07-73916EF238EE}"
@@ -5269,30 +5255,6 @@ Global
 		{313ADEF5-5A2D-4C11-8655-E227445144E2}.Release|x64.Build.0 = Release|Any CPU
 		{313ADEF5-5A2D-4C11-8655-E227445144E2}.Release|x86.ActiveCfg = Release|Any CPU
 		{313ADEF5-5A2D-4C11-8655-E227445144E2}.Release|x86.Build.0 = Release|Any CPU
-		{4C84173F-5C1F-49A1-895A-C0CA11DE84B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{4C84173F-5C1F-49A1-895A-C0CA11DE84B1}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{4C84173F-5C1F-49A1-895A-C0CA11DE84B1}.Debug|x64.ActiveCfg = Debug|Any CPU
-		{4C84173F-5C1F-49A1-895A-C0CA11DE84B1}.Debug|x64.Build.0 = Debug|Any CPU
-		{4C84173F-5C1F-49A1-895A-C0CA11DE84B1}.Debug|x86.ActiveCfg = Debug|Any CPU
-		{4C84173F-5C1F-49A1-895A-C0CA11DE84B1}.Debug|x86.Build.0 = Debug|Any CPU
-		{4C84173F-5C1F-49A1-895A-C0CA11DE84B1}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{4C84173F-5C1F-49A1-895A-C0CA11DE84B1}.Release|Any CPU.Build.0 = Release|Any CPU
-		{4C84173F-5C1F-49A1-895A-C0CA11DE84B1}.Release|x64.ActiveCfg = Release|Any CPU
-		{4C84173F-5C1F-49A1-895A-C0CA11DE84B1}.Release|x64.Build.0 = Release|Any CPU
-		{4C84173F-5C1F-49A1-895A-C0CA11DE84B1}.Release|x86.ActiveCfg = Release|Any CPU
-		{4C84173F-5C1F-49A1-895A-C0CA11DE84B1}.Release|x86.Build.0 = Release|Any CPU
-		{FE095F11-4CD2-406D-A2BB-1BE569603BF0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{FE095F11-4CD2-406D-A2BB-1BE569603BF0}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{FE095F11-4CD2-406D-A2BB-1BE569603BF0}.Debug|x64.ActiveCfg = Debug|Any CPU
-		{FE095F11-4CD2-406D-A2BB-1BE569603BF0}.Debug|x64.Build.0 = Debug|Any CPU
-		{FE095F11-4CD2-406D-A2BB-1BE569603BF0}.Debug|x86.ActiveCfg = Debug|Any CPU
-		{FE095F11-4CD2-406D-A2BB-1BE569603BF0}.Debug|x86.Build.0 = Debug|Any CPU
-		{FE095F11-4CD2-406D-A2BB-1BE569603BF0}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{FE095F11-4CD2-406D-A2BB-1BE569603BF0}.Release|Any CPU.Build.0 = Release|Any CPU
-		{FE095F11-4CD2-406D-A2BB-1BE569603BF0}.Release|x64.ActiveCfg = Release|Any CPU
-		{FE095F11-4CD2-406D-A2BB-1BE569603BF0}.Release|x64.Build.0 = Release|Any CPU
-		{FE095F11-4CD2-406D-A2BB-1BE569603BF0}.Release|x86.ActiveCfg = Release|Any CPU
-		{FE095F11-4CD2-406D-A2BB-1BE569603BF0}.Release|x86.Build.0 = Release|Any CPU
 		{AE06A841-F90D-486A-9DEF-70495DF4D28A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
 		{AE06A841-F90D-486A-9DEF-70495DF4D28A}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{AE06A841-F90D-486A-9DEF-70495DF4D28A}.Debug|x64.ActiveCfg = Debug|Any CPU
@@ -5353,30 +5315,6 @@ Global
 		{8ED505A5-A33A-401E-89BA-3AED7B73DD6A}.Release|x64.Build.0 = Release|Any CPU
 		{8ED505A5-A33A-401E-89BA-3AED7B73DD6A}.Release|x86.ActiveCfg = Release|Any CPU
 		{8ED505A5-A33A-401E-89BA-3AED7B73DD6A}.Release|x86.Build.0 = Release|Any CPU
-		{44B3F6C4-0F65-4649-B4CF-6CDC2094E061}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{44B3F6C4-0F65-4649-B4CF-6CDC2094E061}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{44B3F6C4-0F65-4649-B4CF-6CDC2094E061}.Debug|x64.ActiveCfg = Debug|Any CPU
-		{44B3F6C4-0F65-4649-B4CF-6CDC2094E061}.Debug|x64.Build.0 = Debug|Any CPU
-		{44B3F6C4-0F65-4649-B4CF-6CDC2094E061}.Debug|x86.ActiveCfg = Debug|Any CPU
-		{44B3F6C4-0F65-4649-B4CF-6CDC2094E061}.Debug|x86.Build.0 = Debug|Any CPU
-		{44B3F6C4-0F65-4649-B4CF-6CDC2094E061}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{44B3F6C4-0F65-4649-B4CF-6CDC2094E061}.Release|Any CPU.Build.0 = Release|Any CPU
-		{44B3F6C4-0F65-4649-B4CF-6CDC2094E061}.Release|x64.ActiveCfg = Release|Any CPU
-		{44B3F6C4-0F65-4649-B4CF-6CDC2094E061}.Release|x64.Build.0 = Release|Any CPU
-		{44B3F6C4-0F65-4649-B4CF-6CDC2094E061}.Release|x86.ActiveCfg = Release|Any CPU
-		{44B3F6C4-0F65-4649-B4CF-6CDC2094E061}.Release|x86.Build.0 = Release|Any CPU
-		{7CB23DCD-B416-4293-9848-224077F9E71D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{7CB23DCD-B416-4293-9848-224077F9E71D}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{7CB23DCD-B416-4293-9848-224077F9E71D}.Debug|x64.ActiveCfg = Debug|Any CPU
-		{7CB23DCD-B416-4293-9848-224077F9E71D}.Debug|x64.Build.0 = Debug|Any CPU
-		{7CB23DCD-B416-4293-9848-224077F9E71D}.Debug|x86.ActiveCfg = Debug|Any CPU
-		{7CB23DCD-B416-4293-9848-224077F9E71D}.Debug|x86.Build.0 = Debug|Any CPU
-		{7CB23DCD-B416-4293-9848-224077F9E71D}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{7CB23DCD-B416-4293-9848-224077F9E71D}.Release|Any CPU.Build.0 = Release|Any CPU
-		{7CB23DCD-B416-4293-9848-224077F9E71D}.Release|x64.ActiveCfg = Release|Any CPU
-		{7CB23DCD-B416-4293-9848-224077F9E71D}.Release|x64.Build.0 = Release|Any CPU
-		{7CB23DCD-B416-4293-9848-224077F9E71D}.Release|x86.ActiveCfg = Release|Any CPU
-		{7CB23DCD-B416-4293-9848-224077F9E71D}.Release|x86.Build.0 = Release|Any CPU
 		{69637901-CAD7-4335-81F4-92E03C4DA354}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
 		{69637901-CAD7-4335-81F4-92E03C4DA354}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{69637901-CAD7-4335-81F4-92E03C4DA354}.Debug|x64.ActiveCfg = Debug|Any CPU
@@ -5449,18 +5387,6 @@ Global
 		{2A3B2388-F9F3-4F28-B008-2CD7862A86C4}.Release|x64.Build.0 = Release|Any CPU
 		{2A3B2388-F9F3-4F28-B008-2CD7862A86C4}.Release|x86.ActiveCfg = Release|Any CPU
 		{2A3B2388-F9F3-4F28-B008-2CD7862A86C4}.Release|x86.Build.0 = Release|Any CPU
-		{930CB054-3E69-4721-9F7E-01FB911AAF6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{930CB054-3E69-4721-9F7E-01FB911AAF6A}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{930CB054-3E69-4721-9F7E-01FB911AAF6A}.Debug|x64.ActiveCfg = Debug|Any CPU
-		{930CB054-3E69-4721-9F7E-01FB911AAF6A}.Debug|x64.Build.0 = Debug|Any CPU
-		{930CB054-3E69-4721-9F7E-01FB911AAF6A}.Debug|x86.ActiveCfg = Debug|Any CPU
-		{930CB054-3E69-4721-9F7E-01FB911AAF6A}.Debug|x86.Build.0 = Debug|Any CPU
-		{930CB054-3E69-4721-9F7E-01FB911AAF6A}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{930CB054-3E69-4721-9F7E-01FB911AAF6A}.Release|Any CPU.Build.0 = Release|Any CPU
-		{930CB054-3E69-4721-9F7E-01FB911AAF6A}.Release|x64.ActiveCfg = Release|Any CPU
-		{930CB054-3E69-4721-9F7E-01FB911AAF6A}.Release|x64.Build.0 = Release|Any CPU
-		{930CB054-3E69-4721-9F7E-01FB911AAF6A}.Release|x86.ActiveCfg = Release|Any CPU
-		{930CB054-3E69-4721-9F7E-01FB911AAF6A}.Release|x86.Build.0 = Release|Any CPU
 		{31B7D2B1-47AF-432B-BF07-73916EF238EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
 		{31B7D2B1-47AF-432B-BF07-73916EF238EE}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{31B7D2B1-47AF-432B-BF07-73916EF238EE}.Debug|x64.ActiveCfg = Debug|Any CPU
@@ -7991,9 +7917,6 @@ Global
 		{1CBCF1F9-D90D-484E-A2E9-FD4E4174C05E} = {B27FBAC2-ADA3-4A05-B232-64011B6B2DA3}
 		{A6323D64-C883-46B6-BDA9-916009D44262} = {1CBCF1F9-D90D-484E-A2E9-FD4E4174C05E}
 		{313ADEF5-5A2D-4C11-8655-E227445144E2} = {1CBCF1F9-D90D-484E-A2E9-FD4E4174C05E}
-		{B9704650-5360-416C-9393-FAF707766AA8} = {B27FBAC2-ADA3-4A05-B232-64011B6B2DA3}
-		{4C84173F-5C1F-49A1-895A-C0CA11DE84B1} = {B9704650-5360-416C-9393-FAF707766AA8}
-		{FE095F11-4CD2-406D-A2BB-1BE569603BF0} = {B9704650-5360-416C-9393-FAF707766AA8}
 		{3854EA4A-5530-4FEC-971E-B0CB45C5B19D} = {B27FBAC2-ADA3-4A05-B232-64011B6B2DA3}
 		{AE06A841-F90D-486A-9DEF-70495DF4D28A} = {3854EA4A-5530-4FEC-971E-B0CB45C5B19D}
 		{91A6A69B-21B4-4B05-B188-D0551573DD9B} = {3854EA4A-5530-4FEC-971E-B0CB45C5B19D}
@@ -8002,9 +7925,6 @@ Global
 		{8B37B987-B7A2-4A26-8CF1-7AC1E9FA7ADC} = {F6E6A63A-45BE-46BF-B9B4-DA3DDC8FE4B5}
 		{D510860C-B2DA-41D3-9137-81B029312E71} = {B27FBAC2-ADA3-4A05-B232-64011B6B2DA3}
 		{8ED505A5-A33A-401E-89BA-3AED7B73DD6A} = {D510860C-B2DA-41D3-9137-81B029312E71}
-		{DA9E1AB0-0094-4777-BF3F-BC5596C3CDA9} = {B27FBAC2-ADA3-4A05-B232-64011B6B2DA3}
-		{44B3F6C4-0F65-4649-B4CF-6CDC2094E061} = {DA9E1AB0-0094-4777-BF3F-BC5596C3CDA9}
-		{7CB23DCD-B416-4293-9848-224077F9E71D} = {DA9E1AB0-0094-4777-BF3F-BC5596C3CDA9}
 		{06C916C7-67BF-45DC-9D0B-CEEF0C731451} = {B27FBAC2-ADA3-4A05-B232-64011B6B2DA3}
 		{69637901-CAD7-4335-81F4-92E03C4DA354} = {06C916C7-67BF-45DC-9D0B-CEEF0C731451}
 		{ED060C25-B7B2-414B-BDC7-A77FA0269C9F} = {06C916C7-67BF-45DC-9D0B-CEEF0C731451}
@@ -8012,7 +7932,6 @@ Global
 		{F8111E2B-650F-4A9A-9834-234B5F5DD79D} = {06C916C7-67BF-45DC-9D0B-CEEF0C731451}
 		{302EC23A-FD11-4F56-B3E9-0DEC7C177584} = {06C916C7-67BF-45DC-9D0B-CEEF0C731451}
 		{2A3B2388-F9F3-4F28-B008-2CD7862A86C4} = {06C916C7-67BF-45DC-9D0B-CEEF0C731451}
-		{930CB054-3E69-4721-9F7E-01FB911AAF6A} = {DA9E1AB0-0094-4777-BF3F-BC5596C3CDA9}
 		{CF9D35EC-CA9B-481D-BAAC-5D4654732AB9} = {A39335E5-7A26-4CFD-BF3B-2CFE75113498}
 		{31B7D2B1-47AF-432B-BF07-73916EF238EE} = {CF9D35EC-CA9B-481D-BAAC-5D4654732AB9}
 		{C75B1FB3-6BB7-411A-B76C-06E5E0C3D957} = {A39335E5-7A26-4CFD-BF3B-2CFE75113498}

+ 0 - 2
eng/ProjectReferences.props

@@ -101,9 +101,7 @@
     <ProjectReferenceProvider Include="Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X" ProjectPath="$(RepoRoot)src\Razor\Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X\src\Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X.csproj" />
     <ProjectReferenceProvider Include="Microsoft.AspNetCore.Mvc.Razor.Extensions" ProjectPath="$(RepoRoot)src\Razor\Microsoft.AspNetCore.Mvc.Razor.Extensions\src\Microsoft.AspNetCore.Mvc.Razor.Extensions.csproj" />
     <ProjectReferenceProvider Include="Microsoft.AspNetCore.Razor.Language" ProjectPath="$(RepoRoot)src\Razor\Microsoft.AspNetCore.Razor.Language\src\Microsoft.AspNetCore.Razor.Language.csproj" />
-    <ProjectReferenceProvider Include="rzc" ProjectPath="$(RepoRoot)src\Razor\Microsoft.AspNetCore.Razor.Tools\src\rzc.csproj" />
     <ProjectReferenceProvider Include="Microsoft.CodeAnalysis.Razor" ProjectPath="$(RepoRoot)src\Razor\Microsoft.CodeAnalysis.Razor\src\Microsoft.CodeAnalysis.Razor.csproj" />
-    <ProjectReferenceProvider Include="Microsoft.NET.Sdk.Razor" ProjectPath="$(RepoRoot)src\Razor\Microsoft.NET.Sdk.Razor\src\Microsoft.NET.Sdk.Razor.csproj" />
     <ProjectReferenceProvider Include="Microsoft.AspNetCore.Razor.Runtime" ProjectPath="$(RepoRoot)src\Razor\Razor.Runtime\src\Microsoft.AspNetCore.Razor.Runtime.csproj" />
     <ProjectReferenceProvider Include="Microsoft.AspNetCore.Razor" ProjectPath="$(RepoRoot)src\Razor\Razor\src\Microsoft.AspNetCore.Razor.csproj" />
     <ProjectReferenceProvider Include="Microsoft.AspNetCore.Mvc.Abstractions" ProjectPath="$(RepoRoot)src\Mvc\Mvc.Abstractions\src\Microsoft.AspNetCore.Mvc.Abstractions.csproj" />

+ 0 - 24
eng/targets/CSharp.Common.props

@@ -12,30 +12,6 @@
     <PackageReference Include="MicroBuild.Core" Version="0.3.0" PrivateAssets="All" AllowExplicitReference="true" ExcludeAssets="All" />
   </ItemGroup>
 
-  <PropertyGroup>
-    <_ReferenceLocalRazorSDK
-      Condition="'$(UsingMicrosoftNETSdkWeb)' == 'true' OR '$(UsingMicrosoftNETSdkBlazorWebAssembly)' == 'true' OR '$(RazorSdkCurrentVersionProps)' != '' OR '$(_RazorSdkImportsMicrosoftNetSdk)' == 'true'">true</_ReferenceLocalRazorSDK>
-  </PropertyGroup>
-
-  <ItemGroup Condition="'$(_ReferenceLocalRazorSDK)' == 'true'">
-    <!--
-      Use the Razor SDK as a project reference. The version of the .NET Core SDK we build with often contains a version of the Razor SDK
-      several versions older than latest. We reference the project to ensure it's built before the other projects that use it. Since this
-      is a project reference, we must explicitly import the props file and also specify the output location of the SDK directory.
-    -->
-    <Reference Include="Microsoft.NET.Sdk.Razor"
-      PrivateAssets="All"
-      ReferenceOutputAssembly="false"
-      SkipGetTargetFrameworkProperties="true"
-      UndefineProperties="TargetFramework;TargetFrameworks" />
-  </ItemGroup>
-
-  <ImportGroup Condition="'$(_ReferenceLocalRazorSDK)' == 'true'">
-    <Import Project="$(RepoRoot)eng\targets\GetRazorSDKDirectory.props" />
-    <Import Project="$(RepoRoot)src\Razor\Microsoft.NET.Sdk.Razor\src\build\netstandard2.0\Microsoft.NET.Sdk.Razor.props" />
-  </ImportGroup>
-
-
   <ItemGroup Condition=" '$(IsTestProject)' != 'true' AND '$(DotNetBuildFromSource)' != 'true' ">
     <Reference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" PrivateAssets="All" />
   </ItemGroup>

+ 0 - 5
eng/targets/GetRazorSDKDirectory.props

@@ -1,5 +0,0 @@
-<Project>
-  <PropertyGroup>
-    <RazorSdkDirectoryRoot Condition="'$(RazorSdkDirectoryRoot)' == ''">$(ArtifactsBinDir)Microsoft.NET.Sdk.Razor\$(Configuration)\sdk-output\</RazorSdkDirectoryRoot>
-  </PropertyGroup>
-</Project>

+ 2 - 2
global.json

@@ -1,9 +1,9 @@
 {
   "sdk": {
-    "version": "6.0.100-alpha.1.21063.4"
+    "version": "6.0.100-preview.1.21073.4"
   },
   "tools": {
-    "dotnet": "6.0.100-alpha.1.21063.4",
+    "dotnet": "6.0.100-preview.1.21073.4",
     "runtimes": {
       "dotnet/x64": [
         "2.1.23",

+ 1 - 3
src/Framework/Framework.slnf

@@ -73,9 +73,7 @@
       "src\\ObjectPool\\src\\Microsoft.Extensions.ObjectPool.csproj",
       "src\\Razor\\Microsoft.AspNetCore.Mvc.Razor.Extensions\\src\\Microsoft.AspNetCore.Mvc.Razor.Extensions.csproj",
       "src\\Razor\\Microsoft.AspNetCore.Razor.Language\\src\\Microsoft.AspNetCore.Razor.Language.csproj",
-      "src\\Razor\\Microsoft.AspNetCore.Razor.Tools\\src\\rzc.csproj",
       "src\\Razor\\Microsoft.CodeAnalysis.Razor\\src\\Microsoft.CodeAnalysis.Razor.csproj",
-      "src\\Razor\\Microsoft.NET.Sdk.Razor\\src\\Microsoft.NET.Sdk.Razor.csproj",
       "src\\Razor\\Razor.Runtime\\src\\Microsoft.AspNetCore.Razor.Runtime.csproj",
       "src\\Razor\\Razor\\src\\Microsoft.AspNetCore.Razor.csproj",
       "src\\Security\\Authentication\\Cookies\\src\\Microsoft.AspNetCore.Authentication.Cookies.csproj",
@@ -101,4 +99,4 @@
       "src\\WebEncoders\\src\\Microsoft.Extensions.WebEncoders.csproj"
     ]
   }
-}
+}

+ 0 - 1
src/ProjectTemplates/BlazorTemplates.Tests/BlazorTemplates.Tests.csproj

@@ -38,7 +38,6 @@
     <ProjectReference Include="$(RepoRoot)src\Hosting\Server.IntegrationTesting\src\Microsoft.AspNetCore.Server.IntegrationTesting.csproj" />
     <ProjectReference Include="../testassets/DotNetToolsInstaller/DotNetToolsInstaller.csproj" ReferenceOutputAssembly="false" />
     <ProjectReference Include="../Web.ProjectTemplates/Microsoft.DotNet.Web.ProjectTemplates.csproj" ReferenceOutputAssembly="false" />
-    <Reference Include="Microsoft.NET.Sdk.Razor" ReferenceOutputAssembly="false" SkipGetTargetFrameworkProperties="true" />
   </ItemGroup>
 
   <!-- Shared testing infrastructure for running E2E tests using selenium -->

+ 0 - 12
src/ProjectTemplates/TestInfrastructure/Directory.Build.targets.in

@@ -6,16 +6,4 @@
     <!-- This sets an option which prevents the tests from rolling forward into a newer shared framework. -->
     <UserRuntimeConfig>$(MSBuildThisFileDirectory)runtimeconfig.norollforward.json</UserRuntimeConfig>
   </PropertyGroup>
-
-  <!--
-    The version of the .NET Core SDK we build with often contains a version of the Razor SDK several versions older
-    than latest. We reference the project (see CSharp.Common.props) to ensure it's built before projects that use it.
-    Since this is a project reference, we must explicitly import the props file and also specify the output location
-    of the SDK directory.
-  -->
-  <PropertyGroup>
-    <RazorSdkDirectoryRoot>$(ArtifactsBinDir)Microsoft.NET.Sdk.Razor\${Configuration}\sdk-output\</RazorSdkDirectoryRoot>
-  </PropertyGroup>
-  <Import Project="$(RepoRoot)src\Razor\Microsoft.NET.Sdk.Razor\src\build\netstandard2.0\Microsoft.NET.Sdk.Razor.props"
-      Condition="'$(UsingMicrosoftNETSdkWeb)' == 'true' OR '$(RazorSdkCurrentVersionProps)' != ''" />
 </Project>

+ 0 - 2
src/ProjectTemplates/test/ProjectTemplates.Tests.csproj

@@ -2,7 +2,6 @@
 
   <!-- Shared testing infrastructure for running E2E tests using selenium -->
   <Import Project="$(SharedSourceRoot)E2ETesting\E2ETesting.props" />
-  <Import Project="$(RepoRoot)eng\targets\GetRazorSDKDirectory.props" Condition="'$(IsHelixJob)' != 'true'"/>
 
   <PropertyGroup>
     <TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework>
@@ -51,7 +50,6 @@
     <ProjectReference Include="../Web.ItemTemplates/Microsoft.DotNet.Web.ItemTemplates.csproj" ReferenceOutputAssembly="false" />
     <ProjectReference Include="../Web.ProjectTemplates/Microsoft.DotNet.Web.ProjectTemplates.csproj" ReferenceOutputAssembly="false" />
     <ProjectReference Include="../Web.Spa.ProjectTemplates/Microsoft.DotNet.Web.Spa.ProjectTemplates.csproj" ReferenceOutputAssembly="false" />
-    <Reference Include="Microsoft.NET.Sdk.Razor" ReferenceOutputAssembly="false" SkipGetTargetFrameworkProperties="true" />
   </ItemGroup>
 
   <PropertyGroup>

+ 0 - 116
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/Application.cs

@@ -1,116 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Reflection;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.Extensions.CommandLineUtils;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal class Application : CommandLineApplication
-    {
-        public Application(
-            CancellationToken cancellationToken,
-            ExtensionAssemblyLoader loader,
-            ExtensionDependencyChecker checker,
-            Func<string, MetadataReferenceProperties, PortableExecutableReference> assemblyReferenceProvider,
-            TextWriter output = null,
-            TextWriter error = null)
-        {
-            CancellationToken = cancellationToken;
-            Checker = checker;
-            Loader = loader;
-            AssemblyReferenceProvider = assemblyReferenceProvider;
-            Out = output ?? Out;
-            Error = error ?? Error;
-
-            Name = "rzc";
-            FullName = "Microsoft ASP.NET Core Razor CLI tool";
-            Description = "CLI interface to perform Razor operations.";
-            ShortVersionGetter = GetInformationalVersion;
-
-            HelpOption("-?|-h|--help");
-
-            Commands.Add(new ServerCommand(this));
-            Commands.Add(new ShutdownCommand(this));
-            Commands.Add(new DiscoverCommand(this));
-            Commands.Add(new GenerateCommand(this));
-            Commands.Add(new BrotliCompressCommand(this));
-            Commands.Add(new RewriteCssCommand(this));
-        }
-
-        public CancellationToken CancellationToken { get; }
-
-        public ExtensionAssemblyLoader Loader { get; }
-
-        public ExtensionDependencyChecker Checker { get; }
-
-        public Func<string, MetadataReferenceProperties, PortableExecutableReference> AssemblyReferenceProvider { get; }
-
-        public new int Execute(params string[] args)
-        {
-            try
-            {
-                return base.Execute(ExpandResponseFiles(args));
-            }
-            catch (AggregateException ex) when (ex.InnerException != null)
-            {
-                foreach (var innerException in ex.Flatten().InnerExceptions)
-                {
-                    Error.WriteLine(innerException.Message);
-                    Error.WriteLine(innerException.StackTrace);
-                }
-                return 1;
-            }
-            catch (CommandParsingException ex)
-            {
-                // Don't show a call stack when we have unneeded arguments, just print the error message.
-                // The code that throws this exception will print help, so no need to do it here.
-                Error.WriteLine(ex.Message);
-                return 1;
-            }
-            catch (OperationCanceledException)
-            {
-                // This is a cancellation, not a failure.
-                Error.WriteLine("Cancelled");
-                return 1;
-            }
-            catch (Exception ex)
-            {
-                Error.WriteLine(ex.Message);
-                Error.WriteLine(ex.StackTrace);
-                return 1;
-            }
-        }
-
-        private string GetInformationalVersion()
-        {
-            var assembly = typeof(Application).Assembly;
-            var attribute = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
-            return attribute.InformationalVersion;
-        }
-
-        private static string[] ExpandResponseFiles(string[] args)
-        {
-            var expandedArgs = new List<string>(args.Length);
-            foreach (var arg in args)
-            {
-                if (!arg.StartsWith("@", StringComparison.Ordinal))
-                {
-                    expandedArgs.Add(arg);
-                }
-                else
-                {
-                    var fileName = arg.Substring(1);
-                    expandedArgs.AddRange(File.ReadLines(fileName));
-                }
-            }
-
-            return expandedArgs.ToArray();
-        }
-    }
-}

+ 0 - 70
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/BrotliCompressCommand.cs

@@ -1,70 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-using System.IO.Compression;
-using System.Threading.Tasks;
-using Microsoft.Extensions.CommandLineUtils;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal class BrotliCompressCommand : CommandBase
-    {
-        public BrotliCompressCommand(Application parent)
-            : base(parent, "brotli")
-        {
-            Sources = Option("-s", "files to compress", CommandOptionType.MultipleValue);
-            Outputs = Option("-o", "Output file path", CommandOptionType.MultipleValue);
-            CompressionLevelOption = Option("-c", "Compression level", CommandOptionType.SingleValue);
-        }
-
-        public CommandOption Sources { get; }
-
-        public CommandOption Outputs { get; }
-
-        public CommandOption CompressionLevelOption { get; }
-
-        public CompressionLevel CompressionLevel { get; private set; } = CompressionLevel.Optimal;
-
-        protected override bool ValidateArguments()
-        {
-            if (Sources.Values.Count != Outputs.Values.Count)
-            {
-                Error.WriteLine($"{Sources.Description} has {Sources.Values.Count}, but {Outputs.Description} has {Outputs.Values.Count} values.");
-                return false;
-            }
-
-            if (CompressionLevelOption.HasValue())
-            {
-                if (!Enum.TryParse<CompressionLevel>(CompressionLevelOption.Value(), out var value))
-                {
-                    Error.WriteLine($"Invalid option {CompressionLevelOption.Value()} for {CompressionLevelOption.Template}.");
-                    return false;
-                }
-
-                CompressionLevel = value;
-            }
-
-            return true;
-        }
-
-        protected override Task<int> ExecuteCoreAsync()
-        {
-            Parallel.For(0, Sources.Values.Count, i =>
-            {
-                var source = Sources.Values[i];
-                var output = Outputs.Values[i];
-
-                using var sourceStream = File.OpenRead(source);
-                using var fileStream = new FileStream(output, FileMode.Create);
-
-                using var stream = new BrotliStream(fileStream, CompressionLevel);
-
-                sourceStream.CopyTo(stream);
-            });
-
-            return Task.FromResult(ExitCodeSuccess);
-        }
-    }
-}

+ 0 - 32
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/CachingMetadataReference.cs

@@ -1,32 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using Microsoft.CodeAnalysis;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal sealed class CachingMetadataReference : PortableExecutableReference
-    {
-        private static readonly MetadataCache _metadataCache = new MetadataCache();
-
-        public CachingMetadataReference(string fullPath, MetadataReferenceProperties properties)
-            : base(properties, fullPath)
-        {
-        }
-
-        protected override DocumentationProvider CreateDocumentationProvider()
-        {
-            return DocumentationProvider.Default;
-        }
-
-        protected override Metadata GetMetadataImpl()
-        {
-            return _metadataCache.GetMetadata(FilePath);
-        }
-
-        protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties)
-        {
-            return new CachingMetadataReference(FilePath, properties);
-        }
-    }
-}

+ 0 - 200
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/Client.cs

@@ -1,200 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-using System.IO.Pipes;
-#if NETFRAMEWORK
-using System.Security.AccessControl;
-using System.Security.Principal;
-#endif
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal abstract class Client : IDisposable
-    {
-        private static int counter;
-
-        // From https://github.com/dotnet/corefx/blob/29cd6a0b0ac2993cee23ebaf36ca3d4bce6dd75f/src/System.IO.Pipes/ref/System.IO.Pipes.cs#L93.
-        // Using the enum value directly as this option is not available in netstandard.
-        private const PipeOptions PipeOptionCurrentUserOnly = (PipeOptions)536870912;
-
-        private static readonly PipeOptions _pipeOptions = GetPipeOptions();
-
-        public abstract Stream Stream { get; }
-
-        public abstract string Identifier { get; }
-
-        public void Dispose()
-        {
-            Dispose(disposing: true);
-        }
-
-        public abstract Task WaitForDisconnectAsync(CancellationToken cancellationToken);
-
-        protected virtual void Dispose(bool disposing)
-        {
-        }
-
-        // Based on: https://github.com/dotnet/roslyn/blob/14aed138a01c448143b9acf0fe77a662e3dfe2f4/src/Compilers/Shared/BuildServerConnection.cs#L290
-        public static async Task<Client> ConnectAsync(string pipeName, TimeSpan? timeout, CancellationToken cancellationToken)
-        {
-            var timeoutMilliseconds = timeout == null ? Timeout.Infinite : (int)timeout.Value.TotalMilliseconds;
-
-            try
-            {
-                // Machine-local named pipes are named "\\.\pipe\<pipename>".
-                // We use the SHA1 of the directory the compiler exes live in as the pipe name.
-                // The NamedPipeClientStream class handles the "\\.\pipe\" part for us.
-                ServerLogger.Log("Attempt to open named pipe '{0}'", pipeName);
-
-                var stream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, _pipeOptions);
-                cancellationToken.ThrowIfCancellationRequested();
-
-                ServerLogger.Log("Attempt to connect named pipe '{0}'", pipeName);
-                try
-                {
-                    await stream.ConnectAsync(timeoutMilliseconds, cancellationToken);
-                }
-                catch (Exception e) when (e is IOException || e is TimeoutException)
-                {
-                    // Note: IOException can also indicate timeout.
-                    // From docs:
-                    // - TimeoutException: Could not connect to the server within the specified timeout period.
-                    // - IOException: The server is connected to another client and the  time-out period has expired.
-                    ServerLogger.Log($"Connecting to server timed out after {timeoutMilliseconds} ms");
-                    return null;
-                }
-
-                ServerLogger.Log("Named pipe '{0}' connected", pipeName);
-                cancellationToken.ThrowIfCancellationRequested();
-
-#if NETFRAMEWORK
-                // Verify that we own the pipe.
-                if (!CheckPipeConnectionOwnership(stream))
-                {
-                    ServerLogger.Log("Owner of named pipe is incorrect");
-                    return null;
-                }
-#endif
-
-                return new NamedPipeClient(stream, GetNextIdentifier());
-            }
-            catch (Exception e) when (!(e is TaskCanceledException || e is OperationCanceledException))
-            {
-                ServerLogger.LogException(e, "Exception while connecting to process");
-                return null;
-            }
-        }
-
-#if NETFRAMEWORK
-        /// <summary>
-        /// Check to ensure that the named pipe server we connected to is owned by the same
-        /// user.
-        /// </summary>
-        private static bool CheckPipeConnectionOwnership(NamedPipeClientStream pipeStream)
-        {
-            try
-            {
-                if (PlatformInformation.IsWindows)
-                {
-                    using (var currentIdentity = WindowsIdentity.GetCurrent())
-                    {
-                        var currentOwner = currentIdentity.Owner;
-                        var remotePipeSecurity = GetPipeSecurity(pipeStream);
-                        var remoteOwner = remotePipeSecurity.GetOwner(typeof(SecurityIdentifier));
-
-                        return currentOwner.Equals(remoteOwner);
-                    }
-                }
-
-                // We don't need to verify on non-windows as that will be taken care of by the
-                // PipeOptions.CurrentUserOnly flag.
-                return false;
-            }
-            catch (Exception ex)
-            {
-                ServerLogger.LogException(ex, "Checking pipe connection");
-                return false;
-            }
-        }
-
-        private static ObjectSecurity GetPipeSecurity(PipeStream pipeStream)
-        {
-            return pipeStream.GetAccessControl();
-        }
-#endif
-
-        private static PipeOptions GetPipeOptions()
-        {
-            var options = PipeOptions.Asynchronous;
-
-            if (Enum.IsDefined(typeof(PipeOptions), PipeOptionCurrentUserOnly))
-            {
-                return options | PipeOptionCurrentUserOnly;
-            }
-
-            return options;
-        }
-
-        private static string GetNextIdentifier()
-        {
-            var id = Interlocked.Increment(ref counter);
-            return "clientconnection-" + id;
-        }
-
-        private class NamedPipeClient : Client
-        {
-            public NamedPipeClient(NamedPipeClientStream stream, string identifier)
-            {
-                Stream = stream;
-                Identifier = identifier;
-            }
-
-            public override Stream Stream { get; }
-
-            public override string Identifier { get; }
-
-            public async override Task WaitForDisconnectAsync(CancellationToken cancellationToken)
-            {
-                if (!(Stream is PipeStream pipeStream))
-                {
-                    return;
-                }
-
-                // We have to poll for disconnection by reading, PipeStream.IsConnected isn't reliable unless you
-                // actually do a read - which will cause it to update its state.
-                while (!cancellationToken.IsCancellationRequested && pipeStream.IsConnected)
-                {
-                    await Task.Delay(TimeSpan.FromMilliseconds(100), cancellationToken);
-
-                    try
-                    {
-                        ServerLogger.Log($"Before poking pipe {Identifier}.");
-                        await Stream.ReadAsync(Array.Empty<byte>(), 0, 0, cancellationToken);
-                        ServerLogger.Log($"After poking pipe {Identifier}.");
-                    }
-                    catch (OperationCanceledException)
-                    {
-                    }
-                    catch (Exception e)
-                    {
-                        // It is okay for this call to fail.  Errors will be reflected in the
-                        // IsConnected property which will be read on the next iteration.
-                        ServerLogger.LogException(e, $"Error poking pipe {Identifier}.");
-                    }
-                }
-            }
-
-            protected override void Dispose(bool disposing)
-            {
-                if (disposing)
-                {
-                    Stream.Dispose();
-                }
-            }
-        }
-    }
-}

+ 0 - 59
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/CommandBase.cs

@@ -1,59 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.Extensions.CommandLineUtils;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal abstract class CommandBase : CommandLineApplication
-    {
-        public const int ExitCodeSuccess = 0;
-        public const int ExitCodeFailure = 1;
-        public const int ExitCodeFailureRazorError = 2;
-
-        protected CommandBase(Application parent, string name)
-            : base(throwOnUnexpectedArg: true)
-        {
-            if (parent == null)
-            {
-                throw new ArgumentNullException(nameof(parent));
-            }
-
-            base.Parent = parent;
-            Name = name;
-            Out = parent.Out ?? Out;
-            Error = parent.Error ?? Error;
-
-            Help = HelpOption("-?|-h|--help");
-            OnExecute((Func<Task<int>>)ExecuteAsync);
-        }
-
-        protected new Application Parent => (Application)base.Parent;
-
-        protected CancellationToken Cancelled => Parent?.CancellationToken ?? default;
-
-        protected CommandOption Help { get; }
-
-        protected virtual bool ValidateArguments()
-        {
-            return true;
-        }
-
-        protected abstract Task<int> ExecuteCoreAsync();
-
-        private async Task<int> ExecuteAsync()
-        {
-            if (!ValidateArguments())
-            {
-                ShowHelp();
-                return ExitCodeFailureRazorError;
-            }
-
-            return await ExecuteCoreAsync();
-        }
-    }
-}

+ 0 - 134
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/CompilerHost.cs

@@ -1,134 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal abstract class CompilerHost
-    {
-        public static CompilerHost Create()
-        {
-            return new DefaultCompilerHost();
-        }
-
-        public abstract ServerResponse Execute(ServerRequest request, CancellationToken cancellationToken);
-
-        private class DefaultCompilerHost : CompilerHost
-        {
-            public DefaultCompilerHost()
-            {
-                // The loader needs to live for the lifetime of the server. 
-                //
-                // This means that if a request tries to use a set of binaries that are inconsistent with what
-                // the server already has, then it will be rejected to try again on the client.
-                //
-                // We also check each set of extensions for missing depenencies individually, so that we can
-                // consistently reject a request that doesn't specify everything it needs. Otherwise the request
-                // could succeed sometimes if it relies on transient state.
-                Loader = new DefaultExtensionAssemblyLoader(Path.Combine(Path.GetTempPath(), "Razor-Server"));
-
-                AssemblyReferenceProvider = (path, properties) => new CachingMetadataReference(path, properties);
-            }
-
-            public Func<string, MetadataReferenceProperties, PortableExecutableReference> AssemblyReferenceProvider { get; }
-
-            public ExtensionAssemblyLoader Loader { get; }
-
-            public override ServerResponse Execute(ServerRequest request, CancellationToken cancellationToken)
-            {
-                if (!TryParseArguments(request, out var parsed))
-                {
-                    return new RejectedServerResponse();
-                }
-
-                var exitCode = 0;
-                var commandArgs = parsed.args.ToArray();
-
-                var outputWriter = new StringWriter();
-                var errorWriter = new StringWriter();
-
-                var checker = new DefaultExtensionDependencyChecker(Loader, outputWriter, errorWriter);
-                var app = new Application(cancellationToken, Loader, checker, AssemblyReferenceProvider, outputWriter, errorWriter);
-
-                exitCode = app.Execute(commandArgs);
-
-                var output = outputWriter.ToString();
-                var error = errorWriter.ToString();
-
-                outputWriter.Dispose();
-                errorWriter.Dispose();
-
-                // This will no-op if server logging is not enabled.
-                ServerLogger.Log(output);
-                ServerLogger.Log(error);
-
-                return new CompletedServerResponse(exitCode, utf8output: false, output, error);
-            }
-
-            private bool TryParseArguments(ServerRequest request, out (string workingDirectory, string tempDirectory, string[] args) parsed)
-            {
-                string workingDirectory = null;
-                string tempDirectory = null;
-
-                var args = new List<string>(request.Arguments.Count);
-
-                for (var i = 0; i < request.Arguments.Count; i++)
-                {
-                    var argument = request.Arguments[i];
-                    if (argument.Id == RequestArgument.ArgumentId.CurrentDirectory)
-                    {
-                        workingDirectory = argument.Value;
-                    }
-                    else if (argument.Id == RequestArgument.ArgumentId.TempDirectory)
-                    {
-                        tempDirectory = argument.Value;
-                    }
-                    else if (argument.Id == RequestArgument.ArgumentId.CommandLineArgument)
-                    {
-                        args.Add(argument.Value);
-                    }
-                }
-
-                ServerLogger.Log($"WorkingDirectory = '{workingDirectory}'");
-                ServerLogger.Log($"TempDirectory = '{tempDirectory}'");
-                for (var i = 0; i < args.Count; i++)
-                {
-                    ServerLogger.Log($"Argument[{i}] = '{request.Arguments[i]}'");
-                }
-
-                if (string.IsNullOrEmpty(workingDirectory))
-                {
-                    ServerLogger.Log($"Rejecting build due to missing working directory");
-
-                    parsed = default;
-                    return false;
-                }
-
-                if (string.IsNullOrEmpty(tempDirectory))
-                {
-                    ServerLogger.Log($"Rejecting build due to missing temp directory");
-
-                    parsed = default;
-                    return false;
-                }
-
-                if (string.IsNullOrEmpty(tempDirectory))
-                {
-                    ServerLogger.Log($"Rejecting build due to missing temp directory");
-
-                    parsed = default;
-                    return false;
-                }
-
-                parsed = (workingDirectory, tempDirectory, args.ToArray());
-                return true;
-            }
-        }
-    }
-}

+ 0 - 51
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/CompositeRazorProjectFileSystem.cs

@@ -1,51 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using Microsoft.AspNetCore.Razor.Language;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal class CompositeRazorProjectFileSystem : RazorProjectFileSystem
-    {
-        public CompositeRazorProjectFileSystem(IReadOnlyList<RazorProjectFileSystem> fileSystems)
-        {
-            FileSystems = fileSystems ?? throw new ArgumentNullException(nameof(fileSystems));
-        }
-
-        public IReadOnlyList<RazorProjectFileSystem> FileSystems { get; }
-
-        public override IEnumerable<RazorProjectItem> EnumerateItems(string basePath)
-        {
-            foreach (var fileSystem in FileSystems)
-            {
-                foreach (var result in fileSystem.EnumerateItems(basePath))
-                {
-                    yield return result;
-                }
-            }
-        }
-
-
-        public override RazorProjectItem GetItem(string path)
-        {
-            return GetItem(path, fileKind: null);
-        }
-
-        public override RazorProjectItem GetItem(string path, string fileKind)
-        {
-            RazorProjectItem razorProjectItem = null;
-            foreach (var fileSystem in FileSystems)
-            {
-                razorProjectItem = fileSystem.GetItem(path, fileKind);
-                if (razorProjectItem != null && razorProjectItem.Exists)
-                {
-                    return razorProjectItem;
-                }
-            }
-
-            return razorProjectItem;
-        }
-    }
-}

+ 0 - 207
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ConcurrentLruCache.cs

@@ -1,207 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    /// <summary>
-    /// Cache with a fixed size that evicts the least recently used members.
-    /// Thread-safe.
-    /// This was taken from https://github.com/dotnet/roslyn/blob/749c0ec135d7d080658dc1aa794d15229c3d10d2/src/Compilers/Core/Portable/InternalUtilities/ConcurrentLruCache.cs.
-    /// </summary>
-    internal class ConcurrentLruCache<TKey, TValue>
-    {
-        private readonly int _capacity;
-
-        private readonly Dictionary<TKey, CacheValue> _cache;
-        private readonly LinkedList<TKey> _nodeList;
-        // This is a naive course-grained lock, it can probably be optimized
-        private readonly object _lockObject = new object();
-
-        public ConcurrentLruCache(int capacity)
-            : this (capacity, EqualityComparer<TKey>.Default)
-        {
-        }
-
-        public ConcurrentLruCache(int capacity, IEqualityComparer<TKey> comparer)
-        {
-            if (capacity <= 0)
-            {
-                throw new ArgumentOutOfRangeException(nameof(capacity));
-            }
-            _capacity = capacity;
-            _cache = new Dictionary<TKey, CacheValue>(capacity, comparer);
-            _nodeList = new LinkedList<TKey>();
-        }
-
-        /// <summary>
-        /// Create cache from an array. The cache capacity will be the size
-        /// of the array. All elements of the array will be added to the 
-        /// cache. If any duplicate keys are found in the array a
-        /// <see cref="ArgumentException"/> will be thrown.
-        /// </summary>
-        public ConcurrentLruCache(KeyValuePair<TKey, TValue>[] array)
-            : this(array.Length)
-        {
-            foreach (var kvp in array)
-            {
-                UnsafeAdd(kvp.Key, kvp.Value);
-            }
-        }
-
-        public int Count
-        {
-            get
-            {
-                lock (_lockObject)
-                {
-                    return _cache.Count;
-                }
-            }
-        }
-
-        public void Add(TKey key, TValue value)
-        {
-            lock (_lockObject)
-            {
-                UnsafeAdd(key, value);
-            }
-        }
-
-        public TValue GetOrAdd(TKey key, TValue value)
-        {
-            lock (_lockObject)
-            {
-                if (UnsafeTryGetValue(key, out var result))
-                {
-                    return result;
-                }
-                else
-                {
-                    UnsafeAdd(key, value);
-                    return value;
-                }
-            }
-        }
-
-        public bool TryGetValue(TKey key, out TValue value)
-        {
-            lock (_lockObject)
-            {
-                return UnsafeTryGetValue(key, out value);
-            }
-        }
-
-        public bool Remove(TKey key)
-        {
-            lock (_lockObject)
-            {
-                return UnsafeRemove(key);
-            }
-        }
-
-        /// <summary>
-        /// For testing. Very expensive.
-        /// </summary>
-        internal IEnumerable<KeyValuePair<TKey, TValue>> TestingEnumerable
-        {
-            get
-            {
-                lock (_lockObject)
-                {
-                    foreach (var key in _nodeList)
-                    {
-                        var kvp = new KeyValuePair<TKey, TValue>(key, _cache[key].Value);
-                        yield return kvp;
-                    }
-                }
-            }
-        }
-
-        /// <summary>
-        /// Doesn't lock.
-        /// </summary>
-        private bool UnsafeTryGetValue(TKey key, out TValue value)
-        {
-            if (_cache.TryGetValue(key, out var result))
-            {
-                MoveNodeToTop(result.Node);
-                value = result.Value;
-                return true;
-            }
-            else
-            {
-                value = default(TValue);
-                return false;
-            }
-        }
-
-        private void MoveNodeToTop(LinkedListNode<TKey> node)
-        {
-            if (!object.ReferenceEquals(_nodeList.First, node))
-            {
-                _nodeList.Remove(node);
-                _nodeList.AddFirst(node);
-            }
-        }
-
-        /// <summary>
-        /// Expects non-empty cache. Does not lock.
-        /// </summary>
-        private void UnsafeEvictLastNode()
-        {
-            Debug.Assert(_capacity > 0);
-            var lastNode = _nodeList.Last;
-            _nodeList.Remove(lastNode);
-            _cache.Remove(lastNode.Value);
-        }
-
-        private void UnsafeAddNodeToTop(TKey key, TValue value)
-        {
-            var node = new LinkedListNode<TKey>(key);
-            _cache.Add(key, new CacheValue(value, node));
-            _nodeList.AddFirst(node);
-        }
-
-        /// <summary>
-        /// Doesn't lock.
-        /// </summary>
-        private void UnsafeAdd(TKey key, TValue value)
-        {
-            if (_cache.TryGetValue(key, out var result))
-            {
-                throw new ArgumentException("Key already exists", nameof(key));
-            }
-            else
-            {
-                if (_cache.Count == _capacity)
-                {
-                    UnsafeEvictLastNode();
-                }
-                UnsafeAddNodeToTop(key, value);
-            }
-        }
-
-        private bool UnsafeRemove(TKey key)
-        {
-            _nodeList.Remove(key);
-            return _cache.Remove(key);
-        }
-
-        private struct CacheValue
-        {
-            public CacheValue(TValue value, LinkedListNode<TKey> node)
-            {
-                Value = value;
-                Node = node;
-            }
-
-            public TValue Value { get; }
-
-            public LinkedListNode<TKey> Node { get; }
-        }
-    }
-}

+ 0 - 28
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/Connection.cs

@@ -1,28 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal abstract class Connection : IDisposable
-    {
-        public string Identifier { get; protected set; }
-
-        public Stream Stream { get; protected set; }
-
-        public abstract Task WaitForDisconnectAsync(CancellationToken cancellationToken);
-
-        public void Dispose()
-        {
-            Dispose(disposing: true);
-        }
-
-        protected virtual void Dispose(bool disposing)
-        {
-        }
-    }
-}

+ 0 - 148
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ConnectionHost.cs

@@ -1,148 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-using System.IO.Pipes;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    // Heavily influenced by:
-    // https://github.com/dotnet/roslyn/blob/14aed138a01c448143b9acf0fe77a662e3dfe2f4/src/Compilers/Server/VBCSCompiler/NamedPipeClientConnection.cs#L17
-    internal abstract class ConnectionHost
-    {
-        private static int counter;
-
-        public abstract Task<Connection> WaitForConnectionAsync(CancellationToken cancellationToken);
-
-        public static ConnectionHost Create(string pipeName)
-        {
-            return new NamedPipeConnectionHost(pipeName);
-        }
-
-        private static string GetNextIdentifier()
-        {
-            var id = Interlocked.Increment(ref counter);
-            return "connection-" + id;
-        }
-
-        private class NamedPipeConnectionHost : ConnectionHost
-        {
-            // Size of the buffers to use: 64K
-            private const int PipeBufferSize = 0x10000;
-
-            // From https://github.com/dotnet/corefx/blob/29cd6a0b0ac2993cee23ebaf36ca3d4bce6dd75f/src/System.IO.Pipes/ref/System.IO.Pipes.cs#L93.
-            // Using the enum value directly as this option is not available in netstandard.
-            private const PipeOptions PipeOptionCurrentUserOnly = (PipeOptions)536870912;
-
-            private static readonly PipeOptions _pipeOptions = GetPipeOptions();
-
-            public NamedPipeConnectionHost(string pipeName)
-            {
-                PipeName = pipeName;
-            }
-
-            public string PipeName { get; }
-
-            public async override Task<Connection> WaitForConnectionAsync(CancellationToken cancellationToken)
-            {
-                // Create the pipe and begin waiting for a connection. This  doesn't block, but could fail 
-                // in certain circumstances, such as the OS refusing to create the pipe for some reason 
-                // or the pipe was disconnected before we starting listening.
-                var pipeStream = new NamedPipeServerStream(
-                    PipeName,
-                    PipeDirection.InOut,
-                    NamedPipeServerStream.MaxAllowedServerInstances, // Maximum connections.
-                    PipeTransmissionMode.Byte,
-                    _pipeOptions,
-                    PipeBufferSize, // Default input buffer
-                    PipeBufferSize);// Default output buffer
-
-                ServerLogger.Log("Waiting for new connection");
-                await pipeStream.WaitForConnectionAsync(cancellationToken);
-                ServerLogger.Log("Pipe connection detected.");
-
-                if (Environment.Is64BitProcess || Memory.IsMemoryAvailable())
-                {
-                    ServerLogger.Log("Memory available - accepting connection");
-                    return new NamedPipeConnection(pipeStream, GetNextIdentifier());
-                }
-
-                pipeStream.Close();
-                throw new Exception("Insufficient resources to process new connection.");
-            }
-
-            private static PipeOptions GetPipeOptions()
-            {
-                var options = PipeOptions.Asynchronous | PipeOptions.WriteThrough;
-
-                if (Enum.IsDefined(typeof(PipeOptions), PipeOptionCurrentUserOnly))
-                {
-                    return options | PipeOptionCurrentUserOnly;
-                }
-
-                return options;
-            }
-        }
-
-        private class NamedPipeConnection : Connection
-        {
-            public NamedPipeConnection(NamedPipeServerStream stream, string identifier)
-            {
-                Stream = stream;
-                Identifier = identifier;
-            }
-
-            public async override Task WaitForDisconnectAsync(CancellationToken cancellationToken)
-            {
-                if (!(Stream is PipeStream pipeStream))
-                {
-                    return;
-                }
-
-                // We have to poll for disconnection by reading, PipeStream.IsConnected isn't reliable unless you
-                // actually do a read - which will cause it to update its state.
-                while (!cancellationToken.IsCancellationRequested && pipeStream.IsConnected)
-                {
-                    await Task.Delay(TimeSpan.FromMilliseconds(100), cancellationToken);
-
-                    try
-                    {
-                        ServerLogger.Log($"Before poking pipe {Identifier}.");
-                        await Stream.ReadAsync(Array.Empty<byte>(), 0, 0, cancellationToken);
-                        ServerLogger.Log($"After poking pipe {Identifier}.");
-                    }
-                    catch (OperationCanceledException)
-                    {
-                    }
-                    catch (Exception e)
-                    {
-                        // It is okay for this call to fail.  Errors will be reflected in the
-                        // IsConnected property which will be read on the next iteration.
-                        ServerLogger.LogException(e, $"Error poking pipe {Identifier}.");
-                    }
-                }
-            }
-
-            protected override void Dispose(bool disposing)
-            {
-                ServerLogger.Log($"Pipe {Identifier}: Closing.");
-
-                try
-                {
-                    Stream.Dispose();
-                }
-                catch (Exception ex)
-                {
-                    // The client connection failing to close isn't fatal to the server process.  It is simply a client
-                    // for which we can no longer communicate and that's okay because the Close method indicates we are
-                    // done with the client already.
-                    var message = $"Pipe {Identifier}: Error closing pipe.";
-                    ServerLogger.LogException(ex, message);
-                }
-            }
-        }
-    }
-}

+ 0 - 47
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ConnectionResult.cs

@@ -1,47 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal struct ConnectionResult
-    {
-        public readonly Reason CloseReason;
-        public readonly TimeSpan? KeepAlive;
-
-        public ConnectionResult(Reason closeReason, TimeSpan? keepAlive = null)
-        {
-            CloseReason = closeReason;
-            KeepAlive = keepAlive;
-        }
-
-        public enum Reason
-        {
-            /// <summary>
-            /// There was an error creating the request object and a compilation was never created.
-            /// </summary>
-            CompilationNotStarted,
-
-            /// <summary>
-            /// The compilation completed and results were provided to the client.
-            /// </summary>
-            CompilationCompleted,
-
-            /// <summary>
-            /// The compilation process was initiated and the client disconnected before the results could be provided to them.
-            /// </summary>
-            ClientDisconnect,
-
-            /// <summary>
-            /// There was an unhandled exception processing the result.
-            /// </summary>
-            ClientException,
-
-            /// <summary>
-            /// There was a request from the client to shutdown the server.
-            /// </summary>
-            ClientShutdownRequest,
-        }
-    }
-}

+ 0 - 27
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/DebugMode.cs

@@ -1,27 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Diagnostics;
-using System.Linq;
-using System.Threading;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal static class DebugMode
-    {
-        public static void HandleDebugSwitch(ref string[] args)
-        {
-            if (args.Length > 0 && string.Equals("--debug", args[0], StringComparison.OrdinalIgnoreCase))
-            {
-                args = args.Skip(1).ToArray();
-
-                Console.WriteLine("Waiting for debugger in pid: {0}", Process.GetCurrentProcess().Id);
-                while (!Debugger.IsAttached)
-                {
-                    Thread.Sleep(TimeSpan.FromSeconds(3));
-                }
-            }
-        }
-    }
-}

+ 0 - 241
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/DefaultExtensionAssemblyLoader.cs

@@ -1,241 +0,0 @@
-// Copyright(c) .NET Foundation.All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.IO;
-using System.Reflection;
-using System.Reflection.Metadata;
-using System.Reflection.PortableExecutable;
-using System.Runtime.Loader;
-using Microsoft.CodeAnalysis;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal class DefaultExtensionAssemblyLoader : ExtensionAssemblyLoader
-    {
-        private readonly string _baseDirectory;
-
-        private readonly object _lock = new object();
-        private readonly Dictionary<string, (Assembly assembly, AssemblyIdentity identity)> _loadedByPath;
-        private readonly Dictionary<AssemblyIdentity, Assembly> _loadedByIdentity;
-        private readonly Dictionary<string, AssemblyIdentity> _identityCache;
-        private readonly Dictionary<string, List<string>> _wellKnownAssemblies;
-
-        private ShadowCopyManager _shadowCopyManager;
-
-        public DefaultExtensionAssemblyLoader(string baseDirectory)
-        {
-            _baseDirectory = baseDirectory;
-
-            _loadedByPath = new Dictionary<string, (Assembly assembly, AssemblyIdentity identity)>(StringComparer.OrdinalIgnoreCase);
-            _loadedByIdentity = new Dictionary<AssemblyIdentity, Assembly>();
-            _identityCache = new Dictionary<string, AssemblyIdentity>(StringComparer.OrdinalIgnoreCase);
-            _wellKnownAssemblies = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
-
-            LoadContext = new ExtensionAssemblyLoadContext(AssemblyLoadContext.GetLoadContext(typeof(ExtensionAssemblyLoader).Assembly), this);
-        }
-
-        protected AssemblyLoadContext LoadContext { get; }
-
-        public override void AddAssemblyLocation(string filePath)
-        {
-            if (filePath == null)
-            {
-                throw new ArgumentNullException(nameof(filePath));
-            }
-
-            if (!Path.IsPathRooted(filePath))
-            {
-                throw new ArgumentException(nameof(filePath));
-            }
-
-            var assemblyName = Path.GetFileNameWithoutExtension(filePath);
-            lock (_lock)
-            {
-                if (!_wellKnownAssemblies.TryGetValue(assemblyName, out var paths))
-                {
-                    paths = new List<string>();
-                    _wellKnownAssemblies.Add(assemblyName, paths);
-                }
-
-                if (!paths.Contains(filePath))
-                {
-                    paths.Add(filePath);
-                }
-            }
-        }
-
-        public override Assembly Load(string assemblyName)
-        {
-            if (!AssemblyIdentity.TryParseDisplayName(assemblyName, out var identity))
-            {
-                return null;
-            }
-
-            lock (_lock)
-            {
-                // First, check if this loader already loaded the requested assembly:
-                if (_loadedByIdentity.TryGetValue(identity, out var assembly))
-                {
-                    return assembly;
-                }
-
-                // Second, check if an assembly file of the same simple name was registered with the loader:
-                if (_wellKnownAssemblies.TryGetValue(identity.Name, out var paths))
-                {
-                    // Multiple assemblies of the same simple name but different identities might have been registered.
-                    // Load the one that matches the requested identity (if any).
-                    foreach (var path in paths)
-                    {
-                        var candidateIdentity = GetIdentity(path);
-
-                        if (identity.Equals(candidateIdentity))
-                        {
-                            return LoadFromPathUnsafe(path, candidateIdentity);
-                        }
-                    }
-                }
-
-                // We only support loading by name from 'well-known' paths. If you need to load something by
-                // name and you get here, then that means we don't know where to look.
-                return null;
-            }
-        }
-
-        public override Assembly LoadFromPath(string filePath)
-        {
-            if (filePath == null)
-            {
-                throw new ArgumentNullException(nameof(filePath));
-            }
-
-            if (!Path.IsPathRooted(filePath))
-            {
-                throw new ArgumentException(nameof(filePath));
-            }
-
-            lock (_lock)
-            {
-                return LoadFromPathUnsafe(filePath, identity: null);
-            }
-        }
-
-        private Assembly LoadFromPathUnsafe(string filePath, AssemblyIdentity identity)
-        {
-            // If we've already loaded the assembly by path there should be nothing else to do,
-            // all of our data is up to date.
-            if (_loadedByPath.TryGetValue(filePath, out var entry))
-            {
-                return entry.assembly;
-            }
-
-            // If we've already loaded the assembly by identity, then we might has some updating
-            // to do.
-            identity = identity ?? GetIdentity(filePath);
-            if (identity != null && _loadedByIdentity.TryGetValue(identity, out var assembly))
-            {
-                // An assembly file might be replaced by another file with a different identity.
-                // Last one wins.
-                _loadedByPath[filePath] = (assembly, identity);
-                return assembly;
-            }
-
-            // Ok we don't have this cached. Let's actually try to load the assembly.
-            assembly = LoadFromPathUnsafeCore(CopyAssembly(filePath));
-
-            identity = identity ?? AssemblyIdentity.FromAssemblyDefinition(assembly);
-
-            // It's possible an assembly was loaded by two different paths. Just use the original then.
-            if (_loadedByIdentity.TryGetValue(identity, out var duplicate))
-            {
-                assembly = duplicate;
-            }
-            else
-            {
-                _loadedByIdentity.Add(identity, assembly);
-            }
-
-            _loadedByPath[filePath] = (assembly, identity);
-            return assembly;
-        }
-
-        private AssemblyIdentity GetIdentity(string filePath)
-        {
-            if (!_identityCache.TryGetValue(filePath, out var identity))
-            {
-                identity = ReadAssemblyIdentity(filePath);
-                _identityCache.Add(filePath, identity);
-            }
-
-            return identity;
-        }
-
-        protected virtual string CopyAssembly(string filePath)
-        {
-            if (_baseDirectory == null)
-            {
-                // Don't shadow-copy when base directory is null. This means we're running as a CLI not
-                // a server.
-                return filePath;
-            }
-
-            if (_shadowCopyManager == null)
-            {
-                _shadowCopyManager = new ShadowCopyManager(_baseDirectory);
-            }
-
-            return _shadowCopyManager.AddAssembly(filePath);
-        }
-
-        protected virtual Assembly LoadFromPathUnsafeCore(string filePath)
-        {
-            return LoadContext.LoadFromAssemblyPath(filePath);
-        }
-
-        private static AssemblyIdentity ReadAssemblyIdentity(string filePath)
-        {
-            try
-            {
-                using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
-                using (var reader = new PEReader(stream))
-                {
-                    var metadataReader = reader.GetMetadataReader();
-                    return metadataReader.GetAssemblyIdentity();
-                }
-            }
-            catch
-            {
-            }
-
-            return null;
-        }
-
-        private class ExtensionAssemblyLoadContext : AssemblyLoadContext
-        {
-            private readonly AssemblyLoadContext _parent;
-            private readonly DefaultExtensionAssemblyLoader _loader;
-
-            public ExtensionAssemblyLoadContext(AssemblyLoadContext parent, DefaultExtensionAssemblyLoader loader)
-            {
-                _parent = parent;
-                _loader = loader;
-            }
-
-            protected override Assembly Load(AssemblyName assemblyName)
-            {
-                // Try to load from well-known paths. This will be called when loading a dependency of an extension.
-                var assembly = _loader.Load(assemblyName.ToString());
-                if (assembly != null)
-                {
-                    return assembly;
-                }
-
-                // If we don't have an entry, then fall back to the default load context. This allows extensions
-                // to resolve assemblies that are provided by the host.
-                return _parent.LoadFromAssemblyName(assemblyName);
-            }
-        }
-    }
-}

+ 0 - 158
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/DefaultExtensionDependencyChecker.cs

@@ -1,158 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Reflection;
-using System.Reflection.Metadata;
-using System.Reflection.PortableExecutable;
-using Microsoft.CodeAnalysis;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal class DefaultExtensionDependencyChecker : ExtensionDependencyChecker
-    {
-        // These are treated as prefixes. So `Microsoft.CodeAnalysis.Razor` would be assumed to work.
-        private static readonly string[] DefaultIgnoredAssemblies = new string[]
-        {
-            "mscorlib",
-            "netstandard",
-            "System",
-            "Microsoft.CodeAnalysis",
-            "Microsoft.AspNetCore.Razor.Language",
-        };
-
-        private readonly ExtensionAssemblyLoader _loader;
-        private readonly TextWriter _output;
-        private readonly TextWriter _error;
-        private readonly string[] _ignoredAssemblies;
-
-        public DefaultExtensionDependencyChecker(
-            ExtensionAssemblyLoader loader,
-            TextWriter output,
-            TextWriter error,
-            string[] ignoredAssemblies = null)
-        {
-            _loader = loader;
-            _output = output;
-            _error = error;
-            _ignoredAssemblies = ignoredAssemblies ?? DefaultIgnoredAssemblies;
-        }
-
-        public override bool Check(IEnumerable<string> assmblyFilePaths)
-        {
-            try
-            {
-                return CheckCore(assmblyFilePaths);
-            }
-            catch (Exception ex)
-            {
-                _error.WriteLine("Exception performing Extension dependency check:");
-                _error.WriteLine(ex.ToString());
-                return false;
-            }
-        }
-
-        private bool CheckCore(IEnumerable<string> assemblyFilePaths)
-        {
-            var items = assemblyFilePaths.Select(a => ExtensionVerificationItem.Create(a)).ToArray();
-            var assemblies = new HashSet<AssemblyIdentity>(items.Select(i => i.Identity));
-
-            for (var i = 0; i < items.Length; i++)
-            {
-                var item = items[i];
-                _output.WriteLine($"Verifying assembly at {item.FilePath}");
-
-                if (!Path.IsPathRooted(item.FilePath))
-                {
-                    _error.WriteLine($"The file path '{item.FilePath}' is not a rooted path. File paths must be absolute and fully-qualified.");
-                    return false;
-                }
-
-                foreach (var reference in item.References)
-                {
-                    if (_ignoredAssemblies.Any(n => reference.Name.StartsWith(n, StringComparison.Ordinal)))
-                    {
-                        // This is on the allow list, keep going.
-                        continue;
-                    }
-
-                    if (assemblies.Contains(reference))
-                    {
-                        // This was also provided as a dependency, keep going.
-                        continue;
-                    }
-
-                    // If we get here we can't resolve this assembly. This is an error.
-                    _error.WriteLine($"Extension assembly '{item.Identity.Name}' depends on '{reference.ToString()} which is missing.");
-                    return false;
-                }
-            }
-
-            // Assuming we get this far, the set of assemblies we have is at least a coherent set (barring
-            // version conflicts). Register all of the paths with the loader so they can find each other by
-            // name.
-            for (var i = 0; i < items.Length; i++)
-            {
-                _loader.AddAssemblyLocation(items[i].FilePath);
-            }
-
-            // Now try to load everything. This has the side effect of resolving all of these items
-            // in the loader's caches.
-            for (var i = 0; i < items.Length; i++)
-            {
-                var item = items[i];
-                item.Assembly = _loader.LoadFromPath(item.FilePath);
-            }
-
-            // Third, check that the MVIDs of the files on disk match the MVIDs of the loaded assemblies.
-            for (var i = 0; i < items.Length; i++)
-            {
-                var item = items[i];
-                if (item.Mvid != item.Assembly.ManifestModule.ModuleVersionId)
-                {
-                    _error.WriteLine($"Extension assembly '{item.Identity.Name}' at '{item.FilePath}' has a different ModuleVersionId than loaded assembly '{item.Assembly.FullName}'");
-                    return false;
-                }
-            }
-
-            return true;
-        }
-
-        private class ExtensionVerificationItem
-        {
-            public static ExtensionVerificationItem Create(string filePath)
-            {
-                using (var peReader = new PEReader(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)))
-                {
-                    var metadataReader = peReader.GetMetadataReader();
-                    var identity = metadataReader.GetAssemblyIdentity();
-                    var mvid = metadataReader.GetGuid(metadataReader.GetModuleDefinition().Mvid);
-                    var references = metadataReader.GetReferencedAssembliesOrThrow();
-
-                    return new ExtensionVerificationItem(filePath, identity, mvid, references.ToArray());
-                }
-            }
-
-            private ExtensionVerificationItem(string filePath, AssemblyIdentity identity, Guid mvid, AssemblyIdentity[] references)
-            {
-                FilePath = filePath;
-                Identity = identity;
-                Mvid = mvid;
-                References = references;
-            }
-
-            public string FilePath { get; }
-
-            public Assembly Assembly { get; set; }
-
-            public AssemblyIdentity Identity { get; }
-
-            public Guid Mvid { get; }
-
-            public IReadOnlyList<AssemblyIdentity> References { get; }
-        }
-    }
-}

+ 0 - 472
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/DefaultRequestDispatcher.cs

@@ -1,472 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Linq;
-using System.Runtime;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    // Heavily influenced by:
-    // https://github.com/dotnet/roslyn/blob/14aed138a01c448143b9acf0fe77a662e3dfe2f4/src/Compilers/Server/ServerShared/ServerDispatcher.cs#L15
-    internal class DefaultRequestDispatcher : RequestDispatcher
-    {
-        private readonly CancellationToken _cancellationToken;
-        private readonly CompilerHost _compilerHost;
-        private readonly ConnectionHost _connectionHost;
-        private readonly EventBus _eventBus;
-
-        private KeepAlive _keepAlive;
-        private State _state;
-        private Task _timeoutTask;
-        private Task _gcTask;
-        private Task<Connection> _listenTask;
-        private CancellationTokenSource _listenCancellationTokenSource;
-        private List<Task<ConnectionResult>> _connections = new List<Task<ConnectionResult>>();
-
-        public DefaultRequestDispatcher(
-            ConnectionHost connectionHost,
-            CompilerHost compilerHost,
-            CancellationToken cancellationToken,
-            EventBus eventBus = null,
-            TimeSpan? keepAlive = null)
-        {
-            _connectionHost = connectionHost;
-            _compilerHost = compilerHost;
-            _cancellationToken = cancellationToken;
-
-            _eventBus = eventBus ?? EventBus.Default;
-
-            var keepAliveTimeout = DefaultServerKeepAlive;
-            if (keepAlive.HasValue)
-            {
-                keepAliveTimeout = keepAlive.Value;
-            }
-            _keepAlive = new KeepAlive(keepAliveTimeout, isDefault: true);
-        }
-
-        // The server accepts connections until we reach a state that requires a shutdown. At that
-        // time no new connections will be accepted and the server will drain existing connections.
-        //
-        // The idea is that it's better to let clients fallback to in-proc (and slow down) than it is to keep
-        // running in an undesired state.
-        public override void Run()
-        {
-            _state = State.Running;
-
-            try
-            {
-                Listen();
-
-                do
-                {
-                    Debug.Assert(_listenTask != null);
-
-                    MaybeCreateTimeoutTask();
-                    MaybeCreateGCTask();
-                    WaitForAnyCompletion(_cancellationToken);
-                    CheckCompletedTasks(_cancellationToken);
-                }
-                while (_connections.Count > 0 || _state == State.Running);
-            }
-            finally
-            {
-                _state = State.Completed;
-                _gcTask = null;
-                _timeoutTask = null;
-
-                if (_listenTask != null)
-                {
-                    CloseListenTask();
-                }
-            }
-        }
-
-
-        private void CheckCompletedTasks(CancellationToken cancellationToken)
-        {
-            if (cancellationToken.IsCancellationRequested)
-            {
-                HandleCancellation();
-                return;
-            }
-
-            if (_listenTask.IsCompleted)
-            {
-                HandleCompletedListenTask(cancellationToken);
-            }
-
-            if (_timeoutTask?.IsCompleted == true)
-            {
-                HandleCompletedTimeoutTask();
-            }
-
-            if (_gcTask?.IsCompleted == true)
-            {
-                HandleCompletedGCTask();
-            }
-
-            HandleCompletedConnections();
-        }
-
-        private void HandleCancellation()
-        {
-            Debug.Assert(_listenTask != null);
-
-            // If cancellation has been requested then the server needs to be in the process
-            // of shutting down.
-            _state = State.ShuttingDown;
-
-            CloseListenTask();
-
-            try
-            {
-                Task.WaitAll(_connections.ToArray());
-            }
-            catch
-            {
-                // It's expected that some will throw exceptions, in particular OperationCanceledException.  It's
-                // okay for them to throw so long as they complete.
-            }
-
-            HandleCompletedConnections();
-            Debug.Assert(_connections.Count == 0);
-        }
-
-        /// <summary>
-        /// The server farms out work to Task values and this method needs to wait until at least one of them
-        /// has completed.
-        /// </summary>
-        private void WaitForAnyCompletion(CancellationToken cancellationToken)
-        {
-            var all = new List<Task>(_connections.Count + 3);
-            all.AddRange(_connections);
-            all.Add(_timeoutTask);
-            all.Add(_listenTask);
-            all.Add(_gcTask);
-
-            try
-            {
-                var waitArray = all.Where(x => x != null).ToArray();
-                Task.WaitAny(waitArray, cancellationToken);
-            }
-            catch (OperationCanceledException)
-            {
-                // Thrown when the provided cancellationToken is cancelled.  This is handled in the caller,
-                // here it just serves to break out of the WaitAny call.
-            }
-        }
-
-        private void Listen()
-        {
-            Debug.Assert(_listenTask == null);
-            Debug.Assert(_timeoutTask == null);
-
-            _listenCancellationTokenSource = new CancellationTokenSource();
-            _listenTask = _connectionHost.WaitForConnectionAsync(_listenCancellationTokenSource.Token);
-            _eventBus.ConnectionListening();
-        }
-
-        private void CloseListenTask()
-        {
-            Debug.Assert(_listenTask != null);
-
-            _listenCancellationTokenSource.Cancel();
-            _listenCancellationTokenSource = null;
-            _listenTask = null;
-        }
-
-        private void HandleCompletedListenTask(CancellationToken cancellationToken)
-        {
-            _eventBus.ConnectionReceived();
-
-            // Don't accept any new connections once we're in shutdown mode, instead gracefully reject the request.
-            // This should cause the client to run in process.
-            var accept = _state == State.Running;
-            var connectionTask = AcceptConnection(_listenTask, accept, cancellationToken);
-            _connections.Add(connectionTask);
-
-            // Timeout and GC are only done when there are no active connections.  Now that we have a new
-            // connection cancel out these tasks.
-            _timeoutTask = null;
-            _gcTask = null;
-
-            // Begin listening again for new connections.
-            _listenTask = null;
-            Listen();
-        }
-
-        private void HandleCompletedTimeoutTask()
-        {
-            _eventBus.KeepAliveReached();
-            _listenCancellationTokenSource.Cancel();
-            _timeoutTask = null;
-            _state = State.ShuttingDown;
-        }
-
-        private void HandleCompletedGCTask()
-        {
-            _gcTask = null;
-            for (var i = 0; i < 10; i++)
-            {
-                GC.Collect();
-                GC.WaitForPendingFinalizers();
-            }
-
-            GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
-            GC.Collect();
-        }
-
-        private void MaybeCreateTimeoutTask()
-        {
-            // If there are no active clients running then the server needs to be in a timeout mode.
-            if (_connections.Count == 0 && _timeoutTask == null)
-            {
-                Debug.Assert(_listenTask != null);
-                _timeoutTask = Task.Delay(_keepAlive.TimeSpan);
-            }
-        }
-
-        private void MaybeCreateGCTask()
-        {
-            if (_connections.Count == 0 && _gcTask == null)
-            {
-                _gcTask = Task.Delay(GCTimeout);
-            }
-        }
-
-        /// <summary>
-        /// Checks the completed connection objects.
-        /// </summary>
-        /// <returns>False if the server needs to begin shutting down</returns>
-        private void HandleCompletedConnections()
-        {
-            var shutdown = false;
-            var processedCount = 0;
-            var i = 0;
-            while (i < _connections.Count)
-            {
-                var current = _connections[i];
-                if (!current.IsCompleted)
-                {
-                    i++;
-                    continue;
-                }
-
-                _connections.RemoveAt(i);
-                processedCount++;
-
-                var result = current.Result;
-                if (result.KeepAlive.HasValue)
-                {
-                    var updated = _keepAlive.Update(result.KeepAlive.Value);
-                    if (updated.Equals(_keepAlive))
-                    {
-                        _eventBus.UpdateKeepAlive(updated.TimeSpan);
-                    }
-                }
-
-                switch (result.CloseReason)
-                {
-                    case ConnectionResult.Reason.CompilationCompleted:
-                    case ConnectionResult.Reason.CompilationNotStarted:
-                        // These are all normal end states.  Nothing to do here.
-                        break;
-
-                    case ConnectionResult.Reason.ClientDisconnect:
-                        // Have to assume the worst here which is user pressing Ctrl+C at the command line and
-                        // hence wanting all compilation to end.
-                        _eventBus.ConnectionRudelyEnded();
-                        shutdown = true;
-                        break;
-
-                    case ConnectionResult.Reason.ClientException:
-                    case ConnectionResult.Reason.ClientShutdownRequest:
-                        _eventBus.ConnectionRudelyEnded();
-                        shutdown = true;
-                        break;
-
-                    default:
-                        throw new InvalidOperationException($"Unexpected enum value {result.CloseReason}");
-                }
-            }
-
-            if (processedCount > 0)
-            {
-                _eventBus.ConnectionCompleted(processedCount);
-            }
-
-            if (shutdown)
-            {
-                _state = State.ShuttingDown;
-            }
-        }
-
-        internal async Task<ConnectionResult> AcceptConnection(Task<Connection> task, bool accept, CancellationToken cancellationToken)
-        {
-            Connection connection;
-            try
-            {
-                connection = await task;
-            }
-            catch (Exception ex)
-            {
-                // Unable to establish a connection with the client.  The client is responsible for
-                // handling this case. Nothing else for us to do here.
-                ServerLogger.LogException(ex, "Error creating client named pipe");
-                return new ConnectionResult(ConnectionResult.Reason.CompilationNotStarted);
-            }
-
-            try
-            {
-                using (connection)
-                {
-                    ServerRequest request;
-                    try
-                    {
-                        ServerLogger.Log("Begin reading request.");
-                        request = await ServerRequest.ReadAsync(connection.Stream, cancellationToken).ConfigureAwait(false);
-                        ServerLogger.Log("End reading request.");
-                    }
-                    catch (Exception e)
-                    {
-                        ServerLogger.LogException(e, "Error reading build request.");
-                        return new ConnectionResult(ConnectionResult.Reason.CompilationNotStarted);
-                    }
-
-                    if (request.IsShutdownRequest())
-                    {
-                        // Reply with the PID of this process so that the client can wait for it to exit.
-                        var response = new ShutdownServerResponse(Process.GetCurrentProcess().Id);
-                        await response.WriteAsync(connection.Stream, cancellationToken);
-
-                        // We can safely disconnect the client, then when this connection gets cleaned up by the event loop
-                        // the server will go to a shutdown state.
-                        return new ConnectionResult(ConnectionResult.Reason.ClientShutdownRequest);
-                    }
-                    else if (!accept)
-                    {
-                        // We're already in shutdown mode, respond gracefully so the client can run in-process.
-                        var response = new RejectedServerResponse();
-                        await response.WriteAsync(connection.Stream, cancellationToken).ConfigureAwait(false);
-
-                        return new ConnectionResult(ConnectionResult.Reason.CompilationNotStarted);
-                    }
-                    else
-                    {
-                        // If we get here then this is a real request that we will accept and process.
-                        //
-                        // Kick off both the compilation and a task to monitor the pipe for closing.
-                        var buildCancelled = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
-
-                        var watcher = connection.WaitForDisconnectAsync(buildCancelled.Token);
-                        var worker = ExecuteRequestAsync(request, buildCancelled.Token);
-
-                        // await will end when either the work is complete or the connection is closed.
-                        await Task.WhenAny(worker, watcher);
-
-                        // Do an 'await' on the completed task, preference being compilation, to force
-                        // any exceptions to be realized in this method for logging.
-                        ConnectionResult.Reason reason;
-                        if (worker.IsCompleted)
-                        {
-                            var response = await worker;
-
-                            try
-                            {
-                                ServerLogger.Log("Begin writing response.");
-                                await response.WriteAsync(connection.Stream, cancellationToken);
-                                ServerLogger.Log("End writing response.");
-
-                                reason = ConnectionResult.Reason.CompilationCompleted;
-
-                                _eventBus.CompilationCompleted();
-                            }
-                            catch
-                            {
-                                reason = ConnectionResult.Reason.ClientDisconnect;
-                            }
-                        }
-                        else
-                        {
-                            await watcher;
-                            reason = ConnectionResult.Reason.ClientDisconnect;
-                        }
-
-                        // Begin the tear down of the Task which didn't complete.
-                        buildCancelled.Cancel();
-
-                        return new ConnectionResult(reason, request.KeepAlive);
-                    }
-                }
-            }
-            catch (Exception ex)
-            {
-                ServerLogger.LogException(ex, "Error handling connection");
-                return new ConnectionResult(ConnectionResult.Reason.ClientException);
-            }
-        }
-
-        private Task<ServerResponse> ExecuteRequestAsync(ServerRequest buildRequest, CancellationToken cancellationToken)
-        {
-            Func<ServerResponse> func = () =>
-            {
-                ServerLogger.Log("Begin processing request");
-
-                var response = _compilerHost.Execute(buildRequest, cancellationToken);
-
-                ServerLogger.Log("End processing request");
-                return response;
-            };
-
-            var task = new Task<ServerResponse>(func, cancellationToken, TaskCreationOptions.LongRunning);
-            task.Start();
-            return task;
-        }
-
-        private enum State
-        {
-            /// <summary>
-            /// Server running and accepting all requests
-            /// </summary>
-            Running,
-
-            /// <summary>
-            /// Server processing existing requests, responding to shutdown commands but is not accepting
-            /// new build requests.
-            /// </summary>
-            ShuttingDown,
-
-            /// <summary>
-            /// Server is done.
-            /// </summary>
-            Completed,
-        }
-
-        private struct KeepAlive
-        {
-            public TimeSpan TimeSpan;
-            public bool IsDefault;
-
-            public KeepAlive(TimeSpan timeSpan, bool isDefault)
-            {
-                TimeSpan = timeSpan;
-                IsDefault = isDefault;
-            }
-
-            public KeepAlive Update(TimeSpan timeSpan)
-            {
-                if (IsDefault || timeSpan > TimeSpan)
-                {
-                    return new KeepAlive(timeSpan, isDefault: false);
-                }
-
-                return this;
-            }
-        }
-    }
-}

+ 0 - 225
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/DiscoverCommand.cs

@@ -1,225 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Security.Cryptography;
-using System.Text;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Razor.Language;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Razor;
-using Microsoft.CodeAnalysis.Razor.Serialization;
-using Microsoft.Extensions.CommandLineUtils;
-using Newtonsoft.Json;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal class DiscoverCommand : CommandBase
-    {
-        public DiscoverCommand(Application parent)
-            : base(parent, "discover")
-        {
-            Assemblies = Argument("assemblies", "assemblies to search for tag helpers", multipleValues: true);
-            TagHelperManifest = Option("-o", "output file", CommandOptionType.SingleValue);
-            ProjectDirectory = Option("-p", "project root directory", CommandOptionType.SingleValue);
-            Version = Option("-v|--version", "Razor language version", CommandOptionType.SingleValue);
-            Configuration = Option("-c", "Razor configuration name", CommandOptionType.SingleValue);
-            ExtensionNames = Option("-n", "extension name", CommandOptionType.MultipleValue);
-            ExtensionFilePaths = Option("-e", "extension file path", CommandOptionType.MultipleValue);
-        }
-
-        public CommandArgument Assemblies { get; }
-
-        public CommandOption TagHelperManifest { get; }
-
-        public CommandOption ProjectDirectory { get; }
-
-        public CommandOption Version { get; }
-
-        public CommandOption Configuration { get; }
-
-        public CommandOption ExtensionNames { get; }
-
-        public CommandOption ExtensionFilePaths { get; }
-
-        protected override bool ValidateArguments()
-        {
-            if (string.IsNullOrEmpty(TagHelperManifest.Value()))
-            {
-                Error.WriteLine($"{TagHelperManifest.Description} must be specified.");
-                return false;
-            }
-
-            if (Assemblies.Values.Count == 0)
-            {
-                Error.WriteLine($"{Assemblies.Name} must have at least one value.");
-                return false;
-            }
-
-            if (string.IsNullOrEmpty(ProjectDirectory.Value()))
-            {
-                ProjectDirectory.Values.Add(Environment.CurrentDirectory);
-            }
-
-            if (string.IsNullOrEmpty(Version.Value()))
-            {
-                Error.WriteLine($"{Version.Description} must be specified.");
-                return false;
-            }
-            else if (!RazorLanguageVersion.TryParse(Version.Value(), out _))
-            {
-                Error.WriteLine($"Invalid option {Version.Value()} for Razor language version --version; must be Latest or a valid version in range {RazorLanguageVersion.Version_1_0} to {RazorLanguageVersion.Latest}.");
-                return false;
-            }
-
-            if (string.IsNullOrEmpty(Configuration.Value()))
-            {
-                Error.WriteLine($"{Configuration.Description} must be specified.");
-                return false;
-            }
-
-            if (ExtensionNames.Values.Count != ExtensionFilePaths.Values.Count)
-            {
-                Error.WriteLine($"{ExtensionNames.Description} and {ExtensionFilePaths.Description} should have the same number of values.");
-            }
-
-            foreach (var filePath in ExtensionFilePaths.Values)
-            {
-                if (!Path.IsPathRooted(filePath))
-                {
-                    Error.WriteLine($"Extension file paths must be fully-qualified, absolute paths.");
-                    return false;
-                }
-            }
-
-            return true;
-        }
-
-        protected override Task<int> ExecuteCoreAsync()
-        {
-            if (!Parent.Checker.Check(ExtensionFilePaths.Values))
-            {
-                Error.WriteLine($"Extenions could not be loaded. See output for details.");
-                return Task.FromResult(ExitCodeFailure);
-            }
-
-            // Loading all of the extensions should succeed as the dependency checker will have already
-            // loaded them.
-            var extensions = new RazorExtension[ExtensionNames.Values.Count];
-            for (var i = 0; i < ExtensionNames.Values.Count; i++)
-            {
-                extensions[i] = new AssemblyExtension(ExtensionNames.Values[i], Parent.Loader.LoadFromPath(ExtensionFilePaths.Values[i]));
-            }
-
-            var version = RazorLanguageVersion.Parse(Version.Value());
-            var configuration = RazorConfiguration.Create(version, Configuration.Value(), extensions);
-
-            var result = ExecuteCore(
-                configuration: configuration,
-                projectDirectory: ProjectDirectory.Value(),
-                outputFilePath: TagHelperManifest.Value(),
-                assemblies: Assemblies.Values.ToArray());
-
-            return Task.FromResult(result);
-        }
-
-        private int ExecuteCore(RazorConfiguration configuration, string projectDirectory, string outputFilePath, string[] assemblies)
-        {
-            outputFilePath = Path.Combine(projectDirectory, outputFilePath);
-
-            var metadataReferences = new MetadataReference[assemblies.Length];
-            for (var i = 0; i < assemblies.Length; i++)
-            {
-                metadataReferences[i] = Parent.AssemblyReferenceProvider(assemblies[i], default(MetadataReferenceProperties));
-            }
-
-            var engine = RazorProjectEngine.Create(configuration, RazorProjectFileSystem.Empty, b =>
-            {
-                b.Features.Add(new DefaultMetadataReferenceFeature() { References = metadataReferences });
-                b.Features.Add(new CompilationTagHelperFeature());
-                b.Features.Add(new DefaultTagHelperDescriptorProvider());
-
-                CompilerFeatures.Register(b);
-            });
-
-            var feature = engine.Engine.Features.OfType<ITagHelperFeature>().Single();
-            var tagHelpers = feature.GetDescriptors();
-
-            using (var stream = new MemoryStream())
-            {
-                Serialize(stream, tagHelpers);
-
-                stream.Position = 0;
-
-                var newHash = Hash(stream);
-                var existingHash = Hash(outputFilePath);
-
-                if (!HashesEqual(newHash, existingHash))
-                {
-                    stream.Position = 0;
-                    using (var output = File.Open(outputFilePath, FileMode.Create))
-                    {
-                        stream.CopyTo(output);
-                    }
-                }
-            }
-
-            return ExitCodeSuccess;
-        }
-
-        private static byte[] Hash(string path)
-        {
-            if (!File.Exists(path))
-            {
-                return Array.Empty<byte>();
-            }
-
-            using (var stream = File.OpenRead(path))
-            {
-                return Hash(stream);
-            }
-        }
-
-        private static byte[] Hash(Stream stream)
-        {
-            using (var sha = SHA256.Create())
-            {
-                sha.ComputeHash(stream);
-                return sha.Hash;
-            }
-        }
-
-        private bool HashesEqual(byte[] x, byte[] y)
-        {
-            if (x.Length != y.Length)
-            {
-                return false;
-            }
-
-            for (var i = 0; i < x.Length; i++)
-            {
-                if (x[i] != y[i])
-                {
-                    return false;
-                }
-            }
-
-            return true;
-        }
-
-        private static void Serialize(Stream stream, IReadOnlyList<TagHelperDescriptor> tagHelpers)
-        {
-            using (var writer = new StreamWriter(stream, Encoding.UTF8, bufferSize: 4096, leaveOpen: true))
-            {
-                var serializer = new JsonSerializer();
-                serializer.Converters.Add(new TagHelperDescriptorJsonConverter());
-                serializer.Converters.Add(new RazorDiagnosticJsonConverter());
-
-                serializer.Serialize(writer, tagHelpers);
-            }
-        }
-    }
-}

+ 0 - 68
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/EventBus.cs

@@ -1,68 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal abstract class EventBus
-    {
-        public static readonly EventBus Default = new DefaultEventBus();
-
-        /// <summary>
-        /// Called when the server updates the keep alive value.
-        /// </summary>
-        public virtual void UpdateKeepAlive(TimeSpan timeSpan)
-        {
-        }
-
-        /// <summary>
-        /// Called each time the server listens for new connections.
-        /// </summary>
-        public virtual void ConnectionListening()
-        {
-        }
-
-        /// <summary>
-        /// Called when a connection to the server occurs.
-        /// </summary>
-        public virtual void ConnectionReceived()
-        {
-        }
-
-        /// <summary>
-        /// Called when one or more connections have completed processing.  The number of connections
-        /// processed is provided in <paramref name="count"/>.
-        /// </summary>
-        public virtual void ConnectionCompleted(int count)
-        {
-        }
-        
-        /// <summary>
-        /// Called when a compilation is completed successfully and the response is written to the stream.
-        /// </summary>
-        public virtual void CompilationCompleted()
-        {
-        }
-
-        /// <summary>
-        /// Called when a bad client connection was detected and the server will be shutting down as a 
-        /// result.
-        /// </summary>
-        public virtual void ConnectionRudelyEnded()
-        {
-        }
-
-        /// <summary>
-        /// Called when the server is shutting down because the keep alive timeout was reached.
-        /// </summary>
-        public virtual void KeepAliveReached()
-        {
-        }
-
-        private class DefaultEventBus : EventBus
-        {
-
-        }
-    }
-}

+ 0 - 16
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ExtensionAssemblyLoader.cs

@@ -1,16 +0,0 @@
-// Copyright(c) .NET Foundation.All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Reflection;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal abstract class ExtensionAssemblyLoader
-    {
-        public abstract void AddAssemblyLocation(string filePath);
-
-        public abstract Assembly Load(string assemblyName);
-
-        public abstract Assembly LoadFromPath(string filePath);
-    }
-}

+ 0 - 12
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ExtensionDependencyChecker.cs

@@ -1,12 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal abstract class ExtensionDependencyChecker
-    {
-        public abstract bool Check(IEnumerable<string> extensionFilePaths);
-    }
-}

+ 0 - 425
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/GenerateCommand.cs

@@ -1,425 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Razor.Language;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.Razor;
-using Microsoft.CodeAnalysis.Razor.Serialization;
-using Microsoft.Extensions.CommandLineUtils;
-using Newtonsoft.Json;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal class GenerateCommand : CommandBase
-    {
-        public GenerateCommand(Application parent)
-            : base(parent, "generate")
-        {
-            Sources = Option("-s", ".cshtml files to compile", CommandOptionType.MultipleValue);
-            Outputs = Option("-o", "Generated output file path", CommandOptionType.MultipleValue);
-            RelativePaths = Option("-r", "Relative path", CommandOptionType.MultipleValue);
-            FileKinds = Option("-k", "File kind", CommandOptionType.MultipleValue);
-            CssScopeSources = Option("-cssscopedinput", ".razor file with scoped CSS", CommandOptionType.MultipleValue);
-            CssScopeValues = Option("-cssscopevalue", "CSS scope value for .razor file with scoped CSS", CommandOptionType.MultipleValue);
-            ProjectDirectory = Option("-p", "project root directory", CommandOptionType.SingleValue);
-            TagHelperManifest = Option("-t", "tag helper manifest file", CommandOptionType.SingleValue);
-            Version = Option("-v|--version", "Razor language version", CommandOptionType.SingleValue);
-            Configuration = Option("-c", "Razor configuration name", CommandOptionType.SingleValue);
-            ExtensionNames = Option("-n", "extension name", CommandOptionType.MultipleValue);
-            ExtensionFilePaths = Option("-e", "extension file path", CommandOptionType.MultipleValue);
-            RootNamespace = Option("--root-namespace", "root namespace for generated code", CommandOptionType.SingleValue);
-            CSharpLanguageVersion = Option("--csharp-language-version", "csharp language version generated code", CommandOptionType.SingleValue);
-            GenerateDeclaration = Option("--generate-declaration", "Generate declaration", CommandOptionType.NoValue);
-        }
-
-        public CommandOption Sources { get; }
-
-        public CommandOption Outputs { get; }
-
-        public CommandOption RelativePaths { get; }
-
-        public CommandOption FileKinds { get; }
-
-        public CommandOption CssScopeSources { get; }
-
-        public CommandOption CssScopeValues { get; }
-
-        public CommandOption ProjectDirectory { get; }
-
-        public CommandOption TagHelperManifest { get; }
-
-        public CommandOption Version { get; }
-
-        public CommandOption Configuration { get; }
-
-        public CommandOption ExtensionNames { get; }
-
-        public CommandOption ExtensionFilePaths { get; }
-
-        public CommandOption RootNamespace { get; }
-
-        public CommandOption CSharpLanguageVersion { get; }
-
-        public CommandOption GenerateDeclaration { get; }
-
-        protected override Task<int> ExecuteCoreAsync()
-        {
-            if (!Parent.Checker.Check(ExtensionFilePaths.Values))
-            {
-                Error.WriteLine($"Extensions could not be loaded. See output for details.");
-                return Task.FromResult(ExitCodeFailure);
-            }
-
-            // Loading all of the extensions should succeed as the dependency checker will have already
-            // loaded them.
-            var extensions = new RazorExtension[ExtensionNames.Values.Count];
-            for (var i = 0; i < ExtensionNames.Values.Count; i++)
-            {
-                extensions[i] = new AssemblyExtension(ExtensionNames.Values[i], Parent.Loader.LoadFromPath(ExtensionFilePaths.Values[i]));
-            }
-
-            var version = RazorLanguageVersion.Parse(Version.Value());
-            var configuration = RazorConfiguration.Create(version, Configuration.Value(), extensions);
-
-            var sourceItems = GetSourceItems(
-                Sources.Values, Outputs.Values, RelativePaths.Values,
-                FileKinds.Values, CssScopeSources.Values, CssScopeValues.Values);
-
-            var result = ExecuteCore(
-                configuration: configuration,
-                projectDirectory: ProjectDirectory.Value(),
-                tagHelperManifest: TagHelperManifest.Value(),
-                sourceItems: sourceItems);
-
-            return Task.FromResult(result);
-        }
-
-        protected override bool ValidateArguments()
-        {
-            if (Sources.Values.Count == 0)
-            {
-                Error.WriteLine($"{Sources.Description} should have at least one value.");
-                return false;
-            }
-
-            if (Outputs.Values.Count != Sources.Values.Count)
-            {
-                Error.WriteLine($"{Sources.Description} has {Sources.Values.Count}, but {Outputs.Description} has {Outputs.Values.Count} values.");
-                return false;
-            }
-
-            if (RelativePaths.Values.Count != Sources.Values.Count)
-            {
-                Error.WriteLine($"{Sources.Description} has {Sources.Values.Count}, but {RelativePaths.Description} has {RelativePaths.Values.Count} values.");
-                return false;
-            }
-
-            if (FileKinds.Values.Count != 0 && FileKinds.Values.Count != Sources.Values.Count)
-            {
-                // 2.x tasks do not specify FileKinds - in which case, no values will be present. If a kind for one file is specified, we expect as many kind entries
-                // as sources.
-                Error.WriteLine($"{Sources.Description} has {Sources.Values.Count}, but {FileKinds.Description} has {FileKinds.Values.Count} values.");
-                return false;
-            }
-
-            if (CssScopeSources.Values.Count != CssScopeValues.Values.Count)
-            {
-                // CssScopeSources and CssScopeValues arguments must appear as matched pairs
-                Error.WriteLine($"{CssScopeSources.Description} has {CssScopeSources.Values.Count}, but {CssScopeValues.Description} has {CssScopeValues.Values.Count} values.");
-                return false;
-            }
-
-            if (string.IsNullOrEmpty(ProjectDirectory.Value()))
-            {
-                ProjectDirectory.Values.Add(Environment.CurrentDirectory);
-            }
-
-            if (string.IsNullOrEmpty(Version.Value()))
-            {
-                Error.WriteLine($"{Version.Description} must be specified.");
-                return false;
-            }
-            else if (!RazorLanguageVersion.TryParse(Version.Value(), out _))
-            {
-                Error.WriteLine($"Invalid option {Version.Value()} for Razor language version --version; must be Latest or a valid version in range {RazorLanguageVersion.Version_1_0} to {RazorLanguageVersion.Latest}.");
-                return false;
-            }
-
-            if (string.IsNullOrEmpty(Configuration.Value()))
-            {
-                Error.WriteLine($"{Configuration.Description} must be specified.");
-                return false;
-            }
-
-            if (ExtensionNames.Values.Count != ExtensionFilePaths.Values.Count)
-            {
-                Error.WriteLine($"{ExtensionNames.Description} and {ExtensionFilePaths.Description} should have the same number of values.");
-            }
-
-            foreach (var filePath in ExtensionFilePaths.Values)
-            {
-                if (!Path.IsPathRooted(filePath))
-                {
-                    Error.WriteLine($"Extension file paths must be fully-qualified, absolute paths.");
-                    return false;
-                }
-            }
-
-            return true;
-        }
-
-        private int ExecuteCore(
-            RazorConfiguration configuration,
-            string projectDirectory,
-            string tagHelperManifest,
-            SourceItem[] sourceItems)
-        {
-            tagHelperManifest = Path.Combine(projectDirectory, tagHelperManifest);
-
-            var tagHelpers = GetTagHelpers(tagHelperManifest);
-
-            var compositeFileSystem = new CompositeRazorProjectFileSystem(new[]
-            {
-                GetVirtualRazorProjectSystem(sourceItems),
-                RazorProjectFileSystem.Create(projectDirectory),
-            });
-
-            var success = true;
-
-            var engine = RazorProjectEngine.Create(configuration, compositeFileSystem, b =>
-            {
-                b.Features.Add(new StaticTagHelperFeature() { TagHelpers = tagHelpers, });
-                b.Features.Add(new DefaultTypeNameFeature());
-
-                if (GenerateDeclaration.HasValue())
-                {
-                    b.Features.Add(new SetSuppressPrimaryMethodBodyOptionFeature());
-                    b.Features.Add(new SuppressChecksumOptionsFeature());
-                }
-
-                if (RootNamespace.HasValue())
-                {
-                    b.SetRootNamespace(RootNamespace.Value());
-                }
-
-                if (CSharpLanguageVersion.HasValue())
-                {
-                    // Only set the C# language version if one was specified, otherwise it defaults to whatever
-                    // value was set in the corresponding RazorConfiguration's extensions.
-
-                    var rawLanguageVersion = CSharpLanguageVersion.Value();
-                    if (LanguageVersionFacts.TryParse(rawLanguageVersion, out var csharpLanguageVersion))
-                    {
-                        b.SetCSharpLanguageVersion(csharpLanguageVersion);
-                    }
-                    else
-                    {
-                        success = false;
-                        Error.WriteLine($"Unknown C# language version {rawLanguageVersion}.");
-                    }
-                }
-            });
-
-            var results = GenerateCode(engine, sourceItems);
-            var isGeneratingDeclaration = GenerateDeclaration.HasValue();
-
-            foreach (var result in results)
-            {
-                var errorCount = result.CSharpDocument.Diagnostics.Count;
-                for (var i = 0; i < errorCount; i++)
-                {
-                    var error = result.CSharpDocument.Diagnostics[i];
-                    if (error.Severity == RazorDiagnosticSeverity.Error)
-                    {
-                        success = false;
-                    }
-
-                    if (i < 100)
-                    {
-                        Error.WriteLine(error.ToString());
-
-                        // Only show the first 100 errors to prevent massive string allocations.
-                        if (i == 99)
-                        {
-                            Error.WriteLine($"And {errorCount - i + 1} more warnings/errors.");
-                        }
-                    }
-                }
-
-                if (success)
-                {
-                    // Only output the file if we generated it without errors.
-                    var outputFilePath = result.InputItem.OutputPath;
-                    var generatedCode = result.CSharpDocument.GeneratedCode;
-                    if (isGeneratingDeclaration)
-                    {
-                        // When emiting declarations, only write if it the contents are different.
-                        // This allows build incrementalism to kick in when the declaration remains unchanged between builds.
-                        if (File.Exists(outputFilePath) &&
-                            string.Equals(File.ReadAllText(outputFilePath), generatedCode, StringComparison.Ordinal))
-                        {
-                            continue;
-                        }
-                    }
-
-                    File.WriteAllText(outputFilePath, result.CSharpDocument.GeneratedCode);
-                }
-            }
-
-            return success ? ExitCodeSuccess : ExitCodeFailureRazorError;
-        }
-
-        private VirtualRazorProjectFileSystem GetVirtualRazorProjectSystem(SourceItem[] inputItems)
-        {
-            var project = new VirtualRazorProjectFileSystem();
-            foreach (var item in inputItems)
-            {
-                var projectItem = new DefaultRazorProjectItem(
-                    basePath: "/",
-                    filePath: item.FilePath,
-                    relativePhysicalPath: item.RelativePhysicalPath,
-                    fileKind: item.FileKind,
-                    file: new FileInfo(item.SourcePath),
-                    cssScope: item.CssScope);
-
-                project.Add(projectItem);
-            }
-
-            return project;
-        }
-
-        private IReadOnlyList<TagHelperDescriptor> GetTagHelpers(string tagHelperManifest)
-        {
-            if (!File.Exists(tagHelperManifest))
-            {
-                return Array.Empty<TagHelperDescriptor>();
-            }
-
-            using (var stream = File.OpenRead(tagHelperManifest))
-            {
-                var reader = new JsonTextReader(new StreamReader(stream));
-
-                var serializer = new JsonSerializer();
-                serializer.Converters.Add(new RazorDiagnosticJsonConverter());
-                serializer.Converters.Add(new TagHelperDescriptorJsonConverter());
-
-                var descriptors = serializer.Deserialize<IReadOnlyList<TagHelperDescriptor>>(reader);
-                return descriptors;
-            }
-        }
-
-        private static SourceItem[] GetSourceItems(List<string> sources, List<string> outputs, List<string> relativePath, List<string> fileKinds, List<string> cssScopeSources, List<string> cssScopeValues)
-        {
-            var cssScopeAssociations = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
-            for (var cssScopeSourceIndex = 0; cssScopeSourceIndex < cssScopeSources.Count; cssScopeSourceIndex++)
-            {
-                cssScopeAssociations.Add(cssScopeSources[cssScopeSourceIndex], cssScopeSourceIndex);
-            }
-
-            var items = new SourceItem[sources.Count];
-            for (var i = 0; i < items.Length; i++)
-            {
-                var fileKind = fileKinds.Count > 0 ? fileKinds[i] : "mvc";
-                if (Language.FileKinds.IsComponent(fileKind))
-                {
-                    fileKind = Language.FileKinds.GetComponentFileKindFromFilePath(sources[i]);
-                }
-
-                var cssScopeValue = cssScopeAssociations.TryGetValue(sources[i], out var cssScopeIndex)
-                    ? cssScopeValues[cssScopeIndex]
-                    : null;
-
-                items[i] = new SourceItem(sources[i], outputs[i], relativePath[i], fileKind, cssScopeValue);
-            }
-
-            return items;
-        }
-
-        private OutputItem[] GenerateCode(RazorProjectEngine engine, SourceItem[] inputs)
-        {
-            var outputs = new OutputItem[inputs.Length];
-            Parallel.For(0, outputs.Length, new ParallelOptions() { MaxDegreeOfParallelism = Debugger.IsAttached ? 1 : 4 }, i =>
-            {
-                var inputItem = inputs[i];
-
-                var codeDocument = engine.Process(engine.FileSystem.GetItem(inputItem.FilePath, inputItem.FileKind));
-                var csharpDocument = codeDocument.GetCSharpDocument();
-                outputs[i] = new OutputItem(inputItem, csharpDocument);
-            });
-
-            return outputs;
-        }
-
-        private struct OutputItem
-        {
-            public OutputItem(
-                SourceItem inputItem,
-                RazorCSharpDocument cSharpDocument)
-            {
-                InputItem = inputItem;
-                CSharpDocument = cSharpDocument;
-            }
-
-            public SourceItem InputItem { get; }
-
-            public RazorCSharpDocument CSharpDocument { get; }
-        }
-
-        private readonly struct SourceItem
-        {
-            public SourceItem(string sourcePath, string outputPath, string physicalRelativePath, string fileKind, string cssScope)
-            {
-                SourcePath = sourcePath;
-                OutputPath = outputPath;
-                RelativePhysicalPath = physicalRelativePath;
-                FilePath = '/' + physicalRelativePath
-                    .Replace(Path.DirectorySeparatorChar, '/')
-                    .Replace("//", "/");
-                FileKind = fileKind;
-                CssScope = cssScope;
-            }
-
-            public string SourcePath { get; }
-
-            public string OutputPath { get; }
-
-            public string RelativePhysicalPath { get; }
-
-            public string FilePath { get; }
-
-            public string FileKind { get; }
-
-            public string CssScope { get; }
-        }
-
-        private class StaticTagHelperFeature : ITagHelperFeature
-        {
-            public RazorEngine Engine { get; set; }
-
-            public IReadOnlyList<TagHelperDescriptor> TagHelpers { get; set; }
-
-            public IReadOnlyList<TagHelperDescriptor> GetDescriptors() => TagHelpers;
-        }
-
-        private class SetSuppressPrimaryMethodBodyOptionFeature : RazorEngineFeatureBase, IConfigureRazorCodeGenerationOptionsFeature
-        {
-            public int Order { get; set; }
-
-            public void Configure(RazorCodeGenerationOptionsBuilder options)
-            {
-                if (options == null)
-                {
-                    throw new ArgumentNullException(nameof(options));
-                }
-
-                options.SuppressPrimaryMethodBody = true;
-            }
-        }
-    }
-}

+ 0 - 13
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/Memory.cs

@@ -1,13 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal static class Memory
-    {
-        public static bool IsMemoryAvailable()
-        {
-            return true;
-        }
-    }
-}

+ 0 - 86
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/MetadataCache.cs

@@ -1,86 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Diagnostics;
-using System.IO;
-using System.Reflection.PortableExecutable;
-using Microsoft.CodeAnalysis;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal class MetadataCache
-    {
-        // Store 1000 entries -- arbitrary number
-        private const int CacheSize = 1000;
-        private readonly ConcurrentLruCache<string, MetadataCacheEntry> _metadataCache =
-            new ConcurrentLruCache<string, MetadataCacheEntry>(CacheSize, StringComparer.OrdinalIgnoreCase);
-
-        // For testing purposes only.
-        internal ConcurrentLruCache<string, MetadataCacheEntry> Cache => _metadataCache;
-
-        internal Metadata GetMetadata(string fullPath)
-        {
-            var timestamp = GetFileTimeStamp(fullPath);
-
-            // Check if we have an entry in the dictionary.
-            if (_metadataCache.TryGetValue(fullPath, out var entry))
-            {
-                if (timestamp.HasValue && timestamp.Value == entry.Timestamp)
-                {
-                    // The file has not changed since we cached it. Return the cached entry.
-                    return entry.Metadata;
-                }
-                else
-                {
-                    // The file has changed recently. Remove the cache entry.
-                    _metadataCache.Remove(fullPath);
-                }
-            }
-
-            Metadata metadata;
-            using (var fileStream = File.OpenRead(fullPath))
-            {
-                metadata = AssemblyMetadata.CreateFromStream(fileStream, PEStreamOptions.PrefetchMetadata);
-            }
-
-            _metadataCache.GetOrAdd(fullPath, new MetadataCacheEntry(timestamp.Value, metadata));
-
-            return metadata;
-        }
-
-        private static DateTime? GetFileTimeStamp(string fullPath)
-        {
-            try
-            {
-                Debug.Assert(Path.IsPathRooted(fullPath));
-
-                return File.GetLastWriteTimeUtc(fullPath);
-            }
-            catch (Exception e)
-            {
-                // There are several exceptions that can occur here: NotSupportedException or PathTooLongException
-                // for a bad path, UnauthorizedAccessException for access denied, etc. Rather than listing them all,
-                // just catch all exceptions and log.
-                ServerLogger.LogException(e, $"Error getting timestamp of file {fullPath}.");
-
-                return null;
-            }
-        }
-
-        internal struct MetadataCacheEntry
-        {
-            public MetadataCacheEntry(DateTime timestamp, Metadata metadata)
-            {
-                Debug.Assert(timestamp.Kind == DateTimeKind.Utc);
-
-                Timestamp = timestamp;
-                Metadata = metadata;
-            }
-
-            public DateTime Timestamp { get; }
-
-            public Metadata Metadata { get; }
-        }
-    }
-}

+ 0 - 94
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/MetadataReaderExtensions.cs

@@ -1,94 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Reflection;
-using System.Reflection.Metadata;
-using Microsoft.CodeAnalysis;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal static class MetadataReaderExtensions
-    {
-        internal static AssemblyIdentity GetAssemblyIdentity(this MetadataReader reader)
-        {
-            if (!reader.IsAssembly)
-            {
-                throw new BadImageFormatException();
-            }
-
-            var definition = reader.GetAssemblyDefinition();
-
-            return CreateAssemblyIdentity(
-                reader,
-                definition.Version,
-                definition.Flags,
-                definition.PublicKey,
-                definition.Name,
-                definition.Culture,
-                isReference: false);
-        }
-        
-        internal static AssemblyIdentity[] GetReferencedAssembliesOrThrow(this MetadataReader reader)
-        {
-            var references = new List<AssemblyIdentity>(reader.AssemblyReferences.Count);
-
-            foreach (var referenceHandle in reader.AssemblyReferences)
-            {
-                var reference = reader.GetAssemblyReference(referenceHandle);
-                references.Add(CreateAssemblyIdentity(
-                    reader,
-                    reference.Version,
-                    reference.Flags,
-                    reference.PublicKeyOrToken,
-                    reference.Name,
-                    reference.Culture,
-                    isReference: true));
-            }
-
-            return references.ToArray();
-        }
-        
-        private static AssemblyIdentity CreateAssemblyIdentity(
-            MetadataReader reader,
-            Version version,
-            AssemblyFlags flags,
-            BlobHandle publicKey,
-            StringHandle name,
-            StringHandle culture,
-            bool isReference)
-        {
-            var publicKeyOrToken = reader.GetBlobContent(publicKey);
-            bool hasPublicKey;
-
-            if (isReference)
-            {
-                hasPublicKey = (flags & AssemblyFlags.PublicKey) != 0;
-            }
-            else
-            {
-                // Assembly definitions never contain a public key token, they only can have a full key or nothing,
-                // so the flag AssemblyFlags.PublicKey does not make sense for them and is ignored.
-                // See Ecma-335, Partition II Metadata, 22.2 "Assembly : 0x20".
-                // This also corresponds to the behavior of the native C# compiler and sn.exe tool.
-                hasPublicKey = !publicKeyOrToken.IsEmpty;
-            }
-
-            if (publicKeyOrToken.IsEmpty)
-            {
-                publicKeyOrToken = default;
-            }
-
-            return new AssemblyIdentity(
-                name: reader.GetString(name),
-                version: version,
-                cultureName: culture.IsNil ? null : reader.GetString(culture),
-                publicKeyOrToken: publicKeyOrToken,
-                hasPublicKey: hasPublicKey,
-                isRetargetable: (flags & AssemblyFlags.Retargetable) != 0,
-                contentType: (AssemblyContentType)((int)(flags & AssemblyFlags.ContentTypeMask) >> 9));
-        }
-    }
-}

+ 0 - 22
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/MutexName.cs

@@ -1,22 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal static class MutexName
-    {
-        public static string GetClientMutexName(string pipeName)
-        {
-            return $"{pipeName}.client";
-        }
-
-        public static string GetServerMutexName(string pipeName)
-        {
-            // We want to prefix this with Global\ because we want this mutex to be visible
-            // across terminal sessions which is useful for cases like shutdown.
-            // https://msdn.microsoft.com/en-us/library/system.threading.mutex(v=vs.110).aspx#Remarks
-            // This still wouldn't allow other users to access the server because the pipe will fail to connect.
-            return $"Global\\{pipeName}.server";
-        }
-    }
-}

+ 0 - 60
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/PipeName.cs

@@ -1,60 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-using System.Security.Cryptography;
-using System.Text;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal static class PipeName
-    {
-        // We want each pipe to unique and predictable based on the inputs of:
-        // - user (security)
-        // - path of tool on disk (version)
-        // 
-        // This allows us to meet the security and version compat requirements just by selecting a pipe name.
-        //
-        // This is similar to (and based on) the code used by Roslyn in VBCSCompiler:
-        // https://github.com/dotnet/roslyn/blob/c273b6a9f19570a344c274ae89185b3a2b64d93d/src/Compilers/Shared/BuildServerConnection.cs#L528
-        public static string ComputeDefault(string toolDirectory = null)
-        {
-            if (string.IsNullOrEmpty(toolDirectory))
-            {
-                // This can be null in cases where we don't have a way of knowing the tool assembly path like when someone manually
-                // invokes the cli tool without passing in a pipe name as argument.
-                toolDirectory = AppDomain.CurrentDomain.BaseDirectory;
-            }
-
-            // Include a prefix so we can't conflict with VBCSCompiler if we somehow end up in the same directory.
-            // That would be a pretty wacky bug to try and unravel.
-            var baseName = ComputeBaseName("Razor:" + toolDirectory);
-
-            // Prefix with username
-            var userName = Environment.UserName;
-            if (userName == null)
-            {
-                return null;
-            }
-
-            return $"{userName}.{baseName}";
-        }
-        
-        private static string ComputeBaseName(string baseDirectory)
-        {
-            // Normalize away trailing slashes. File APIs are not consistent about including it, so it's
-            // best to normalize and avoid ending up with two servers running accidentally.
-            baseDirectory = baseDirectory.TrimEnd(Path.DirectorySeparatorChar);
-
-            using (var sha = SHA256.Create())
-            {
-                var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(baseDirectory));
-                return Convert.ToBase64String(bytes)
-                    .Substring(0, 25) // We only have ~50 total characters on Mac, so strip that down
-                    .Replace("/", "_")
-                    .Replace("=", string.Empty);
-            }
-        }
-    }
-}

+ 0 - 53
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/Program.cs

@@ -1,53 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal static class Program
-    {
-        public static int Main(string[] args)
-        {
-            DebugMode.HandleDebugSwitch(ref args);
-
-            var cancel = new CancellationTokenSource();
-            Console.CancelKeyPress += (sender, e) => { cancel.Cancel(); };
-
-            var outputWriter = new StringWriter();
-            var errorWriter = new StringWriter();
-
-            // Prevent shadow copying.
-            var loader = new DefaultExtensionAssemblyLoader(baseDirectory: null);
-            var checker = new DefaultExtensionDependencyChecker(loader, outputWriter, errorWriter);
-
-            var application = new Application(
-                cancel.Token,
-                loader,
-                checker,
-                (path, properties) => MetadataReference.CreateFromFile(path, properties),
-                outputWriter,
-                errorWriter);
-
-            var result = application.Execute(args);
-
-            var output = outputWriter.ToString();
-            var error = errorWriter.ToString();
-
-            outputWriter.Dispose();
-            errorWriter.Dispose();
-
-            Console.Write(output);
-            Console.Error.Write(error);
-
-            // This will no-op if server logging is not enabled.
-            ServerLogger.Log(output);
-            ServerLogger.Log(error);
-
-            return result;
-        }
-    }
-}

+ 0 - 9
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/Properties/AssemblyInfo.cs

@@ -1,9 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Runtime.CompilerServices;
-
-[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Razor.Tools.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
-[assembly: InternalsVisibleTo("Microsoft.NET.Sdk.Razor.IntegrationTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
-[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
-

+ 0 - 29
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/RequestDispatcher.cs

@@ -1,29 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Threading;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal abstract class RequestDispatcher
-    {
-        /// <summary>
-        /// Default time the server will stay alive after the last request disconnects.
-        /// </summary>
-        public static readonly TimeSpan DefaultServerKeepAlive = TimeSpan.FromMinutes(10);
-
-        /// <summary>
-        /// Time to delay after the last connection before initiating a garbage collection
-        /// in the server.
-        /// </summary>
-        public static readonly TimeSpan GCTimeout = TimeSpan.FromSeconds(30);
-
-        public abstract void Run();
-
-        public static RequestDispatcher Create(ConnectionHost connectionHost, CompilerHost compilerHost, CancellationToken cancellationToken, EventBus eventBus, TimeSpan? keepAlive = null)
-        {
-            return new DefaultRequestDispatcher(connectionHost, compilerHost, cancellationToken, eventBus, keepAlive);
-        }
-    }
-}

+ 0 - 432
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/RewriteCssCommand.cs

@@ -1,432 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Razor.Language;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.Css.Parser.Parser;
-using Microsoft.Css.Parser.Tokens;
-using Microsoft.Css.Parser.TreeItems;
-using Microsoft.Css.Parser.TreeItems.AtDirectives;
-using Microsoft.Css.Parser.TreeItems.Selectors;
-using Microsoft.Extensions.CommandLineUtils;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal class RewriteCssCommand : CommandBase
-    {
-        private const string DeepCombinatorText = "::deep";
-        private readonly static TimeSpan _regexTimeout = TimeSpan.FromSeconds(1);
-        private readonly static Regex _deepCombinatorRegex = new Regex($@"^{DeepCombinatorText}\s*", RegexOptions.None, _regexTimeout);
-        private readonly static Regex _trailingCombinatorRegex = new Regex(@"\s+[\>\+\~]$", RegexOptions.None, _regexTimeout);
-
-        public RewriteCssCommand(Application parent)
-            : base(parent, "rewritecss")
-        {
-            Sources = Option("-s", "Files to rewrite", CommandOptionType.MultipleValue);
-            Outputs = Option("-o", "Output file paths", CommandOptionType.MultipleValue);
-            CssScopes = Option("-c", "CSS scope identifiers", CommandOptionType.MultipleValue);
-        }
-
-        public CommandOption Sources { get; }
-
-        public CommandOption Outputs { get; }
-
-        public CommandOption CssScopes { get; }
-
-        protected override bool ValidateArguments()
-        {
-            if (Sources.Values.Count != Outputs.Values.Count)
-            {
-                Error.WriteLine($"{Sources.Description} has {Sources.Values.Count}, but {Outputs.Description} has {Outputs.Values.Count} values.");
-                return false;
-            }
-
-            if (Sources.Values.Count != CssScopes.Values.Count)
-            {
-                Error.WriteLine($"{Sources.Description} has {Sources.Values.Count}, but {CssScopes.Description} has {CssScopes.Values.Count} values.");
-                return false;
-            }
-
-            return true;
-        }
-
-        protected override Task<int> ExecuteCoreAsync()
-        {
-            var allDiagnostics = new ConcurrentQueue<RazorDiagnostic>();
-
-            Parallel.For(0, Sources.Values.Count, i =>
-            {
-                var source = Sources.Values[i];
-                var output = Outputs.Values[i];
-                var cssScope = CssScopes.Values[i];
-
-                using var inputSourceStream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
-                var inputSourceText = SourceText.From(inputSourceStream);
-
-                var rewrittenCss = AddScopeToSelectors(source, inputSourceText, cssScope, out var diagnostics);
-                if (diagnostics.Any())
-                {
-                    foreach (var diagnostic in diagnostics)
-                    {
-                        allDiagnostics.Enqueue(diagnostic);
-                    }
-                }
-                else
-                {
-                    File.WriteAllText(output, rewrittenCss);
-                }
-            });
-
-            foreach (var diagnostic in allDiagnostics)
-            {
-                Error.WriteLine(diagnostic.ToString());
-            }
-
-            return Task.FromResult(allDiagnostics.Any() ? ExitCodeFailure : ExitCodeSuccess);
-        }
-
-        // Public for tests
-        public static string AddScopeToSelectors(string filePath, string inputSource, string cssScope, out IEnumerable<RazorDiagnostic> diagnostics)
-            => AddScopeToSelectors(filePath, SourceText.From(inputSource), cssScope, out diagnostics);
-
-        private static string AddScopeToSelectors(string filePath, SourceText inputSourceText, string cssScope, out IEnumerable<RazorDiagnostic> diagnostics)
-        {
-            var cssParser = new DefaultParserFactory().CreateParser();
-            var inputText = inputSourceText.ToString();
-            var stylesheet = cssParser.Parse(inputText, insertComments: false);
-
-            var resultBuilder = new StringBuilder();
-            var previousInsertionPosition = 0;
-            var foundDiagnostics = new List<RazorDiagnostic>();
-
-            var ensureNoImportsVisitor = new EnsureNoImports(filePath, inputSourceText, stylesheet, foundDiagnostics);
-            ensureNoImportsVisitor.Visit();
-
-            var scopeInsertionPositionsVisitor = new FindScopeInsertionEdits(stylesheet);
-            scopeInsertionPositionsVisitor.Visit();
-            foreach (var edit in scopeInsertionPositionsVisitor.Edits)
-            {
-                resultBuilder.Append(inputText.Substring(previousInsertionPosition, edit.Position - previousInsertionPosition));
-                previousInsertionPosition = edit.Position;
-
-                switch (edit)
-                {
-                    case InsertSelectorScopeEdit _:
-                        resultBuilder.AppendFormat(CultureInfo.InvariantCulture, "[{0}]", cssScope);
-                        break;
-                    case InsertKeyframesNameScopeEdit _:
-                        resultBuilder.AppendFormat(CultureInfo.InvariantCulture, "-{0}", cssScope);
-                        break;
-                    case DeleteContentEdit deleteContentEdit:
-                        previousInsertionPosition += deleteContentEdit.DeleteLength;
-                        break;
-                    default:
-                        throw new NotImplementedException($"Unknown edit type: '{edit}'");
-                }
-            }
-
-            resultBuilder.Append(inputText.Substring(previousInsertionPosition));
-
-            diagnostics = foundDiagnostics;
-            return resultBuilder.ToString();
-        }
-
-        private static bool TryFindKeyframesIdentifier(AtDirective atDirective, out ParseItem identifier)
-        {
-            var keyword = atDirective.Keyword;
-            if (string.Equals(keyword?.Text, "keyframes", StringComparison.OrdinalIgnoreCase))
-            {
-                var nextSiblingText = keyword.NextSibling?.Text;
-                if (!string.IsNullOrEmpty(nextSiblingText))
-                {
-                    identifier = keyword.NextSibling;
-                    return true;
-                }
-            }
-
-            identifier = null;
-            return false;
-        }
-
-        private class FindScopeInsertionEdits : Visitor
-        {
-            public List<CssEdit> Edits { get; } = new List<CssEdit>();
-
-            private readonly HashSet<string> _keyframeIdentifiers;
-
-            public FindScopeInsertionEdits(ComplexItem root) : base(root)
-            {
-                // Before we start, we need to know the full set of keyframe names declared in this document
-                var keyframesIdentifiersVisitor = new FindKeyframesIdentifiersVisitor(root);
-                keyframesIdentifiersVisitor.Visit();
-                _keyframeIdentifiers = keyframesIdentifiersVisitor.KeyframesIdentifiers
-                    .Select(x => x.Text)
-                    .ToHashSet(StringComparer.Ordinal); // Keyframe names are case-sensitive
-            }
-
-            protected override void VisitSelector(Selector selector)
-            {
-                // For a ruleset like ".first child, .second { ... }", we'll see two selectors:
-                //   ".first child," containing two simple selectors: ".first" and "child"
-                //   ".second", containing one simple selector: ".second"
-                // Our goal is to insert immediately after the final simple selector within each selector
-
-                // If there's a deep combinator among the sequence of simple selectors, we consider that to signal
-                // the end of the set of simple selectors for us to look at, plus we strip it out
-                var allSimpleSelectors = selector.Children.OfType<SimpleSelector>();
-                var firstDeepCombinator = allSimpleSelectors.FirstOrDefault(s => _deepCombinatorRegex.IsMatch(s.Text));
-
-                var lastSimpleSelector = allSimpleSelectors.TakeWhile(s => s != firstDeepCombinator).LastOrDefault();
-                if (lastSimpleSelector != null)
-                {
-                    Edits.Add(new InsertSelectorScopeEdit { Position = FindPositionToInsertInSelector(lastSimpleSelector) });
-                }
-                else if (firstDeepCombinator != null)
-                {
-                    // For a leading deep combinator, we want to insert the scope attribute at the start
-                    // Otherwise the result would be a CSS rule that isn't scoped at all
-                    Edits.Add(new InsertSelectorScopeEdit { Position = firstDeepCombinator.Start });
-                }
-
-                // Also remove the deep combinator if we matched one
-                if (firstDeepCombinator != null)
-                {
-                    Edits.Add(new DeleteContentEdit { Position = firstDeepCombinator.Start, DeleteLength = DeepCombinatorText.Length });
-                }
-            }
-
-            private int FindPositionToInsertInSelector(SimpleSelector lastSimpleSelector)
-            {
-                var children = lastSimpleSelector.Children;
-                for (var i  = 0; i < children.Count; i++)
-                {
-                    switch (children[i])
-                    {
-                        // Selectors like "a > ::deep b" get parsed as [[a][>]][::deep][b], and we want to
-                        // insert right after the "a". So if we're processing a SimpleSelector like [[a][>]],
-                        // consider the ">" to signal the "insert before" position.
-                        case TokenItem t when IsTrailingCombinator(t.TokenType):
-
-                        // Similarly selectors like "a::before" get parsed as [[a][::before]], and we want to
-                        // insert right after the "a".  So if we're processing a SimpleSelector like [[a][::before]],
-                        // consider the pseudoelement to signal the "insert before" position.
-                        case PseudoElementSelector:
-                        case PseudoElementFunctionSelector:
-                        case PseudoClassSelector s when IsSingleColonPseudoElement(s):
-                            // Insert after the previous token if there is one, otherwise before the whole thing
-                            return i > 0 ? children[i - 1].AfterEnd : lastSimpleSelector.Start;
-                    }
-                }
-
-                // Since we didn't find any children that signal the insert-before position,
-                // insert after the whole thing
-                return lastSimpleSelector.AfterEnd;
-            }
-
-            private static bool IsSingleColonPseudoElement(PseudoClassSelector selector)
-            {
-                // See https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements
-                // Normally, pseudoelements require a double-colon prefix. However the following "original set"
-                // of pseudoelements also support single-colon prefixes for back-compatibility with older versions
-                // of the W3C spec. Our CSS parser sees them as pseudoselectors rather than pseudoelements, so
-                // we have to special-case them. The single-colon option doesn't exist for other more modern
-                // pseudoelements.
-                var selectorText = selector.Text;
-                return string.Equals(selectorText, ":after", StringComparison.OrdinalIgnoreCase)
-                    || string.Equals(selectorText, ":before", StringComparison.OrdinalIgnoreCase)
-                    || string.Equals(selectorText, ":first-letter", StringComparison.OrdinalIgnoreCase)
-                    || string.Equals(selectorText, ":first-line", StringComparison.OrdinalIgnoreCase);
-            }
-
-            private static bool IsTrailingCombinator(CssTokenType tokenType)
-            {
-                switch (tokenType)
-                {
-                    case CssTokenType.Plus:
-                    case CssTokenType.Tilde:
-                    case CssTokenType.Greater:
-                        return true;
-                    default:
-                        return false;
-                }
-            }
-
-            protected override void VisitAtDirective(AtDirective item)
-            {
-                // Whenever we see "@keyframes something { ... }", we want to insert right after "something"
-                if (TryFindKeyframesIdentifier(item, out var identifier))
-                {
-                    Edits.Add(new InsertKeyframesNameScopeEdit { Position = identifier.AfterEnd });
-                }
-                else
-                {
-                    VisitDefault(item);
-                }
-            }
-
-            protected override void VisitDeclaration(Declaration item)
-            {
-                switch (item.PropertyNameText)
-                {
-                    case "animation":
-                    case "animation-name":
-                        // The first two tokens are <propertyname> and <colon> (otherwise we wouldn't be here).
-                        // After that, any of the subsequent tokens might be the animation name.
-                        // Unfortunately the rules for determining which token is the animation name are very
-                        // complex - https://developer.mozilla.org/en-US/docs/Web/CSS/animation#Syntax
-                        // Fortunately we only want to rewrite animation names that are explicitly declared in
-                        // the same document (we don't want to add scopes to references to global keyframes)
-                        // so it's sufficient just to match known animation names.
-                        var animationNameTokens = item.Children.Skip(2).OfType<TokenItem>()
-                            .Where(x => x.TokenType == CssTokenType.Identifier && _keyframeIdentifiers.Contains(x.Text));
-                        foreach (var token in animationNameTokens)
-                        {
-                            Edits.Add(new InsertKeyframesNameScopeEdit { Position = token.AfterEnd });
-                        }
-                        break;
-                    default:
-                        // We don't need to do anything else with other declaration types
-                        break;
-                }
-            }
-        }
-
-        private class FindKeyframesIdentifiersVisitor : Visitor
-        {
-            public FindKeyframesIdentifiersVisitor(ComplexItem root) : base(root)
-            {
-            }
-
-            public List<ParseItem> KeyframesIdentifiers { get; } = new List<ParseItem>();
-
-            protected override void VisitAtDirective(AtDirective item)
-            {
-                if (TryFindKeyframesIdentifier(item, out var identifier))
-                {
-                    KeyframesIdentifiers.Add(identifier);
-                }
-                else
-                {
-                    VisitDefault(item);
-                }
-            }
-        }
-
-        private class EnsureNoImports : Visitor
-        {
-            private readonly string _filePath;
-            private readonly SourceText _sourceText;
-            private readonly List<RazorDiagnostic> _diagnostics;
-
-            public EnsureNoImports(string filePath, SourceText sourceText, ComplexItem root, List<RazorDiagnostic> diagnostics) : base(root)
-            {
-                _filePath = filePath;
-                _sourceText = sourceText;
-                _diagnostics = diagnostics;
-            }
-
-            protected override void VisitAtDirective(AtDirective item)
-            {
-                if (item.Children.Count >= 2
-                    && item.Children[0] is TokenItem firstChild
-                    && firstChild.TokenType == CssTokenType.At
-                    && item.Children[1] is TokenItem secondChild
-                    && string.Equals(secondChild.Text, "import", StringComparison.OrdinalIgnoreCase))
-                {
-                    var linePosition = _sourceText.Lines.GetLinePosition(item.Start);
-                    var sourceSpan = new SourceSpan(_filePath, item.Start, linePosition.Line, linePosition.Character, item.Length);
-                    _diagnostics.Add(RazorDiagnosticFactory.CreateCssRewriting_ImportNotAllowed(sourceSpan));
-                }
-
-                base.VisitAtDirective(item);
-            }
-        }
-
-        private class Visitor
-        {
-            private readonly ComplexItem _root;
-
-            public Visitor(ComplexItem root)
-            {
-                _root = root ?? throw new ArgumentNullException(nameof(root));
-            }
-
-            public void Visit()
-            {
-                VisitDefault(_root);
-            }
-
-            protected virtual void VisitSelector(Selector item)
-            {
-                VisitDefault(item);
-            }
-
-            protected virtual void VisitAtDirective(AtDirective item)
-            {
-                VisitDefault(item);
-            }
-
-            protected virtual void VisitDeclaration(Declaration item)
-            {
-                VisitDefault(item);
-            }
-
-            protected virtual void VisitDefault(ParseItem item)
-            {
-                if (item is ComplexItem complexItem)
-                {
-                    VisitDescendants(complexItem);
-                }
-            }
-
-            private void VisitDescendants(ComplexItem container)
-            {
-                foreach (var child in container.Children)
-                {
-                    switch (child)
-                    {
-                        case Selector selector:
-                            VisitSelector(selector);
-                            break;
-                        case AtDirective atDirective:
-                            VisitAtDirective(atDirective);
-                            break;
-                        case Declaration declaration:
-                            VisitDeclaration(declaration);
-                            break;
-                        default:
-                            VisitDefault(child);
-                            break;
-                    }
-                }
-            }
-        }
-
-        private abstract class CssEdit
-        {
-            public int Position { get; set; }
-        }
-
-        private class InsertSelectorScopeEdit : CssEdit
-        {
-        }
-
-        private class InsertKeyframesNameScopeEdit : CssEdit
-        {
-        }
-
-        private class DeleteContentEdit : CssEdit
-        {
-            public int DeleteLength { get; set; }
-        }
-    }
-}

+ 0 - 189
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerCommand.cs

@@ -1,189 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Diagnostics;
-using System.Globalization;
-using System.IO;
-using System.Reflection;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.Extensions.CommandLineUtils;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal class ServerCommand : CommandBase
-    {
-        public ServerCommand(Application parent)
-            : base(parent, "server")
-        {
-            Pipe = Option("-p|--pipe", "name of named pipe", CommandOptionType.SingleValue);
-            KeepAlive = Option("-k|--keep-alive", "sets the default idle timeout for the server in seconds", CommandOptionType.SingleValue);
-        }
-
-        // For testing purposes only.
-        internal ServerCommand(Application parent, string pipeName, int? keepAlive = null)
-            : this(parent)
-        {
-            if (!string.IsNullOrEmpty(pipeName))
-            {
-                Pipe.Values.Add(pipeName);
-            }
-
-            if (keepAlive.HasValue)
-            {
-                KeepAlive.Values.Add(keepAlive.Value.ToString(CultureInfo.InvariantCulture));
-            }
-        }
-
-        public CommandOption Pipe { get; }
-
-        public CommandOption KeepAlive { get; }
-
-        protected override bool ValidateArguments()
-        {
-            if (string.IsNullOrEmpty(Pipe.Value()))
-            {
-                Pipe.Values.Add(PipeName.ComputeDefault());
-            }
-
-            return true;
-        }
-
-        protected override Task<int> ExecuteCoreAsync()
-        {
-            // Make sure there's only one server with the same identity at a time.
-            var serverMutexName = MutexName.GetServerMutexName(Pipe.Value());
-            Mutex serverMutex = null;
-            var holdsMutex = false;
-
-            try
-            {
-                serverMutex = new Mutex(initiallyOwned: true, name: serverMutexName, createdNew: out holdsMutex);
-            }
-            catch (Exception ex)
-            {
-                // The Mutex constructor can throw in certain cases. One specific example is docker containers
-                // where the /tmp directory is restricted. In those cases there is no reliable way to execute
-                // the server and we need to fall back to the command line.
-                // Example: https://github.com/dotnet/roslyn/issues/24124
-
-                Error.Write($"Server mutex creation failed. {ex.Message}");
-
-                return Task.FromResult(-1);
-            }
-
-            if (!holdsMutex)
-            {
-                // Another server is running, just exit.
-                Error.Write("Another server already running...");
-                return Task.FromResult(1);
-            }
-
-            FileStream pidFileStream = null;
-            try
-            {
-                try
-                {
-                    // Write the process and pipe information to a file in a well-known location.
-                    pidFileStream = WritePidFile();
-                }
-                catch (Exception ex)
-                {
-                    // Something happened when trying to write to the pid file. Log and move on.
-                    ServerLogger.LogException(ex, "Failed to create PID file.");
-                }
-
-                TimeSpan? keepAlive = null;
-                if (KeepAlive.HasValue() && int.TryParse(KeepAlive.Value(), out var result))
-                {
-                    // Keep alive times are specified in seconds
-                    keepAlive = TimeSpan.FromSeconds(result);
-                }
-
-                var host = ConnectionHost.Create(Pipe.Value());
-
-                var compilerHost = CompilerHost.Create();
-                ExecuteServerCore(host, compilerHost, Cancelled, eventBus: null, keepAlive: keepAlive);
-            }
-            finally
-            {
-                serverMutex.ReleaseMutex();
-                serverMutex.Dispose();
-                pidFileStream?.Close();
-            }
-
-            return Task.FromResult(0);
-        }
-
-        protected virtual void ExecuteServerCore(ConnectionHost host, CompilerHost compilerHost, CancellationToken cancellationToken, EventBus eventBus, TimeSpan? keepAlive)
-        {
-            var dispatcher = RequestDispatcher.Create(host, compilerHost, cancellationToken, eventBus, keepAlive);
-            dispatcher.Run();
-        }
-
-        protected virtual FileStream WritePidFile()
-        {
-            var path = GetPidFilePath(env => Environment.GetEnvironmentVariable(env));
-            return WritePidFile(path);
-        }
-
-        // Internal for testing.
-        internal virtual FileStream WritePidFile(string directoryPath)
-        {
-            if (string.IsNullOrEmpty(directoryPath))
-            {
-                // Invalid path. Bail.
-                return null;
-            }
-
-            // To make all the running rzc servers more discoverable, We want to write the process Id and pipe name to a file.
-            // The file contents will be in the following format,
-            //
-            // <PID>
-            // rzc
-            // path/to/rzc.dll
-            // <pipename>
-
-            const int DefaultBufferSize = 4096;
-            var processId = Process.GetCurrentProcess().Id;
-            var fileName = $"rzc-{processId}";
-
-            // Make sure the directory exists.
-            Directory.CreateDirectory(directoryPath);
-
-            var path = Path.Combine(directoryPath, fileName);
-            var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, DefaultBufferSize, FileOptions.DeleteOnClose);
-
-            using (var writer = new StreamWriter(fileStream, Encoding.UTF8, DefaultBufferSize, leaveOpen: true))
-            {
-                var rzcPath = Assembly.GetExecutingAssembly().Location;
-                var content = $"{processId}{Environment.NewLine}rzc{Environment.NewLine}{rzcPath}{Environment.NewLine}{Pipe.Value()}";
-                writer.Write(content);
-            }
-
-            return fileStream;
-        }
-
-        // Internal for testing.
-        internal virtual string GetPidFilePath(Func<string, string> getEnvironmentVariable)
-        {
-            var path = getEnvironmentVariable("DOTNET_BUILD_PIDFILE_DIRECTORY");
-            if (string.IsNullOrEmpty(path))
-            {
-                var homeEnvVariable = PlatformInformation.IsWindows ? "USERPROFILE" : "HOME";
-                var homePath = getEnvironmentVariable(homeEnvVariable);
-                if (string.IsNullOrEmpty(homePath))
-                {
-                    // Couldn't locate the user profile directory. Bail.
-                    return null;
-                }
-
-                path = Path.Combine(homePath, ".dotnet", "pids", "build");
-            }
-
-            return path;
-        }
-    }
-}

+ 0 - 58
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/CompletedServerResponse.cs

@@ -1,58 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    /// <summary>
-    /// Represents a Response from the server. A response is as follows.
-    /// 
-    ///  Field Name         Type            Size (bytes)
-    /// --------------------------------------------------
-    ///  Length             UInteger        4
-    ///  ReturnCode         Integer         4
-    ///  Output             String          Variable
-    ///  ErrorOutput        String          Variable
-    /// 
-    /// Strings are encoded via a character count prefix as a 
-    /// 32-bit integer, followed by an array of characters.
-    /// 
-    /// </summary>
-    internal sealed class CompletedServerResponse : ServerResponse
-    {
-        public readonly int ReturnCode;
-        public readonly bool Utf8Output;
-        public readonly string Output;
-        public readonly string ErrorOutput;
-
-        public CompletedServerResponse(int returnCode, bool utf8output, string output, string error)
-        {
-            ReturnCode = returnCode;
-            Utf8Output = utf8output;
-            Output = output;
-            ErrorOutput = error;
-        }
-
-        public override ResponseType Type => ResponseType.Completed;
-
-        public static CompletedServerResponse Create(BinaryReader reader)
-        {
-            var returnCode = reader.ReadInt32();
-            var utf8Output = reader.ReadBoolean();
-            var output = ServerProtocol.ReadLengthPrefixedString(reader);
-            var errorOutput = ServerProtocol.ReadLengthPrefixedString(reader);
-
-            return new CompletedServerResponse(returnCode, utf8Output, output, errorOutput);
-        }
-
-        protected override void AddResponseBody(BinaryWriter writer)
-        {
-            writer.Write(ReturnCode);
-            writer.Write(Utf8Output);
-            ServerProtocol.WriteLengthPrefixedString(writer, Output);
-            ServerProtocol.WriteLengthPrefixedString(writer, ErrorOutput);
-        }
-    }
-}

+ 0 - 17
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/MismatchedVersionServerResponse.cs

@@ -1,17 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal sealed class MismatchedVersionServerResponse : ServerResponse
-    {
-        public override ResponseType Type => ResponseType.MismatchedVersion;
-
-        /// <summary>
-        /// MismatchedVersion has no body.
-        /// </summary>
-        protected override void AddResponseBody(BinaryWriter writer) { }
-    }
-}

+ 0 - 89
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/NativeMethods.cs

@@ -1,89 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Runtime.InteropServices;
-using System.Text;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-    internal struct STARTUPINFO
-    {
-        internal Int32 cb;
-        internal string lpReserved;
-        internal string lpDesktop;
-        internal string lpTitle;
-        internal Int32 dwX;
-        internal Int32 dwY;
-        internal Int32 dwXSize;
-        internal Int32 dwYSize;
-        internal Int32 dwXCountChars;
-        internal Int32 dwYCountChars;
-        internal Int32 dwFillAttribute;
-        internal Int32 dwFlags;
-        internal Int16 wShowWindow;
-        internal Int16 cbReserved2;
-        internal IntPtr lpReserved2;
-        internal IntPtr hStdInput;
-        internal IntPtr hStdOutput;
-        internal IntPtr hStdError;
-    }
-
-    [StructLayout(LayoutKind.Sequential)]
-    internal struct PROCESS_INFORMATION
-    {
-        public IntPtr hProcess;
-        public IntPtr hThread;
-        public int dwProcessId;
-        public int dwThreadId;
-    }
-
-    /// <summary>
-    /// Interop methods.
-    /// </summary>
-    internal static class NativeMethods
-    {
-        #region Constants
-
-        internal static readonly IntPtr NullPtr = IntPtr.Zero;
-        internal static readonly IntPtr InvalidIntPtr = new IntPtr((int)-1);
-
-        internal const uint NORMAL_PRIORITY_CLASS = 0x0020;
-        internal const uint CREATE_NO_WINDOW = 0x08000000;
-        internal const Int32 STARTF_USESTDHANDLES = 0x00000100;
-        internal const int ERROR_SUCCESS = 0;
-
-        #endregion
-
-        //------------------------------------------------------------------------------
-        // CloseHandle
-        //------------------------------------------------------------------------------
-        [DllImport("kernel32.dll", SetLastError = true)]
-        [return: MarshalAs(UnmanagedType.Bool)]
-        internal static extern bool CloseHandle(IntPtr hObject);
-
-        //------------------------------------------------------------------------------
-        // CreateProcess
-        //------------------------------------------------------------------------------
-        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
-        [return: MarshalAs(UnmanagedType.Bool)]
-        internal static extern bool CreateProcess
-        (
-            string lpApplicationName,
-            [In, Out]StringBuilder lpCommandLine,
-            IntPtr lpProcessAttributes,
-            IntPtr lpThreadAttributes,
-            [In, MarshalAs(UnmanagedType.Bool)]
-            bool bInheritHandles,
-            uint dwCreationFlags,
-            IntPtr lpEnvironment,
-            string lpCurrentDirectory,
-            [In] ref STARTUPINFO lpStartupInfo,
-            out PROCESS_INFORMATION lpProcessInformation
-        );
-
-        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
-        internal static extern IntPtr GetCommandLine();
-    }
-}

+ 0 - 17
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/RejectedServerResponse.cs

@@ -1,17 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal sealed class RejectedServerResponse : ServerResponse
-    {
-        public override ResponseType Type => ResponseType.Rejected;
-
-        /// <summary>
-        /// RejectedResponse has no body.
-        /// </summary>
-        protected override void AddResponseBody(BinaryWriter writer) { }
-    }
-}

+ 0 - 72
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/RequestArgument.cs

@@ -1,72 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    /// <summary>
-    /// A command line argument to the compilation. 
-    /// An argument is formatted as follows:
-    /// 
-    ///  Field Name         Type            Size (bytes)
-    /// --------------------------------------------------
-    ///  ID                 UInteger        4
-    ///  Index              UInteger        4
-    ///  Value              String          Variable
-    /// 
-    /// Strings are encoded via a length prefix as a signed
-    /// 32-bit integer, followed by an array of characters.
-    /// </summary>
-    internal readonly struct RequestArgument
-    {
-        public readonly ArgumentId Id;
-        public readonly int ArgumentIndex;
-        public readonly string Value;
-
-        public RequestArgument(ArgumentId argumentId, int argumentIndex, string value)
-        {
-            Id = argumentId;
-            ArgumentIndex = argumentIndex;
-            Value = value;
-        }
-
-        public static RequestArgument ReadFromBinaryReader(BinaryReader reader)
-        {
-            var argId = (ArgumentId)reader.ReadInt32();
-            var argIndex = reader.ReadInt32();
-            var value = ServerProtocol.ReadLengthPrefixedString(reader);
-            return new RequestArgument(argId, argIndex, value);
-        }
-
-        public void WriteToBinaryWriter(BinaryWriter writer)
-        {
-            writer.Write((int)Id);
-            writer.Write(ArgumentIndex);
-            ServerProtocol.WriteLengthPrefixedString(writer, Value);
-        }
-
-        public enum ArgumentId
-        {
-            // The current directory of the client
-            CurrentDirectory = 0x51147221,
-
-            // A comment line argument. The argument index indicates which one (0 .. N)
-            CommandLineArgument,
-
-            // Request a longer keep alive time for the server
-            KeepAlive,
-
-            // Request a server shutdown from the client
-            Shutdown,
-
-            // The directory to use for temporary operations.
-            TempDirectory,
-        }
-
-        public override string ToString()
-        {
-            return $"{Id} {Value}";
-        }
-    }
-}

+ 0 - 390
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/ServerConnection.cs

@@ -1,390 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.Runtime.InteropServices;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.Extensions.CommandLineUtils;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal static class ServerConnection
-    {
-        private const string ServerName = "rzc.dll";
-
-        // Spend up to 1s connecting to existing process (existing processes should be always responsive).
-        private const int TimeOutMsExistingProcess = 1000;
-
-        // Spend up to 20s connecting to a new process, to allow time for it to start.
-        private const int TimeOutMsNewProcess = 20000;
-
-        // Custom delegate that contains an out param to use with TryCreateServerCore method.
-        private delegate TResult TryCreateServerCoreDelegate<T1, T2, T3, T4, out TResult>(T1 arg1, T2 arg2, out T3 arg3, T4 arg4);
-
-        public static bool WasServerMutexOpen(string mutexName)
-        {
-            Mutex mutex = null;
-            var open = false;
-            try
-            {
-                open = Mutex.TryOpenExisting(mutexName, out mutex);
-            }
-            catch
-            {
-                // In the case an exception occurred trying to open the Mutex then
-                // the assumption is that it's not open.
-            }
-
-            mutex?.Dispose();
-
-            return open;
-        }
-
-        /// <summary>
-        /// Gets the value of the temporary path for the current environment assuming the working directory
-        /// is <paramref name="workingDir"/>.  This function must emulate <see cref="Path.GetTempPath"/> as
-        /// closely as possible.
-        /// </summary>
-        public static string GetTempPath(string workingDir)
-        {
-            if (PlatformInformation.IsUnix)
-            {
-                // Unix temp path is fine: it does not use the working directory
-                // (it uses ${TMPDIR} if set, otherwise, it returns /tmp)
-                return Path.GetTempPath();
-            }
-
-            var tmp = Environment.GetEnvironmentVariable("TMP");
-            if (Path.IsPathRooted(tmp))
-            {
-                return tmp;
-            }
-
-            var temp = Environment.GetEnvironmentVariable("TEMP");
-            if (Path.IsPathRooted(temp))
-            {
-                return temp;
-            }
-
-            if (!string.IsNullOrEmpty(workingDir))
-            {
-                if (!string.IsNullOrEmpty(tmp))
-                {
-                    return Path.Combine(workingDir, tmp);
-                }
-
-                if (!string.IsNullOrEmpty(temp))
-                {
-                    return Path.Combine(workingDir, temp);
-                }
-            }
-
-            var userProfile = Environment.GetEnvironmentVariable("USERPROFILE");
-            if (Path.IsPathRooted(userProfile))
-            {
-                return userProfile;
-            }
-
-            return Environment.GetEnvironmentVariable("SYSTEMROOT");
-        }
-
-        public static Task<ServerResponse> RunOnServer(
-            string pipeName,
-            IList<string> arguments,
-            ServerPaths serverPaths,
-            CancellationToken cancellationToken,
-            string keepAlive = null,
-            bool debug = false)
-        {
-            if (string.IsNullOrEmpty(pipeName))
-            {
-                pipeName = PipeName.ComputeDefault(serverPaths.ClientDirectory);
-            }
-
-            return RunOnServerCore(
-                arguments,
-                serverPaths,
-                pipeName: pipeName,
-                keepAlive: keepAlive,
-                timeoutOverride: null,
-                tryCreateServerFunc: TryCreateServerCore,
-                cancellationToken: cancellationToken,
-                debug: debug);
-        }
-
-        private static async Task<ServerResponse> RunOnServerCore(
-            IList<string> arguments,
-            ServerPaths serverPaths,
-            string pipeName,
-            string keepAlive,
-            int? timeoutOverride,
-            TryCreateServerCoreDelegate<string, string, int?, bool, bool> tryCreateServerFunc,
-            CancellationToken cancellationToken,
-            bool debug)
-        {
-            if (pipeName == null)
-            {
-                return new RejectedServerResponse();
-            }
-
-            if (serverPaths.TempDirectory == null)
-            {
-                return new RejectedServerResponse();
-            }
-
-            var clientDir = serverPaths.ClientDirectory;
-            var timeoutNewProcess = timeoutOverride ?? TimeOutMsNewProcess;
-            var timeoutExistingProcess = timeoutOverride ?? TimeOutMsExistingProcess;
-            var clientMutexName = MutexName.GetClientMutexName(pipeName);
-            Task<Client> pipeTask = null;
-
-            Mutex clientMutex = null;
-            var holdsMutex = false;
-
-            try
-            {
-                try
-                {
-                    clientMutex = new Mutex(initiallyOwned: true, name: clientMutexName, createdNew: out holdsMutex);
-                }
-                catch (Exception ex)
-                {
-                    // The Mutex constructor can throw in certain cases. One specific example is docker containers
-                    // where the /tmp directory is restricted. In those cases there is no reliable way to execute
-                    // the server and we need to fall back to the command line.
-                    // Example: https://github.com/dotnet/roslyn/issues/24124
-
-                    ServerLogger.LogException(ex, "Client mutex creation failed.");
-
-                    return new RejectedServerResponse();
-                }
-
-                if (!holdsMutex)
-                {
-                    try
-                    {
-                        holdsMutex = clientMutex.WaitOne(timeoutNewProcess);
-
-                        if (!holdsMutex)
-                        {
-                            return new RejectedServerResponse();
-                        }
-                    }
-                    catch (AbandonedMutexException)
-                    {
-                        holdsMutex = true;
-                    }
-                }
-
-                // Check for an already running server
-                var serverMutexName = MutexName.GetServerMutexName(pipeName);
-                var wasServerRunning = WasServerMutexOpen(serverMutexName);
-                var timeout = wasServerRunning ? timeoutExistingProcess : timeoutNewProcess;
-
-                if (wasServerRunning || tryCreateServerFunc(clientDir, pipeName, out var _, debug))
-                {
-                    pipeTask = Client.ConnectAsync(pipeName, TimeSpan.FromMilliseconds(timeout), cancellationToken);
-                }
-            }
-            finally
-            {
-                if (holdsMutex)
-                {
-                    clientMutex?.ReleaseMutex();
-                }
-
-                clientMutex?.Dispose();
-            }
-
-            if (pipeTask != null)
-            {
-                var client = await pipeTask.ConfigureAwait(false);
-                if (client != null)
-                {
-                    var request = ServerRequest.Create(
-                        serverPaths.WorkingDirectory,
-                        serverPaths.TempDirectory,
-                        arguments,
-                        keepAlive);
-
-                    return await TryProcessRequest(client, request, cancellationToken).ConfigureAwait(false);
-                }
-            }
-
-            return new RejectedServerResponse();
-        }
-
-        /// <summary>
-        /// Try to process the request using the server. Returns a null-containing Task if a response
-        /// from the server cannot be retrieved.
-        /// </summary>
-        private static async Task<ServerResponse> TryProcessRequest(
-            Client client,
-            ServerRequest request,
-            CancellationToken cancellationToken)
-        {
-            ServerResponse response;
-            using (client)
-            {
-                // Write the request
-                try
-                {
-                    ServerLogger.Log("Begin writing request");
-                    await request.WriteAsync(client.Stream, cancellationToken).ConfigureAwait(false);
-                    ServerLogger.Log("End writing request");
-                }
-                catch (Exception e)
-                {
-                    ServerLogger.LogException(e, "Error writing build request.");
-                    return new RejectedServerResponse();
-                }
-
-                // Wait for the compilation and a monitor to detect if the server disconnects
-                var serverCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
-
-                ServerLogger.Log("Begin reading response");
-
-                var responseTask = ServerResponse.ReadAsync(client.Stream, serverCts.Token);
-                var monitorTask = client.WaitForDisconnectAsync(serverCts.Token);
-                await Task.WhenAny(new[] { responseTask, monitorTask }).ConfigureAwait(false);
-
-                ServerLogger.Log("End reading response");
-
-                if (responseTask.IsCompleted)
-                {
-                    // await the task to log any exceptions
-                    try
-                    {
-                        response = await responseTask.ConfigureAwait(false);
-                    }
-                    catch (Exception e)
-                    {
-                        ServerLogger.LogException(e, "Error reading response");
-                        response = new RejectedServerResponse();
-                    }
-                }
-                else
-                {
-                    ServerLogger.Log("Server disconnect");
-                    response = new RejectedServerResponse();
-                }
-
-                // Cancel whatever task is still around
-                serverCts.Cancel();
-                Debug.Assert(response != null);
-                return response;
-            }
-        }
-
-        // Internal for testing.
-        internal static bool TryCreateServerCore(string clientDir, string pipeName, out int? processId, bool debug = false)
-        {
-            processId = null;
-
-            // The server should be in the same directory as the client
-            var expectedCompilerPath = Path.Combine(clientDir, ServerName);
-            var expectedPath = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet";
-            var argumentList = new string[]
-            {
-                expectedCompilerPath,
-                debug ? "--debug" : "",
-                "server",
-                "-p",
-                pipeName
-            };
-            var processArguments = ArgumentEscaper.EscapeAndConcatenate(argumentList);
-
-            if (!File.Exists(expectedCompilerPath))
-            {
-                return false;
-            }
-
-            if (PlatformInformation.IsWindows)
-            {
-                // Currently, there isn't a way to use the Process class to create a process without
-                // inheriting handles(stdin/stdout/stderr) from its parent. This might cause the parent process
-                // to block on those handles. So we use P/Invoke. This code was taken from MSBuild task starting code.
-                // The work to customize this behavior is being tracked by https://github.com/dotnet/corefx/issues/306.
-
-                var startInfo = new STARTUPINFO();
-                startInfo.cb = Marshal.SizeOf(startInfo);
-                startInfo.hStdError = NativeMethods.InvalidIntPtr;
-                startInfo.hStdInput = NativeMethods.InvalidIntPtr;
-                startInfo.hStdOutput = NativeMethods.InvalidIntPtr;
-                startInfo.dwFlags = NativeMethods.STARTF_USESTDHANDLES;
-                var dwCreationFlags = NativeMethods.NORMAL_PRIORITY_CLASS | NativeMethods.CREATE_NO_WINDOW;
-
-                ServerLogger.Log("Attempting to create process '{0}'", expectedPath);
-
-                var builder = new StringBuilder($@"""{expectedPath}"" {processArguments}");
-
-                var success = NativeMethods.CreateProcess(
-                    lpApplicationName: null,
-                    lpCommandLine: builder,
-                    lpProcessAttributes: NativeMethods.NullPtr,
-                    lpThreadAttributes: NativeMethods.NullPtr,
-                    bInheritHandles: false,
-                    dwCreationFlags: dwCreationFlags,
-                    lpEnvironment: NativeMethods.NullPtr, // Inherit environment
-                    lpCurrentDirectory: clientDir,
-                    lpStartupInfo: ref startInfo,
-                    lpProcessInformation: out var processInfo);
-
-                if (success)
-                {
-                    ServerLogger.Log("Successfully created process with process id {0}", processInfo.dwProcessId);
-                    NativeMethods.CloseHandle(processInfo.hProcess);
-                    NativeMethods.CloseHandle(processInfo.hThread);
-                    processId = processInfo.dwProcessId;
-                }
-                else
-                {
-                    ServerLogger.Log("Failed to create process. GetLastError={0}", Marshal.GetLastWin32Error());
-                }
-                return success;
-            }
-            else
-            {
-                try
-                {
-                    var startInfo = new ProcessStartInfo()
-                    {
-                        FileName = expectedPath,
-                        Arguments = processArguments,
-                        UseShellExecute = false,
-                        WorkingDirectory = clientDir,
-                        RedirectStandardInput = true,
-                        RedirectStandardOutput = true,
-                        RedirectStandardError = true,
-                        CreateNoWindow = true
-                    };
-
-                    var process = Process.Start(startInfo);
-                    processId = process.Id;
-
-                    return true;
-                }
-                catch
-                {
-                    return false;
-                }
-            }
-        }
-    }
-
-    /// <summary>
-    /// This class provides simple properties for determining whether the current platform is Windows or Unix-based.
-    /// We intentionally do not use System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(...) because
-    /// it incorrectly reports 'true' for 'Windows' in desktop builds running on Unix-based platforms via Mono.
-    /// </summary>
-    internal static class PlatformInformation
-    {
-        public static bool IsWindows => Path.DirectorySeparatorChar == '\\';
-        public static bool IsUnix => Path.DirectorySeparatorChar == '/';
-    }
-}

+ 0 - 146
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/ServerLogger.cs

@@ -1,146 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Diagnostics;
-using System.Globalization;
-using System.IO;
-using System.Text;
-using System.Threading;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    /// <summary>
-    /// Class for logging information about what happens in the server and client parts of the
-    /// Razor command line compiler and build tasks. Useful for debugging what is going on.
-    /// </summary>
-    /// <remarks>
-    /// To use the logging, set the environment variable RAZORBUILDSERVER_LOG to the name
-    /// of a file to log to. This file is logged to by both client and server components.
-    /// </remarks>
-    internal class ServerLogger
-    {
-        // Environment variable, if set, to enable logging and set the file to log to.
-        private const string EnvironmentVariable = "RAZORBUILDSERVER_LOG";
-
-        private static readonly Stream s_loggingStream;
-        private static string s_prefix = "---";
-
-        /// <summary>
-        /// Static class initializer that initializes logging.
-        /// </summary>
-        static ServerLogger()
-        {
-            s_loggingStream = null;
-
-            try
-            {
-                // Check if the environment
-                var loggingFileName = Environment.GetEnvironmentVariable(EnvironmentVariable);
-
-                if (loggingFileName != null)
-                {
-                    IsLoggingEnabled = true;
-
-                    // If the environment variable contains the path of a currently existing directory,
-                    // then use a process-specific name for the log file and put it in that directory.
-                    // Otherwise, assume that the environment variable specifies the name of the log file.
-                    if (Directory.Exists(loggingFileName))
-                    {
-                        loggingFileName = Path.Combine(loggingFileName, $"razorserver.{GetCurrentProcessId()}.log");
-                    }
-
-                    // Open allowing sharing. We allow multiple processes to log to the same file, so we use share mode to allow that.
-                    s_loggingStream = new FileStream(loggingFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
-                }
-            }
-            catch (Exception e)
-            {
-                LogException(e, "Failed to create logging stream");
-            }
-        }
-
-        public static bool IsLoggingEnabled { get; }
-
-        /// <summary>
-        /// Set the logging prefix that describes our role.
-        /// Typically a 3-letter abbreviation. If logging happens before this, it's logged with "---".
-        /// </summary>
-        public static void Initialize(string outputPrefix)
-        {
-            s_prefix = outputPrefix;
-        }
-
-        /// <summary>
-        /// Log an exception. Also logs information about inner exceptions.
-        /// </summary>
-        public static void LogException(Exception e, string reason)
-        {
-            if (IsLoggingEnabled)
-            {
-                Log("Exception '{0}' occurred during '{1}'. Stack trace:\r\n{2}", e.Message, reason, e.StackTrace);
-
-                var innerExceptionLevel = 0;
-
-                e = e.InnerException;
-                while (e != null)
-                {
-                    Log("Inner exception[{0}] '{1}'. Stack trace: \r\n{1}", innerExceptionLevel, e.Message, e.StackTrace);
-                    e = e.InnerException;
-                    innerExceptionLevel += 1;
-                }
-            }
-        }
-
-        /// <summary>
-        /// Log a line of text to the logging file, with string.Format arguments.
-        /// </summary>
-        public static void Log(string format, params object[] arguments)
-        {
-            if (IsLoggingEnabled)
-            {
-                Log(string.Format(CultureInfo.InvariantCulture, format, arguments));
-            }
-        }
-
-        /// <summary>
-        /// Log a line of text to the logging file.
-        /// </summary>
-        /// <param name="message"></param>
-        public static void Log(string message)
-        {
-            if (IsLoggingEnabled)
-            {
-                var prefix = GetLoggingPrefix();
-
-                var output = prefix + message + "\r\n";
-                var bytes = Encoding.UTF8.GetBytes(output);
-
-                // Because multiple processes might be logging to the same file, we always seek to the end,
-                // write, and flush.
-                s_loggingStream.Seek(0, SeekOrigin.End);
-                s_loggingStream.Write(bytes, 0, bytes.Length);
-                s_loggingStream.Flush();
-            }
-        }
-
-        private static int GetCurrentProcessId()
-        {
-            var process = Process.GetCurrentProcess();
-            return process.Id;
-        }
-
-        private static int GetCurrentThreadId()
-        {
-            return Environment.CurrentManagedThreadId;
-        }
-
-        /// <summary>
-        /// Get the string that prefixes all log entries. Shows the process, thread, and time.
-        /// </summary>
-        private static string GetLoggingPrefix()
-        {
-            return string.Format(CultureInfo.InvariantCulture, "{0} PID={1} TID={2} Ticks={3}: ", s_prefix, GetCurrentProcessId(), GetCurrentThreadId(), Environment.TickCount);
-        }
-    }
-}

+ 0 - 33
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/ServerPaths.cs

@@ -1,33 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal struct ServerPaths
-    {
-        internal ServerPaths(string clientDir, string workingDir, string tempDir)
-        {
-            ClientDirectory = clientDir;
-            WorkingDirectory = workingDir;
-            TempDirectory = tempDir;
-        }
-
-        /// <summary>
-        /// The path which contains the Razor compiler binaries and response files.
-        /// </summary>
-        internal string ClientDirectory { get; }
-
-        /// <summary>
-        /// The path in which the Razor compilation takes place.
-        /// </summary>
-        internal string WorkingDirectory { get; }
-
-        /// <summary>
-        /// The temporary directory a compilation should use instead of <see cref="Path.GetTempPath"/>.  The latter
-        /// relies on global state individual compilations should ignore.
-        /// </summary>
-        internal string TempDirectory { get; }
-    }
-}

+ 0 - 70
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/ServerProtocol.cs

@@ -1,70 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal static class ServerProtocol
-    {
-        /// <summary>
-        /// The version number for this protocol.
-        /// </summary>
-        public static readonly uint ProtocolVersion = 2;
-
-        /// <summary>
-        /// Read a string from the Reader where the string is encoded
-        /// as a length prefix (signed 32-bit integer) followed by
-        /// a sequence of characters.
-        /// </summary>
-        public static string ReadLengthPrefixedString(BinaryReader reader)
-        {
-            var length = reader.ReadInt32();
-            return new string(reader.ReadChars(length));
-        }
-
-        /// <summary>
-        /// Write a string to the Writer where the string is encoded
-        /// as a length prefix (signed 32-bit integer) follows by
-        /// a sequence of characters.
-        /// </summary>
-        public static void WriteLengthPrefixedString(BinaryWriter writer, string value)
-        {
-            writer.Write(value.Length);
-            writer.Write(value.ToCharArray());
-        }
-
-        /// <summary>
-        /// This task does not complete until we are completely done reading.
-        /// </summary>
-        internal static async Task ReadAllAsync(
-            Stream stream,
-            byte[] buffer,
-            int count,
-            CancellationToken cancellationToken)
-        {
-            var totalBytesRead = 0;
-            do
-            {
-                ServerLogger.Log("Attempting to read {0} bytes from the stream", count - totalBytesRead);
-                var bytesRead = await stream.ReadAsync(
-                    buffer,
-                    totalBytesRead,
-                    count - totalBytesRead,
-                    cancellationToken)
-                    .ConfigureAwait(false);
-
-                if (bytesRead == 0)
-                {
-                    ServerLogger.Log("Unexpected -- read 0 bytes from the stream.");
-                    throw new EndOfStreamException("Reached end of stream before end of read.");
-                }
-                ServerLogger.Log("Read {0} bytes", bytesRead);
-                totalBytesRead += bytesRead;
-            } while (totalBytesRead < count);
-            ServerLogger.Log("Finished read");
-        }
-    }
-}

+ 0 - 216
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/ServerRequest.cs

@@ -1,216 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-
-// After the server pipe is connected, it forks off a thread to handle the connection, and creates
-// a new instance of the pipe to listen for new clients. When it gets a request, it validates
-// the security and elevation level of the client. If that fails, it disconnects the client. Otherwise,
-// it handles the request, sends a response (described by Response class) back to the client, then
-// disconnects the pipe and ends the thread.
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    /// <summary>
-    /// Represents a request from the client. A request is as follows.
-    /// 
-    ///  Field Name         Type                Size (bytes)
-    /// ----------------------------------------------------
-    ///  Length             Integer             4
-    ///  Argument Count     UInteger            4
-    ///  Arguments          Argument[]          Variable
-    /// 
-    /// See <see cref="RequestArgument"/> for the format of an
-    /// Argument.
-    /// 
-    /// </summary>
-    internal class ServerRequest
-    {
-        public ServerRequest(uint protocolVersion, IEnumerable<RequestArgument> arguments)
-        {
-            ProtocolVersion = protocolVersion;
-            Arguments = new ReadOnlyCollection<RequestArgument>(arguments.ToList());
-
-            if (Arguments.Count > ushort.MaxValue)
-            {
-                throw new ArgumentOutOfRangeException(
-                    nameof(arguments),
-                    $"Too many arguments: maximum of {ushort.MaxValue} arguments allowed.");
-            }
-        }
-
-        public uint ProtocolVersion { get; }
-
-        public ReadOnlyCollection<RequestArgument> Arguments { get; }
-
-        public TimeSpan? KeepAlive
-        {
-            get
-            {
-                TimeSpan? keepAlive = null;
-                foreach (var argument in Arguments)
-                {
-                    if (argument.Id == RequestArgument.ArgumentId.KeepAlive)
-                    {
-                        // If the value is not a valid integer for any reason, ignore it and continue with the current timeout. 
-                        // The client is responsible for validating the argument.
-                        if (int.TryParse(argument.Value, out var result))
-                        {
-                            // Keep alive times are specified in seconds
-                            keepAlive = TimeSpan.FromSeconds(result);
-                        }
-                    }
-                }
-
-                return keepAlive;
-            }
-        }
-
-        public bool IsShutdownRequest()
-        {
-            return Arguments.Count >= 1 && Arguments[0].Id == RequestArgument.ArgumentId.Shutdown;
-        }
-
-        public static ServerRequest Create(
-            string workingDirectory,
-            string tempDirectory,
-            IList<string> args,
-            string keepAlive = null)
-        {
-            ServerLogger.Log("Creating ServerRequest");
-            ServerLogger.Log($"Working directory: {workingDirectory}");
-            ServerLogger.Log($"Temp directory: {tempDirectory}");
-
-            var requestLength = args.Count + 1;
-            var requestArgs = new List<RequestArgument>(requestLength)
-            {
-                new RequestArgument(RequestArgument.ArgumentId.CurrentDirectory, 0, workingDirectory),
-                new RequestArgument(RequestArgument.ArgumentId.TempDirectory, 0, tempDirectory)
-            };
-
-            if (keepAlive != null)
-            {
-                requestArgs.Add(new RequestArgument(RequestArgument.ArgumentId.KeepAlive, 0, keepAlive));
-            }
-
-            for (var i = 0; i < args.Count; ++i)
-            {
-                var arg = args[i];
-                ServerLogger.Log($"argument[{i}] = {arg}");
-                requestArgs.Add(new RequestArgument(RequestArgument.ArgumentId.CommandLineArgument, i, arg));
-            }
-
-            return new ServerRequest(ServerProtocol.ProtocolVersion, requestArgs);
-        }
-
-        public static ServerRequest CreateShutdown()
-        {
-            var requestArgs = new[]
-            {
-                new RequestArgument(RequestArgument.ArgumentId.Shutdown, argumentIndex: 0, value: ""),
-                new RequestArgument(RequestArgument.ArgumentId.CommandLineArgument, argumentIndex: 1, value: "shutdown"),
-            };
-            return new ServerRequest(ServerProtocol.ProtocolVersion, requestArgs);
-        }
-
-        /// <summary>
-        /// Read a Request from the given stream.
-        /// 
-        /// The total request size must be less than 1MB.
-        /// </summary>
-        /// <returns>null if the Request was too large, the Request otherwise.</returns>
-        public static async Task<ServerRequest> ReadAsync(Stream inStream, CancellationToken cancellationToken)
-        {
-            // Read the length of the request
-            var lengthBuffer = new byte[4];
-            ServerLogger.Log("Reading length of request");
-            await ServerProtocol.ReadAllAsync(inStream, lengthBuffer, 4, cancellationToken).ConfigureAwait(false);
-            var length = BitConverter.ToInt32(lengthBuffer, 0);
-
-            // Back out if the request is > 1MB
-            if (length > 0x100000)
-            {
-                ServerLogger.Log("Request is over 1MB in length, cancelling read.");
-                return null;
-            }
-
-            cancellationToken.ThrowIfCancellationRequested();
-
-            // Read the full request
-            var requestBuffer = new byte[length];
-            await ServerProtocol.ReadAllAsync(inStream, requestBuffer, length, cancellationToken).ConfigureAwait(false);
-
-            cancellationToken.ThrowIfCancellationRequested();
-
-            ServerLogger.Log("Parsing request");
-            // Parse the request into the Request data structure.
-            using (var reader = new BinaryReader(new MemoryStream(requestBuffer), Encoding.Unicode))
-            {
-                var protocolVersion = reader.ReadUInt32();
-                var argumentCount = reader.ReadUInt32();
-
-                var argumentsBuilder = new List<RequestArgument>((int)argumentCount);
-
-                for (var i = 0; i < argumentCount; i++)
-                {
-                    cancellationToken.ThrowIfCancellationRequested();
-                    argumentsBuilder.Add(RequestArgument.ReadFromBinaryReader(reader));
-                }
-
-                return new ServerRequest(protocolVersion, argumentsBuilder);
-            }
-        }
-
-        /// <summary>
-        /// Write a Request to the stream.
-        /// </summary>
-        public async Task WriteAsync(Stream outStream, CancellationToken cancellationToken = default(CancellationToken))
-        {
-            using (var memoryStream = new MemoryStream())
-            using (var writer = new BinaryWriter(memoryStream, Encoding.Unicode))
-            {
-                // Format the request.
-                ServerLogger.Log("Formatting request");
-                writer.Write(ProtocolVersion);
-                writer.Write(Arguments.Count);
-                foreach (var arg in Arguments)
-                {
-                    cancellationToken.ThrowIfCancellationRequested();
-                    arg.WriteToBinaryWriter(writer);
-                }
-                writer.Flush();
-
-                cancellationToken.ThrowIfCancellationRequested();
-
-                // Write the length of the request
-                var length = checked((int)memoryStream.Length);
-
-                // Back out if the request is > 1 MB
-                if (memoryStream.Length > 0x100000)
-                {
-                    ServerLogger.Log("Request is over 1MB in length, cancelling write");
-                    throw new ArgumentOutOfRangeException();
-                }
-
-                // Send the request to the server
-                ServerLogger.Log("Writing length of request.");
-                await outStream
-                    .WriteAsync(BitConverter.GetBytes(length), 0, 4, cancellationToken)
-                    .ConfigureAwait(false);
-
-                ServerLogger.Log("Writing request of size {0}", length);
-                // Write the request
-                memoryStream.Position = 0;
-                await memoryStream
-                    .CopyToAsync(outStream, bufferSize: length, cancellationToken: cancellationToken)
-                    .ConfigureAwait(false);
-            }
-        }
-    }
-}

+ 0 - 132
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/ServerResponse.cs

@@ -1,132 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-
-// After the server pipe is connected, it forks off a thread to handle the connection, and creates
-// a new instance of the pipe to listen for new clients. When it gets a request, it validates
-// the security and elevation level of the client. If that fails, it disconnects the client. Otherwise,
-// it handles the request, sends a response (described by Response class) back to the client, then
-// disconnects the pipe and ends the thread.
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    /// <summary>
-    /// Base class for all possible responses to a request.
-    /// The ResponseType enum should list all possible response types
-    /// and ReadResponse creates the appropriate response subclass based
-    /// on the response type sent by the client.
-    /// The format of a response is:
-    ///
-    /// Field Name       Field Type          Size (bytes)
-    /// -------------------------------------------------
-    /// responseLength   int (positive)      4  
-    /// responseType     enum ResponseType   4
-    /// responseBody     Response subclass   variable
-    /// </summary>
-    internal abstract class ServerResponse
-    {
-        public enum ResponseType
-        {
-            // The client and server are using incompatible protocol versions.
-            MismatchedVersion,
-
-            // The build request completed on the server and the results are contained
-            // in the message. 
-            Completed,
-
-            // The shutdown request completed and the server process information is 
-            // contained in the message. 
-            Shutdown,
-
-            // The request was rejected by the server.  
-            Rejected,
-        }
-
-        public abstract ResponseType Type { get; }
-
-        public async Task WriteAsync(Stream outStream, CancellationToken cancellationToken)
-        {
-            using (var memoryStream = new MemoryStream())
-            using (var writer = new BinaryWriter(memoryStream, Encoding.Unicode))
-            {
-                // Format the response
-                ServerLogger.Log("Formatting Response");
-                writer.Write((int)Type);
-
-                AddResponseBody(writer);
-                writer.Flush();
-
-                cancellationToken.ThrowIfCancellationRequested();
-
-                // Send the response to the client
-
-                // Write the length of the response
-                var length = checked((int)memoryStream.Length);
-
-                ServerLogger.Log("Writing response length");
-                // There is no way to know the number of bytes written to
-                // the pipe stream. We just have to assume all of them are written.
-                await outStream
-                    .WriteAsync(BitConverter.GetBytes(length), 0, 4, cancellationToken)
-                    .ConfigureAwait(false);
-
-                // Write the response
-                ServerLogger.Log("Writing response of size {0}", length);
-                memoryStream.Position = 0;
-                await memoryStream
-                    .CopyToAsync(outStream, bufferSize: length, cancellationToken: cancellationToken)
-                    .ConfigureAwait(false);
-            }
-        }
-
-        protected abstract void AddResponseBody(BinaryWriter writer);
-
-        /// <summary>
-        /// May throw exceptions if there are pipe problems.
-        /// </summary>
-        /// <param name="stream"></param>
-        /// <param name="cancellationToken"></param>
-        /// <returns></returns>
-        public static async Task<ServerResponse> ReadAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken))
-        {
-            ServerLogger.Log("Reading response length");
-            // Read the response length
-            var lengthBuffer = new byte[4];
-            await ServerProtocol.ReadAllAsync(stream, lengthBuffer, 4, cancellationToken).ConfigureAwait(false);
-            var length = BitConverter.ToUInt32(lengthBuffer, 0);
-
-            // Read the response
-            ServerLogger.Log("Reading response of length {0}", length);
-            var responseBuffer = new byte[length];
-            await ServerProtocol.ReadAllAsync(
-                stream,
-                responseBuffer,
-                responseBuffer.Length,
-                cancellationToken)
-                .ConfigureAwait(false);
-
-            using (var reader = new BinaryReader(new MemoryStream(responseBuffer), Encoding.Unicode))
-            {
-                var responseType = (ResponseType)reader.ReadInt32();
-
-                switch (responseType)
-                {
-                    case ResponseType.Completed:
-                        return CompletedServerResponse.Create(reader);
-                    case ResponseType.MismatchedVersion:
-                        return new MismatchedVersionServerResponse();
-                    case ResponseType.Shutdown:
-                        return ShutdownServerResponse.Create(reader);
-                    case ResponseType.Rejected:
-                        return new RejectedServerResponse();
-                    default:
-                        throw new InvalidOperationException("Received invalid response type from server.");
-                }
-            }
-        }
-    }
-}

+ 0 - 30
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/ShutdownServerResponse.cs

@@ -1,30 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal sealed class ShutdownServerResponse : ServerResponse
-    {
-        public readonly int ServerProcessId;
-
-        public ShutdownServerResponse(int serverProcessId)
-        {
-            ServerProcessId = serverProcessId;
-        }
-
-        public override ResponseType Type => ResponseType.Shutdown;
-
-        protected override void AddResponseBody(BinaryWriter writer)
-        {
-            writer.Write(ServerProcessId);
-        }
-
-        public static ShutdownServerResponse Create(BinaryReader reader)
-        {
-            var serverProcessId = reader.ReadInt32();
-            return new ShutdownServerResponse(serverProcessId);
-        }
-    }
-}

+ 0 - 170
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ShadowCopyManager.cs

@@ -1,170 +0,0 @@
-// Copyright(c) .NET Foundation.All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    // Note that this class has no thread-safety guarantees. The caller should use a lock 
-    // if concurrency is required.
-    internal class ShadowCopyManager : IDisposable
-    {
-        // Note that this class uses the *existance* of the Mutex to lock a directory.
-        //
-        // Nothing in this code actually ever acquires the Mutex, we just try to see if it exists
-        // already.
-        private readonly Mutex _mutex;
-
-        private int _counter;
-
-        public ShadowCopyManager(string baseDirectory = null)
-        {
-            BaseDirectory = baseDirectory ?? Path.Combine(Path.GetTempPath(), "Razor", "ShadowCopy");
-
-            var guid = Guid.NewGuid().ToString("N").ToLowerInvariant();
-            UniqueDirectory = Path.Combine(BaseDirectory, guid);
-
-            _mutex = new Mutex(initiallyOwned: false, name: guid);
-
-            Directory.CreateDirectory(UniqueDirectory);
-        }
-
-        public string BaseDirectory { get; }
-
-        public string UniqueDirectory { get; }
-
-        public string AddAssembly(string filePath)
-        {
-            var assemblyDirectory = CreateUniqueDirectory();
-
-            var destination = Path.Combine(assemblyDirectory, Path.GetFileName(filePath));
-            CopyFile(filePath, destination);
-            
-            var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
-            var resourcesNameWithoutExtension = fileNameWithoutExtension + ".resources";
-            var resourcesNameWithExtension = resourcesNameWithoutExtension + ".dll";
-
-            foreach (var directory in Directory.EnumerateDirectories(Path.GetDirectoryName(filePath)))
-            {
-                var directoryName = Path.GetFileName(directory);
-
-                var resourcesPath = Path.Combine(directory, resourcesNameWithExtension);
-                if (File.Exists(resourcesPath))
-                {
-                    var resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithExtension);
-                    CopyFile(resourcesPath, resourcesShadowCopyPath);
-                }
-
-                resourcesPath = Path.Combine(directory, resourcesNameWithoutExtension, resourcesNameWithExtension);
-                if (File.Exists(resourcesPath))
-                {
-                    var resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithoutExtension, resourcesNameWithExtension);
-                    CopyFile(resourcesPath, resourcesShadowCopyPath);
-                }
-            }
-
-            return destination;
-        }
-
-        public void Dispose()
-        {
-            _mutex.ReleaseMutex();
-        }
-
-        public Task PurgeUnusedDirectoriesAsync()
-        {
-            return Task.Run((Action)PurgeUnusedDirectories);
-        }
-
-        private string CreateUniqueDirectory()
-        {
-            var id = _counter++;
-
-            var directory = Path.Combine(UniqueDirectory, id.ToString(CultureInfo.InvariantCulture));
-            Directory.CreateDirectory(directory);
-            return directory;
-        }
-
-        private void CopyFile(string originalPath, string shadowCopyPath)
-        {
-            var directory = Path.GetDirectoryName(shadowCopyPath);
-            Directory.CreateDirectory(directory);
-
-            File.Copy(originalPath, shadowCopyPath);
-
-            MakeWritable(new FileInfo(shadowCopyPath));
-        }
-
-        private void MakeWritable(string directoryPath)
-        {
-            var directory = new DirectoryInfo(directoryPath);
-
-            foreach (var file in directory.EnumerateFiles(searchPattern: "*", searchOption: SearchOption.AllDirectories))
-            {
-                MakeWritable(file);
-            }
-        }
-
-        private void MakeWritable(FileInfo file)
-        {
-            try
-            {
-                if (file.IsReadOnly)
-                {
-                    file.IsReadOnly = false;
-                }
-            }
-            catch
-            {
-                // There are many reasons this could fail. Ignore it and keep going.
-            }
-        }
-
-        private void PurgeUnusedDirectories()
-        {
-            IEnumerable<string> directories;
-            try
-            {
-                directories = Directory.EnumerateDirectories(BaseDirectory);
-            }
-            catch (DirectoryNotFoundException)
-            {
-                return;
-            }
-
-            foreach (var directory in directories)
-            {
-                Mutex mutex = null;
-                try
-                {
-                    // We only want to try deleting the directory if no-one else is currently using it.
-                    //
-                    // Note that the mutex name is the name of the directory. This is OK because we're using
-                    // GUIDs as directory/mutex names.
-                    if (!Mutex.TryOpenExisting(Path.GetFileName(directory).ToLowerInvariant(), out mutex))
-                    {
-                        MakeWritable(directory);
-                        Directory.Delete(directory, recursive: true);
-                    }
-                }
-                catch
-                {
-                    // If something goes wrong we will leave it to the next run to clean up.
-                    // Just swallow the exception and move on.
-                }
-                finally
-                {
-                    if (mutex != null)
-                    {
-                        mutex.Dispose();
-                    }
-                }
-            }
-        }
-    }
-}

+ 0 - 97
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ShutdownCommand.cs

@@ -1,97 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Diagnostics;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.Extensions.CommandLineUtils;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal class ShutdownCommand : CommandBase
-    {
-        public ShutdownCommand(Application parent)
-            : base(parent, "shutdown")
-        {
-            Pipe = Option("-p|--pipe", "name of named pipe", CommandOptionType.SingleValue);
-            Wait = Option("-w|--wait", "wait for shutdown", CommandOptionType.NoValue);
-        }
-
-        public CommandOption Pipe { get; }
-
-        public CommandOption Wait { get; }
-
-        protected override bool ValidateArguments()
-        {
-            if (string.IsNullOrEmpty(Pipe.Value()))
-            {
-                Pipe.Values.Add(PipeName.ComputeDefault());
-            }
-
-            return true;
-        }
-
-        protected async override Task<int> ExecuteCoreAsync()
-        {
-            if (!IsServerRunning())
-            {
-                // server isn't running right now
-                Out.Write("Server is not running.");
-                return 0;
-            }
-
-            try
-            {
-                using (var client = await Client.ConnectAsync(Pipe.Value(), timeout: TimeSpan.FromSeconds(5), cancellationToken: Cancelled))
-                {
-                    if (client == null)
-                    {
-                        throw new InvalidOperationException("Couldn't connect to the server.");
-                    }
-
-                    var request = ServerRequest.CreateShutdown();
-                    await request.WriteAsync(client.Stream, Cancelled).ConfigureAwait(false);
-
-                    var response = ((ShutdownServerResponse)await ServerResponse.ReadAsync(client.Stream, Cancelled));
-
-                    if (Wait.HasValue())
-                    {
-                        try
-                        {
-                            var process = Process.GetProcessById(response.ServerProcessId);
-                            process.WaitForExit();
-                        }
-                        catch (Exception ex)
-                        {
-                            // There is an inherent race here with the server process.  If it has already shutdown
-                            // by the time we try to access it then the operation has succeeded.
-                            Error.Write(ex);
-                        }
-
-                        Out.Write("Server pid:{0} shut down completed.", response.ServerProcessId);
-                    }
-                }
-            }
-            catch (Exception ex) when (IsServerRunning())
-            {
-                // Ignore an exception that occurred while the server was shutting down.
-                Error.Write(ex);
-            }
-
-            return 0;
-        }
-
-        private bool IsServerRunning()
-        {
-            if (Mutex.TryOpenExisting(MutexName.GetServerMutexName(Pipe.Value()), out var mutex))
-            {
-                mutex.Dispose();
-                return true;
-            }
-
-            return false;
-        }
-    }
-}

+ 0 - 3
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/runtimeconfig.template.json

@@ -1,3 +0,0 @@
-{
-    "rollForwardOnNoCandidateFx": 2
-}

+ 0 - 49
src/Razor/Microsoft.AspNetCore.Razor.Tools/src/rzc.csproj

@@ -1,49 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
-  <PropertyGroup>
-    <Description>Razor is a markup syntax for adding server-side logic to web pages. This assembly contains infrastructure supporting Razor MSBuild integration.</Description>
-    <TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework>
-    <OutputType>Exe</OutputType>
-    <AssemblyName>rzc</AssemblyName>
-
-    <!-- This is not a package, it is part of Razor SDK. -->
-    <IsPackable>false</IsPackable>
-    <IsShipping>false</IsShipping>
-
-    <!-- Don't produce rzc.exe -->
-    <UseAppHost>false</UseAppHost>
-    <RuntimeIdentifier />
-
-    <!-- Need to build this project in source build -->
-    <ExcludeFromSourceBuild>false</ExcludeFromSourceBuild>
-  </PropertyGroup>
-
-  <ItemGroup>
-    <Compile Include="$(SharedSourceRoot)RazorShared\TagHelperDescriptorJsonConverter.cs">
-      <Link>Shared\TagHelperDescriptorJsonConverter.cs</Link>
-    </Compile>
-    <Compile Include="$(SharedSourceRoot)RazorShared\RazorDiagnosticJsonConverter.cs">
-      <Link>Shared\RazorDiagnosticJsonConverter.cs</Link>
-    </Compile>
-    <Compile Include="$(SharedSourceRoot)RazorShared\JsonReaderExtensions.cs">
-      <Link>Shared\JsonReaderExtensions.cs</Link>
-    </Compile>
-    <Compile Include="$(SharedSourceRoot)CommandLineUtils\**\*.cs" />
-  </ItemGroup>
-
-  <ItemGroup>
-    <Reference Include="Microsoft.CodeAnalysis.Razor" />
-    <Reference Include="Microsoft.Css.Parser" />
-    <Reference Include="Newtonsoft.Json" />
-  </ItemGroup>
-
-  <!-- This makes it so that the runtimeconfig.json is included as part of the build output of the project that references this project. -->
-  <Target Name="PreserveRuntimeConfig" BeforeTargets="GetCopyToOutputDirectoryItems">
-    <ItemGroup>
-      <AllItemsFullPathWithTargetPath Include="$(ProjectRuntimeConfigFilePath)">
-        <TargetPath>$(ProjectRuntimeConfigFileName)</TargetPath>
-        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
-      </AllItemsFullPathWithTargetPath>
-    </ItemGroup>
-  </Target>
-</Project>

+ 0 - 81
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/CompositeRazorProjectFileSystemTest.cs

@@ -1,81 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Linq;
-using Microsoft.AspNetCore.Razor.Language;
-using Moq;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    public class CompositeRazorProjectFileSystemTest
-    {
-        [Fact]
-        public void EnumerateItems_ReturnsResultsFromAllFileSystems()
-        {
-            // Arrange
-            var basePath = "base-path";
-            var file1 = new TestRazorProjectItem("file1");
-            var file2 = new TestRazorProjectItem("file2");
-            var file3 = new TestRazorProjectItem("file3");
-            var fileSystem1 = Mock.Of<RazorProjectFileSystem>(
-                f => f.EnumerateItems(basePath) == new[] { file1 });
-            var fileSystem2 = Mock.Of<RazorProjectFileSystem>(
-                f => f.EnumerateItems(basePath) == Enumerable.Empty<RazorProjectItem>());
-            var fileSystem3 = Mock.Of<RazorProjectFileSystem>(
-                f => f.EnumerateItems(basePath) == new[] { file2, file3, });
-
-            var compositeRazorProjectFileSystem = new CompositeRazorProjectFileSystem(new[] { fileSystem1, fileSystem2, fileSystem3 });
-
-            // Act
-            var result = compositeRazorProjectFileSystem.EnumerateItems(basePath);
-
-            // Assert
-            Assert.Equal(new[] { file1, file2, file3 }, result);
-        }
-
-        [Fact]
-        public void EnumerateItems_ReturnsEmptySequence_IfNoFileSystemReturnsResults()
-        {
-            // Arrange
-            var basePath = "base-path";
-            var fileSystem1 = Mock.Of<RazorProjectFileSystem>(
-                f => f.EnumerateItems(basePath) == Enumerable.Empty<RazorProjectItem>());
-            var fileSystem2 = Mock.Of<RazorProjectFileSystem>(
-                f => f.EnumerateItems(basePath) == Enumerable.Empty<RazorProjectItem>());
-
-            var compositeRazorProjectFileSystem = new CompositeRazorProjectFileSystem(new[] { fileSystem1, fileSystem2 });
-
-            // Act
-            var result = compositeRazorProjectFileSystem.EnumerateItems(basePath);
-
-            // Assert
-            Assert.Empty(result);
-        }
-
-        [Fact]
-        public void GetItem_ReturnsFirstInstanceThatExists()
-        {
-            // Arrange
-            var basePath = "base-path";
-            var filePath = "file-path";
-            var file1 = new NotFoundProjectItem(basePath, filePath, fileKind: null);
-            var file2 = new TestRazorProjectItem(filePath);
-            RazorProjectItem nullItem = null;
-            var fileSystem1 = Mock.Of<RazorProjectFileSystem>(
-                f => f.GetItem(filePath, null) == file1);
-            var fileSystem2 = Mock.Of<RazorProjectFileSystem>(
-                f => f.GetItem(filePath, null) == nullItem);
-            var fileSystem3 = Mock.Of<RazorProjectFileSystem>(
-                f => f.GetItem(filePath, null) == file2);
-
-            var compositeRazorProjectFileSystem = new CompositeRazorProjectFileSystem(new[] { fileSystem1, fileSystem2, fileSystem3 });
-
-            // Act
-            var result = compositeRazorProjectFileSystem.GetItem(filePath, fileKind: null);
-
-            // Assert
-            Assert.Same(file2, result);
-        }
-    }
-}

+ 0 - 120
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/ConcurrentLruCacheTest.cs

@@ -1,120 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    public class ConcurrentLruCacheTest
-    {
-        [Fact]
-        public void ConcurrentLruCache_HoldsCapacity()
-        {
-            // Arrange
-            var input = GetKeyValueArray(Enumerable.Range(1, 3));
-            var expected = input.Reverse();
-
-            // Act
-            var cache = new ConcurrentLruCache<int, int>(input);
-
-            // Assert
-            Assert.Equal(expected, cache.TestingEnumerable);
-        }
-
-        [Fact]
-        public void Add_ThrowsIfKeyExists()
-        {
-            // Arrange
-            var input = GetKeyValueArray(Enumerable.Range(1, 3));
-            var cache = new ConcurrentLruCache<int, int>(input);
-
-            // Act & Assert
-            var exception = Assert.Throws<ArgumentException>(() => cache.Add(1, 1));
-            Assert.StartsWith("Key already exists", exception.Message);
-        }
-
-        [Fact]
-        public void GetOrAdd_AddsIfKeyDoesNotExist()
-        {
-            // Arrange
-            var input = GetKeyValueArray(Enumerable.Range(1, 3));
-            var expected = GetKeyValueArray(Enumerable.Range(2, 3)).Reverse();
-            var cache = new ConcurrentLruCache<int, int>(input);
-
-            // Act
-            cache.GetOrAdd(4, 4);
-
-            // Assert
-            Assert.Equal(expected, cache.TestingEnumerable);
-        }
-
-        [Fact]
-        public void Remove_RemovesEntry()
-        {
-            // Arrange
-            var input = GetKeyValueArray(Enumerable.Range(1, 3));
-            var expected = GetKeyValueArray(Enumerable.Range(1, 2)).Reverse();
-            var cache = new ConcurrentLruCache<int, int>(input);
-
-            // Act
-            var result = cache.Remove(3);
-
-            // Assert
-            Assert.True(result);
-            Assert.Equal(expected, cache.TestingEnumerable);
-        }
-
-        [Fact]
-        public void Remove_KeyNotFound_ReturnsFalse()
-        {
-            // Arrange
-            var input = GetKeyValueArray(Enumerable.Range(1, 3));
-            var cache = new ConcurrentLruCache<int, int>(input);
-
-            // Act
-            var result = cache.Remove(4);
-
-            // Assert
-            Assert.False(result);
-        }
-
-        [Fact]
-        public void Add_NoRead_EvictsLastNode()
-        {
-            // Arrange
-            var input = GetKeyValueArray(Enumerable.Range(1, 3));
-            var expected = GetKeyValueArray(Enumerable.Range(2, 3)).Reverse();
-            var cache = new ConcurrentLruCache<int, int>(input);
-
-            // Act
-            cache.Add(4, 4);
-
-            // Assert
-            Assert.Equal(expected, cache.TestingEnumerable);
-        }
-
-        [Fact]
-        public void Add_ReadLastNode_EvictsSecondOldestNode()
-        {
-            // Arrange
-            var input = GetKeyValueArray(Enumerable.Range(1, 3));
-            var expected = GetKeyValueArray(new int[] { 4, 1, 3 });
-            var cache = new ConcurrentLruCache<int, int>(input);
-
-            // Act
-            cache.GetOrAdd(1, 1); // Read to make this MRU
-            cache.Add(4, 4); // Add a new node
-
-            // Assert
-            Assert.Equal(expected, cache.TestingEnumerable);
-        }
-
-        private KeyValuePair<int, int>[] GetKeyValueArray(IEnumerable<int> inputArray)
-        {
-            return inputArray.Select(v => new KeyValuePair<int, int>(v, v)).ToArray();
-        }
-    }
-}

+ 0 - 128
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/DefaultExtensionAssemblyLoaderTest.cs

@@ -1,128 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using System.Text;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    public class DefaultExtensionAssemblyLoaderTest
-    {
-        [Fact]
-        public void LoadFromPath_CanLoadAssembly()
-        {
-            using (var directory = TempDirectory.Create())
-            {
-                // Arrange
-                var alphaFilePath = LoaderTestResources.Alpha.WriteToFile(directory.DirectoryPath, "Alpha.dll");
-
-                var loader = new TestDefaultExtensionAssemblyLoader(Path.Combine(directory.DirectoryPath, "shadow"));
-
-                // Act
-                var assembly = loader.LoadFromPath(alphaFilePath);
-
-                // Assert
-                Assert.NotNull(assembly);
-            }
-        }
-
-        [Fact]
-        public void LoadFromPath_DoesNotAddDuplicates_AfterLoadingByName()
-        {
-            using (var directory = TempDirectory.Create())
-            {
-                // Arrange
-                var alphaFilePath = LoaderTestResources.Alpha.WriteToFile(directory.DirectoryPath, "Alpha.dll");
-                var alphaFilePath2 = LoaderTestResources.Alpha.WriteToFile(directory.DirectoryPath, "Alpha2.dll");
-
-                var loader = new TestDefaultExtensionAssemblyLoader(Path.Combine(directory.DirectoryPath, "shadow"));
-                loader.AddAssemblyLocation(alphaFilePath);
-
-                var assembly1 = loader.Load("Alpha");
-
-                // Act
-                var assembly2 = loader.LoadFromPath(alphaFilePath2);
-
-                // Assert
-                Assert.Same(assembly1, assembly2);
-            }
-        }
-
-        [Fact]
-        public void LoadFromPath_DoesNotAddDuplicates_AfterLoadingByPath()
-        {
-            using (var directory = TempDirectory.Create())
-            {
-                // Arrange
-                var alphaFilePath = LoaderTestResources.Alpha.WriteToFile(directory.DirectoryPath, "Alpha.dll");
-                var alphaFilePath2 = LoaderTestResources.Alpha.WriteToFile(directory.DirectoryPath, "Alpha2.dll");
-
-                var loader = new TestDefaultExtensionAssemblyLoader(Path.Combine(directory.DirectoryPath, "shadow"));
-                var assembly1 = loader.LoadFromPath(alphaFilePath);
-
-                // Act
-                var assembly2 = loader.LoadFromPath(alphaFilePath2);
-
-                // Assert
-                Assert.Same(assembly1, assembly2);
-            }
-        }
-
-        [Fact]
-        public void Load_CanLoadAssemblyByName_AfterLoadingByPath()
-        {
-            using (var directory = TempDirectory.Create())
-            {
-                // Arrange
-                var alphaFilePath = LoaderTestResources.Alpha.WriteToFile(directory.DirectoryPath, "Alpha.dll");
-
-                var loader = new TestDefaultExtensionAssemblyLoader(Path.Combine(directory.DirectoryPath, "shadow"));
-                var assembly1 = loader.LoadFromPath(alphaFilePath);
-
-                // Act
-                var assembly2 = loader.Load(assembly1.FullName);
-
-                // Assert
-                Assert.Same(assembly1, assembly2);
-            }
-        }
-
-        [Fact]
-        public void LoadFromPath_WithDependencyPathsSpecified_CanLoadAssemblyDependencies()
-        {
-            using (var directory = TempDirectory.Create())
-            {
-                // Arrange
-                var alphaFilePath = LoaderTestResources.Alpha.WriteToFile(directory.DirectoryPath, "Alpha.dll");
-                var betaFilePath = LoaderTestResources.Beta.WriteToFile(directory.DirectoryPath, "Beta.dll");
-                var gammaFilePath = LoaderTestResources.Gamma.WriteToFile(directory.DirectoryPath, "Gamma.dll");
-                var deltaFilePath = LoaderTestResources.Delta.WriteToFile(directory.DirectoryPath, "Delta.dll");
-
-                var loader = new TestDefaultExtensionAssemblyLoader(Path.Combine(directory.DirectoryPath, "shadow"));
-                loader.AddAssemblyLocation(gammaFilePath);
-                loader.AddAssemblyLocation(deltaFilePath);
-
-                // Act
-                var alpha = loader.LoadFromPath(alphaFilePath);
-                var beta = loader.LoadFromPath(betaFilePath);
-
-                // Assert
-                var builder = new StringBuilder();
-
-                var a = alpha.CreateInstance("Alpha.A");
-                a.GetType().GetMethod("Write").Invoke(a, new object[] { builder, "Test A" });
-
-                var b = beta.CreateInstance("Beta.B");
-                b.GetType().GetMethod("Write").Invoke(b, new object[] { builder, "Test B" });
-                var expected = @"Delta: Gamma: Alpha: Test A
-Delta: Gamma: Beta: Test B
-";
-
-                var actual = builder.ToString();
-
-                Assert.Equal(expected, actual, ignoreLineEndingDifferences: true);
-            }
-        }
-    }
-}

+ 0 - 111
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/DefaultExtensionDependencyCheckerTest.cs

@@ -1,111 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-using Moq;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    public class DefaultExtensionDependencyCheckerTest
-    {
-        [Fact]
-        public void Check_ReturnsFalse_WithMissingDependency()
-        {
-            using (var directory = TempDirectory.Create())
-            {
-                // Arrange
-                var output = new StringWriter();
-
-                var alphaFilePath = LoaderTestResources.Alpha.WriteToFile(directory.DirectoryPath, "Alpha.dll");
-
-                var loader = new TestDefaultExtensionAssemblyLoader(Path.Combine(directory.DirectoryPath, "shadow"));
-                var checker = new DefaultExtensionDependencyChecker(loader, output, output);
-
-                // Act
-                var result = checker.Check(new[] { alphaFilePath, });
-
-                // Assert
-                Assert.False(result, "Check should not have passed: " + output.ToString());
-            }
-        }
-
-        [Fact]
-        public void Check_ReturnsTrue_WithAllDependenciesProvided()
-        {
-            using (var directory = TempDirectory.Create())
-            {
-                // Arrange
-                var output = new StringWriter();
-
-                var alphaFilePath = LoaderTestResources.Alpha.WriteToFile(directory.DirectoryPath, "Alpha.dll");
-                var betaFilePath = LoaderTestResources.Beta.WriteToFile(directory.DirectoryPath, "Beta.dll");
-                var gammaFilePath = LoaderTestResources.Gamma.WriteToFile(directory.DirectoryPath, "Gamma.dll");
-                var deltaFilePath = LoaderTestResources.Delta.WriteToFile(directory.DirectoryPath, "Delta.dll");
-
-                var loader = new TestDefaultExtensionAssemblyLoader(Path.Combine(directory.DirectoryPath, "shadow"));
-                var checker = new DefaultExtensionDependencyChecker(loader, output, output);
-
-                // Act
-                var result = checker.Check(new[] { alphaFilePath, betaFilePath, gammaFilePath, deltaFilePath, });
-
-                // Assert
-                Assert.True(result, "Check should have passed: " + output.ToString());
-            }
-        }
-
-        [Fact]
-        public void Check_ReturnsFalse_WhenAssemblyHasDifferentMVID()
-        {
-            using (var directory = TempDirectory.Create())
-            {
-                // Arrange
-                var output = new StringWriter();
-
-                // Load Beta.dll from the future Alpha.dll path to prime the assembly loader
-                var alphaFilePath = LoaderTestResources.Beta.WriteToFile(directory.DirectoryPath, "Alpha.dll");
-                var betaFilePath = LoaderTestResources.Beta.WriteToFile(directory.DirectoryPath, "Beta.dll");
-                var gammaFilePath = LoaderTestResources.Gamma.WriteToFile(directory.DirectoryPath, "Gamma.dll");
-                var deltaFilePath = LoaderTestResources.Delta.WriteToFile(directory.DirectoryPath, "Delta.dll");
-
-                var loader = new TestDefaultExtensionAssemblyLoader(Path.Combine(directory.DirectoryPath, "shadow"));
-                var checker = new DefaultExtensionDependencyChecker(loader, output, output);
-
-                // This will cause the loader to cache some inconsistent information.
-                loader.LoadFromPath(alphaFilePath);
-                LoaderTestResources.Alpha.WriteToFile(directory.DirectoryPath, "Alpha.dll");
-
-                // Act
-                var result = checker.Check(new[] { alphaFilePath, gammaFilePath, deltaFilePath, });
-
-                // Assert
-                Assert.False(result, "Check should not have passed: " + output.ToString());
-            }
-        }
-
-        [Fact]
-        public void Check_ReturnsFalse_WhenLoaderThrows()
-        {
-            using (var directory = TempDirectory.Create())
-            {
-                // Arrange
-                var output = new StringWriter();
-                
-                var deltaFilePath = LoaderTestResources.Delta.WriteToFile(directory.DirectoryPath, "Delta.dll");
-
-                var loader = new Mock<ExtensionAssemblyLoader>();
-                loader
-                    .Setup(l => l.LoadFromPath(It.IsAny<string>()))
-                    .Throws(new InvalidOperationException());
-                var checker = new DefaultExtensionDependencyChecker(loader.Object, output, output);
-
-                // Act
-                var result = checker.Check(new[] { deltaFilePath, });
-
-                // Assert
-                Assert.False(result, "Check should not have passed: " + output.ToString());
-            }
-        }
-    }
-}

+ 0 - 572
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/DefaultRequestDispatcherTest.cs

@@ -1,572 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Moq;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    public class DefaultRequestDispatcherTest
-    {
-        private static ServerRequest EmptyServerRequest => new ServerRequest(1, Array.Empty<RequestArgument>());
-
-        private static ServerResponse EmptyServerResponse => new CompletedServerResponse(
-            returnCode: 0,
-            utf8output: false,
-            output: string.Empty,
-            error: string.Empty);
-
-        [Fact]
-        public async Task AcceptConnection_ReadingRequestFails_ClosesConnection()
-        {
-            // Arrange
-            var stream = Mock.Of<Stream>();
-            var compilerHost = CreateCompilerHost();
-            var connectionHost = CreateConnectionHost();
-            var dispatcher = new DefaultRequestDispatcher(connectionHost, compilerHost, CancellationToken.None);
-            var connection = CreateConnection(stream);
-
-            // Act
-            var result = await dispatcher.AcceptConnection(
-                Task.FromResult<Connection>(connection), accept: true, cancellationToken: CancellationToken.None);
-
-            // Assert
-            Assert.Equal(ConnectionResult.Reason.CompilationNotStarted, result.CloseReason);
-        }
-
-        /// <summary>
-        /// A failure to write the results to the client is considered a client disconnection.  Any error
-        /// from when the build starts to when the write completes should be handled this way. 
-        /// </summary>
-        [Fact]
-        public async Task AcceptConnection_WritingResultsFails_ClosesConnection()
-        {
-            // Arrange
-            var memoryStream = new MemoryStream();
-            await EmptyServerRequest.WriteAsync(memoryStream, CancellationToken.None).ConfigureAwait(true);
-            memoryStream.Position = 0;
-
-            var stream = new Mock<Stream>(MockBehavior.Strict);
-            stream
-                .Setup(x => x.ReadAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
-                .Returns((byte[] array, int start, int length, CancellationToken ct) => memoryStream.ReadAsync(array, start, length, ct));
-
-            var connection = CreateConnection(stream.Object);
-            var compilerHost = CreateCompilerHost(c =>
-            {
-                c.ExecuteFunc = (req, ct) =>
-                {
-                    return EmptyServerResponse;
-                };
-            });
-            var connectionHost = CreateConnectionHost();
-            var dispatcher = new DefaultRequestDispatcher(connectionHost, compilerHost, CancellationToken.None);
-
-            // Act
-            // We expect WriteAsync to fail because the mock stream doesn't have a corresponding setup.
-            var connectionResult = await dispatcher.AcceptConnection(
-                Task.FromResult<Connection>(connection), accept: true, cancellationToken: CancellationToken.None);
-
-            // Assert
-            Assert.Equal(ConnectionResult.Reason.ClientDisconnect, connectionResult.CloseReason);
-            Assert.Null(connectionResult.KeepAlive);
-        }
-
-        /// <summary>
-        /// Ensure the Connection correctly handles the case where a client disconnects while in the 
-        /// middle of executing a request.
-        /// </summary>
-        [Fact]
-        public async Task AcceptConnection_ClientDisconnectsWhenExecutingRequest_ClosesConnection()
-        {
-            // Arrange
-            var connectionHost = Mock.Of<ConnectionHost>();
-
-            // Fake a long running task here that we can validate later on.
-            var buildTaskSource = new TaskCompletionSource<bool>();
-            var buildTaskCancellationToken = default(CancellationToken);
-            var compilerHost = CreateCompilerHost(c =>
-            {
-                c.ExecuteFunc = (req, ct) =>
-                {
-                    Task.WaitAll(buildTaskSource.Task);
-                    return EmptyServerResponse;
-                };
-            });
-
-            var dispatcher = new DefaultRequestDispatcher(connectionHost, compilerHost, CancellationToken.None);
-            var readyTaskSource = new TaskCompletionSource<bool>();
-            var disconnectTaskSource = new TaskCompletionSource<bool>();
-            var connectionTask = CreateConnectionWithEmptyServerRequest(c =>
-            {
-                c.WaitForDisconnectAsyncFunc = (ct) =>
-                {
-                    buildTaskCancellationToken = ct;
-                    readyTaskSource.SetResult(true);
-                    return disconnectTaskSource.Task;
-                };
-            });
-
-            var handleTask = dispatcher.AcceptConnection(
-                connectionTask, accept: true, cancellationToken: CancellationToken.None);
-
-            // Wait until WaitForDisconnectAsync task is actually created and running.
-            await readyTaskSource.Task.ConfigureAwait(false);
-
-            // Act
-            // Now simulate a disconnect by the client.
-            disconnectTaskSource.SetResult(true);
-            var connectionResult = await handleTask;
-            buildTaskSource.SetResult(true);
-
-            // Assert
-            Assert.Equal(ConnectionResult.Reason.ClientDisconnect, connectionResult.CloseReason);
-            Assert.Null(connectionResult.KeepAlive);
-            Assert.True(buildTaskCancellationToken.IsCancellationRequested);
-        }
-
-        [Fact]
-        public async Task AcceptConnection_AcceptFalse_RejectsBuildRequest()
-        {
-            // Arrange
-            var stream = new TestableStream();
-            await EmptyServerRequest.WriteAsync(stream.ReadStream, CancellationToken.None);
-            stream.ReadStream.Position = 0;
-
-            var connection = CreateConnection(stream);
-            var connectionHost = CreateConnectionHost();
-            var compilerHost = CreateCompilerHost();
-            var dispatcher = new DefaultRequestDispatcher(connectionHost, compilerHost, CancellationToken.None);
-
-            // Act
-            var connectionResult = await dispatcher.AcceptConnection(
-                Task.FromResult<Connection>(connection), accept: false, cancellationToken: CancellationToken.None);
-
-            // Assert
-            Assert.Equal(ConnectionResult.Reason.CompilationNotStarted, connectionResult.CloseReason);
-            stream.WriteStream.Position = 0;
-            var response = await ServerResponse.ReadAsync(stream.WriteStream).ConfigureAwait(false);
-            Assert.Equal(ServerResponse.ResponseType.Rejected, response.Type);
-        }
-
-        [Fact]
-        public async Task AcceptConnection_ShutdownRequest_ReturnsShutdownResponse()
-        {
-            // Arrange
-            var stream = new TestableStream();
-            await ServerRequest.CreateShutdown().WriteAsync(stream.ReadStream, CancellationToken.None);
-            stream.ReadStream.Position = 0;
-
-            var connection = CreateConnection(stream);
-            var connectionHost = CreateConnectionHost();
-            var compilerHost = CreateCompilerHost();
-            var dispatcher = new DefaultRequestDispatcher(connectionHost, compilerHost, CancellationToken.None);
-
-            // Act
-            var connectionResult = await dispatcher.AcceptConnection(
-                Task.FromResult<Connection>(connection), accept: true, cancellationToken: CancellationToken.None);
-
-            // Assert
-            Assert.Equal(ConnectionResult.Reason.ClientShutdownRequest, connectionResult.CloseReason);
-            stream.WriteStream.Position = 0;
-            var response = await ServerResponse.ReadAsync(stream.WriteStream).ConfigureAwait(false);
-            Assert.Equal(ServerResponse.ResponseType.Shutdown, response.Type);
-        }
-
-        [Fact]
-        public async Task AcceptConnection_ConnectionHostThrowsWhenConnecting_ClosesConnection()
-        {
-            // Arrange
-            var connectionHost = new Mock<ConnectionHost>(MockBehavior.Strict);
-            connectionHost.Setup(c => c.WaitForConnectionAsync(It.IsAny<CancellationToken>())).Throws(new Exception());
-            var compilerHost = CreateCompilerHost();
-            var dispatcher = new DefaultRequestDispatcher(connectionHost.Object, compilerHost, CancellationToken.None);
-            var connection = CreateConnection(Mock.Of<Stream>());
-
-            // Act
-            var connectionResult = await dispatcher.AcceptConnection(
-                Task.FromResult<Connection>(connection), accept: true, cancellationToken: CancellationToken.None);
-
-            // Assert
-            Assert.Equal(ConnectionResult.Reason.CompilationNotStarted, connectionResult.CloseReason);
-            Assert.Null(connectionResult.KeepAlive);
-        }
-
-        [Fact]
-        public async Task AcceptConnection_ClientConnectionThrowsWhenConnecting_ClosesConnection()
-        {
-            // Arrange
-            var compilerHost = CreateCompilerHost();
-            var connectionHost = CreateConnectionHost();
-            var dispatcher = new DefaultRequestDispatcher(connectionHost, compilerHost, CancellationToken.None);
-            var connectionTask = Task.FromException<Connection>(new Exception());
-
-            // Act
-            var connectionResult = await dispatcher.AcceptConnection(
-                connectionTask, accept: true, cancellationToken: CancellationToken.None);
-
-            // Assert
-            Assert.Equal(ConnectionResult.Reason.CompilationNotStarted, connectionResult.CloseReason);
-            Assert.Null(connectionResult.KeepAlive);
-        }
-
-        [Fact]
-        public async Task Dispatcher_ClientConnectionThrowsWhenExecutingRequest_ClosesConnection()
-        {
-            // Arrange
-            var called = false;
-            var connectionTask = CreateConnectionWithEmptyServerRequest(c =>
-            {
-                c.WaitForDisconnectAsyncFunc = (ct) =>
-                {
-                    called = true;
-                    throw new Exception();
-                };
-            });
-
-            var compilerHost = CreateCompilerHost();
-            var connectionHost = CreateConnectionHost();
-            var dispatcher = new DefaultRequestDispatcher(connectionHost, compilerHost, CancellationToken.None);
-
-            // Act
-            var connectionResult = await dispatcher.AcceptConnection(
-                connectionTask, accept: true, cancellationToken: CancellationToken.None);
-
-            // Assert
-            Assert.True(called);
-            Assert.Equal(ConnectionResult.Reason.ClientException, connectionResult.CloseReason);
-            Assert.Null(connectionResult.KeepAlive);
-        }
-
-        [Fact]
-        public void Dispatcher_NoConnections_HitsKeepAliveTimeout()
-        {
-            // Arrange
-            var keepAlive = TimeSpan.FromSeconds(3);
-            var compilerHost = CreateCompilerHost();
-            var connectionHost = new Mock<ConnectionHost>();
-            connectionHost
-                .Setup(x => x.WaitForConnectionAsync(It.IsAny<CancellationToken>()))
-                .Returns(new TaskCompletionSource<Connection>().Task);
-
-            var eventBus = new TestableEventBus();
-            var dispatcher = new DefaultRequestDispatcher(connectionHost.Object, compilerHost, CancellationToken.None, eventBus, keepAlive);
-            var startTime = DateTime.Now;
-
-            // Act
-            dispatcher.Run();
-
-            // Assert
-            Assert.True(eventBus.HitKeepAliveTimeout);
-        }
-
-        /// <summary>
-        /// Ensure server respects keep alive and shuts down after processing a single connection.
-        /// </summary>
-        [Fact]
-        public void Dispatcher_ProcessSingleConnection_HitsKeepAliveTimeout()
-        {
-            // Arrange
-            var connectionTask = CreateConnectionWithEmptyServerRequest();
-            var keepAlive = TimeSpan.FromSeconds(1);
-            var compilerHost = CreateCompilerHost(c =>
-            {
-                c.ExecuteFunc = (req, ct) =>
-                {
-                    return EmptyServerResponse;
-                };
-            });
-            var connectionHost = CreateConnectionHost(connectionTask, new TaskCompletionSource<Connection>().Task);
-
-            var eventBus = new TestableEventBus();
-            var dispatcher = new DefaultRequestDispatcher(connectionHost, compilerHost, CancellationToken.None, eventBus, keepAlive);
-
-            // Act
-            dispatcher.Run();
-
-            // Assert
-            Assert.Equal(1, eventBus.CompletedCount);
-            Assert.True(eventBus.LastProcessedTime.HasValue);
-            Assert.True(eventBus.HitKeepAliveTimeout);
-        }
-
-        /// <summary>
-        /// Ensure server respects keep alive and shuts down after processing multiple connections.
-        /// </summary>
-        [Fact]
-        public void Dispatcher_ProcessMultipleConnections_HitsKeepAliveTimeout()
-        {
-            // Arrange
-            var count = 5;
-            var list = new List<Task<Connection>>();
-            for (var i = 0; i < count; i++)
-            {
-                var connectionTask = CreateConnectionWithEmptyServerRequest();
-                list.Add(connectionTask);
-            }
-
-            list.Add(new TaskCompletionSource<Connection>().Task);
-            var connectionHost = CreateConnectionHost(list.ToArray());
-            var compilerHost = CreateCompilerHost(c =>
-            {
-                c.ExecuteFunc = (req, ct) =>
-                {
-                    return EmptyServerResponse;
-                };
-            });
-
-            var keepAlive = TimeSpan.FromSeconds(1);
-            var eventBus = new TestableEventBus();
-            var dispatcher = new DefaultRequestDispatcher(connectionHost, compilerHost, CancellationToken.None, eventBus, keepAlive);
-
-            // Act
-            dispatcher.Run();
-
-            // Assert
-            Assert.Equal(count, eventBus.CompletedCount);
-            Assert.True(eventBus.LastProcessedTime.HasValue);
-            Assert.True(eventBus.HitKeepAliveTimeout);
-        }
-
-        /// <summary>
-        /// Ensure server respects keep alive and shuts down after processing simultaneous connections.
-        /// </summary>
-        [Fact]
-        public async Task Dispatcher_ProcessSimultaneousConnections_HitsKeepAliveTimeout()
-        {
-            // Arrange
-            var totalCount = 2;
-            var readySource = new TaskCompletionSource<bool>();
-            var list = new List<TaskCompletionSource<bool>>();
-            var connectionHost = new Mock<ConnectionHost>();
-            connectionHost
-                .Setup(x => x.WaitForConnectionAsync(It.IsAny<CancellationToken>()))
-                .Returns((CancellationToken ct) =>
-                {
-                    if (list.Count < totalCount)
-                    {
-                        var source = new TaskCompletionSource<bool>();
-                        var connectionTask = CreateConnectionWithEmptyServerRequest(c =>
-                        {
-                            // Keep the connection active until we decide to end it.
-                            c.WaitForDisconnectAsyncFunc = _ => source.Task;
-                        });
-                        list.Add(source);
-                        return connectionTask;
-                    }
-
-                    readySource.SetResult(true);
-                    return new TaskCompletionSource<Connection>().Task;
-                });
-
-            var compilerHost = CreateCompilerHost(c =>
-            {
-                c.ExecuteFunc = (req, ct) =>
-                {
-                    return EmptyServerResponse;
-                };
-            });
-
-            var eventBus = new TestableEventBus();
-            var completedCompilations = 0;
-            var allCompilationsComplete = new TaskCompletionSource<bool>();
-            eventBus.CompilationComplete += (obj, args) =>
-            {
-                if (++completedCompilations == totalCount)
-                {
-                    // All compilations have completed.
-                    allCompilationsComplete.SetResult(true);
-                }
-            };
-            var keepAlive = TimeSpan.FromSeconds(1);
-            var dispatcherTask = Task.Run(() =>
-            {
-                var dispatcher = new DefaultRequestDispatcher(connectionHost.Object, compilerHost, CancellationToken.None, eventBus, keepAlive);
-                dispatcher.Run();
-            });
-
-            // Wait for all connections to be created.
-            await readySource.Task;
-
-            // Wait for all compilations to complete.
-            await allCompilationsComplete.Task;
-
-            // Now allow all the connections to be disconnected.
-            foreach (var source in list)
-            {
-                source.SetResult(true);
-            }
-
-            // Act
-            // Now dispatcher should be in an idle state with no active connections.
-            await dispatcherTask;
-
-            // Assert
-            Assert.False(eventBus.HasDetectedBadConnection);
-            Assert.Equal(totalCount, eventBus.CompletedCount);
-            Assert.True(eventBus.LastProcessedTime.HasValue, "LastProcessedTime should have had a value.");
-            Assert.True(eventBus.HitKeepAliveTimeout, "HitKeepAliveTimeout should have been hit.");
-        }
-
-        [Fact]
-        public void Dispatcher_ClientConnectionThrows_BeginsShutdown()
-        {
-            // Arrange
-            var listenCancellationToken = default(CancellationToken);
-            var firstConnectionTask = CreateConnectionWithEmptyServerRequest(c =>
-            {
-                c.WaitForDisconnectAsyncFunc = (ct) =>
-                {
-                    listenCancellationToken = ct;
-                    return Task.Delay(Timeout.Infinite, ct).ContinueWith<Connection>(_ => null);
-                };
-            });
-            var secondConnectionTask = CreateConnectionWithEmptyServerRequest(c =>
-            {
-                c.WaitForDisconnectAsyncFunc = (ct) => throw new Exception();
-            });
-
-            var compilerHost = CreateCompilerHost();
-            var connectionHost = CreateConnectionHost(
-                firstConnectionTask,
-                secondConnectionTask,
-                new TaskCompletionSource<Connection>().Task);
-            var keepAlive = TimeSpan.FromSeconds(10);
-            var eventBus = new TestableEventBus();
-            var dispatcher = new DefaultRequestDispatcher(connectionHost, compilerHost, CancellationToken.None, eventBus, keepAlive);
-
-            // Act
-            dispatcher.Run();
-
-            // Assert
-            Assert.True(eventBus.HasDetectedBadConnection);
-            Assert.True(listenCancellationToken.IsCancellationRequested);
-        }
-
-        private static TestableConnection CreateConnection(Stream stream, string identifier = null)
-        {
-            return new TestableConnection(stream, identifier ?? "identifier");
-        }
-
-        private static async Task<Connection> CreateConnectionWithEmptyServerRequest(Action<TestableConnection> configureConnection = null)
-        {
-            var memoryStream = new MemoryStream();
-            await EmptyServerRequest.WriteAsync(memoryStream, CancellationToken.None);
-            memoryStream.Position = 0;
-            var connection = CreateConnection(memoryStream);
-            configureConnection?.Invoke(connection);
-
-            return connection;
-        }
-
-        private static ConnectionHost CreateConnectionHost(params Task<Connection>[] connections)
-        {
-            var host = new Mock<ConnectionHost>();
-            if (connections.Length > 0)
-            {
-                var index = 0;
-                host
-                    .Setup(x => x.WaitForConnectionAsync(It.IsAny<CancellationToken>()))
-                    .Returns((CancellationToken ct) => connections[index++]);
-            }
-
-            return host.Object;
-        }
-
-        private static TestableCompilerHost CreateCompilerHost(Action<TestableCompilerHost> configureCompilerHost = null)
-        {
-            var compilerHost = new TestableCompilerHost();
-            configureCompilerHost?.Invoke(compilerHost);
-
-            return compilerHost;
-        }
-
-        private class TestableCompilerHost : CompilerHost
-        {
-            internal Func<ServerRequest, CancellationToken, ServerResponse> ExecuteFunc;
-
-            public override ServerResponse Execute(ServerRequest request, CancellationToken cancellationToken)
-            {
-                if (ExecuteFunc != null)
-                {
-                    return ExecuteFunc(request, cancellationToken);
-                }
-
-                return EmptyServerResponse;
-            }
-        }
-
-        private class TestableConnection : Connection
-        {
-            internal Func<CancellationToken, Task> WaitForDisconnectAsyncFunc;
-
-            public TestableConnection(Stream stream, string identifier)
-            {
-                Stream = stream;
-                Identifier = identifier;
-                WaitForDisconnectAsyncFunc = ct => Task.Delay(Timeout.Infinite, ct);
-            }
-
-            public override Task WaitForDisconnectAsync(CancellationToken cancellationToken)
-            {
-                return WaitForDisconnectAsyncFunc(cancellationToken);
-            }
-        }
-
-        private class TestableStream : Stream
-        {
-            internal readonly MemoryStream ReadStream = new MemoryStream();
-            internal readonly MemoryStream WriteStream = new MemoryStream();
-
-            public override bool CanRead => true;
-            public override bool CanSeek => false;
-            public override bool CanWrite => true;
-            public override long Length { get { throw new NotImplementedException(); } }
-            public override long Position
-            {
-                get { throw new NotImplementedException(); }
-                set { throw new NotImplementedException(); }
-            }
-
-            public override void Flush()
-            {
-            }
-
-            public override int Read(byte[] buffer, int offset, int count)
-            {
-                return ReadStream.Read(buffer, offset, count);
-            }
-
-            public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
-            {
-                return ReadStream.ReadAsync(buffer, offset, count, cancellationToken);
-            }
-
-            public override long Seek(long offset, SeekOrigin origin)
-            {
-                throw new NotImplementedException();
-            }
-
-            public override void SetLength(long value)
-            {
-                throw new NotImplementedException();
-            }
-
-            public override void Write(byte[] buffer, int offset, int count)
-            {
-                WriteStream.Write(buffer, offset, count);
-            }
-
-            public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
-            {
-                return WriteStream.WriteAsync(buffer, offset, count, cancellationToken);
-            }
-        }
-    }
-}

+ 0 - 49
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/Infrastructure/ServerData.cs

@@ -1,49 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal sealed class ServerData : IDisposable
-    {
-        internal CancellationTokenSource CancellationTokenSource { get; }
-        internal Task<ServerStats> ServerTask { get; }
-        internal Task ListenTask { get; }
-        internal string PipeName { get; }
-
-        internal ServerData(CancellationTokenSource cancellationTokenSource, string pipeName, Task<ServerStats> serverTask, Task listenTask)
-        {
-            CancellationTokenSource = cancellationTokenSource;
-            PipeName = pipeName;
-            ServerTask = serverTask;
-            ListenTask = listenTask;
-        }
-
-        internal async Task<ServerStats> CancelAndCompleteAsync()
-        {
-            CancellationTokenSource.Cancel();
-            return await ServerTask;
-        }
-
-        internal async Task Verify(int connections, int completed)
-        {
-            var stats = await CancelAndCompleteAsync().ConfigureAwait(false);
-            Assert.Equal(connections, stats.Connections);
-            Assert.Equal(completed, stats.CompletedConnections);
-        }
-
-        public void Dispose()
-        {
-            if (!CancellationTokenSource.IsCancellationRequested)
-            {
-                CancellationTokenSource.Cancel();
-            }
-
-            ServerTask.Wait();
-        }
-    }
-}

+ 0 - 17
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/Infrastructure/ServerStats.cs

@@ -1,17 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal struct ServerStats
-    {
-        internal readonly int Connections;
-        internal readonly int CompletedConnections;
-
-        internal ServerStats(int connections, int completedConnections)
-        {
-            Connections = connections;
-            CompletedConnections = completedConnections;
-        }
-    }
-}

+ 0 - 156
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/Infrastructure/ServerUtilities.cs

@@ -1,156 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis;
-using Moq;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal static class ServerUtilities
-    {
-        internal static string DefaultClientDirectory { get; } = Path.GetDirectoryName(typeof(ServerUtilities).Assembly.Location);
-
-        internal static ServerPaths CreateBuildPaths(string workingDir, string tempDir)
-        {
-            return new ServerPaths(
-                clientDir: DefaultClientDirectory,
-                workingDir: workingDir,
-                tempDir: tempDir);
-        }
-
-        internal static ServerData CreateServer(
-            string pipeName = null,
-            CompilerHost compilerHost = null,
-            ConnectionHost connectionHost = null,
-            Action<object, EventArgs> onListening = null)
-        {
-            pipeName = pipeName ?? Guid.NewGuid().ToString();
-            compilerHost = compilerHost ?? CompilerHost.Create();
-            connectionHost = connectionHost ?? ConnectionHost.Create(pipeName);
-
-            var serverStatsSource = new TaskCompletionSource<ServerStats>();
-            var serverListenSource = new TaskCompletionSource<bool>();
-            var cts = new CancellationTokenSource();
-            var mutexName = MutexName.GetServerMutexName(pipeName);
-            var thread = new Thread(_ =>
-            {
-                var eventBus = new TestableEventBus();
-                eventBus.Listening += (sender, e) => { serverListenSource.TrySetResult(true); };
-                if (onListening != null)
-                {
-                    eventBus.Listening += (sender, e) => onListening(sender, e);
-                }
-                try
-                {
-                    RunServer(
-                        pipeName,
-                        connectionHost,
-                        compilerHost,
-                        cts.Token,
-                        eventBus,
-                        Timeout.InfiniteTimeSpan);
-                }
-                finally
-                {
-                    var serverStats = new ServerStats(connections: eventBus.ConnectionCount, completedConnections: eventBus.CompletedCount);
-                    serverStatsSource.SetResult(serverStats);
-                }
-            });
-
-            thread.Start();
-
-            // The contract of this function is that it will return once the server has started.  Spin here until
-            // we can verify the server has started or simply failed to start.
-            while (ServerConnection.WasServerMutexOpen(mutexName) != true && thread.IsAlive)
-            {
-                Thread.Yield();
-            }
-
-            return new ServerData(cts, pipeName, serverStatsSource.Task, serverListenSource.Task);
-        }
-
-        internal static async Task<ServerResponse> Send(string pipeName, ServerRequest request)
-        {
-            using (var client = await Client.ConnectAsync(pipeName, timeout: null, cancellationToken: default).ConfigureAwait(false))
-            {
-                await request.WriteAsync(client.Stream).ConfigureAwait(false);
-                return await ServerResponse.ReadAsync(client.Stream).ConfigureAwait(false);
-            }
-        }
-
-        internal static async Task<int> SendShutdown(string pipeName)
-        {
-            var response = await Send(pipeName, ServerRequest.CreateShutdown());
-            return ((ShutdownServerResponse)response).ServerProcessId;
-        }
-
-        internal static int RunServer(
-            string pipeName,
-            ConnectionHost host,
-            CompilerHost compilerHost,
-            CancellationToken cancellationToken = default,
-            EventBus eventBus = null,
-            TimeSpan? keepAlive = null)
-        {
-            var command = new TestableServerCommand(host, compilerHost, cancellationToken, eventBus, keepAlive);
-            var args = new List<string>
-            {
-                "-p",
-                pipeName
-            };
-
-            var result = command.Execute(args.ToArray());
-            return result;
-        }
-
-        private class TestableServerCommand : ServerCommand
-        {
-            private readonly ConnectionHost _host;
-            private readonly CompilerHost _compilerHost;
-            private readonly EventBus _eventBus;
-            private readonly CancellationToken _cancellationToken;
-            private readonly TimeSpan? _keepAlive;
-
-            public TestableServerCommand(
-                ConnectionHost host,
-                CompilerHost compilerHost,
-                CancellationToken ct,
-                EventBus eventBus,
-                TimeSpan? keepAlive)
-                : base(new Application(ct, Mock.Of<ExtensionAssemblyLoader>(), Mock.Of<ExtensionDependencyChecker>(), (path, properties) => Mock.Of<PortableExecutableReference>()))
-            {
-                _host = host;
-                _compilerHost = compilerHost;
-                _cancellationToken = ct;
-                _eventBus = eventBus;
-                _keepAlive = keepAlive;
-            }
-
-            protected override void ExecuteServerCore(
-                ConnectionHost host,
-                CompilerHost compilerHost,
-                CancellationToken cancellationToken,
-                EventBus eventBus,
-                TimeSpan? keepAlive = null)
-            {
-                base.ExecuteServerCore(
-                    _host ?? host,
-                    _compilerHost ?? compilerHost,
-                    _cancellationToken,
-                    _eventBus ?? eventBus,
-                    _keepAlive ?? keepAlive);
-            }
-
-            protected override FileStream WritePidFile()
-            {
-                // Disable writing PID file as it is tested separately.
-                return null;
-            }
-        }
-    }
-}

+ 0 - 64
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/Infrastructure/TestableEventBus.cs

@@ -1,64 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal class TestableEventBus : EventBus
-    {
-        public event EventHandler Listening;
-        public event EventHandler CompilationComplete;
-
-        public int ListeningCount { get; private set; }
-
-        public int ConnectionCount { get; private set; }
-
-        public int CompletedCount { get; private set; }
-
-        public DateTime? LastProcessedTime { get; private set; }
-
-        public TimeSpan? KeepAlive { get; private set; }
-
-        public bool HasDetectedBadConnection { get; private set; }
-
-        public bool HitKeepAliveTimeout { get; private set; }
-
-        public override void ConnectionListening()
-        {
-            ListeningCount++;
-            Listening?.Invoke(this, EventArgs.Empty);
-        }
-
-        public override void ConnectionReceived()
-        {
-            ConnectionCount++;
-        }
-
-        public override void ConnectionCompleted(int count)
-        {
-            CompletedCount += count;
-            LastProcessedTime = DateTime.Now;
-        }
-
-        public override void CompilationCompleted()
-        {
-            CompilationComplete?.Invoke(this, EventArgs.Empty);
-        }
-
-        public override void UpdateKeepAlive(TimeSpan timeSpan)
-        {
-            KeepAlive = timeSpan;
-        }
-
-        public override void ConnectionRudelyEnded()
-        {
-            HasDetectedBadConnection = true;
-        }
-
-        public override void KeepAliveReached()
-        {
-            HitKeepAliveTimeout = true;
-        }
-    }
-}

+ 0 - 146
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/LoaderTestResources.cs

@@ -1,146 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal static class LoaderTestResources
-    {
-        static LoaderTestResources()
-        {
-            Delta = CreateAssemblyBlob("Delta", Array.Empty<AssemblyBlob>(), @"
-using System.Text;
-
-namespace Delta
-{
-    public class D
-    {
-        public void Write(StringBuilder sb, string s)
-        {
-            sb.AppendLine(""Delta: "" + s);
-        }
-    }
-}
-");
-
-            Gamma = CreateAssemblyBlob("Gamma", new[] { Delta, }, @"
-using System.Text;
-using Delta;
-
-namespace Gamma
-{
-    public class G
-    {
-        public void Write(StringBuilder sb, string s)
-        {
-            D d = new D();
-
-            d.Write(sb, ""Gamma: "" + s);
-        }
-    }
-}
-");
-
-            Alpha = CreateAssemblyBlob("Alpha", new[] { Gamma, }, @"
-using System.Text;
-using Gamma;
-
-namespace Alpha
-{
-    public class A
-    {
-        public void Write(StringBuilder sb, string s)
-        {
-            G g = new G();
-
-            g.Write(sb, ""Alpha: "" + s);
-        }
-    }
-}
-");
-
-            Beta = CreateAssemblyBlob("Beta", new[] { Gamma, }, @"
-using System.Text;
-using Gamma;
-
-namespace Beta
-{
-    public class B
-    {
-        public void Write(StringBuilder sb, string s)
-        {
-            G g = new G();
-
-            g.Write(sb, ""Beta: "" + s);
-        }
-    }
-}
-");
-        }
-
-        public static AssemblyBlob Alpha { get; }
-
-        public static AssemblyBlob Beta { get; }
-
-        public static AssemblyBlob Delta { get; }
-
-        public static AssemblyBlob Gamma { get; }
-
-        private static AssemblyBlob CreateAssemblyBlob(string assemblyName, AssemblyBlob[] references, string text)
-        {
-            var defaultReferences = new[]
-            {
-                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
-            };
-
-            var compilation = CSharpCompilation.Create(
-                assemblyName,
-                new[] { CSharpSyntaxTree.ParseText(text) },
-                references.Select(r => r.ToMetadataReference()).Concat(defaultReferences),
-                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
-
-            using (var assemblyStream = new MemoryStream())
-            using (var symbolStream = new MemoryStream())
-            {
-                var result = compilation.Emit(assemblyStream, symbolStream);
-                Assert.Empty(result.Diagnostics);
-
-                return new AssemblyBlob(assemblyName, assemblyStream.GetBuffer(), symbolStream.GetBuffer());
-            }
-        }
-
-        public class AssemblyBlob
-        {
-            public AssemblyBlob(string assemblyName, byte[] assemblyBytes, byte[] symbolBytes)
-            {
-                AssemblyName = assemblyName;
-                AssemblyBytes = assemblyBytes;
-                SymbolBytes = symbolBytes;
-            }
-
-            public string AssemblyName { get; }
-
-            public byte[] AssemblyBytes { get; }
-
-            public byte[] SymbolBytes { get; }
-
-            public MetadataReference ToMetadataReference()
-            {
-                return MetadataReference.CreateFromImage(AssemblyBytes);
-            }
-
-            internal string WriteToFile(string directoryPath, string fileName)
-            {
-                var filePath = Path.Combine(directoryPath, fileName);
-                File.WriteAllBytes(filePath, AssemblyBytes);
-                return filePath;
-            }
-        }
-    }
-}

+ 0 - 103
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/MetadataCacheTest.cs

@@ -1,103 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    public class MetadataCacheTest
-    {
-        [Fact]
-        public void GetMetadata_AddsToCache()
-        {
-            using (var directory = TempDirectory.Create())
-            {
-                // Arrange
-                var metadataCache = new MetadataCache();
-                var assemblyFilePath = LoaderTestResources.Delta.WriteToFile(directory.DirectoryPath, "Delta.dll");
-
-                // Act
-                var result = metadataCache.GetMetadata(assemblyFilePath);
-
-                // Assert
-                Assert.NotNull(result);
-                Assert.Equal(1, metadataCache.Cache.Count);
-            }
-        }
-
-        [Fact]
-        public void GetMetadata_UsesCache()
-        {
-            using (var directory = TempDirectory.Create())
-            {
-                // Arrange
-                var metadataCache = new MetadataCache();
-                var assemblyFilePath = LoaderTestResources.Delta.WriteToFile(directory.DirectoryPath, "Delta.dll");
-
-                // Act 1
-                var result = metadataCache.GetMetadata(assemblyFilePath);
-
-                // Assert 1
-                Assert.NotNull(result);
-                Assert.Equal(1, metadataCache.Cache.Count);
-
-                // Act 2
-                var cacheResult = metadataCache.GetMetadata(assemblyFilePath);
-
-                // Assert 2
-                Assert.Same(result, cacheResult);
-                Assert.Equal(1, metadataCache.Cache.Count);
-            }
-        }
-
-        [Fact]
-        public void GetMetadata_MultipleFiles_ReturnsDifferentResultsAndAddsToCache()
-        {
-            using (var directory = TempDirectory.Create())
-            {
-                // Arrange
-                var metadataCache = new MetadataCache();
-                var assemblyFilePath1 = LoaderTestResources.Delta.WriteToFile(directory.DirectoryPath, "Delta.dll");
-                var assemblyFilePath2 = LoaderTestResources.Gamma.WriteToFile(directory.DirectoryPath, "Gamma.dll");
-
-                // Act
-                var result1 = metadataCache.GetMetadata(assemblyFilePath1);
-                var result2 = metadataCache.GetMetadata(assemblyFilePath2);
-
-                // Assert
-                Assert.NotSame(result1, result2);
-                Assert.Equal(2, metadataCache.Cache.Count);
-            }
-        }
-
-        [Fact]
-        public void GetMetadata_ReplacesCache_IfFileTimestampChanged()
-        {
-            using (var directory = TempDirectory.Create())
-            {
-                // Arrange
-                var metadataCache = new MetadataCache();
-                var assemblyFilePath = LoaderTestResources.Delta.WriteToFile(directory.DirectoryPath, "Delta.dll");
-
-                // Act 1
-                var result = metadataCache.GetMetadata(assemblyFilePath);
-
-                // Assert 1
-                Assert.NotNull(result);
-                var entry = Assert.Single(metadataCache.Cache.TestingEnumerable);
-                Assert.Same(result, entry.Value.Metadata);
-
-                // Act 2
-                // Update the timestamp of the file
-                File.SetLastWriteTimeUtc(assemblyFilePath, File.GetLastWriteTimeUtc(assemblyFilePath).AddSeconds(1));
-                var cacheResult = metadataCache.GetMetadata(assemblyFilePath);
-
-                // Assert 2
-                Assert.NotSame(result, cacheResult);
-                entry = Assert.Single(metadataCache.Cache.TestingEnumerable);
-                Assert.Same(cacheResult, entry.Value.Metadata);
-            }
-        }
-    }
-}

+ 0 - 16
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/Microsoft.AspNetCore.Razor.Tools.Test.csproj

@@ -1,16 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
-  <PropertyGroup>
-    <TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework>
-    <DefaultItemExcludes>$(DefaultItemExcludes);TestFiles\**</DefaultItemExcludes>
-
-    <!-- Tests do not work on Helix yet -->
-    <BuildHelixPayload>false</BuildHelixPayload>
-  </PropertyGroup>
-
-  <ItemGroup>
-    <Reference Include="rzc" />
-    <ProjectReference Include="..\..\test\Microsoft.AspNetCore.Razor.Test.Common\Microsoft.AspNetCore.Razor.Test.Common.csproj" />
-  </ItemGroup>
-
-</Project>

+ 0 - 45
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/MvcShim.cs

@@ -1,45 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using System.Reflection;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal static class MvcShim
-    {
-        public static readonly string AssemblyName = "Microsoft.AspNetCore.Razor.Test.MvcShim";
-
-        private static Assembly _assembly;
-        private static CSharpCompilation _baseCompilation;
-
-        public static Assembly Assembly
-        {
-            get
-            {
-                if (_assembly == null)
-                {
-                    var filePath = Path.Combine(Directory.GetCurrentDirectory(), AssemblyName + ".dll");
-                    _assembly = Assembly.LoadFrom(filePath);
-                }
-
-                return _assembly;
-            }
-        }
-
-        public static CSharpCompilation BaseCompilation
-        {
-            get
-            {
-                if (_baseCompilation == null)
-                {
-                    _baseCompilation = TestCompilation.Create(Assembly);
-                }
-
-                return _baseCompilation;
-            }
-        }
-    }
-}

+ 0 - 6
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/Properties/AssemblyInfo.cs

@@ -1,6 +0,0 @@
-// Copyright(c) .NET Foundation.All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Runtime.CompilerServices;
-
-[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]

+ 0 - 391
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/RewriteCssCommandTest.cs

@@ -1,391 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using Microsoft.AspNetCore.Razor.Language;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    public class RewriteCssCommandTest
-    {
-        [Fact]
-        public void HandlesEmptyFile()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", string.Empty, "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(string.Empty, result);
-        }
-
-        [Fact]
-        public void AddsScopeAfterSelector()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    .myclass { color: red; }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    .myclass[TestScope] { color: red; }
-", result);
-        }
-
-        [Fact]
-        public void HandlesMultipleSelectors()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    .first, .second { color: red; }
-    .third { color: blue; }
-    :root { color: green; }
-    * { color: white; }
-    #some-id { color: yellow; }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    .first[TestScope], .second[TestScope] { color: red; }
-    .third[TestScope] { color: blue; }
-    :root[TestScope] { color: green; }
-    *[TestScope] { color: white; }
-    #some-id[TestScope] { color: yellow; }
-", result);
-        }
-
-        [Fact]
-        public void HandlesComplexSelectors()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    .first div > li, body .second:not(.fancy)[attr~=whatever] { color: red; }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    .first div > li[TestScope], body .second:not(.fancy)[attr~=whatever][TestScope] { color: red; }
-", result);
-        }
-
-        [Fact]
-        public void HandlesSpacesAndCommentsWithinSelectors()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    .first /* space at end {} */ div , .myclass /* comment at end */ { color: red; }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    .first /* space at end {} */ div[TestScope] , .myclass[TestScope] /* comment at end */ { color: red; }
-", result);
-        }
-
-        [Fact]
-        public void HandlesPseudoClasses()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    a:fake-pseudo-class { color: red; }
-    a:focus b:hover { color: green; }
-    tr:nth-child(4n + 1) { color: blue; }
-    a:has(b > c) { color: yellow; }
-    a:last-child > ::deep b { color: pink; }
-    a:not(#something) { color: purple; }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    a:fake-pseudo-class[TestScope] { color: red; }
-    a:focus b:hover[TestScope] { color: green; }
-    tr:nth-child(4n + 1)[TestScope] { color: blue; }
-    a:has(b > c)[TestScope] { color: yellow; }
-    a:last-child[TestScope] >  b { color: pink; }
-    a:not(#something)[TestScope] { color: purple; }
-", result);
-        }
-
-        [Fact]
-        public void HandlesPseudoElements()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    a::before { content: ""✋""; }
-    a::after::placeholder { content: ""🐯""; }
-    custom-element::part(foo) { content: ""🤷‍""; }
-    a::before > ::deep another { content: ""👞""; }
-    a::fake-PsEuDo-element { content: ""🐔""; }
-    ::selection { content: ""😾""; }
-    other, ::selection { content: ""👂""; }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    a[TestScope]::before { content: ""✋""; }
-    a[TestScope]::after::placeholder { content: ""🐯""; }
-    custom-element[TestScope]::part(foo) { content: ""🤷‍""; }
-    a[TestScope]::before >  another { content: ""👞""; }
-    a[TestScope]::fake-PsEuDo-element { content: ""🐔""; }
-    [TestScope]::selection { content: ""😾""; }
-    other[TestScope], [TestScope]::selection { content: ""👂""; }
-", result);
-        }
-
-        [Fact]
-        public void HandlesSingleColonPseudoElements()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    a:after { content: ""x""; }
-    a:before { content: ""x""; }
-    a:first-letter { content: ""x""; }
-    a:first-line { content: ""x""; }
-    a:AFTER { content: ""x""; }
-    a:not(something):before { content: ""x""; }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    a[TestScope]:after { content: ""x""; }
-    a[TestScope]:before { content: ""x""; }
-    a[TestScope]:first-letter { content: ""x""; }
-    a[TestScope]:first-line { content: ""x""; }
-    a[TestScope]:AFTER { content: ""x""; }
-    a:not(something)[TestScope]:before { content: ""x""; }
-", result);
-        }
-
-        [Fact]
-        public void RespectsDeepCombinator()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    .first ::deep .second { color: red; }
-    a ::deep b, c ::deep d { color: blue; }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    .first[TestScope]  .second { color: red; }
-    a[TestScope]  b, c[TestScope]  d { color: blue; }
-", result);
-        }
-
-        [Fact]
-        public void RespectsDeepCombinatorWithDirectDescendant()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    a  >  ::deep b { color: red; }
-    c ::deep  >  d { color: blue; }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    a[TestScope]  >   b { color: red; }
-    c[TestScope]   >  d { color: blue; }
-", result);
-        }
-
-        [Fact]
-        public void RespectsDeepCombinatorWithAdjacentSibling()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    a + ::deep b { color: red; }
-    c ::deep + d { color: blue; }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    a[TestScope] +  b { color: red; }
-    c[TestScope]  + d { color: blue; }
-", result);
-        }
-
-        [Fact]
-        public void RespectsDeepCombinatorWithGeneralSibling()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    a ~ ::deep b { color: red; }
-    c ::deep ~ d { color: blue; }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    a[TestScope] ~  b { color: red; }
-    c[TestScope]  ~ d { color: blue; }
-", result);
-        }
-
-        [Fact]
-        public void IgnoresMultipleDeepCombinators()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    .first ::deep .second ::deep .third { color:red; }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    .first[TestScope]  .second ::deep .third { color:red; }
-", result);
-        }
-
-        [Fact]
-        public void RespectsDeepCombinatorWithSpacesAndComments()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    .a .b /* comment ::deep 1 */  ::deep  /* comment ::deep 2 */  .c /* ::deep */ .d { color: red; }
-    ::deep * { color: blue; } /* Leading deep combinator */
-    another ::deep { color: green }  /* Trailing deep combinator */
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    .a .b[TestScope] /* comment ::deep 1 */    /* comment ::deep 2 */  .c /* ::deep */ .d { color: red; }
-    [TestScope] * { color: blue; } /* Leading deep combinator */
-    another[TestScope]  { color: green }  /* Trailing deep combinator */
-", result);
-        }
-
-        [Fact]
-        public void HandlesAtBlocks()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    .myclass { color: red; }
-
-    @media only screen and (max-width: 600px) {
-        .another .thing {
-            content: 'This should not be a selector: .fake-selector { color: red }'
-        }
-    }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    .myclass[TestScope] { color: red; }
-
-    @media only screen and (max-width: 600px) {
-        .another .thing[TestScope] {
-            content: 'This should not be a selector: .fake-selector { color: red }'
-        }
-    }
-", result);
-        }
-
-        [Fact]
-        public void AddsScopeToKeyframeNames()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    @keyframes my-animation { /* whatever */ }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    @keyframes my-animation-TestScope { /* whatever */ }
-", result);
-        }
-
-        [Fact]
-        public void RewritesAnimationNamesWhenMatchingKnownKeyframes()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    .myclass {
-        color: red;
-        animation: /* ignore comment */ my-animation 1s infinite;
-    }
-
-    .another-thing { animation-name: different-animation; }
-
-    h1 { animation: unknown-animation; } /* Should not be scoped */
-
-    @keyframes my-animation { /* whatever */ }
-    @keyframes different-animation { /* whatever */ }
-    @keyframes unused-animation { /* whatever */ }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    .myclass[TestScope] {
-        color: red;
-        animation: /* ignore comment */ my-animation-TestScope 1s infinite;
-    }
-
-    .another-thing[TestScope] { animation-name: different-animation-TestScope; }
-
-    h1[TestScope] { animation: unknown-animation; } /* Should not be scoped */
-
-    @keyframes my-animation-TestScope { /* whatever */ }
-    @keyframes different-animation-TestScope { /* whatever */ }
-    @keyframes unused-animation-TestScope { /* whatever */ }
-", result);
-        }
-
-        [Fact]
-        public void RewritesMultipleAnimationNames()
-        {
-            // Arrange/act
-            var result = RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    .myclass1 { animation-name: my-animation , different-animation }
-    .myclass2 { animation: 4s linear 0s alternate my-animation infinite, different-animation 0s }
-    @keyframes my-animation { }
-    @keyframes different-animation { }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Empty(diagnostics);
-            Assert.Equal(@"
-    .myclass1[TestScope] { animation-name: my-animation-TestScope , different-animation-TestScope }
-    .myclass2[TestScope] { animation: 4s linear 0s alternate my-animation-TestScope infinite, different-animation-TestScope 0s }
-    @keyframes my-animation-TestScope { }
-    @keyframes different-animation-TestScope { }
-", result);
-        }
-
-        [Fact]
-        public void RejectsImportStatements()
-        {
-            // Arrange/act
-            RewriteCssCommand.AddScopeToSelectors("file.css", @"
-    @import ""basic-import.css"";
-    @import ""import-with-media-type.css"" print;
-    @import ""import-with-media-query.css"" screen and (orientation:landscape);
-    @ImPoRt /* comment */ ""scheme://path/to/complex-import"" /* another-comment */ screen;
-    @otheratrule ""should-not-cause-error.css"";
-    /* @import ""should-be-ignored-because-it-is-in-a-comment.css""; */
-    .myclass { color: red; }
-", "TestScope", out var diagnostics);
-
-            // Assert
-            Assert.Collection(diagnostics,
-                diagnostic => Assert.Equal("file.css(2,5): Error RZ5000: @import rules are not supported within scoped CSS files because the loading order would be undefined. @import may only be placed in non-scoped CSS files.", diagnostic.ToString()),
-                diagnostic => Assert.Equal("file.css(3,5): Error RZ5000: @import rules are not supported within scoped CSS files because the loading order would be undefined. @import may only be placed in non-scoped CSS files.", diagnostic.ToString()),
-                diagnostic => Assert.Equal("file.css(4,5): Error RZ5000: @import rules are not supported within scoped CSS files because the loading order would be undefined. @import may only be placed in non-scoped CSS files.", diagnostic.ToString()),
-                diagnostic => Assert.Equal("file.css(5,5): Error RZ5000: @import rules are not supported within scoped CSS files because the loading order would be undefined. @import may only be placed in non-scoped CSS files.", diagnostic.ToString()));
-        }
-    }
-}

+ 0 - 120
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/ServerCommandTest.cs

@@ -1,120 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Diagnostics;
-using System.Globalization;
-using System.IO;
-using System.Text;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Moq;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    public class ServerCommandTest
-    {
-        [Fact]
-        public void WritePidFile_WorksAsExpected()
-        {
-            // Arrange
-            var expectedProcessId = Process.GetCurrentProcess().Id;
-            var expectedRzcPath = typeof(ServerCommand).Assembly.Location;
-            var expectedFileName = $"rzc-{expectedProcessId}";
-            var directoryPath = Path.Combine(Path.GetTempPath(), "RazorTest", Guid.NewGuid().ToString());
-            var path = Path.Combine(directoryPath, expectedFileName);
-
-            var pipeName = Guid.NewGuid().ToString();
-            var server = GetServerCommand(pipeName);
-
-            // Act & Assert
-            try
-            {
-                using (var _ = server.WritePidFile(directoryPath))
-                {
-                    Assert.True(File.Exists(path));
-
-                    // Make sure another stream can be opened while the write stream is still open.
-                    using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Write | FileShare.Delete))
-                    using (var reader = new StreamReader(fileStream, Encoding.UTF8))
-                    {
-                        var lines = reader.ReadToEnd().Split(Environment.NewLine);
-                        Assert.Equal(new[] { expectedProcessId.ToString(CultureInfo.InvariantCulture), "rzc", expectedRzcPath, pipeName }, lines);
-                    }
-                }
-
-                // Make sure the file is deleted on dispose.
-                Assert.False(File.Exists(path));
-            }
-            finally
-            {
-                // Cleanup after the test.
-                if (Directory.Exists(directoryPath))
-                {
-                    Directory.Delete(directoryPath, recursive: true);
-                }
-            }
-        }
-
-        [Fact]
-        public void GetPidFilePath_ReturnsCorrectDefaultPath()
-        {
-            // Arrange
-            var expectedPath = Path.Combine("homeDir", ".dotnet", "pids", "build");
-            var server = GetServerCommand();
-
-            // Act
-            var directoryPath = server.GetPidFilePath(getEnvironmentVariable: env =>
-            {
-                if (env == "DOTNET_BUILD_PIDFILE_DIRECTORY")
-                {
-                    return null;
-                }
-
-                return "homeDir";
-            });
-
-            // Assert
-            Assert.Equal(expectedPath, directoryPath);
-        }
-
-        [Fact]
-        public void GetPidFilePath_UsesEnvironmentVariablePathIfSpecified()
-        {
-            // Arrange
-            var expectedPath = "/Some/directory/path/";
-            var server = GetServerCommand();
-
-            // Act
-            var directoryPath = server.GetPidFilePath(getEnvironmentVariable: env => expectedPath);
-
-            // Assert
-            Assert.Equal(expectedPath, directoryPath);
-        }
-
-        [Fact]
-        public void GetPidFilePath_NullEnvironmentVariableValue_ReturnsNull()
-        {
-            // Arrange
-            var server = GetServerCommand();
-
-            // Act
-            var directoryPath = server.GetPidFilePath(getEnvironmentVariable: env => null);
-
-            // Assert
-            Assert.Null(directoryPath);
-        }
-
-        private ServerCommand GetServerCommand(string pipeName = null)
-        {
-            var application = new Application(
-                CancellationToken.None,
-                Mock.Of<ExtensionAssemblyLoader>(),
-                Mock.Of<ExtensionDependencyChecker>(),
-                (path, properties) => MetadataReference.CreateFromFile(path, properties));
-
-            return new ServerCommand(application, pipeName);
-        }
-    }
-}

+ 0 - 291
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/ServerLifecycleTest.cs

@@ -1,291 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Testing;
-using Moq;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    public class ServerLifecycleTest
-    {
-        private static ServerRequest EmptyServerRequest => new ServerRequest(1, Array.Empty<RequestArgument>());
-
-        private static ServerResponse EmptyServerResponse => new CompletedServerResponse(
-            returnCode: 0,
-            utf8output: false,
-            output: string.Empty,
-            error: string.Empty);
-
-        [Fact]
-        public void ServerStartup_MutexAlreadyAcquired_Fails()
-        {
-            // Arrange
-            var pipeName = Guid.NewGuid().ToString("N");
-            var mutexName = MutexName.GetServerMutexName(pipeName);
-            var compilerHost = new Mock<CompilerHost>(MockBehavior.Strict);
-            var host = new Mock<ConnectionHost>(MockBehavior.Strict);
-
-            // Act & Assert
-            using (var mutex = new Mutex(initiallyOwned: true, name: mutexName, createdNew: out var holdsMutex))
-            {
-                Assert.True(holdsMutex);
-                try
-                {
-                    var result = ServerUtilities.RunServer(pipeName, host.Object, compilerHost.Object);
-
-                    // Assert failure
-                    Assert.Equal(1, result);
-                }
-                finally
-                {
-                    mutex.ReleaseMutex();
-                }
-            }
-        }
-
-        [Fact]
-        public void ServerStartup_SuccessfullyAcquiredMutex()
-        {
-            // Arrange, Act & Assert
-            var pipeName = Guid.NewGuid().ToString("N");
-            var mutexName = MutexName.GetServerMutexName(pipeName);
-            var compilerHost = new Mock<CompilerHost>(MockBehavior.Strict);
-            var host = new Mock<ConnectionHost>(MockBehavior.Strict);
-            host
-                .Setup(x => x.WaitForConnectionAsync(It.IsAny<CancellationToken>()))
-                .Returns(() =>
-                {
-                    // Use a thread instead of Task to guarantee this code runs on a different
-                    // thread and we can validate the mutex state. 
-                    var source = new TaskCompletionSource<bool>();
-                    var thread = new Thread(_ =>
-                    {
-                        Mutex mutex = null;
-                        try
-                        {
-                            Assert.True(Mutex.TryOpenExisting(mutexName, out mutex));
-                            Assert.False(mutex.WaitOne(millisecondsTimeout: 0));
-                            source.SetResult(true);
-                        }
-                        catch (Exception ex)
-                        {
-                            source.SetException(ex);
-                            throw;
-                        }
-                        finally
-                        {
-                            mutex?.Dispose();
-                        }
-                    });
-
-                    // Synchronously wait here.  Don't returned a Task value because we need to 
-                    // ensure the above check completes before the server hits a timeout and 
-                    // releases the mutex. 
-                    thread.Start();
-                    source.Task.Wait();
-
-                    return new TaskCompletionSource<Connection>().Task;
-                });
-
-            var result = ServerUtilities.RunServer(pipeName, host.Object, compilerHost.Object, keepAlive: TimeSpan.FromSeconds(1));
-            Assert.Equal(0, result);
-        }
-
-        [Fact]
-        public async Task ServerRunning_ShutdownRequest_processesSuccessfully()
-        {
-            // Arrange
-            using (var serverData = ServerUtilities.CreateServer())
-            {
-                // Act
-                var serverProcessId = await ServerUtilities.SendShutdown(serverData.PipeName);
-
-                // Assert
-                Assert.Equal(Process.GetCurrentProcess().Id, serverProcessId);
-                await serverData.Verify(connections: 1, completed: 1);
-            }
-        }
-
-        /// <summary>
-        /// A shutdown request should not abort an existing compilation.  It should be allowed to run to 
-        /// completion.
-        /// </summary>
-        [Fact]
-        public async Task ServerRunning_ShutdownRequest_DoesNotAbortCompilation()
-        {
-            // Arrange
-            var startCompilationSource = new TaskCompletionSource<bool>();
-            var finishCompilationSource = new TaskCompletionSource<bool>();
-            var host = CreateCompilerHost(c => c.ExecuteFunc = (req, ct) =>
-            {
-                // At this point, the connection has been accepted and the compilation has started.
-                startCompilationSource.SetResult(true);
-
-                // We want this to keep running even after the shutdown is seen.
-                finishCompilationSource.Task.Wait();
-                return EmptyServerResponse;
-            });
-
-            using (var serverData = ServerUtilities.CreateServer(compilerHost: host))
-            {
-                var compileTask = ServerUtilities.Send(serverData.PipeName, EmptyServerRequest);
-
-                // Wait for the request to go through and trigger compilation.
-                await startCompilationSource.Task;
-
-                // Act
-                // The compilation is now in progress, send the shutdown.
-                await ServerUtilities.SendShutdown(serverData.PipeName);
-                Assert.False(compileTask.IsCompleted);
-
-                // Now let the task complete.
-                finishCompilationSource.SetResult(true);
-
-                // Assert
-                var response = await compileTask;
-                Assert.Equal(ServerResponse.ResponseType.Completed, response.Type);
-                Assert.Equal(0, ((CompletedServerResponse)response).ReturnCode);
-
-                await serverData.Verify(connections: 2, completed: 2);
-            }
-        }
-
-        /// <summary>
-        /// Multiple clients should be able to send shutdown requests to the server.
-        /// </summary>
-        [Fact]
-        public async Task ServerRunning_MultipleShutdownRequests_HandlesSuccessfully()
-        {
-            // Arrange
-            var startCompilationSource = new TaskCompletionSource<bool>();
-            var finishCompilationSource = new TaskCompletionSource<bool>();
-            var host = CreateCompilerHost(c => c.ExecuteFunc = (req, ct) =>
-            {
-                // At this point, the connection has been accepted and the compilation has started.
-                startCompilationSource.SetResult(true);
-
-                // We want this to keep running even after the shutdown is seen.
-                finishCompilationSource.Task.Wait();
-                return EmptyServerResponse;
-            });
-
-            using (var serverData = ServerUtilities.CreateServer(compilerHost: host))
-            {
-                var compileTask = ServerUtilities.Send(serverData.PipeName, EmptyServerRequest);
-
-                // Wait for the request to go through and trigger compilation.
-                await startCompilationSource.Task;
-
-                // Act
-                for (var i = 0; i < 10; i++)
-                {
-                    // The compilation is now in progress, send the shutdown.
-                    var processId = await ServerUtilities.SendShutdown(serverData.PipeName);
-                    Assert.Equal(Process.GetCurrentProcess().Id, processId);
-                    Assert.False(compileTask.IsCompleted);
-                }
-
-                // Now let the task complete.
-                finishCompilationSource.SetResult(true);
-
-                // Assert
-                var response = await compileTask;
-                Assert.Equal(ServerResponse.ResponseType.Completed, response.Type);
-                Assert.Equal(0, ((CompletedServerResponse)response).ReturnCode);
-
-                await serverData.Verify(connections: 11, completed: 11);
-            }
-        }
-
-        // https://github.com/aspnet/Razor/issues/1991
-        [ConditionalFact]
-        [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
-        public async Task ServerRunning_CancelCompilation_CancelsSuccessfully()
-        {
-            // Arrange
-            const int requestCount = 5;
-            var count = 0;
-            var completionSource = new TaskCompletionSource<bool>();
-            var host = CreateCompilerHost(c => c.ExecuteFunc = (req, ct) =>
-            {
-                if (Interlocked.Increment(ref count) == requestCount)
-                {
-                    completionSource.SetResult(true);
-                }
-
-                ct.WaitHandle.WaitOne();
-                return new RejectedServerResponse();
-            });
-
-            var semaphore = new SemaphoreSlim(1);
-            Action<object, EventArgs> onListening = (s, e) =>
-            {
-                semaphore.Release();
-            };
-            using (var serverData = ServerUtilities.CreateServer(compilerHost: host, onListening: onListening))
-            {
-                // Send all the requests.
-                var clients = new List<Client>();
-                for (var i = 0; i < requestCount; i++)
-                {
-                    // Wait for the server to start listening.
-                    await semaphore.WaitAsync(TimeSpan.FromMinutes(1));
-
-                    var client = await Client.ConnectAsync(serverData.PipeName, timeout: null, cancellationToken: default);
-                    await EmptyServerRequest.WriteAsync(client.Stream);
-                    clients.Add(client);
-                }
-
-                // Act
-                // Wait until all of the connections are being processed by the server. 
-                await completionSource.Task;
-
-                // Now cancel
-                var stats = await serverData.CancelAndCompleteAsync();
-
-                // Assert
-                Assert.Equal(requestCount, stats.Connections);
-                Assert.Equal(requestCount, count);
-
-                // Read the server response to each client.
-                foreach (var client in clients)
-                {
-                    var task = ServerResponse.ReadAsync(client.Stream);
-                    // We expect this to throw because the stream is already closed.
-                    await Assert.ThrowsAnyAsync<IOException>(() => task);
-                    client.Dispose();
-                }
-            }
-        }
-
-        private static TestableCompilerHost CreateCompilerHost(Action<TestableCompilerHost> configureCompilerHost = null)
-        {
-            var compilerHost = new TestableCompilerHost();
-            configureCompilerHost?.Invoke(compilerHost);
-
-            return compilerHost;
-        }
-
-        private class TestableCompilerHost : CompilerHost
-        {
-            internal Func<ServerRequest, CancellationToken, ServerResponse> ExecuteFunc;
-
-            public override ServerResponse Execute(ServerRequest request, CancellationToken cancellationToken)
-            {
-                if (ExecuteFunc != null)
-                {
-                    return ExecuteFunc(request, cancellationToken);
-                }
-
-                return EmptyServerResponse;
-            }
-        }
-    }
-}

+ 0 - 128
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/ServerProtocol/ServerProtocolTest.cs

@@ -1,128 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Immutable;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    public class ServerProtocolTest
-    {
-        [Fact]
-        public async Task ServerResponse_WriteRead_RoundtripsProperly()
-        {
-            // Arrange
-            var response = new CompletedServerResponse(42, utf8output: false, output: "a string", error: "an error");
-            var memoryStream = new MemoryStream();
-
-            // Act
-            await response.WriteAsync(memoryStream, CancellationToken.None);
-
-            // Assert
-            Assert.True(memoryStream.Position > 0);
-            memoryStream.Position = 0;
-            var result = (CompletedServerResponse)await ServerResponse.ReadAsync(memoryStream, CancellationToken.None);
-            Assert.Equal(42, result.ReturnCode);
-            Assert.False(result.Utf8Output);
-            Assert.Equal("a string", result.Output);
-            Assert.Equal("an error", result.ErrorOutput);
-        }
-
-        [Fact]
-        public async Task ServerRequest_WriteRead_RoundtripsProperly()
-        {
-            // Arrange
-            var request = new ServerRequest(
-                ServerProtocol.ProtocolVersion,
-                ImmutableArray.Create(
-                    new RequestArgument(RequestArgument.ArgumentId.CurrentDirectory, argumentIndex: 0, value: "directory"),
-                    new RequestArgument(RequestArgument.ArgumentId.CommandLineArgument, argumentIndex: 1, value: "file")));
-            var memoryStream = new MemoryStream();
-
-            // Act
-            await request.WriteAsync(memoryStream, CancellationToken.None);
-
-            // Assert
-            Assert.True(memoryStream.Position > 0);
-            memoryStream.Position = 0;
-            var read = await ServerRequest.ReadAsync(memoryStream, CancellationToken.None);
-            Assert.Equal(ServerProtocol.ProtocolVersion, read.ProtocolVersion);
-            Assert.Equal(2, read.Arguments.Count);
-            Assert.Equal(RequestArgument.ArgumentId.CurrentDirectory, read.Arguments[0].Id);
-            Assert.Equal(0, read.Arguments[0].ArgumentIndex);
-            Assert.Equal("directory", read.Arguments[0].Value);
-            Assert.Equal(RequestArgument.ArgumentId.CommandLineArgument, read.Arguments[1].Id);
-            Assert.Equal(1, read.Arguments[1].ArgumentIndex);
-            Assert.Equal("file", read.Arguments[1].Value);
-        }
-
-        [Fact]
-        public void CreateShutdown_CreatesCorrectShutdownRequest()
-        {
-            // Arrange & Act
-            var request = ServerRequest.CreateShutdown();
-
-            // Assert
-            Assert.Equal(2, request.Arguments.Count);
-
-            var argument1 = request.Arguments[0];
-            Assert.Equal(RequestArgument.ArgumentId.Shutdown, argument1.Id);
-            Assert.Equal(0, argument1.ArgumentIndex);
-            Assert.Equal("", argument1.Value);
-
-            var argument2 = request.Arguments[1];
-            Assert.Equal(RequestArgument.ArgumentId.CommandLineArgument, argument2.Id);
-            Assert.Equal(1, argument2.ArgumentIndex);
-            Assert.Equal("shutdown", argument2.Value);
-        }
-
-        [Fact]
-        public async Task ShutdownRequest_WriteRead_RoundtripsProperly()
-        {
-            // Arrange
-            var memoryStream = new MemoryStream();
-            var request = ServerRequest.CreateShutdown();
-
-            // Act
-            await request.WriteAsync(memoryStream, CancellationToken.None);
-
-            // Assert
-            memoryStream.Position = 0;
-            var read = await ServerRequest.ReadAsync(memoryStream, CancellationToken.None);
-
-            var argument1 = request.Arguments[0];
-            Assert.Equal(RequestArgument.ArgumentId.Shutdown, argument1.Id);
-            Assert.Equal(0, argument1.ArgumentIndex);
-            Assert.Equal("", argument1.Value);
-
-            var argument2 = request.Arguments[1];
-            Assert.Equal(RequestArgument.ArgumentId.CommandLineArgument, argument2.Id);
-            Assert.Equal(1, argument2.ArgumentIndex);
-            Assert.Equal("shutdown", argument2.Value);
-        }
-
-        [Fact]
-        public async Task ShutdownResponse_WriteRead_RoundtripsProperly()
-        {
-            // Arrange & Act 1
-            var memoryStream = new MemoryStream();
-            var response = new ShutdownServerResponse(42);
-
-            // Assert 1
-            Assert.Equal(ServerResponse.ResponseType.Shutdown, response.Type);
-
-            // Act 2
-            await response.WriteAsync(memoryStream, CancellationToken.None);
-
-            // Assert 2
-            memoryStream.Position = 0;
-            var read = await ServerResponse.ReadAsync(memoryStream, CancellationToken.None);
-            Assert.Equal(ServerResponse.ResponseType.Shutdown, read.Type);
-            var typed = (ShutdownServerResponse)read;
-            Assert.Equal(42, typed.ServerProcessId);
-        }
-    }
-}

+ 0 - 30
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/TempDirectory.cs

@@ -1,30 +0,0 @@
-// Copyright(c) .NET Foundation.All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal class TempDirectory : IDisposable
-    {
-        public static TempDirectory Create()
-        {
-            var directoryPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("n"));
-            Directory.CreateDirectory(directoryPath);
-            return new TempDirectory(directoryPath);
-        }
-
-        private TempDirectory(string directoryPath)
-        {
-            DirectoryPath = directoryPath;
-        }
-
-        public string DirectoryPath { get; }
-        
-        public void Dispose()
-        {
-            Directory.Delete(DirectoryPath, recursive: true);
-        }
-    }
-}

+ 0 - 25
src/Razor/Microsoft.AspNetCore.Razor.Tools/test/TestDefaultExtensionAssemblyLoader.cs

@@ -1,25 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using System.Reflection;
-
-namespace Microsoft.AspNetCore.Razor.Tools
-{
-    internal class TestDefaultExtensionAssemblyLoader : DefaultExtensionAssemblyLoader
-    {
-        public TestDefaultExtensionAssemblyLoader(string baseDirectory)
-            : base(baseDirectory)
-        {
-        }
-
-        protected override Assembly LoadFromPathUnsafeCore(string filePath)
-        {
-            // Force a load from streams so we don't lock the files on disk. This way we can test
-            // shadow copying without leaving a mess behind.
-            var bytes = File.ReadAllBytes(filePath);
-            var stream = new MemoryStream(bytes);
-            return LoadContext.LoadFromStream(stream);
-        }
-    }
-}

+ 0 - 193
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/ApplicationPartDiscoveryIntegrationTest.cs

@@ -1,193 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Testing;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class ApplicationPartDiscoveryIntegrationTest : MSBuildIntegrationTestBase, IClassFixture<BuildServerTestFixture>
-    {
-        public ApplicationPartDiscoveryIntegrationTest(BuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        [Fact]
-        [InitializeTestProject("AppWithP2PReference", additionalProjects: "ClassLibrary")]
-        public Task Build_ProjectWithDependencyThatReferencesMvc_AddsAttribute_WhenBuildingUsingDotnetMsbuild()
-            => Build_ProjectWithDependencyThatReferencesMvc_AddsAttribute(MSBuildProcessKind.Dotnet);
-
-        [ConditionalFact(Skip = "net5.0 TFM is not recognized on Desktop MSBuild. A VS update will be needed.")]
-        [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
-        [InitializeTestProject("AppWithP2PReference", additionalProjects: "ClassLibrary")]
-        public Task Build_ProjectWithDependencyThatReferencesMvc_AddsAttribute_WhenBuildingUsingDesktopMsbuild()
-            => Build_ProjectWithDependencyThatReferencesMvc_AddsAttribute(MSBuildProcessKind.Desktop);
-
-        private async Task Build_ProjectWithDependencyThatReferencesMvc_AddsAttribute(MSBuildProcessKind msBuildProcessKind)
-        {
-            var result = await DotnetMSBuild("Build", msBuildProcessKind: msBuildProcessKind);
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "AppWithP2PReference.MvcApplicationPartsAssemblyInfo.cs");
-            Assert.FileContains(result, Path.Combine(IntermediateOutputPath, "AppWithP2PReference.MvcApplicationPartsAssemblyInfo.cs"), "[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartAttribute(\"ClassLibrary\")]");
-            Assert.AssemblyHasAttribute(result, Path.Combine(OutputPath, "AppWithP2PReference.dll"), "Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartAttribute");
-        }
-
-        [Fact]
-        [InitializeTestProject("AppWithP2PReference", additionalProjects: "ClassLibrary")]
-        public async Task Build_ProjectWithDependencyThatReferencesMvc_DoesNotGenerateAttributeIfFlagIsReset()
-        {
-            var result = await DotnetMSBuild("Build /p:GenerateMvcApplicationPartsAssemblyAttributes=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "AppWithP2PReference.MvcApplicationPartsAssemblyInfo.cs");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_ProjectWithoutMvcReferencingDependencies_DoesNotGenerateAttribute()
-        {
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.MvcApplicationPartsAssemblyInfo.cs");
-
-            // We should produced a cache file for build incrementalism
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.MvcApplicationPartsAssemblyInfo.cache");
-        }
-
-        [Fact]
-        [InitializeTestProject("AppWithP2PReference", additionalProjects: "ClassLibrary")]
-        public async Task BuildIncrementalism_WhenApplicationPartAttributeIsGenerated()
-        {
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            var generatedAttributeFile = Path.Combine(IntermediateOutputPath, "AppWithP2PReference.MvcApplicationPartsAssemblyInfo.cs");
-            var cacheFile = Path.Combine(IntermediateOutputPath, "AppWithP2PReference.MvcApplicationPartsAssemblyInfo.cache");
-            var outputFile = Path.Combine(IntermediateOutputPath, "AppWithP2PReference.dll");
-            Assert.FileExists(result, generatedAttributeFile);
-            Assert.FileContains(result, generatedAttributeFile, "[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartAttribute(\"ClassLibrary\")]");
-
-            var generatedFilethumbPrint = GetThumbPrint(generatedAttributeFile);
-            var cacheFileThumbPrint = GetThumbPrint(cacheFile);
-            var outputFileThumbPrint = GetThumbPrint(outputFile);
-
-            await AssertIncrementalBuild();
-            await AssertIncrementalBuild();
-
-            async Task AssertIncrementalBuild()
-            {
-                result = await DotnetMSBuild("Build");
-
-                Assert.BuildPassed(result);
-
-                Assert.FileExists(result, generatedAttributeFile);
-                Assert.Equal(generatedFilethumbPrint, GetThumbPrint(generatedAttributeFile));
-                Assert.Equal(cacheFileThumbPrint, GetThumbPrint(cacheFile));
-                Assert.Equal(outputFileThumbPrint, GetThumbPrint(outputFile));
-                Assert.AssemblyHasAttribute(result, Path.Combine(OutputPath, "AppWithP2PReference.dll"), "Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartAttribute");
-            }
-        }
-
-        // Regression test for https://github.com/dotnet/aspnetcore/issues/11315
-        [Fact]
-        [InitializeTestProject("AppWithP2PReference", additionalProjects: "ClassLibrary")]
-        public async Task BuildIncrementalism_CausingRecompilation_WhenApplicationPartAttributeIsGenerated()
-        {
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            var generatedAttributeFile = Path.Combine(IntermediateOutputPath, "AppWithP2PReference.MvcApplicationPartsAssemblyInfo.cs");
-            Assert.FileExists(result, generatedAttributeFile);
-            Assert.FileContains(result, generatedAttributeFile, "[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartAttribute(\"ClassLibrary\")]");
-
-            var thumbPrint = GetThumbPrint(generatedAttributeFile);
-
-            // Touch a file in the main app which should call recompilation, but not the Mvc discovery tasks to re-run.
-            File.AppendAllText(Path.Combine(Project.DirectoryPath, "Program.cs"), " ");
-            result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, generatedAttributeFile);
-            Assert.Equal(thumbPrint, GetThumbPrint(generatedAttributeFile));
-            Assert.AssemblyHasAttribute(result, Path.Combine(OutputPath, "AppWithP2PReference.dll"), "Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartAttribute");
-        }
-
-        [Fact(Skip = "https://github.com/dotnet/aspnetcore/issues/13303")]
-        [InitializeTestProject("SimpleMvcFSharp", language: "F#", additionalProjects: "ClassLibrary")]
-        public async Task Build_ProjectWithDependencyThatReferencesMvc_AddsAttributeToNonCSharpProjects()
-        {
-            AddProjectFileContent(
-@"
-    <ItemGroup>
-        <ProjectReference Include=""..\ClassLibrary\ClassLibrary.csproj"" />
-    </ItemGroup>
-");
-
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvcFSharp.MvcApplicationPartsAssemblyInfo.fs");
-            Assert.FileContains(result, Path.Combine(IntermediateOutputPath, "SimpleMvcFSharp.MvcApplicationPartsAssemblyInfo.fs"), "<assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartAttribute(\"ClassLibrary\")>");
-            Assert.AssemblyHasAttribute(result, Path.Combine(OutputPath, "SimpleMvcFSharp.dll"), "Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartAttribute");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task BuildIncrementalism_WhenApplicationPartAttributeIsNotGenerated()
-        {
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            var generatedAttributeFile = Path.Combine(IntermediateOutputPath, "SimpleMvc.MvcApplicationPartsAssemblyInfo.cs");
-            var cacheFile = Path.Combine(IntermediateOutputPath, "SimpleMvc.MvcApplicationPartsAssemblyInfo.cache");
-            var outputFile = Path.Combine(IntermediateOutputPath, "SimpleMvc.dll");
-            Assert.FileDoesNotExist(result, generatedAttributeFile);
-            Assert.FileExists(result, cacheFile);
-
-            var cacheFilethumbPrint = GetThumbPrint(cacheFile);
-            var outputFilethumbPrint = GetThumbPrint(outputFile);
-
-            // Couple rounds of incremental builds.
-            await AssertIncrementalBuild();
-            await AssertIncrementalBuild();
-            await AssertIncrementalBuild();
-
-            async Task AssertIncrementalBuild()
-            {
-                result = await DotnetMSBuild("Build");
-
-                Assert.BuildPassed(result);
-
-                Assert.FileDoesNotExist(result, generatedAttributeFile);
-                Assert.FileExists(result, cacheFile);
-                Assert.Equal(cacheFilethumbPrint, GetThumbPrint(cacheFile));
-                Assert.Equal(outputFilethumbPrint, GetThumbPrint(outputFile));
-            }
-        }
-
-        [Fact]
-        [InitializeTestProject("AppWithP2PReference", additionalProjects: "ClassLibrary")]
-        public async Task Build_ProjectWithMissingAssemblyReference_PrintsWarning()
-        {
-            var result = await DotnetMSBuild("Build /p:BuildProjectReferences=false");
-
-            Assert.BuildFailed(result);
-
-            Assert.BuildWarning(result, "RAZORSDK1007");
-            Assert.BuildError(result, "CS0006");
-        }
-    }
-}

+ 0 - 416
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildIncrementalismTest.cs

@@ -1,416 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Runtime.InteropServices;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Testing;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class BuildIncrementalismTest : MSBuildIntegrationTestBase, IClassFixture<BuildServerTestFixture>
-    {
-        public BuildIncrementalismTest(BuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        [ConditionalFact]
-        [OSSkipCondition(OperatingSystems.MacOSX | OperatingSystems.Linux, SkipReason = "See https://github.com/aspnet/Razor/issues/2219")]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task BuildIncremental_SimpleMvc_PersistsTargetInputFile()
-        {
-            // Arrange
-            var thumbprintLookup = new Dictionary<string, FileThumbPrint>();
-
-            // Act 1
-            var result = await DotnetMSBuild("Build");
-
-            var directoryPath = Path.Combine(result.Project.DirectoryPath, IntermediateOutputPath);
-            var filesToIgnore = new[]
-            {
-                // These files are generated on every build.
-                Path.Combine(directoryPath, "SimpleMvc.csproj.CopyComplete"),
-                Path.Combine(directoryPath, "SimpleMvc.csproj.FileListAbsolute.txt"),
-            };
-
-            var files = Directory.GetFiles(directoryPath).Where(p => !filesToIgnore.Contains(p));
-            foreach (var file in files)
-            {
-                var thumbprint = GetThumbPrint(file);
-                thumbprintLookup[file] = thumbprint;
-            }
-
-            // Assert 1
-            Assert.BuildPassed(result);
-
-            // Act & Assert 2
-            for (var i = 0; i < 2; i++)
-            {
-                // We want to make sure nothing changed between multiple incremental builds.
-                using (var razorGenDirectoryLock = LockDirectory(RazorIntermediateOutputPath))
-                {
-                    result = await DotnetMSBuild("Build");
-                }
-
-                Assert.BuildPassed(result);
-                foreach (var file in files)
-                {
-                    var thumbprint = GetThumbPrint(file);
-                    Assert.Equal(thumbprintLookup[file], thumbprint);
-                }
-            }
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorGenerate_RegeneratesTagHelperInputs_IfFileChanges()
-        {
-            // Act - 1
-            var expectedTagHelperCacheContent = @"""Name"":""SimpleMvc.SimpleTagHelper""";
-            var result = await DotnetMSBuild("Build");
-            var file = Path.Combine(Project.DirectoryPath, "SimpleTagHelper.cs");
-            var tagHelperOutputCache = Path.Combine(IntermediateOutputPath, "SimpleMvc.TagHelpers.output.cache");
-            var generatedFile = Path.Combine(RazorIntermediateOutputPath, "Views", "Home", "Index.cshtml.g.cs");
-
-            // Assert - 1
-            Assert.BuildPassed(result);
-            Assert.FileContains(result, tagHelperOutputCache, expectedTagHelperCacheContent);
-            var fileThumbPrint = GetThumbPrint(generatedFile);
-
-            // Act - 2
-            // Update the source content and build. We should expect the outputs to be regenerated.
-            ReplaceContent(string.Empty, file);
-            result = await DotnetMSBuild("Build");
-
-            // Assert - 2
-            Assert.BuildPassed(result);
-            Assert.FileDoesNotContain(result, tagHelperOutputCache, @"""Name"":""SimpleMvc.SimpleTagHelper""");
-            var newThumbPrint = GetThumbPrint(generatedFile);
-            Assert.NotEqual(fileThumbPrint, newThumbPrint);
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_ErrorInGeneratedCode_ReportsMSBuildError_OnIncrementalBuild()
-        {
-            // Introducing a Razor semantic error
-            ReplaceContent("@{ // Unterminated code block", "Views", "Home", "Index.cshtml");
-
-            // Regular build
-            await VerifyError();
-
-            // Incremental build
-            await VerifyError();
-
-            async Task VerifyError()
-            {
-                var result = await DotnetMSBuild("Build");
-
-                Assert.BuildFailed(result);
-
-                var filePath = Path.Combine(Project.DirectoryPath, "Views", "Home", "Index.cshtml");
-                var location = filePath + "(1,2)";
-                if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
-                {
-                    // Absolute paths on OSX don't work well.
-                    location = null;
-                }
-
-                Assert.BuildError(result, "RZ1006", location: location);
-
-                // Compilation failed without creating the views assembly
-                Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.dll");
-                Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-
-                // File with error does not get written to disk.
-                Assert.FileDoesNotExist(result, IntermediateOutputPath, "Razor", "Views", "Home", "Index.cshtml.g.cs");
-            }
-        }
-
-        [Fact]
-        [InitializeTestProject("MvcWithComponents")]
-        public async Task BuildComponents_ErrorInGeneratedCode_ReportsMSBuildError_OnIncrementalBuild()
-        {
-            // Introducing a Razor semantic error
-            ReplaceContent("@{ // Unterminated code block", "Views", "Shared", "NavMenu.razor");
-
-            // Regular build
-            await VerifyError();
-
-            // Incremental build
-            await VerifyError();
-
-            async Task VerifyError()
-            {
-                var result = await DotnetMSBuild("Build");
-
-                Assert.BuildFailed(result);
-
-                // This needs to be relative path. Tracked by https://github.com/aspnet/Razor/issues/2187.
-                var filePath = Path.Combine(Project.DirectoryPath, "Views", "Shared", "NavMenu.razor");
-                var location = filePath + "(1,2)";
-                if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
-                {
-                    // Absolute paths on OSX don't work well.
-                    location = null;
-                }
-
-                Assert.BuildError(result, "RZ1006", location: location);
-
-                // Compilation failed without creating the views assembly
-                Assert.FileDoesNotExist(result, IntermediateOutputPath, "MvcWithComponents.dll");
-                Assert.FileDoesNotExist(result, IntermediateOutputPath, "MvcWithComponents.Views.dll");
-
-                // File with error does not get written to disk.
-                Assert.FileDoesNotExist(result, IntermediateOutputPath, "RazorComponents", "Views", "Shared", "NavMenu.razor.g.cs");
-            }
-        }
-
-        [Fact]
-        [InitializeTestProject("MvcWithComponents")]
-        public async Task BuildComponents_DoesNotRegenerateComponentDefinition_WhenDefinitionIsUnchanged()
-        {
-            // Act - 1
-            var updatedContent = "Some content";
-            var tagHelperOutputCache = Path.Combine(IntermediateOutputPath, "MvcWithComponents.TagHelpers.output.cache");
-
-            var generatedFile = Path.Combine(RazorIntermediateOutputPath, "Views", "Shared", "NavMenu.razor.g.cs");
-            var generatedDefinitionFile = Path.Combine(RazorComponentIntermediateOutputPath, "Views", "Shared", "NavMenu.razor.g.cs");
-
-            // Assert - 1
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-            var outputFile = Path.Combine(OutputPath, "MvcWithComponents.dll");
-            Assert.FileExists(result, OutputPath, "MvcWithComponents.dll");
-            var outputAssemblyThumbprint = GetThumbPrint(outputFile);
-
-            Assert.FileExists(result, generatedDefinitionFile);
-            var generatedDefinitionThumbprint = GetThumbPrint(generatedDefinitionFile);
-            Assert.FileExists(result, generatedFile);
-            var generatedFileThumbprint = GetThumbPrint(generatedFile);
-
-            Assert.FileExists(result, tagHelperOutputCache);
-            Assert.FileContains(
-                result,
-                tagHelperOutputCache,
-                @"""Name"":""MvcWithComponents.Views.Shared.NavMenu""");
-
-            var definitionThumbprint = GetThumbPrint(tagHelperOutputCache);
-
-            // Act - 2
-            ReplaceContent(updatedContent, "Views", "Shared", "NavMenu.razor");
-            result = await DotnetMSBuild("Build");
-
-            // Assert - 2
-            Assert.FileExists(result, generatedDefinitionFile);
-            // Definition file remains unchanged.
-            Assert.Equal(generatedDefinitionThumbprint, GetThumbPrint(generatedDefinitionFile));
-            Assert.FileExists(result, generatedFile);
-            // Generated file should change and include the new content.
-            Assert.NotEqual(generatedFileThumbprint, GetThumbPrint(generatedFile));
-            Assert.FileContains(result, generatedFile, updatedContent);
-
-            // TagHelper cache should remain unchanged.
-            Assert.Equal(definitionThumbprint, GetThumbPrint(tagHelperOutputCache));
-        }
-
-        [Fact]
-        [InitializeTestProject("MvcWithComponents")]
-        public async Task BuildComponents_RegeneratesComponentDefinition_WhenFilesChange()
-        {
-            // Act - 1
-            var updatedContent = "@code { [Parameter] public string AParameter { get; set; } }";
-            var tagHelperOutputCache = Path.Combine(IntermediateOutputPath, "MvcWithComponents.TagHelpers.output.cache");
-
-            var generatedFile = Path.Combine(RazorIntermediateOutputPath, "Views", "Shared", "NavMenu.razor.g.cs");
-            var generatedDefinitionFile = Path.Combine(RazorComponentIntermediateOutputPath, "Views", "Shared", "NavMenu.razor.g.cs");
-
-            // Assert - 1
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-            var outputFile = Path.Combine(OutputPath, "MvcWithComponents.dll");
-            Assert.FileExists(result, OutputPath, "MvcWithComponents.dll");
-            var outputAssemblyThumbprint = GetThumbPrint(outputFile);
-
-            Assert.FileExists(result, generatedDefinitionFile);
-            var generatedDefinitionThumbprint = GetThumbPrint(generatedDefinitionFile);
-            Assert.FileExists(result, generatedFile);
-            var generatedFileThumbprint = GetThumbPrint(generatedFile);
-
-            Assert.FileExists(result, tagHelperOutputCache);
-            Assert.FileContains(
-                result,
-                tagHelperOutputCache,
-                @"""Name"":""MvcWithComponents.Views.Shared.NavMenu""");
-
-            var definitionThumbprint = GetThumbPrint(tagHelperOutputCache);
-
-            // Act - 2
-            ReplaceContent(updatedContent, "Views", "Shared", "NavMenu.razor");
-            result = await DotnetMSBuild("Build");
-
-            // Assert - 2
-            Assert.FileExists(result, OutputPath, "MvcWithComponents.dll");
-            Assert.NotEqual(outputAssemblyThumbprint, GetThumbPrint(outputFile));
-
-            Assert.FileExists(result, generatedDefinitionFile);
-            Assert.NotEqual(generatedDefinitionThumbprint, GetThumbPrint(generatedDefinitionFile));
-            Assert.FileExists(result, generatedFile);
-            Assert.NotEqual(generatedFileThumbprint, GetThumbPrint(generatedFile));
-
-            Assert.FileExists(result, tagHelperOutputCache);
-            Assert.FileContains(
-                result,
-                tagHelperOutputCache,
-                @"""Name"":""MvcWithComponents.Views.Shared.NavMenu""");
-
-            Assert.FileContains(
-                result,
-                tagHelperOutputCache,
-                "AParameter");
-
-            Assert.NotEqual(definitionThumbprint, GetThumbPrint(tagHelperOutputCache));
-        }
-
-        [Fact]
-        [InitializeTestProject("MvcWithComponents")]
-        public async Task BuildComponents_DoesNotModifyFiles_IfFilesDoNotChange()
-        {
-            // Act - 1
-            var tagHelperOutputCache = Path.Combine(IntermediateOutputPath, "MvcWithComponents.TagHelpers.output.cache");
-
-            var file = Path.Combine(Project.DirectoryPath, "Views", "Shared", "NavMenu.razor.g.cs");
-            var generatedFile = Path.Combine(RazorIntermediateOutputPath, "Views", "Shared", "NavMenu.razor.g.cs");
-            var generatedDefinitionFile = Path.Combine(RazorComponentIntermediateOutputPath, "Views", "Shared", "NavMenu.razor.g.cs");
-
-            // Assert - 1
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-            var outputFile = Path.Combine(OutputPath, "MvcWithComponents.dll");
-            Assert.FileExists(result, OutputPath, "MvcWithComponents.dll");
-            var outputAssemblyThumbprint = GetThumbPrint(outputFile);
-
-            Assert.FileExists(result, generatedDefinitionFile);
-            var generatedDefinitionThumbprint = GetThumbPrint(generatedDefinitionFile);
-            Assert.FileExists(result, generatedFile);
-            var generatedFileThumbprint = GetThumbPrint(generatedFile);
-
-            Assert.FileExists(result, tagHelperOutputCache);
-            Assert.FileContains(
-                result,
-                tagHelperOutputCache,
-                @"""Name"":""MvcWithComponents.Views.Shared.NavMenu""");
-
-            var definitionThumbprint = GetThumbPrint(tagHelperOutputCache);
-
-            // Act - 2
-            result = await DotnetMSBuild("Build");
-
-            // Assert - 2
-            Assert.FileExists(result, OutputPath, "MvcWithComponents.dll");
-            Assert.Equal(outputAssemblyThumbprint, GetThumbPrint(outputFile));
-
-            Assert.FileExists(result, generatedDefinitionFile);
-            Assert.Equal(generatedDefinitionThumbprint, GetThumbPrint(generatedDefinitionFile));
-            Assert.FileExists(result, generatedFile);
-            Assert.Equal(generatedFileThumbprint, GetThumbPrint(generatedFile));
-
-            Assert.FileExists(result, tagHelperOutputCache);
-            Assert.FileContains(
-                result,
-                tagHelperOutputCache,
-                @"""Name"":""MvcWithComponents.Views.Shared.NavMenu""");
-
-            Assert.Equal(definitionThumbprint, GetThumbPrint(tagHelperOutputCache));
-        }
-
-        [Fact]
-        [InitializeTestProject("AppWithP2PReference", additionalProjects: "ClassLibrary")]
-        public async Task IncrementalBuild_WithP2P_WorksWhenBuildProjectReferencesIsDisabled()
-        {
-            // Simulates building the same way VS does by setting BuildProjectReferences=false.
-            // With this flag, the only target called is GetCopyToOutputDirectoryItems on the referenced project.
-            // We need to ensure that we continue providing Razor binaries and symbols as files to be copied over.
-            var result = await DotnetMSBuild(target: default);
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, OutputPath, "AppWithP2PReference.dll");
-            Assert.FileExists(result, OutputPath, "AppWithP2PReference.Views.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.Views.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.Views.pdb");
-
-            result = await DotnetMSBuild(target: "Clean", "/p:BuildProjectReferences=false");
-            Assert.BuildPassed(result);
-
-            Assert.FileDoesNotExist(result, OutputPath, "AppWithP2PReference.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "AppWithP2PReference.Views.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "ClassLibrary.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "ClassLibrary.Views.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "ClassLibrary.Views.pdb");
-
-            // dotnet msbuild /p:BuildProjectReferences=false
-            result = await DotnetMSBuild(target: default, "/p:BuildProjectReferences=false");
-
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, OutputPath, "AppWithP2PReference.dll");
-            Assert.FileExists(result, OutputPath, "AppWithP2PReference.Views.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.Views.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("ClassLibrary")]
-        public async Task Build_TouchesUpToDateMarkerFile()
-        {
-            // Remove the components so that they don't interfere with these tests
-            Directory.Delete(Path.Combine(Project.DirectoryPath, "Components"), recursive: true);
-
-            var classLibraryDll = Path.Combine(IntermediateOutputPath, "ClassLibrary.dll");
-            var classLibraryViewsDll = Path.Combine(IntermediateOutputPath, "ClassLibrary.Views.dll");
-            var markerFile = Path.Combine(IntermediateOutputPath, "ClassLibrary.csproj.CopyComplete");
-
-            var result = await DotnetMSBuild("Build");
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, classLibraryDll);
-            Assert.FileExists(result, classLibraryViewsDll);
-            Assert.FileExists(result, markerFile);
-
-            // Gather thumbprints before incremental build.
-            var classLibraryThumbPrint = GetThumbPrint(classLibraryDll);
-            var classLibraryViewsThumbPrint = GetThumbPrint(classLibraryViewsDll);
-            var markerFileThumbPrint = GetThumbPrint(markerFile);
-
-            result = await DotnetMSBuild("Build");
-            Assert.BuildPassed(result);
-
-            // Verify thumbprint file is unchanged between true incremental builds
-            Assert.Equal(classLibraryThumbPrint, GetThumbPrint(classLibraryDll));
-            Assert.Equal(classLibraryViewsThumbPrint, GetThumbPrint(classLibraryViewsDll));
-            // In practice, this should remain unchanged. However, since our tests reference
-            // binaries from other projects, this file gets updated by Microsoft.Common.targets
-            Assert.NotEqual(markerFileThumbPrint, GetThumbPrint(markerFile));
-
-            // Change a cshtml file and verify ClassLibrary.Views.dll and marker file are updated
-            File.AppendAllText(Path.Combine(Project.DirectoryPath, "Views", "_ViewImports.cshtml"), Environment.NewLine);
-
-            result = await DotnetMSBuild("Build");
-            Assert.BuildPassed(result);
-
-            Assert.Equal(classLibraryThumbPrint, GetThumbPrint(classLibraryDll));
-            Assert.NotEqual(classLibraryViewsThumbPrint, GetThumbPrint(classLibraryViewsDll));
-            Assert.NotEqual(markerFileThumbPrint, GetThumbPrint(markerFile));
-        }
-    }
-}

+ 0 - 745
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildIntegrationTest.cs

@@ -1,745 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-using System.Linq;
-using System.Runtime.InteropServices;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Testing;
-using Microsoft.Extensions.DependencyModel;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class BuildIntegrationTest : MSBuildIntegrationTestBase, IClassFixture<BuildServerTestFixture>
-    {
-        public BuildIntegrationTest(BuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public Task Build_SimpleMvc_UsingDotnetMSBuildAndWithoutBuildServer_CanBuildSuccessfully()
-            => Build_SimpleMvc_WithoutBuildServer_CanBuildSuccessfully(MSBuildProcessKind.Dotnet);
-
-        [ConditionalFact]
-        [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
-        [InitializeTestProject("SimpleMvc")]
-        public Task Build_SimpleMvc_UsingDesktopMSBuildAndWithoutBuildServer_CanBuildSuccessfully()
-            => Build_SimpleMvc_WithoutBuildServer_CanBuildSuccessfully(MSBuildProcessKind.Desktop);
-
-        // This test is identical to the ones in BuildServerIntegrationTest except this one explicitly disables the Razor build server.
-        private async Task Build_SimpleMvc_WithoutBuildServer_CanBuildSuccessfully(MSBuildProcessKind msBuildProcessKind)
-        {
-            var result = await DotnetMSBuild("Build",
-                "/p:UseRazorBuildServer=false",
-                suppressBuildServer: true,
-                msBuildProcessKind: msBuildProcessKind);
-
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, OutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, OutputPath, "SimpleMvc.pdb");
-            Assert.FileExists(result, OutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, OutputPath, "SimpleMvc.Views.pdb");
-
-            if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
-            {
-                // GetFullPath on OSX doesn't work well in travis. We end up computing a different path than will
-                // end up in the MSBuild logs.
-                Assert.BuildOutputContainsLine(result, $"SimpleMvc -> {Path.Combine(Path.GetFullPath(Project.DirectoryPath), OutputPath, "SimpleMvc.Views.dll")}");
-            }
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_SimpleMvc_NoopsWithNoFiles()
-        {
-            Directory.Delete(Path.Combine(Project.DirectoryPath, "Views"), recursive: true);
-
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, OutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, OutputPath, "SimpleMvc.pdb");
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.Views.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.Views.pdb");
-
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.Views.pdb");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.RazorTargetAssemblyInfo.cs");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_SimpleMvc_NoopsWithRazorCompileOnBuild_False()
-        {
-            var result = await DotnetMSBuild("Build", "/p:RazorCompileOnBuild=false");
-
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, OutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, OutputPath, "SimpleMvc.pdb");
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.Views.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_ErrorInGeneratedCode_ReportsMSBuildError()
-        {
-            // Introducing a C# semantic error
-            ReplaceContent("@{ var foo = \"\".Substring(\"bleh\"); }", "Views", "Home", "Index.cshtml");
-
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildFailed(result);
-
-            // Verifying that the error correctly gets mapped to the original source
-            var filePath = Path.Combine(Project.DirectoryPath, "Views", "Home", "Index.cshtml");
-            var location = filePath + "(1,27)";
-            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
-            {
-                // Absolute paths on OSX don't work well.
-                location = null;
-            }
-            Assert.BuildError(result, "CS1503", location);
-
-            // Compilation failed without creating the views assembly
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.dll");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimplePages")]
-        public async Task Build_Works_WhenFilesAtDifferentPathsHaveSameNamespaceHierarchy()
-        {
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimplePages.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimplePages.Views.dll");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_RazorOutputPath_SetToNonDefault()
-        {
-            var customOutputPath = Path.Combine("bin", Configuration, Project.TargetFramework, "Razor");
-            var result = await DotnetMSBuild("Build", $"/p:RazorOutputPath={customOutputPath}");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.pdb");
-
-            Assert.FileExists(result, customOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, customOutputPath, "SimpleMvc.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_MvcRazorOutputPath_SetToNonDefault()
-        {
-            var customOutputPath = Path.Combine("bin", Configuration, Project.TargetFramework, "Razor");
-            var result = await DotnetMSBuild("Build", $"/p:MvcRazorOutputPath={customOutputPath}");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.pdb");
-
-            Assert.FileExists(result, customOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, customOutputPath, "SimpleMvc.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_SkipsCopyingBinariesToOutputDirectory_IfCopyBuildOutputToOutputDirectory_IsUnset()
-        {
-            var result = await DotnetMSBuild("Build", "/p:CopyBuildOutputToOutputDirectory=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.Views.dll");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_SkipsCopyingBinariesToOutputDirectory_IfCopyOutputSymbolsToOutputDirectory_IsUnset()
-        {
-            var result = await DotnetMSBuild("Build", "/p:CopyOutputSymbolsToOutputDirectory=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.pdb");
-
-            Assert.FileExists(result, OutputPath, "SimpleMvc.Views.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_Works_WhenSymbolsAreNotGenerated()
-        {
-            var result = await DotnetMSBuild("Build", "/p:DebugType=none");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.pdb");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.Views.pdb");
-
-            Assert.FileExists(result, OutputPath, "SimpleMvc.Views.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.pdb");
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("AppWithP2PReference", additionalProjects: "ClassLibrary")]
-        public async Task Build_WithP2P_CopiesRazorAssembly()
-        {
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, OutputPath, "AppWithP2PReference.dll");
-            Assert.FileExists(result, OutputPath, "AppWithP2PReference.pdb");
-            Assert.FileExists(result, OutputPath, "AppWithP2PReference.Views.dll");
-            Assert.FileExists(result, OutputPath, "AppWithP2PReference.Views.pdb");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.pdb");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.Views.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimplePages", additionalProjects: "LinkedDir")]
-        public async Task Build_SetsUpEmbeddedResourcesWithLogicalName()
-        {
-            // Arrange
-            var additionalProjectContent = @"
-<ItemGroup>
-  <Content Include=""..\LinkedDir\LinkedFile.cshtml"" Link=""LinkedFileOut\LinkedFile.cshtml"" />
-</ItemGroup>
-";
-            AddProjectFileContent(additionalProjectContent);
-            Directory.CreateDirectory(Path.Combine(Project.DirectoryPath, "..", "LinkedDir"));
-
-            var result = await DotnetMSBuild("Build", "/t:_IntrospectRazorEmbeddedResources /p:EmbedRazorGenerateSources=true");
-
-            Assert.BuildPassed(result);
-
-            Assert.BuildOutputContainsLine(result, $@"CompileResource: {Path.Combine("Pages", "Index.cshtml")} /Pages/Index.cshtml");
-            Assert.BuildOutputContainsLine(result, $@"CompileResource: {Path.Combine("Areas", "Products", "Pages", "_ViewStart.cshtml")} /Areas/Products/Pages/_ViewStart.cshtml");
-            Assert.BuildOutputContainsLine(result, $@"CompileResource: {Path.Combine("..", "LinkedDir", "LinkedFile.cshtml")} /LinkedFileOut/LinkedFile.cshtml");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_WithViews_ProducesDepsFileWithCompilationContext_ButNoReferences()
-        {
-            var customDefine = "RazorSdkTest";
-            var result = await DotnetMSBuild("Build", $"/p:DefineConstants={customDefine}");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, OutputPath, "SimpleMvc.deps.json");
-            var depsFilePath = Path.Combine(Project.DirectoryPath, OutputPath, "SimpleMvc.deps.json");
-            var dependencyContext = ReadDependencyContext(depsFilePath);
-
-            // Pick a couple of libraries and ensure they have some compile references
-            var packageReference = dependencyContext.CompileLibraries.First(l => l.Name == "System.Diagnostics.DiagnosticSource");
-            Assert.NotEmpty(packageReference.Assemblies);
-
-            var projectReference = dependencyContext.CompileLibraries.First(l => l.Name == "SimpleMvc");
-            Assert.NotEmpty(projectReference.Assemblies);
-
-            Assert.Contains(customDefine, dependencyContext.CompilationOptions.Defines);
-
-            // Verify no refs folder is produced
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "refs"), "*.dll");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_WithPreserveCompilationReferencesEnabled_ProducesRefsDirectory()
-        {
-            // This simulates the behavior of 3.0 with RuntimeCompilation enabled
-            AddProjectFileContent(@"
-            <PropertyGroup>
-                <PreserveCompilationReferences>true</PreserveCompilationReferences>
-            </PropertyGroup>");
-
-            var result = await DotnetMSBuild("Build");
-
-            // Verify no refs folder is produced
-            Assert.FileExists(result, OutputPath, "refs", "mscorlib.dll");
-        }
-
-        [Fact]
-        [InitializeTestProject("ClassLibrary")]
-        public async Task Build_CodeGensAssemblyInfoUsingValuesFromProject()
-        {
-            var razorAssemblyInfoPath = Path.Combine(IntermediateOutputPath, "ClassLibrary.RazorTargetAssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, razorAssemblyInfoPath);
-            Assert.FileContains(result, razorAssemblyInfoPath, "[assembly: System.Reflection.AssemblyCopyrightAttribute(\"© Microsoft\")]");
-            Assert.FileContains(result, razorAssemblyInfoPath, "[assembly: System.Reflection.AssemblyProductAttribute(\"Razor Test\")]");
-            Assert.FileContains(result, razorAssemblyInfoPath, "[assembly: System.Reflection.AssemblyCompanyAttribute(\"Microsoft\")]");
-            Assert.FileContains(result, razorAssemblyInfoPath, "[assembly: System.Reflection.AssemblyTitleAttribute(\"ClassLibrary.Views\")]");
-            Assert.FileContains(result, razorAssemblyInfoPath, "[assembly: System.Reflection.AssemblyVersionAttribute(\"1.0.0.0\")]");
-            Assert.FileContains(result, razorAssemblyInfoPath, "[assembly: System.Reflection.AssemblyFileVersionAttribute(\"1.0.0.0\")]");
-            Assert.FileContains(result, razorAssemblyInfoPath, "[assembly: System.Reflection.AssemblyInformationalVersionAttribute(\"1.0.0\")]");
-            Assert.FileContains(result, razorAssemblyInfoPath, "[assembly: System.Reflection.AssemblyDescriptionAttribute(\"ClassLibrary Description\")]");
-        }
-
-        [Fact]
-        [InitializeTestProject("ClassLibrary")]
-        public async Task Build_UsesRazorSpecificAssemblyProperties()
-        {
-            var razorTargetAssemblyInfo = Path.Combine(IntermediateOutputPath, "ClassLibrary.RazorTargetAssemblyInfo.cs");
-            var buildArguments = "/p:RazorAssemblyFileVersion=2.0.0.100 /p:RazorAssemblyInformationalVersion=2.0.0-preview " +
-                "/p:RazorAssemblyTitle=MyRazorViews /p:RazorAssemblyVersion=2.0.0 " +
-                "/p:RazorAssemblyDescription=MyRazorDescription";
-            var result = await DotnetMSBuild("Build", buildArguments);
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, razorTargetAssemblyInfo);
-            Assert.FileContains(result, razorTargetAssemblyInfo, "[assembly: System.Reflection.AssemblyDescriptionAttribute(\"MyRazorDescription\")]");
-            Assert.FileContains(result, razorTargetAssemblyInfo, "[assembly: System.Reflection.AssemblyTitleAttribute(\"MyRazorViews\")]");
-            Assert.FileContains(result, razorTargetAssemblyInfo, "[assembly: System.Reflection.AssemblyVersionAttribute(\"2.0.0\")]");
-            Assert.FileContains(result, razorTargetAssemblyInfo, "[assembly: System.Reflection.AssemblyFileVersionAttribute(\"2.0.0.100\")]");
-            Assert.FileContains(result, razorTargetAssemblyInfo, "[assembly: System.Reflection.AssemblyInformationalVersionAttribute(\"2.0.0-preview\")]");
-        }
-
-        [Fact]
-        [InitializeTestProject("ClassLibrary")]
-        public async Task Build_DoesNotGenerateAssemblyInfo_IfGenerateRazorTargetAssemblyInfo_IsSetToFalse()
-        {
-            var result = await DotnetMSBuild("Build", "/p:GenerateRazorTargetAssemblyInfo=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "ClassLibrary.AssemblyInfo.cs");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "ClassLibrary.RazorTargetAssemblyInfo.cs");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_AddsApplicationPartAttributes()
-        {
-            var razorAssemblyInfoPath = Path.Combine(IntermediateOutputPath, "SimpleMvc.RazorAssemblyInfo.cs");
-            var razorTargetAssemblyInfo = Path.Combine(IntermediateOutputPath, "SimpleMvc.RazorTargetAssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, razorAssemblyInfoPath);
-            Assert.FileContains(result, razorAssemblyInfoPath, "[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.RelatedAssemblyAttribute(\"SimpleMvc.Views\")]");
-
-            Assert.FileExists(result, razorTargetAssemblyInfo);
-            Assert.FileContains(result, razorTargetAssemblyInfo, "[assembly: System.Reflection.AssemblyTitleAttribute(\"SimpleMvc.Views\")]");
-            Assert.FileContains(result, razorTargetAssemblyInfo, "[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.ProvideApplicationPartFactoryAttribute(\"Microsoft.AspNetCore.Mvc.ApplicationParts.CompiledRazorAssemblyApplicationPartFac\"");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_AddsApplicationPartAttributes_WhenEnableDefaultRazorTargetAssemblyInfoAttributes_IsFalse()
-        {
-            var razorTargetAssemblyInfo = Path.Combine(IntermediateOutputPath, "SimpleMvc.RazorTargetAssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build", "/p:EnableDefaultRazorTargetAssemblyInfoAttributes=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.AssemblyInfo.cs");
-            Assert.FileExists(result, razorTargetAssemblyInfo);
-            Assert.FileDoesNotContain(result, razorTargetAssemblyInfo, "[assembly: System.Reflection.AssemblyTitleAttribute");
-            Assert.FileContains(result, razorTargetAssemblyInfo, "[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.ProvideApplicationPartFactoryAttribute(\"Microsoft.AspNetCore.Mvc.ApplicationParts.CompiledRazorAssemblyApplicationPartFac\"");
-        }
-
-        [Fact]
-        [InitializeTestProject("ClassLibrary")]
-        public async Task Build_UsesSpecifiedApplicationPartFactoryTypeName()
-        {
-            var razorTargetAssemblyInfo = Path.Combine(IntermediateOutputPath, "ClassLibrary.RazorTargetAssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build", "/p:ProvideApplicationPartFactoryAttributeTypeName=CustomFactory");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, razorTargetAssemblyInfo);
-            Assert.FileContains(result, razorTargetAssemblyInfo, "[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.ProvideApplicationPartFactoryAttribute(\"CustomFactory\"");
-        }
-
-        [Fact]
-        [InitializeTestProject("ClassLibrary")]
-        public async Task Build_DoesNotGenerateProvideApplicationPartFactoryAttribute_IfGenerateProvideApplicationPartFactoryAttributeIsUnset()
-        {
-            var razorTargetAssemblyInfo = Path.Combine(IntermediateOutputPath, "ClassLibrary.RazorTargetAssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build", "/p:GenerateProvideApplicationPartFactoryAttribute=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, razorTargetAssemblyInfo);
-            Assert.FileDoesNotContain(result, razorTargetAssemblyInfo, "[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.ProvideApplicationPartFactoryAttribute");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_DoesNotAddRelatedAssemblyPart_IfViewCompilationIsDisabled()
-        {
-            var razorAssemblyInfo = Path.Combine(IntermediateOutputPath, "SimpleMvc.RazorAssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build", "/p:RazorCompileOnBuild=false /p:RazorCompileOnPublish=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileDoesNotExist(result, razorAssemblyInfo);
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.RazorTargetAssemblyInfo.cs");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_AddsRelatedAssemblyPart_IfCompileOnPublishIsAllowed()
-        {
-            var razorAssemblyInfo = Path.Combine(IntermediateOutputPath, "SimpleMvc.RazorAssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build", "/p:RazorCompileOnBuild=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, razorAssemblyInfo);
-            Assert.FileContains(result, razorAssemblyInfo, "[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.RelatedAssemblyAttribute(\"SimpleMvc.Views\")]");
-
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.RazorTargetAssemblyInfo.cs");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_AddsRelatedAssemblyPart_IfGenerateAssemblyInfoIsFalse()
-        {
-            var razorAssemblyInfo = Path.Combine(IntermediateOutputPath, "SimpleMvc.RazorAssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build", "/p:GenerateAssemblyInfo=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, razorAssemblyInfo);
-            Assert.FileContains(result, razorAssemblyInfo, "[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.RelatedAssemblyAttribute(\"SimpleMvc.Views\")]");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_WithGenerateRazorHostingAssemblyInfoFalse_DoesNotGenerateHostingAttributes()
-        {
-            var razorAssemblyInfo = Path.Combine(IntermediateOutputPath, "SimpleMvc.RazorAssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build", "/p:GenerateRazorHostingAssemblyInfo=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, razorAssemblyInfo);
-            Assert.FileDoesNotContain(result, razorAssemblyInfo, "Microsoft.AspNetCore.Razor.Hosting.RazorLanguageVersionAttribute");
-            Assert.FileDoesNotContain(result, razorAssemblyInfo, "Microsoft.AspNetCore.Razor.Hosting.RazorConfigurationNameAttribute");
-            Assert.FileDoesNotContain(result, razorAssemblyInfo, "Microsoft.AspNetCore.Razor.Hosting.RazorExtensionAssemblyNameAttribute");
-            Assert.FileContains(result, razorAssemblyInfo, "[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.RelatedAssemblyAttribute(\"SimpleMvc.Views\")]");
-        }
-
-        [Fact]
-        [InitializeTestProject("ClassLibrary")]
-        public async Task Build_DoesNotGenerateHostingAttributes_InClassLibraryProjects()
-        {
-            var razorAssemblyInfo = Path.Combine(IntermediateOutputPath, "ClassLibrary.AssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, razorAssemblyInfo);
-            Assert.FileDoesNotContain(result, razorAssemblyInfo, "Microsoft.AspNetCore.Razor.Hosting.RazorLanguageVersionAttribute");
-            Assert.FileDoesNotContain(result, razorAssemblyInfo, "Microsoft.AspNetCore.Razor.Hosting.RazorConfigurationNameAttribute");
-            Assert.FileDoesNotContain(result, razorAssemblyInfo, "Microsoft.AspNetCore.Razor.Hosting.RazorExtensionAssemblyNameAttribute");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_GeneratesHostingAttributes_WhenGenerateRazorHostingAssemblyInfoIsSet()
-        {
-            var razorAssemblyInfo = Path.Combine(IntermediateOutputPath, "SimpleMvc.AssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build", "/p:GenerateRazorHostingAssemblyInfo=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, razorAssemblyInfo);
-            Assert.FileDoesNotContain(result, razorAssemblyInfo, "Microsoft.AspNetCore.Razor.Hosting.RazorLanguageVersionAttribute");
-            Assert.FileDoesNotContain(result, razorAssemblyInfo, "Microsoft.AspNetCore.Razor.Hosting.RazorConfigurationNameAttribute");
-        }
-
-        [Fact(Skip = "https://github.com/dotnet/aspnetcore/issues/13303")]
-        [InitializeTestProject("SimpleMvcFSharp", language: "F#")]
-        public async Task Build_SimpleMvcFSharp_NoopsWithoutFailing()
-        {
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, OutputPath, "SimpleMvcFSharp.dll");
-            Assert.FileExists(result, OutputPath, "SimpleMvcFSharp.pdb");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvcFSharp.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvcFSharp.pdb");
-
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvcFSharp.Views.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvcFSharp.Views.pdb");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvcFSharp.RazorAssemblyInfo.cs");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvcFSharp.RazorAssemblyInfo.fs");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_WithGenerateRazorAssemblyInfo_False_DoesNotGenerateAssemblyInfo()
-        {
-            var razorAssemblyInfo = Path.Combine(IntermediateOutputPath, "SimpleMvc.RazorAssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build", "/p:GenerateRazorAssemblyInfo=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.pdb");
-
-            Assert.FileDoesNotExist(result, razorAssemblyInfo);
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_WithGenerateRazorTargetAssemblyInfo_False_DoesNotGenerateAssemblyInfo()
-        {
-            var razorAssemblyInfo = Path.Combine(IntermediateOutputPath, "SimpleMvc.RazorAssemblyInfo.cs");
-            var razorTargetAssemblyInfo = Path.Combine(IntermediateOutputPath, "SimpleMvc.RazorTargetAssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build", "/p:GenerateRazorTargetAssemblyInfo=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.pdb");
-
-            Assert.FileExists(result, razorAssemblyInfo);
-            Assert.FileDoesNotExist(result, razorTargetAssemblyInfo);
-        }
-
-        [Fact]
-        [InitializeTestProject("AppWithP2PReference", additionalProjects: new[] { "ClassLibrary", "ClassLibrary2" })]
-        public async Task Build_WithP2P_WorksWhenBuildProjectReferencesIsDisabled()
-        {
-            // Simulates building the same way VS does by setting BuildProjectReferences=false.
-            // With this flag, P2P references aren't resolved during GetCopyToOutputDirectoryItems. This test ensures that
-            // no Razor work is done in such a scenario and the build succeeds.
-            var additionalProjectContent = @"
-<ItemGroup>
-  <ProjectReference Include=""..\ClassLibrary2\ClassLibrary2.csproj"" />
-</ItemGroup>
-";
-            AddProjectFileContent(additionalProjectContent);
-
-            var result = await DotnetMSBuild(target: default);
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, OutputPath, "AppWithP2PReference.dll");
-            Assert.FileExists(result, OutputPath, "AppWithP2PReference.Views.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.Views.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary2.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary2.Views.dll");
-
-            // Force a rebuild of ClassLibrary2 by changing a file
-            var class2Path = Path.Combine(Project.SolutionPath, "ClassLibrary2", "Class2.cs");
-            File.AppendAllText(class2Path, Environment.NewLine + "// Some changes");
-
-            // dotnet msbuild /p:BuildProjectReferences=false
-            result = await DotnetMSBuild(target: default, "/p:BuildProjectReferences=false");
-
-            Assert.BuildPassed(result);
-        }
-
-        [Fact]
-        [InitializeTestProject("AppWithP2PReference", additionalProjects: new[] { "ClassLibrary", "ClassLibraryMvc21" })]
-        public async Task Build_WithP2P_Referencing21Project_Works()
-        {
-            // Verifies building with different versions of Razor.Tasks works. Loosely modeled after the repro
-            // scenario listed in https://github.com/Microsoft/msbuild/issues/3572
-            var additionalProjectContent = @"
-<ItemGroup>
-  <ProjectReference Include=""..\ClassLibraryMvc21\ClassLibraryMvc21.csproj"" />
-</ItemGroup>
-";
-            AddProjectFileContent(additionalProjectContent);
-
-            var result = await DotnetMSBuild(target: default);
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, OutputPath, "AppWithP2PReference.dll");
-            Assert.FileExists(result, OutputPath, "AppWithP2PReference.Views.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.Views.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibraryMvc21.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibraryMvc21.Views.dll");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_WithStartupObjectSpecified_Works()
-        {
-            var result = await DotnetMSBuild("Build", $"/p:StartupObject=SimpleMvc.Program");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.pdb");
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_WithDeterministicFlagSet_OutputsDeterministicViewsAssembly()
-        {
-            // Build 1
-            var result = await DotnetMSBuild("Build", $"/p:Deterministic=true");
-
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            var filePath = Path.Combine(result.Project.DirectoryPath, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            var firstAssemblyBytes = File.ReadAllBytes(filePath);
-
-            // Build 2
-            result = await DotnetMSBuild("Rebuild", $"/p:Deterministic=true");
-
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            var secondAssemblyBytes = File.ReadAllBytes(filePath);
-
-            Assert.Equal(firstAssemblyBytes, secondAssemblyBytes);
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_WithoutServer_ErrorDuringBuild_DisplaysErrorInMsBuildOutput()
-        {
-            var result = await DotnetMSBuild(
-                "Build",
-                "/p:UseRazorBuildServer=false /p:RazorLangVersion=99.0",
-                suppressBuildServer: true);
-
-            Assert.BuildFailed(result);
-            Assert.BuildOutputContainsLine(
-                result,
-                $"Invalid option 99.0 for Razor language version --version; must be Latest or a valid version in range 1.0 to 5.0.");
-
-            // Compilation failed without creating the views assembly
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.dll");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_ImplicitCSharp8_NullableEnforcement_WarningsDuringBuild_NoBuildServer()
-        {
-            var result = await DotnetMSBuild(
-                "Build",
-                "/p:Nullable=enable",
-                suppressBuildServer: true);
-            var indexFilePath = Path.Combine(RazorIntermediateOutputPath, "Views", "Home", "Index.cshtml.g.cs");
-
-            Assert.BuildPassed(result, allowWarnings: true);
-            Assert.BuildWarning(result, "CS8618");
-            Assert.FileContainsLine(result, indexFilePath, "#nullable restore");
-            Assert.FileContainsLine(result, indexFilePath, "#nullable disable");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_ExplicitCSharp73_NullableEnforcement_Disabled_NoNullableFeature_NoBuildServer()
-        {
-            var result = await DotnetMSBuild(
-                "Build",
-                "/p:LangVersion=7.3",
-                suppressBuildServer: true);
-            var indexFilePath = Path.Combine(RazorIntermediateOutputPath, "Views", "Home", "Index.cshtml.g.cs");
-
-            Assert.BuildPassed(result, allowWarnings: false);
-            Assert.FileDoesNotContainLine(result, indexFilePath, "#nullable restore");
-            Assert.FileDoesNotContainLine(result, indexFilePath, "#nullable disable");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_ExplicitCSharp8_NullableEnforcement_WarningsDuringBuild_BuildServer()
-        {
-            var result = await DotnetMSBuild(
-                "Build",
-                "/p:LangVersion=8.0 /p:Nullable=enable");
-            var indexFilePath = Path.Combine(RazorIntermediateOutputPath, "Views", "Home", "Index.cshtml.g.cs");
-
-            Assert.BuildPassed(result, allowWarnings: true);
-            Assert.BuildWarning(result, "CS8618");
-            Assert.FileContainsLine(result, indexFilePath, "#nullable restore");
-            Assert.FileContainsLine(result, indexFilePath, "#nullable disable");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_CSharp8_NullableEnforcement_WarningsDuringBuild_NoBuildServer()
-        {
-            var result = await DotnetMSBuild(
-                "Build",
-                "/p:LangVersion=8.0 /p:Nullable=enable",
-                suppressBuildServer: true);
-            var indexFilePath = Path.Combine(RazorIntermediateOutputPath, "Views", "Home", "Index.cshtml.g.cs");
-
-            Assert.BuildPassed(result, allowWarnings: true);
-            Assert.BuildWarning(result, "CS8618");
-            Assert.FileContainsLine(result, indexFilePath, "#nullable restore");
-            Assert.FileContainsLine(result, indexFilePath, "#nullable disable");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_Mvc_WithoutAddRazorSupportForMvc()
-        {
-            var result = await DotnetMSBuild(
-                "Build",
-                "/p:AddRazorSupportForMvc=false",
-                suppressBuildServer: true);
-
-            Assert.BuildWarning(result, "RAZORSDK1004");
-        }
-
-        [Fact]
-        [InitializeTestProject("ClassLibrary")]
-        public async Task Build_WithNoResolvedRazorConfiguration()
-        {
-AddProjectFileContent(@"
-<PropertyGroup>
-    <RazorDefaultConfiguration>Custom12.3</RazorDefaultConfiguration>
-</PropertyGroup>");
-
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildWarning(result, "RAZORSDK1000");
-        }
-
-        private static DependencyContext ReadDependencyContext(string depsFilePath)
-        {
-            var reader = new DependencyContextJsonReader();
-            using (var stream = File.OpenRead(depsFilePath))
-            {
-                return reader.Read(stream);
-            }
-        }
-    }
-}

+ 0 - 291
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildIntrospectionTest.cs

@@ -1,291 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using System.Linq;
-using System.Reflection;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Testing;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class BuildIntrospectionTest : MSBuildIntegrationTestBase, IClassFixture<BuildServerTestFixture>
-    {
-        public BuildIntrospectionTest(BuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorSdk_AddsProjectCapabilities()
-        {
-            var result = await DotnetMSBuild("_IntrospectProjectCapabilityItems");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, "ProjectCapability: DotNetCoreRazor");
-            Assert.BuildOutputContainsLine(result, "ProjectCapability: DotNetCoreRazorConfiguration");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorSdk_AddsCshtmlFilesToUpToDateCheckInput()
-        {
-            var result = await DotnetMSBuild("_IntrospectUpToDateCheck");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, $"UpToDateCheckInput: {Path.Combine("Views", "Home", "Index.cshtml")}");
-            Assert.BuildOutputContainsLine(result, $"UpToDateCheckInput: {Path.Combine("Views", "_ViewStart.cshtml")}");
-            Assert.BuildOutputContainsLine(result, $"UpToDateCheckBuilt: {Path.Combine(IntermediateOutputPath, "SimpleMvc.Views.dll")}");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorSdk_AddsGeneratedRazorFilesAndAssemblyInfoToRazorCompile()
-        {
-            var result = await DotnetMSBuild("Build", "/t:_IntrospectRazorCompileItems");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, $"RazorCompile: {Path.Combine(IntermediateOutputPath, "Razor", "Views", "Home", "Index.cshtml.g.cs")}");
-            Assert.BuildOutputContainsLine(result, $"RazorCompile: {Path.Combine(IntermediateOutputPath, "SimpleMvc.RazorTargetAssemblyInfo.cs")}");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorSdk_UsesUseSharedCompilationToSetDefaultValueOfUseRazorBuildServer()
-        {
-            var result = await DotnetMSBuild("Build", "/t:_IntrospectUseRazorBuildServer /p:UseSharedCompilation=false");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, "UseRazorBuildServer: false");
-        }
-
-        [Fact]
-        [InitializeTestProject("ClassLibrary")]
-        public async Task GetCopyToOutputDirectoryItems_WhenNoFileIsPresent_ReturnsEmptySequence()
-        {
-            var result = await DotnetMSBuild(target: default);
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, OutputPath, "ClassLibrary.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.Views.dll");
-
-            result = await DotnetMSBuild(target: "GetCopyToOutputDirectoryItems", "/t:_IntrospectGetCopyToOutputDirectoryItems /p:BuildProjectReferences=false");
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, "AllItemsFullPathWithTargetPath: ClassLibrary.Views.dll");
-            Assert.BuildOutputContainsLine(result, "AllItemsFullPathWithTargetPath: ClassLibrary.Views.pdb");
-
-            // Remove all views from the class library
-            Directory.Delete(Path.Combine(Project.DirectoryPath, "Views"), recursive: true);
-
-            // dotnet msbuild /p:BuildProjectReferences=false
-            result = await DotnetMSBuild(target: "GetCopyToOutputDirectoryItems", "/t:_IntrospectGetCopyToOutputDirectoryItems /p:BuildProjectReferences=false");
-
-            Assert.BuildOutputDoesNotContainLine(result, "AllItemsFullPathWithTargetPath: ClassLibrary.Views.dll");
-            Assert.BuildOutputDoesNotContainLine(result, "AllItemsFullPathWithTargetPath: ClassLibrary.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc31")]
-        public async Task RazorSdk_ResolvesRazorLangVersionTo30ForNetCoreApp30Projects()
-        {
-            var result = await DotnetMSBuild("ResolveRazorConfiguration", "/t:_IntrospectResolvedConfiguration");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, "RazorLangVersion: 3.0");
-            Assert.BuildOutputContainsLine(result, "ResolvedRazorConfiguration: MVC-3.0");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorSdk_ResolvesRazorLangVersionTo50ForNetCoreApp50Projects()
-        {
-            var result = await DotnetMSBuild("ResolveRazorConfiguration", "/t:_IntrospectResolvedConfiguration");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, "RazorLangVersion: 5.0");
-            Assert.BuildOutputContainsLine(result, "ResolvedRazorConfiguration: MVC-3.0");
-        }
-
-        [Fact]
-        [InitializeTestProject("ComponentLibrary")]
-        public async Task RazorSdk_ResolvesRazorLangVersionFromValueSpecified()
-        {
-            var result = await DotnetMSBuild("ResolveRazorConfiguration", "/t:_IntrospectResolvedConfiguration");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, "RazorLangVersion: 3.0");
-            Assert.BuildOutputContainsLine(result, "ResolvedRazorConfiguration: Default");
-        }
-
-        [Fact]
-        [InitializeTestProject("ComponentLibrary")]
-        public async Task RazorSdk_ResolvesRazorLangVersionTo21WhenUnspecified()
-        {
-            // This is equivalent to not specifying a value for RazorLangVersion
-            AddProjectFileContent("<PropertyGroup><RazorLangVersion /></PropertyGroup>");
-
-            var result = await DotnetMSBuild("ResolveRazorConfiguration", "/t:_IntrospectResolvedConfiguration");
-
-            Assert.BuildPassed(result, allowWarnings: true);
-            Assert.BuildOutputContainsLine(result, "RazorLangVersion: 2.1");
-            // BuildOutputContainsLine matches entire lines, so it's fine to Assert the following.
-            Assert.BuildOutputContainsLine(result, "ResolvedRazorConfiguration:");
-        }
-
-        [Fact]
-        [InitializeTestProject("ComponentLibrary")]
-        public async Task RazorSdk_WithRazorLangVersionLatest()
-        {
-            var result = await DotnetMSBuild("ResolveRazorConfiguration", "/t:_IntrospectResolvedConfiguration /p:RazorLangVersion=Latest");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, "RazorLangVersion: Latest");
-            Assert.BuildOutputContainsLine(result, "ResolvedRazorConfiguration: Default");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorSdk_ResolvesRazorConfigurationToMvc30()
-        {
-            var result = await DotnetMSBuild("ResolveRazorConfiguration", "/t:_IntrospectResolvedConfiguration");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, "RazorLangVersion: 5.0");
-            Assert.BuildOutputContainsLine(result, "ResolvedRazorConfiguration: MVC-3.0");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task UpToDateReloadFileTypes_Default()
-        {
-            var result = await DotnetMSBuild("_IntrospectUpToDateReloadFileTypes");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, "UpToDateReloadFileTypes: ;.cs;.razor;.resx;.cshtml");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task UpToDateReloadFileTypes_WithRuntimeCompilation()
-        {
-            AddProjectFileContent(
-@"
-<PropertyGroup>
-    <RazorUpToDateReloadFileTypes>$(RazorUpToDateReloadFileTypes.Replace('.cshtml', ''))</RazorUpToDateReloadFileTypes>
-</PropertyGroup>");
-
-            var result = await DotnetMSBuild("_IntrospectUpToDateReloadFileTypes");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, "UpToDateReloadFileTypes: ;.cs;.razor;.resx;");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task UpToDateReloadFileTypes_WithwWorkAroundRemoved()
-        {
-            var result = await DotnetMSBuild("_IntrospectUpToDateReloadFileTypes", "/p:_RazorUpToDateReloadFileTypesAllowWorkaround=false");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, "UpToDateReloadFileTypes: ;.cs;.razor;.resx;.cshtml");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task UpToDateReloadFileTypes_WithRuntimeCompilationAndWorkaroundRemoved()
-        {
-            AddProjectFileContent(
-@"
-<PropertyGroup>
-    <RazorUpToDateReloadFileTypes>$(RazorUpToDateReloadFileTypes.Replace('.cshtml', ''))</RazorUpToDateReloadFileTypes>
-</PropertyGroup>");
-
-            var result = await DotnetMSBuild("_IntrospectUpToDateReloadFileTypes", "/p:_RazorUpToDateReloadFileTypesAllowWorkaround=false");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, "UpToDateReloadFileTypes: ;.cs;.razor;.resx;");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task IntrospectJsonContentFiles()
-        {
-            var result = await DotnetMSBuild("_IntrospectContentItems");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, "Content: appsettings.json CopyToOutputDirectory=PreserveNewest CopyToPublishDirectory=PreserveNewest ExcludeFromSingleFile=true");
-            Assert.BuildOutputContainsLine(result, "Content: appsettings.Development.json CopyToOutputDirectory=PreserveNewest CopyToPublishDirectory=PreserveNewest ExcludeFromSingleFile=true");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task IntrospectJsonContentFiles_WithExcludeConfigFilesFromBuildOutputSet()
-        {
-            // Verifies that the fix for https://github.com/dotnet/aspnetcore/issues/14017 works.
-            var result = await DotnetMSBuild("_IntrospectContentItems", "/p:ExcludeConfigFilesFromBuildOutput=true");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, "Content: appsettings.json CopyToOutputDirectory= CopyToPublishDirectory=PreserveNewest ExcludeFromSingleFile=true");
-            Assert.BuildOutputContainsLine(result, "Content: appsettings.Development.json CopyToOutputDirectory= CopyToPublishDirectory=PreserveNewest ExcludeFromSingleFile=true");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task IntrospectRazorTasksDllPath()
-        {
-            // Regression test for https://github.com/dotnet/aspnetcore/issues/17308
-            var solutionRoot = GetType().Assembly.GetCustomAttributes<AssemblyMetadataAttribute>()
-                .First(a => a.Key == "Testing.RepoRoot")
-                .Value;
-
-            var tfm =
-#if NETCOREAPP
-                "net6.0";
-#else
-#error Target framework needs to be updated.
-#endif
-
-            var expected = Path.Combine(solutionRoot, "artifacts", "bin", "Microsoft.NET.Sdk.Razor", Configuration, "sdk-output", "tasks", tfm, "Microsoft.NET.Sdk.Razor.Tasks.dll");
-
-            // Verifies the fix for https://github.com/dotnet/aspnetcore/issues/17308
-            var result = await DotnetMSBuild("_IntrospectRazorTasks");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, $"RazorTasksPath: {expected}");
-        }
-
-        [ConditionalFact(Skip = "https://github.com/dotnet/aspnetcore/issues/24427")]
-        [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task IntrospectRazorTasksDllPath_DesktopMsBuild()
-        {
-            var solutionRoot = GetType().Assembly.GetCustomAttributes<AssemblyMetadataAttribute>()
-                .First(a => a.Key == "Testing.RepoRoot")
-                .Value;
-
-            var tfm = "net46";
-            var expected = Path.Combine(solutionRoot, "artifacts", "bin", "Microsoft.NET.Sdk.Razor", Configuration, "sdk-output", "tasks", tfm, "Microsoft.NET.Sdk.Razor.Tasks.dll");
-
-            // Verifies the fix for https://github.com/dotnet/aspnetcore/issues/17308
-            var result = await DotnetMSBuild("_IntrospectRazorTasks", msBuildProcessKind: MSBuildProcessKind.Desktop);
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, $"RazorTasksPath: {expected}");
-        }
-
-        [Fact]
-        [InitializeTestProject("ComponentApp")]
-        public async Task IntrospectRazorSdkWatchItems()
-        {
-            // Arrange
-            var result = await DotnetMSBuild("_IntrospectWatchItems");
-
-            Assert.BuildPassed(result);
-            Assert.BuildOutputContainsLine(result, "Watch: Index.razor");
-            Assert.BuildOutputContainsLine(result, "Watch: Index.razor.css");
-        }
-    }
-}

+ 0 - 110
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildPerformanceTest.cs

@@ -1,110 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Text.RegularExpressions;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class BuildPerformanceTest : MSBuildIntegrationTestBase, IClassFixture<BuildServerTestFixture>
-    {
-        public BuildPerformanceTest(BuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task BuildMvcApp()
-        {
-            var result = await DotnetMSBuild(target: default, args: "/clp:PerformanceSummary");
-
-            Assert.BuildPassed(result);
-            var summary = ParseTaskPerformanceSummary(result.Output);
-
-            Assert.Equal(1, summary.First(f => f.Name == "RazorGenerate").Calls);
-            Assert.Equal(1, summary.First(f => f.Name == "RazorTagHelper").Calls);
-
-            // Incremental builds
-            for (var i = 0; i < 2; i++)
-            {
-                result = await DotnetMSBuild(target: default, args: "/clp:PerformanceSummary");
-
-                Assert.BuildPassed(result);
-                summary = ParseTaskPerformanceSummary(result.Output);
-
-                Assert.DoesNotContain(summary, item => item.Name == "RazorGenerate");
-                Assert.DoesNotContain(summary, item => item.Name == "RazorTagHelper");
-            }
-        }
-
-        [Fact]
-        [InitializeTestProject("MvcWithComponents")]
-        public async Task BuildMvcAppWithComponents()
-        {
-            var result = await DotnetMSBuild(target: default, args: "/clp:PerformanceSummary");
-
-            Assert.BuildPassed(result);
-            var summary = ParseTaskPerformanceSummary(result.Output);
-
-            // One for declaration build, one for the "real" code gen
-            Assert.Equal(2, summary.First(f => f.Name == "RazorGenerate").Calls);
-            Assert.Equal(1, summary.First(f => f.Name == "RazorTagHelper").Calls);
-
-            // Incremental builds
-            for (var i = 0; i < 2; i++)
-            {
-                result = await DotnetMSBuild(target: default, args: "/clp:PerformanceSummary");
-
-                Assert.BuildPassed(result);
-                summary = ParseTaskPerformanceSummary(result.Output);
-
-                Assert.DoesNotContain(summary, item => item.Name == "RazorGenerate");
-                Assert.DoesNotContain(summary, item => item.Name == "RazorTagHelper");
-            }
-        }
-
-        private List<PerformanceSummaryEntry> ParseTaskPerformanceSummary(string output)
-        {
-            const string Header = "Task Performance Summary:";
-            var lines = output.Split(Environment.NewLine);
-            var taskSection = Array.LastIndexOf(lines, Header);
-            Assert.True(taskSection != -1, $"Could not find line ${Header} in {output}");
-
-            var entries = new List<PerformanceSummaryEntry>();
-            // 6 ms  FindAppConfigFile                          4 calls
-            var matcher = new Regex(@"\s+(?<time>\w+) ms\s+(?<name>\w+)\s+(?<calls>\d+) calls");
-            for (var i = taskSection + 1; i < lines.Length; i++)
-            {
-                if (string.IsNullOrWhiteSpace(lines[i]))
-                {
-                    continue;
-                }
-
-                var match = matcher.Match(lines[i]);
-                Assert.True(match.Success, $"Line {lines[i]} did not match. Full Output: {output}");
-
-                var entry = new PerformanceSummaryEntry
-                {
-                    Name = match.Groups["name"].Value,
-                    Calls = int.Parse(match.Groups["calls"].Value, CultureInfo.InvariantCulture),
-                };
-                entries.Add(entry);
-            }
-
-            return entries;
-        }
-
-        private class PerformanceSummaryEntry
-        {
-            public string Name { get; set; }
-
-            public int Calls { get; set; }
-        }
-    }
-}

+ 0 - 274
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildServerIntegrationTest.cs

@@ -1,274 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Diagnostics;
-using System.IO;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Testing;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class BuildServerIntegrationTest : MSBuildIntegrationTestBase, IClassFixture<BuildServerTestFixture>
-    {
-
-        public BuildServerIntegrationTest(BuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public Task Build_SimpleMvc_WithServer_UsingDotnetMSBuild_CanBuildSuccessfully()
-            => Build_SimpleMvc_CanBuildSuccessfully(MSBuildProcessKind.Dotnet);
-
-        [ConditionalFact]
-        [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
-        [InitializeTestProject("SimpleMvc")]
-        public Task Build_SimpleMvc_WithServer_UsingDesktopMSBuild_CanBuildSuccessfully()
-            => Build_SimpleMvc_CanBuildSuccessfully(MSBuildProcessKind.Desktop);
-
-        private async Task Build_SimpleMvc_CanBuildSuccessfully(MSBuildProcessKind msBuildProcessKind)
-        {
-            var result = await DotnetMSBuild(
-                "Build",
-                "/p:_RazorForceBuildServer=true",
-                msBuildProcessKind: msBuildProcessKind);
-
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, OutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, OutputPath, "SimpleMvc.pdb");
-            Assert.FileExists(result, OutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, OutputPath, "SimpleMvc.Views.pdb");
-
-            // Verify RazorTagHelper works
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.TagHelpers.input.cache");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.TagHelpers.output.cache");
-            Assert.FileContains(
-                result,
-                Path.Combine(IntermediateOutputPath, "SimpleMvc.TagHelpers.output.cache"),
-                @"""Name"":""SimpleMvc.SimpleTagHelper""");
-
-            // Verify RazorGenerate works
-            Assert.FileCountEquals(result, 8, RazorIntermediateOutputPath, "*.cs");
-        }
-
-        [Fact]
-        [InitializeTestProject(originalProjectName: "SimpleMvc", targetProjectName: "SimpleMvc", baseDirectory: "Whitespace in path")]
-        public async Task Build_AppWithWhitespaceInPath_CanBuildSuccessfully()
-        {
-            var result = await DotnetMSBuild(
-                "Build",
-                "/p:_RazorForceBuildServer=true");
-
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, OutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, OutputPath, "SimpleMvc.pdb");
-            Assert.FileExists(result, OutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, OutputPath, "SimpleMvc.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject(originalProjectName: "SimpleMvc", targetProjectName: "Whitespace in name", baseDirectory: "")]
-        public async Task Build_AppWithWhitespaceInName_CanBuildSuccessfully()
-        {
-            // We need to separately restore the project in order to ensure this project uses the latest Roslyn. Without this
-            // the Csc task from Roslyn would have already been loaded and any update to it from nuget packages would not have
-            // an effect. This allows us to create our obj/Whitespace in name.csproj.nuget.g.props file (we renamed the project)
-            // and then properly build the project with an appropriate Csc.
-            await DotnetMSBuild("Restore");
-
-            var result = await DotnetMSBuild(
-                "Build",
-                "/p:_RazorForceBuildServer=true");
-
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, OutputPath, "Whitespace in name.dll");
-            Assert.FileExists(result, OutputPath, "Whitespace in name.pdb");
-            Assert.FileExists(result, OutputPath, "Whitespace in name.Views.dll");
-            Assert.FileExists(result, OutputPath, "Whitespace in name.Views.pdb");
-
-            Assert.FileExists(result, IntermediateOutputPath, "Whitespace in name.Views.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "Whitespace in name.RazorCoreGenerate.cache");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Home", "Index.cshtml.g.cs");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_ErrorInServer_DisplaysErrorInMsBuildOutput()
-        {
-            var result = await DotnetMSBuild(
-                "Build",
-                "/p:_RazorForceBuildServer=true /p:RazorLangVersion=99.0");
-
-            Assert.BuildFailed(result);
-            Assert.BuildOutputContainsLine(
-                result,
-                $"Invalid option 99.0 for Razor language version --version; must be Latest or a valid version in range 1.0 to 5.0.");
-
-            // Compilation failed without creating the views assembly
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.dll");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_ServerConnectionMutexCreationFails_FallsBackToInProcessRzc()
-        {
-            // Use an invalid pipe name to make the Mutex constructor throw.
-            var pipeName = "Invalid\\name";
-            var result = await DotnetMSBuild(
-                "Build",
-                "/p:_RazorForceBuildServer=true",
-                buildServerPipeName: pipeName);
-
-            // We expect this to fail because we don't allow it to fallback to in process execution.
-            Assert.BuildFailed(result);
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-
-            // Try to build again without forcing it to run on build server.
-            result = await DotnetMSBuild(
-                "Build",
-                "/p:_RazorForceBuildServer=false",
-                buildServerPipeName: pipeName);
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-
-            // Note: We don't need to handle server clean up here because it will fail before
-            // it reaches server creation part.
-        }
-
-        // Skipping on MacOS because of https://github.com/dotnet/corefx/issues/33141.
-        [ConditionalFact]
-        [OSSkipCondition(OperatingSystems.MacOSX)]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task ManualServerShutdown_NoPipeName_ShutsDownServer()
-        {
-            // We are trying to test whether the correct pipe name is generated (from the location of rzc tool)
-            // when we don't explicitly specify a pipe name.
-
-            // Publish rzc tool to a temporary path. This is the location based on which the pipe name is generated.
-            var repositoryRoot = ProjectDirectory.SearchUp(AppContext.BaseDirectory, "global.json");
-            var solutionRoot = Path.Combine(repositoryRoot, "src", "Razor");
-            var toolAssemblyDirectory = Path.Combine(solutionRoot, "Microsoft.AspNetCore.Razor.Tools", "src");
-            var toolAssemblyPath = Path.Combine(toolAssemblyDirectory, "rzc.csproj");
-            var projectDirectory = new TestProjectDirectory(solutionRoot, toolAssemblyDirectory, toolAssemblyPath);
-            var publishDir = Path.Combine(Path.GetTempPath(), "Razor", Path.GetRandomFileName(), "RzcPublish");
-            var publishResult = await MSBuildProcessManager.RunProcessAsync(projectDirectory, $"/t:Publish /p:PublishDir=\"{publishDir}\"");
-
-            try
-            {
-                // Make sure publish succeeded.
-                Assert.BuildPassed(publishResult);
-
-                // Run the build using the published tool
-                var toolAssembly = Path.Combine(publishDir, "rzc.dll");
-                var result = await DotnetMSBuild(
-                    "Build",
-                    $"/p:_RazorForceBuildServer=true /p:_RazorSdkToolAssembly={toolAssembly}",
-                    suppressBuildServer: true); // We don't want to specify a pipe name
-
-                Assert.BuildPassed(result);
-
-                // Manually shutdown the server
-                var processStartInfo = new ProcessStartInfo()
-                {
-                    WorkingDirectory = publishDir,
-                    UseShellExecute = false,
-                    RedirectStandardError = true,
-                    RedirectStandardOutput = true,
-                    FileName = "dotnet",
-                    Arguments = $"{toolAssembly} shutdown -w"
-                };
-
-                var logFilePath = Path.Combine(publishDir, "out.log");
-                processStartInfo.Environment.Add("RAZORBUILDSERVER_LOG", logFilePath);
-                var shutdownResult = await MSBuildProcessManager.RunProcessCoreAsync(processStartInfo);
-
-                Assert.Equal(0, shutdownResult.ExitCode);
-                var output = await File.ReadAllTextAsync(logFilePath);
-                Assert.Contains("shut down completed", output);
-            }
-            finally
-            {
-                // Finally delete the temporary publish directory
-                ProjectDirectory.CleanupDirectory(publishDir);
-            }
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_WithWhiteSpaceInPipeName_BuildsSuccessfully()
-        {
-            // Start the server
-            var pipeName = "pipe with whitespace";
-            var fixture = new BuildServerTestFixture(pipeName);
-
-            try
-            {
-                // Run a build
-                var result = await DotnetMSBuild(
-                    "Build",
-                    "/p:_RazorForceBuildServer=true",
-                    buildServerPipeName: pipeName);
-
-                Assert.BuildPassed(result);
-                Assert.FileExists(result, OutputPath, "SimpleMvc.dll");
-                Assert.FileExists(result, OutputPath, "SimpleMvc.pdb");
-                Assert.FileExists(result, OutputPath, "SimpleMvc.Views.dll");
-                Assert.FileExists(result, OutputPath, "SimpleMvc.Views.pdb");
-            }
-            finally
-            {
-                // Shutdown the server
-                fixture.Dispose();
-            }
-        }
-
-        [Fact]
-        [InitializeTestProject("MvcWithComponents")]
-        public async Task Build_MvcWithComponents()
-        {
-            var tagHelperOutputCacheFile = Path.Combine(IntermediateOutputPath, "MvcWithComponents.TagHelpers.output.cache");
-
-            var result = await DotnetMSBuild(
-                "Build",
-                "/p:_RazorForceBuildServer=true");
-
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, OutputPath, "MvcWithComponents.dll");
-            Assert.FileExists(result, OutputPath, "MvcWithComponents.pdb");
-            Assert.FileExists(result, OutputPath, "MvcWithComponents.Views.dll");
-            Assert.FileExists(result, OutputPath, "MvcWithComponents.Views.pdb");
-
-            // Verify tag helper discovery from components work
-            Assert.FileExists(result, tagHelperOutputCacheFile);
-            Assert.FileContains(
-                result,
-                tagHelperOutputCacheFile,
-                @"""Name"":""MvcWithComponents.TestComponent""");
-
-            Assert.FileContains(
-                result,
-                tagHelperOutputCacheFile,
-                @"""Name"":""MvcWithComponents.Views.Shared.NavMenu""");
-
-            Assert.FileContains(
-                result,
-                tagHelperOutputCacheFile,
-                @"""Name"":""MvcWithComponents.SimpleTagHelper""");
-        }
-
-        private class TestProjectDirectory : ProjectDirectory
-        {
-            public TestProjectDirectory(string solutionPath, string directoryPath, string projectFilePath)
-                : base(solutionPath, directoryPath, projectFilePath)
-            {
-            }
-        }
-    }
-}

+ 0 - 29
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildServerTestFixture.cs

@@ -1,29 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using Microsoft.AspNetCore.Razor.Tools;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    /// <summary>
-    /// A test fixture that initializes a server as part of it's ctor.
-    /// Note that this fixture will always initialize a server of the current version since it
-    /// invokes the ServerConnection API from the referenced rzc.
-    /// </summary>
-    public class BuildServerTestFixture : BuildServerTestFixtureBase, IDisposable
-    {
-        public BuildServerTestFixture() : this(Guid.NewGuid().ToString())
-        {
-        }
-
-        internal BuildServerTestFixture(string pipeName)
-            : base(pipeName)
-        {
-            if (!ServerConnection.TryCreateServerCore(Environment.CurrentDirectory, pipeName, out _))
-            {
-                throw new InvalidOperationException($"Failed to start the build server at pipe {pipeName}.");
-            }
-        }
-    }
-}

+ 0 - 65
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildServerTestFixtureBase.cs

@@ -1,65 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Runtime.InteropServices;
-using System.Threading;
-using Microsoft.AspNetCore.Razor.Tools;
-using Microsoft.CodeAnalysis;
-using Moq;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public abstract class BuildServerTestFixtureBase : IDisposable
-    {
-        private static readonly TimeSpan _defaultShutdownTimeout = TimeSpan.FromSeconds(120);
-
-        protected BuildServerTestFixtureBase(string pipeName)
-        {
-            PipeName = pipeName;
-        }
-
-        public string PipeName { get; }
-
-        public void Dispose()
-        {
-            // Shutdown the build server.
-            using (var cts = new CancellationTokenSource(_defaultShutdownTimeout))
-            {
-                var writer = new StringWriter();
-
-                cts.Token.Register(() =>
-                {
-                    var output = writer.ToString();
-                    throw new TimeoutException($"Shutting down the build server at pipe {PipeName} took longer than expected.{Environment.NewLine}Output: {output}.");
-                });
-
-                var application = new Application(cts.Token, Mock.Of<ExtensionAssemblyLoader>(), Mock.Of<ExtensionDependencyChecker>(), (path, properties) => Mock.Of<PortableExecutableReference>(), writer, writer);
-
-                var args = new List<string>
-                {
-                    "shutdown",
-                    "-p",
-                    PipeName,
-                };
-
-                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
-                {
-                    // Workaround for https://github.com/dotnet/corefx/issues/31713. On Linux, the server shuts down but hangs around as defunct process
-                    // We'll send a shutdown request but not wait for it.
-                    args.Add("-w");
-                }
-
-                var exitCode = application.Execute(args.ToArray());
-                if (exitCode != 0)
-                {
-                    var output = writer.ToString();
-                    throw new InvalidOperationException(
-                        $"Build server at pipe {PipeName} failed to shutdown with exit code {exitCode}. Output: {output}");
-                }
-            }
-        }
-    }
-}

+ 0 - 38
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildWithComponents31IntegrationTest.cs

@@ -1,38 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class BuildWithComponents31IntegrationTest : MSBuildIntegrationTestBase, IClassFixture<BuildServerTestFixture>
-    {
-        public BuildWithComponents31IntegrationTest(BuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        [Fact]
-        [InitializeTestProject("blazor31")]
-        public async Task Build_Components_WithDotNetCoreMSBuild_Works()
-        {
-            Project.TargetFramework = "netcoreapp3.1";
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, OutputPath, "blazor31.dll");
-            Assert.FileExists(result, OutputPath, "blazor31.pdb");
-            Assert.FileExists(result, OutputPath, "blazor31.Views.dll");
-            Assert.FileExists(result, OutputPath, "blazor31.Views.pdb");
-
-            Assert.AssemblyContainsType(result, Path.Combine(OutputPath, "blazor31.dll"), "blazor31.Pages.Index");
-            Assert.AssemblyContainsType(result, Path.Combine(OutputPath, "blazor31.dll"), "blazor31.Shared.NavMenu");
-
-            // Verify a regular View appears in the views dll, but not in the main assembly.
-            Assert.AssemblyDoesNotContainType(result, Path.Combine(OutputPath, "blazor31.dll"), "blazor31.Pages.Pages__Host");
-            Assert.AssemblyContainsType(result, Path.Combine(OutputPath, "blazor31.Views.dll"), "blazor31.Pages.Pages__Host");
-        }
-    }
-}

+ 0 - 149
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/BuildWithComponentsIntegrationTest.cs

@@ -1,149 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Testing;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class BuildWithComponentsIntegrationTest : MSBuildIntegrationTestBase, IClassFixture<BuildServerTestFixture>
-    {
-        public BuildWithComponentsIntegrationTest(BuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        [Fact]
-        [InitializeTestProject("MvcWithComponents")]
-        public Task Build_Components_WithDotNetCoreMSBuild_Works() => Build_ComponentsWorks(MSBuildProcessKind.Dotnet);
-
-        [ConditionalFact]
-        [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
-        [InitializeTestProject("MvcWithComponents")]
-        public Task Build_Components_WithDesktopMSBuild_Works() => Build_ComponentsWorks(MSBuildProcessKind.Desktop);
-
-        [Fact]
-        [InitializeTestProject("ComponentApp")]
-        public async Task Build_DoesNotProduceMvcArtifacts_IfProjectDoesNotContainRazorGenerateItems()
-        {
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, OutputPath, "ComponentApp.dll");
-            Assert.FileExists(result, OutputPath, "ComponentApp.pdb");
-
-            // Verify component compilation succeeded
-            Assert.AssemblyContainsType(result, Path.Combine(OutputPath, "ComponentApp.dll"), "ComponentApp.Components.Pages.Counter");
-
-            // Verify MVC artifacts do not appear in the output.
-            Assert.FileDoesNotExist(result, OutputPath, "ComponentApp.Views.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "ComponentApp.Views.pdb");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.RazorAssemblyInfo.cs");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.RazorTargetAssemblyInfo.cs");
-        }
-
-        [Fact]
-        [InitializeTestProject("ComponentApp")]
-        public async Task Build_Successful_WhenThereAreWarnings()
-        {
-            ReplaceContent("<UnrecognizedComponent />", "Components", "Pages", "Index.razor");
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result, allowWarnings: true);
-
-            Assert.FileExists(result, OutputPath, "ComponentApp.dll");
-            Assert.FileExists(result, OutputPath, "ComponentApp.pdb");
-
-            // Verify component compilation succeeded
-            Assert.AssemblyContainsType(result, Path.Combine(OutputPath, "ComponentApp.dll"), "ComponentApp.Components.Pages.Counter");
-
-            Assert.BuildWarning(result, "RZ10012");
-        }
-
-        [Fact]
-        [InitializeTestProject("ComponentLibrary")]
-        public async Task Build_WithoutRazorLangVersion_ProducesWarning()
-        {
-            Project.TargetFramework = "netstandard2.0";
-            var result = await DotnetMSBuild("Build", "/p:RazorLangVersion=");
-
-            Assert.BuildPassed(result, allowWarnings: true);
-
-            // We should see a build warning
-            Assert.BuildWarning(result, "RAZORSDK1005");
-        }
-
-        [Fact]
-        [InitializeTestProject("ComponentLibrary")]
-        public async Task Building_NetstandardComponentLibrary()
-        {
-            Project.TargetFramework = "netstandard2.0";
-
-            // Build
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, OutputPath, "ComponentLibrary.dll");
-            Assert.FileExists(result, OutputPath, "ComponentLibrary.pdb");
-            Assert.FileDoesNotExist(result, OutputPath, "ComponentLibrary.Views.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "ComponentLibrary.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("ComponentLibrary")]
-        public async Task Build_DoesNotProduceRefsDirectory()
-        {
-            Project.TargetFramework = "netstandard2.0";
-
-            // Build
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, OutputPath, "ComponentLibrary.dll");
-           Assert.FileCountEquals(result, 0, Path.Combine(OutputPath, "refs"), "*.dll");
-        }
-
-        [Fact]
-        [InitializeTestProject("ComponentLibrary")]
-        public async Task Publish_DoesNotProduceRefsDirectory()
-        {
-            Project.TargetFramework = "netstandard2.0";
-
-            // Build
-            var result = await DotnetMSBuild("Publish");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, PublishOutputPath, "ComponentLibrary.dll");
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "refs"), "*.dll");
-        }
-
-        private async Task Build_ComponentsWorks(MSBuildProcessKind msBuildProcessKind)
-        {
-            var result = await DotnetMSBuild("Build", msBuildProcessKind: msBuildProcessKind);
-
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, OutputPath, "MvcWithComponents.dll");
-            Assert.FileExists(result, OutputPath, "MvcWithComponents.pdb");
-            Assert.FileExists(result, OutputPath, "MvcWithComponents.Views.dll");
-            Assert.FileExists(result, OutputPath, "MvcWithComponents.Views.pdb");
-
-            Assert.AssemblyContainsType(result, Path.Combine(OutputPath, "MvcWithComponents.dll"), "MvcWithComponents.TestComponent");
-            Assert.AssemblyContainsType(result, Path.Combine(OutputPath, "MvcWithComponents.dll"), "MvcWithComponents.Views.Shared.NavMenu");
-
-            // This is a component file with a .cshtml extension. It should appear in the main assembly, but not in the views dll.
-            Assert.AssemblyContainsType(result, Path.Combine(OutputPath, "MvcWithComponents.dll"), "MvcWithComponents.Components.Counter");
-            Assert.AssemblyDoesNotContainType(result, Path.Combine(OutputPath, "MvcWithComponents.Views.dll"), "MvcWithComponents.Components.Counter");
-            Assert.AssemblyDoesNotContainType(result, Path.Combine(OutputPath, "MvcWithComponents.Views.dll"), "AspNetCore.Components_Counter");
-
-            // Verify a regular View appears in the views dll, but not in the main assembly.
-            Assert.AssemblyDoesNotContainType(result, Path.Combine(OutputPath, "MvcWithComponents.dll"), "AspNetCore.Views.Home.Index");
-            Assert.AssemblyDoesNotContainType(result, Path.Combine(OutputPath, "MvcWithComponents.dll"), "AspNetCore.Views_Home_Index");
-            Assert.AssemblyContainsType(result, Path.Combine(OutputPath, "MvcWithComponents.Views.dll"), "AspNetCore.Views_Home_Index");
-        }
-    }
-}

+ 0 - 102
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/ConfigurationMetadataIntegrationTest.cs

@@ -1,102 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class ConfigurationMetadataIntegrationTest : MSBuildIntegrationTestBase, IClassFixture<BuildServerTestFixture>
-    {
-        public ConfigurationMetadataIntegrationTest(BuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_DoesNotAddHostingMetadata_ByDefault()
-        {
-            var razorAssemblyInfo = Path.Combine(IntermediateOutputPath, "SimpleMvc.RazorAssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.pdb");
-
-            Assert.FileExists(result, razorAssemblyInfo);
-            Assert.FileContainsLine(
-                result,
-                razorAssemblyInfo,
-                "[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.RelatedAssemblyAttribute(\"SimpleMvc.Views\")]");
-            Assert.FileDoesNotContainLine(
-                result,
-                razorAssemblyInfo,
-                "[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorLanguageVersionAttribute(\"3.0\")]");
-            Assert.FileDoesNotContainLine(
-                result,
-                razorAssemblyInfo,
-                "[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorConfigurationNameAttribute(\"MVC-3.0\")]");
-            Assert.FileDoesNotContainLine(
-                result,
-                razorAssemblyInfo,
-                "[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorExtensionAssemblyNameAttribute(\"MVC-3.0\", \"Microsoft.AspNetCore.Mvc.Razor.Extensions\")]");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Build_WithGenerateRazorHostingAssemblyInfo_AddsConfigurationMetadata()
-        {
-            var razorAssemblyInfo = Path.Combine(IntermediateOutputPath, "SimpleMvc.RazorAssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build", "/p:GenerateRazorHostingAssemblyInfo=true");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.pdb");
-
-            Assert.FileExists(result, razorAssemblyInfo);
-            Assert.FileContainsLine(
-                result,
-                razorAssemblyInfo,
-                "[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorLanguageVersionAttribute(\"5.0\")]");
-            Assert.FileContainsLine(
-                result,
-                razorAssemblyInfo,
-                "[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorConfigurationNameAttribute(\"MVC-3.0\")]");
-            Assert.FileContainsLine(
-                result,
-                razorAssemblyInfo,
-                "[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorExtensionAssemblyNameAttribute(\"MVC-3.0\", \"Microsoft.AspNetCore.Mvc.Razor.Extensions\")]");
-        }
-
-        [Fact]
-        [InitializeTestProject("ClassLibrary")]
-        public async Task Build_ForClassLibrary_SuppressesConfigurationMetadata()
-        {
-            var razorAssemblyInfo = Path.Combine(IntermediateOutputPath, "ClassLibrary.RazorAssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "ClassLibrary.Views.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "ClassLibrary.Views.pdb");
-
-            Assert.FileExists(result, razorAssemblyInfo);
-            Assert.FileDoesNotContainLine(
-                result,
-                razorAssemblyInfo,
-                "[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorLanguageVersionAttribute(\"3.0\")]");
-            Assert.FileDoesNotContainLine(
-                result,
-                razorAssemblyInfo,
-                "[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorConfigurationNameAttribute(\"MVC-3.0\")]");
-            Assert.FileDoesNotContainLine(
-                result,
-                razorAssemblyInfo,
-                "[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorExtensionAssemblyNameAttribute(\"MVC-3.0\", \"Microsoft.AspNetCore.Razor.Extensions\")]");
-        }
-    }
-}

+ 0 - 92
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/DesignTimeBuildIntegrationTest.cs

@@ -1,92 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class DesignTimeBuildIntegrationTest : MSBuildIntegrationTestBase, IClassFixture<BuildServerTestFixture>
-    {
-        public DesignTimeBuildIntegrationTest(BuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task DesignTimeBuild_DoesNotRunRazorTargets()
-        {
-            // Using Compile here instead of CompileDesignTime because the latter is only defined when using
-            // the VS targets. This is a close enough simulation for an SDK project
-            var result = await DotnetMSBuild("Compile", "/p:DesignTimeBuild=true /clp:PerformanceSummary");
-
-            Assert.BuildPassed(result);
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.pdb");
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.Views.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.Views.pdb");
-
-            // This target should be part of the design time build.
-            Assert.Contains("_GenerateRazorAssemblyInfo", result.Output);
-
-            // We don't want to see the expensive Razor targets in the performance summary, since they shouldn't run
-            // during a design time build.
-            Assert.DoesNotContain("RazorCoreGenerate", result.Output);
-            Assert.DoesNotContain("RazorCoreCompile", result.Output);
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorGenerateDesignTime_ReturnsRazorGenerateWithTargetPath()
-        {
-            var result = await DotnetMSBuild("RazorGenerateDesignTime;_IntrospectRazorGenerateWithTargetPath");
-
-            Assert.BuildPassed(result);
-
-            var filePaths = new string[]
-            {
-                Path.Combine("Views", "Home", "About.cshtml"),
-                Path.Combine("Views", "Home", "Contact.cshtml"),
-                Path.Combine("Views", "Home", "Index.cshtml"),
-                Path.Combine("Views", "Shared", "Error.cshtml"),
-                Path.Combine("Views", "Shared", "_Layout.cshtml"),
-                Path.Combine("Views", "Shared", "_ValidationScriptsPartial.cshtml"),
-                Path.Combine("Views", "_ViewImports.cshtml"),
-                Path.Combine("Views", "_ViewStart.cshtml"),
-            };
-
-            foreach (var filePath in filePaths)
-            {
-                Assert.BuildOutputContainsLine(
-                    result,
-                    $@"RazorGenerateWithTargetPath: {filePath} {filePath} {Path.Combine(RazorIntermediateOutputPath, filePath + ".g.cs")}");
-            }
-        }
-
-        [Fact]
-        [InitializeTestProject("ComponentLibrary")]
-        public async Task RazorGenerateComponentDesignTime_ReturnsRazorComponentWithTargetPath()
-        {
-            Project.TargetFramework = "netstandard2.0";
-
-            var result = await DotnetMSBuild("RazorGenerateComponentDesignTime;_IntrospectRazorComponentWithTargetPath");
-
-            Assert.BuildPassed(result);
-
-            var filePaths = new string[]
-            {
-                Path.Combine("GenericComponent.razor"),
-                Path.Combine("MyComponent.razor"),
-            };
-
-            foreach (var filePath in filePaths)
-            {
-                Assert.BuildOutputContainsLine(
-                    result,
-                    $@"RazorComponentWithTargetPath: {filePath} {filePath} {Path.Combine(RazorIntermediateOutputPath, filePath + ".g.cs")} {Path.Combine(RazorComponentIntermediateOutputPath, filePath + ".g.cs")}");
-            }
-        }
-    }
-}

+ 0 - 9
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/Directory.Build.props

@@ -1,9 +0,0 @@
-<Project>
-  <!-- UseVSTestRunner must be configured before the $(RepoRoot)\Directory.Build.props is included. -->
-  <PropertyGroup>
-    <UseVSTestRunner>true</UseVSTestRunner>
-    <TestRunnerAdditionalArguments>$(TestRunnerAdditionalArguments) --blame "CollectHangDump;TestTimeout=6m"</TestRunnerAdditionalArguments>
-  </PropertyGroup>
-
-  <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory)..\, Directory.Build.props))\Directory.Build.props" />
-</Project>

+ 0 - 53
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/InitializeTestProjectAttribute.cs

@@ -1,53 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Reflection;
-using Xunit.Sdk;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class InitializeTestProjectAttribute : BeforeAfterTestAttribute
-    {
-        private readonly string _originalProjectName;
-        private readonly string _testProjectName;
-        private readonly string _baseDirectory;
-        private readonly string[] _additionalProjects;
-        private readonly string _language;
-
-        public InitializeTestProjectAttribute(string projectName, string language = "C#", params string[] additionalProjects)
-            : this (projectName, projectName, string.Empty, language, additionalProjects)
-        {
-        }
-
-        public InitializeTestProjectAttribute(string originalProjectName, string targetProjectName, string baseDirectory, string language = "C#", string[] additionalProjects = null)
-        {
-            _originalProjectName = originalProjectName;
-            _testProjectName = targetProjectName;
-            _baseDirectory = baseDirectory;
-            _additionalProjects = additionalProjects ?? Array.Empty<string>();
-            _language = language;
-        }
-
-        public override void Before(MethodInfo methodUnderTest)
-        {
-            if (!typeof(MSBuildIntegrationTestBase).GetTypeInfo().IsAssignableFrom(methodUnderTest.DeclaringType.GetTypeInfo()))
-            {
-                throw new InvalidOperationException($"This should be used on a class derived from {typeof(MSBuildIntegrationTestBase)}");
-            }
-
-            MSBuildIntegrationTestBase.Project = ProjectDirectory.Create(_originalProjectName, new ProjectDirectory.ProjectDirectoryOptions(_baseDirectory, _testProjectName, _language), _additionalProjects);
-        }
-
-        public override void After(MethodInfo methodUnderTest)
-        {
-            if (!typeof(MSBuildIntegrationTestBase).GetTypeInfo().IsAssignableFrom(methodUnderTest.DeclaringType.GetTypeInfo()))
-            {
-                throw new InvalidOperationException($"This should be used on a class derived from {typeof(MSBuildIntegrationTestBase)}");
-            }
-
-            MSBuildIntegrationTestBase.Project.Dispose();
-            MSBuildIntegrationTestBase.Project = null;
-        }
-    }
-}

+ 0 - 18
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/LegacyBuildServerTestFixture.cs

@@ -1,18 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    /// <summary>
-    /// A fixture that relies on the build task to spin up the build server.
-    /// </summary>
-    public class LegacyBuildServerTestFixture : BuildServerTestFixtureBase
-    {
-        public LegacyBuildServerTestFixture()
-            : base(Guid.NewGuid().ToString())
-        {
-        }
-    }
-}

+ 0 - 165
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/MSBuildIntegrationTestBase.cs

@@ -1,165 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Reflection;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using Moq;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public abstract class MSBuildIntegrationTestBase
-    {
-        private static readonly AsyncLocal<ProjectDirectory> _project = new AsyncLocal<ProjectDirectory>();
-
-        protected MSBuildIntegrationTestBase(BuildServerTestFixtureBase buildServer)
-        {
-            BuildServer = buildServer;
-        }
-
-#if DEBUG
-        protected string Configuration => "Debug";
-#elif RELEASE
-        protected string Configuration => "Release";
-#else
-#error Configuration not supported
-#endif
-
-        protected string IntermediateOutputPath => Path.Combine("obj", Configuration, Project.TargetFramework);
-
-        protected string OutputPath => Path.Combine("bin", Configuration, Project.TargetFramework);
-
-        protected string PublishOutputPath => Path.Combine(OutputPath, "publish");
-
-        protected string GetRidSpecificPublishOutputPath(string rid) => Path.Combine(OutputPath, rid, "publish");
-
-        // Used by the test framework to set the project that we're working with
-        internal static ProjectDirectory Project
-        {
-            get { return _project.Value; }
-            set { _project.Value = value; }
-        }
-
-        protected string RazorIntermediateOutputPath => Path.Combine(IntermediateOutputPath, "Razor");
-
-        protected string RazorComponentIntermediateOutputPath => Path.Combine(IntermediateOutputPath, "RazorDeclaration");
-
-        protected BuildServerTestFixtureBase BuildServer { get; set; }
-
-        internal Task<MSBuildResult> DotnetMSBuild(
-            string target,
-            string args = null,
-            bool suppressTimeout = false,
-            bool suppressBuildServer = false,
-            string buildServerPipeName = null,
-            MSBuildProcessKind msBuildProcessKind = MSBuildProcessKind.Dotnet)
-        {
-            var timeout = suppressTimeout ? (TimeSpan?)Timeout.InfiniteTimeSpan : null;
-
-            var buildArgumentList = new List<string>
-            {
-                // Disable node-reuse. We don't want msbuild processes to stick around
-                // once the test is completed.
-                "/nr:false",
-
-                // Always generate a bin log for debugging purposes
-                "/bl",
-
-                // Let the test app know it is running as part of a test.
-                "/p:RunningAsTest=true",
-
-                $"/p:MicrosoftNETCoreAppRuntimeVersion={BuildVariables.MicrosoftNETCoreAppRuntimeVersion}",
-                $"/p:MicrosoftNetCompilersToolsetVersion={BuildVariables.MicrosoftNetCompilersToolsetVersion}",
-                $"/p:RazorSdkDirectoryRoot={BuildVariables.RazorSdkDirectoryRoot}",
-                $"/p:RepoRoot={BuildVariables.RepoRoot}",
-            };
-
-            if (!suppressBuildServer)
-            {
-                buildArgumentList.Add($@"/p:_RazorBuildServerPipeName=""{buildServerPipeName ?? BuildServer.PipeName}""");
-            }
-
-            if (!string.IsNullOrEmpty(target))
-            {
-                buildArgumentList.Add($"/t:{target}");
-            }
-            else
-            {
-                buildArgumentList.Add($"/t:Build");
-            }
-
-            buildArgumentList.Add($"/p:Configuration={Configuration} {args}");
-            var buildArguments = string.Join(" ", buildArgumentList);
-
-            return MSBuildProcessManager.RunProcessAsync(
-                Project,
-                buildArguments,
-                timeout,
-                msBuildProcessKind);
-        }
-
-        internal void AddProjectFileContent(string content)
-            => Project.AddProjectFileContent(content);
-
-        internal void ReplaceContent(string content, params string[] paths)
-        {
-            if (content == null)
-            {
-                throw new ArgumentNullException(nameof(content));
-            }
-
-            if (paths == null)
-            {
-                throw new ArgumentNullException(nameof(paths));
-            }
-
-            var filePath = Path.Combine(Project.DirectoryPath, Path.Combine(paths));
-            if (!File.Exists(filePath))
-            {
-                throw new InvalidOperationException($"File {filePath} could not be found.");
-            }
-
-            File.WriteAllText(filePath, content, Encoding.UTF8);
-            // Timestamps on xplat are precise only to a second. Update it's last write time by at least 1 second
-            // so we can ensure that MSBuild recognizes the file change. See https://github.com/dotnet/corefx/issues/26024
-            File.SetLastWriteTimeUtc(filePath, File.GetLastWriteTimeUtc(filePath).AddSeconds(1));
-        }
-
-        /// <summary>
-        /// Locks all files, discovered at the time of method invocation, under the
-        /// specified <paramref name="directory" /> from reads or writes.
-        /// </summary>
-        public IDisposable LockDirectory(string directory)
-        {
-            directory = Path.Combine(Project.DirectoryPath, directory);
-            var disposables = new List<IDisposable>();
-            foreach (var file in Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories))
-            {
-                disposables.Add(LockFile(file));
-            }
-
-            var disposable = new Mock<IDisposable>();
-            disposable.Setup(d => d.Dispose())
-                .Callback(() => disposables.ForEach(d => d.Dispose()));
-
-            return disposable.Object;
-        }
-
-        public IDisposable LockFile(string path)
-        {
-            path = Path.Combine(Project.DirectoryPath, path);
-            return File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None);
-        }
-
-        public FileThumbPrint GetThumbPrint(string path)
-        {
-            path = Path.Combine(Project.DirectoryPath, path);
-            return FileThumbPrint.Create(path);
-        }
-    }
-}

+ 0 - 79
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/Microsoft.NET.Sdk.Razor.IntegrationTests.csproj

@@ -1,79 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
-  <PropertyGroup>
-    <!--
-      There's not much value in multi-targeting here, this doesn't run much .NET code, it tests MSBuild.
-
-      This is also a partial workaround for https://github.com/Microsoft/msbuild/issues/2661 - this project
-      has netcoreapp dependencies that need to be built first.
-    -->
-    <TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework>
-    <PreserveCompilationContext>true</PreserveCompilationContext>
-    <DefineConstants Condition="'$(PreserveWorkingDirectory)'=='true'">$(DefineConstants);PRESERVE_WORKING_DIRECTORY</DefineConstants>
-
-    <!-- Tests do not work on Helix yet. When enabled, add Publish to BeforeTargets of RestoreTestProjects. -->
-    <BuildHelixPayload>false</BuildHelixPayload>
-    <TestAppsRoot>$(MSBuildProjectDirectory)\..\..\test\testassets\</TestAppsRoot>
-  </PropertyGroup>
-
-  <Import Project="$(SharedSourceRoot)MSBuild.Testing\MSBuild.Testing.targets" />
-
-  <ItemGroup>
-    <None Include="xunit.runner.json" CopyToOutputDirectory="PreserveNewest" />
-  </ItemGroup>
-
-  <ItemGroup>
-    <Reference Include="Microsoft.Build.Utilities.Core" />
-    <Reference Include="Microsoft.Extensions.DependencyModel" />
-  </ItemGroup>
-
-  <ItemGroup>
-    <Reference Include="rzc" />
-    <ProjectReference Include="..\..\test\Microsoft.AspNetCore.Razor.Test.MvcShim.ClassLib\Microsoft.AspNetCore.Razor.Test.MvcShim.ClassLib.csproj" />
-    <Reference Include="Microsoft.NET.Sdk.Razor" ReferenceOutputAssembly="false" SkipGetTargetFrameworkProperties="true" />
-  </ItemGroup>
-
-  <!-- Ensure shared framework and targeting packs are laid out under .dotnet/ before executing tests. -->
-  <ItemGroup Condition=" '$(DotNetBuildFromSource)' != 'true' ">
-    <ProjectReference Include="$(RepoRoot)src\Framework\App.Ref\src\Microsoft.AspNetCore.App.Ref.csproj"
-        Condition=" $(IsTargetingPackBuilding) "
-        ReferenceOutputAssembly="false"
-        SkipGetTargetFrameworkProperties="true" />
-    <ProjectReference Include="$(RepoRoot)src\Framework\App.Runtime\src\Microsoft.AspNetCore.App.Runtime.csproj"
-        Condition=" !$(IsTargetingPackBuilding) "
-        ReferenceOutputAssembly="false"
-        SkipGetTargetFrameworkProperties="true" />
-  </ItemGroup>
-
-  <Target Name="GenerateTestData" BeforeTargets="GetAssemblyAttributes">
-    <Exec Condition="'$(OS)' == 'Windows_NT'" Command="&quot;$(NuGetPackageRoot)vswhere\$(VSWhereVersion)\tools\vswhere.exe&quot; -latest -prerelease -property installationPath -requires Microsoft.Component.MSBuild" ConsoleToMsBuild="true" StandardErrorImportance="high">
-      <Output TaskParameter="ConsoleOutput" PropertyName="_VSInstallDir" />
-    </Exec>
-    <Error Condition="'$(OS)' == 'Windows_NT' and '$(_VSInstallDir)'=='' and '$(Test)' == 'true'" Text="Visual Studio not found on Windows." />
-
-    <PropertyGroup>
-      <_DesktopMSBuildPath Condition="'$(OS)' == 'Windows_NT' and Exists('$(_VSInstallDir)\MSBuild\Current\Bin\msbuild.exe')">$(_VSInstallDir)\MSBuild\Current\Bin\msbuild.exe</_DesktopMSBuildPath>
-      <_DesktopMSBuildPath Condition="'$(OS)' == 'Windows_NT' and Exists('$(_VSInstallDir)\MSBuild\15.0\Bin\msbuild.exe')">$(_VSInstallDir)\MSBuild\15.0\Bin\msbuild.exe</_DesktopMSBuildPath>
-    </PropertyGroup>
-
-    <Error Condition="'$(OS)' == 'Windows_NT' and '$(_DesktopMSBuildPath)'=='' and '$(Test)' == 'true'" Text="MSBuild.exe not found on Windows." />
-
-    <ItemGroup>
-      <AssemblyAttribute Include="System.Reflection.AssemblyMetadataAttribute">
-        <_Parameter1>DesktopMSBuildPath</_Parameter1>
-        <_Parameter2>$(_DesktopMSBuildPath)</_Parameter2>
-      </AssemblyAttribute>
-    </ItemGroup>
-  </Target>
-
-  <Target Name="RestoreTestProjects" BeforeTargets="RunTests;Test;VSTest" Condition=" '$(DotNetBuildFromSource)' != 'true' ">
-    <MSBuild Projects="..\..\test\testassets\RestoreTestProjects\RestoreTestProjects.csproj" Targets="Restore" Properties="RepoRoot=$(RepoRoot)" />
-    <MSBuild Projects="..\..\test\testassets\PackageLibraryDirectDependency\PackageLibraryDirectDependency.csproj" Targets="Restore" Properties="RepoRoot=$(RepoRoot)" />
-    <MSBuild Projects="..\..\test\testassets\PackageLibraryTransitiveDependency\PackageLibraryTransitiveDependency.csproj" Targets="Restore" Properties="RepoRoot=$(RepoRoot)" />
-  </Target>
-
-  <Target Name="EnsureLogFolder" AfterTargets="Build">
-    <MakeDir Directories="$([MSBuild]::NormalizeDirectory('$(ArtifactsDir)', 'log', '$(_BuildConfig)'))" />
-  </Target>
-
-</Project>

+ 0 - 91
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/MvcBuildIntegrationTest21.cs

@@ -1,91 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class MvcBuildIntegrationTest21 : MvcBuildIntegrationTestLegacy
-    {
-        public MvcBuildIntegrationTest21(LegacyBuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        public override string TestProjectName => "SimpleMvc21";
-        public override string TargetFramework => "netcoreapp2.1";
-
-        [Fact]
-        public async Task Building_WorksWhenMultipleRazorConfigurationsArePresent()
-        {
-            using (var project = CreateTestProject())
-            {
-                AddProjectFileContent(@"
-<ItemGroup>
-    <RazorConfiguration Include=""MVC-2.1"">
-      <Extensions>MVC-2.1;$(CustomRazorExtension)</Extensions>
-    </RazorConfiguration>
-</ItemGroup>");
-
-                // Build
-                var result = await DotnetMSBuild("Build");
-
-                Assert.BuildPassed(result);
-                Assert.FileExists(result, OutputPath, "SimpleMvc21.dll");
-                Assert.FileExists(result, OutputPath, "SimpleMvc21.pdb");
-                Assert.FileExists(result, OutputPath, "SimpleMvc21.Views.dll");
-                Assert.FileExists(result, OutputPath, "SimpleMvc21.Views.pdb");
-            }
-        }
-
-        [Fact]
-        public virtual async Task Build_DoesNotAddRelatedAssemblyPart_IfToolSetIsNotRazorSdk()
-        {
-            using (CreateTestProject())
-            {
-                var razorAssemblyInfo = Path.Combine(IntermediateOutputPath, $"{TestProjectName}.RazorAssemblyInfo.cs");
-                var result = await DotnetMSBuild("Build", "/p:RazorCompileToolSet=MvcPrecompilation");
-
-                Assert.BuildPassed(result);
-
-                Assert.FileDoesNotExist(result, razorAssemblyInfo);
-                Assert.FileDoesNotExist(result, IntermediateOutputPath, $"{TestProjectName}.RazorTargetAssemblyInfo.cs");
-            }
-        }
-
-        [Fact]
-        public virtual async Task Publish_NoopsWithMvcRazorCompileOnPublish_False()
-        {
-            using (CreateTestProject())
-            {
-                var result = await DotnetMSBuild("Publish", "/p:MvcRazorCompileOnPublish=false");
-
-                Assert.BuildPassed(result);
-
-                // Everything we do should noop - including building the app.
-                Assert.FileExists(result, PublishOutputPath, OutputFileName);
-                Assert.FileExists(result, PublishOutputPath, $"{TestProjectName}.pdb");
-                Assert.FileDoesNotExist(result, PublishOutputPath, $"{TestProjectName}.Views.dll");
-                Assert.FileDoesNotExist(result, PublishOutputPath, $"{TestProjectName}.Views.pdb");
-            }
-        }
-
-        [Fact] // This will use the old precompilation tool, RazorSDK shouldn't get involved.
-        public virtual async Task Build_WithMvcRazorCompileOnPublish_Noops()
-        {
-            using (CreateTestProject())
-            {
-                var result = await DotnetMSBuild("Build", "/p:MvcRazorCompileOnPublish=true");
-
-                Assert.BuildPassed(result);
-
-                Assert.FileExists(result, IntermediateOutputPath, OutputFileName);
-                Assert.FileExists(result, IntermediateOutputPath, OutputFileName);
-                Assert.FileDoesNotExist(result, IntermediateOutputPath, $"{TestProjectName}.Views.dll");
-                Assert.FileDoesNotExist(result, IntermediateOutputPath, $"{TestProjectName}.Views.pdb");
-            }
-        }
-    }
-}

+ 0 - 47
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/MvcBuildIntegrationTest22.cs

@@ -1,47 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Testing;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class MvcBuildIntegrationTest22 : MvcBuildIntegrationTestLegacy
-    {
-        public MvcBuildIntegrationTest22(LegacyBuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        public override string TestProjectName => "SimpleMvc22";
-        public override string TargetFramework => "netcoreapp2.2";
-
-        [ConditionalFact]
-        [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
-        public async Task BuildProject_UsingDesktopMSBuild()
-        {
-            using var _ = CreateTestProject();
-
-            // Build
-            // This is a regression test for https://github.com/dotnet/aspnetcore/issues/28333. We're trying to ensure
-            // building in Desktop when DOTNET_HOST_PATH is not configured continues to work.
-            // Explicitly unset it to verify a value is not being picked up as an ambient value.
-            var result = await DotnetMSBuild("Build", args: "/p:DOTNET_HOST_PATH=", msBuildProcessKind: MSBuildProcessKind.Desktop);
-
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, OutputPath, OutputFileName);
-            Assert.FileExists(result, OutputPath, $"{TestProjectName}.pdb");
-            Assert.FileExists(result, OutputPath, $"{TestProjectName}.Views.dll");
-            Assert.FileExists(result, OutputPath, $"{TestProjectName}.Views.pdb");
-
-            // Verify RazorTagHelper works
-            Assert.FileExists(result, IntermediateOutputPath, $"{TestProjectName}.TagHelpers.input.cache");
-            Assert.FileExists(result, IntermediateOutputPath, $"{TestProjectName}.TagHelpers.output.cache");
-            Assert.FileContains(
-                result,
-                Path.Combine(IntermediateOutputPath, $"{TestProjectName}.TagHelpers.output.cache"),
-                @"""Name"":""SimpleMvc.SimpleTagHelper""");
-        }
-    }
-}

+ 0 - 48
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/MvcBuildIntegrationTest31.cs

@@ -1,48 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class MvcBuildIntegrationTest31 : MvcBuildIntegrationTestLegacy
-    {
-        public MvcBuildIntegrationTest31(LegacyBuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        public override string TestProjectName => "SimpleMvc31";
-        public override string TargetFramework => "netcoreapp3.1";
-
-        [Fact]
-        public async Task Build_WithGenerateRazorHostingAssemblyInfo_AddsConfigurationMetadata()
-        {
-            using var project = CreateTestProject();
-
-            var razorAssemblyInfo = Path.Combine(IntermediateOutputPath, "SimpleMvc31.RazorAssemblyInfo.cs");
-            var result = await DotnetMSBuild("Build", "/p:GenerateRazorHostingAssemblyInfo=true");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc31.Views.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc31.Views.pdb");
-
-            Assert.FileExists(result, razorAssemblyInfo);
-            Assert.FileContainsLine(
-                result,
-                razorAssemblyInfo,
-                "[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorLanguageVersionAttribute(\"3.0\")]");
-            Assert.FileContainsLine(
-                result,
-                razorAssemblyInfo,
-                "[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorConfigurationNameAttribute(\"MVC-3.0\")]");
-            Assert.FileContainsLine(
-                result,
-                razorAssemblyInfo,
-                "[assembly: Microsoft.AspNetCore.Razor.Hosting.RazorExtensionAssemblyNameAttribute(\"MVC-3.0\", \"Microsoft.AspNetCore.Mvc.Razor.Extensions\")]");
-        }
-    }
-}

+ 0 - 146
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/MvcBuildIntegrationTestLegacy.cs

@@ -1,146 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Testing;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public abstract class MvcBuildIntegrationTestLegacy :
-        MSBuildIntegrationTestBase,
-        IClassFixture<LegacyBuildServerTestFixture>
-    {
-        public abstract string TestProjectName { get; }
-        public abstract string TargetFramework { get; }
-        public virtual string OutputFileName => $"{TestProjectName}.dll";
-
-        public MvcBuildIntegrationTestLegacy(LegacyBuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        protected IDisposable CreateTestProject()
-        {
-            Project = ProjectDirectory.Create(TestProjectName);
-            Project.TargetFramework = TargetFramework;
-
-            return new Disposable();
-        }
-
-        [Fact]
-        public virtual async Task Building_Project()
-        {
-            using (CreateTestProject())
-            {
-                // Build
-                var result = await DotnetMSBuild("Build");
-
-                Assert.BuildPassed(result);
-                Assert.FileExists(result, OutputPath, OutputFileName);
-                Assert.FileExists(result, OutputPath, $"{TestProjectName}.pdb");
-                Assert.FileExists(result, OutputPath, $"{TestProjectName}.Views.dll");
-                Assert.FileExists(result, OutputPath, $"{TestProjectName}.Views.pdb");
-
-                // Verify RazorTagHelper works
-                Assert.FileExists(result, IntermediateOutputPath, $"{TestProjectName}.TagHelpers.input.cache");
-                Assert.FileExists(result, IntermediateOutputPath, $"{TestProjectName}.TagHelpers.output.cache");
-                Assert.FileContains(
-                    result,
-                    Path.Combine(IntermediateOutputPath, $"{TestProjectName}.TagHelpers.output.cache"),
-                    @"""Name"":""SimpleMvc.SimpleTagHelper""");
-            }
-        }
-
-        [Fact]
-        public virtual async Task BuildingProject_CopyToOutputDirectoryFiles()
-        {
-            using (CreateTestProject())
-            {
-                // Build
-                var result = await DotnetMSBuild("Build");
-
-                Assert.BuildPassed(result);
-                // No cshtml files should be in the build output directory
-                Assert.FileCountEquals(result, 0, Path.Combine(OutputPath, "Views"), "*.cshtml");
-
-                // For .NET Core projects, no ref assemblies should be present in the output directory.
-                Assert.FileCountEquals(result, 0, Path.Combine(OutputPath, "refs"), "*.dll");
-            }
-        }
-
-        [Fact]
-        public virtual async Task Publish_Project()
-        {
-            using (CreateTestProject())
-            {
-                var result = await DotnetMSBuild("Publish");
-
-                Assert.BuildPassed(result);
-
-                Assert.FileExists(result, PublishOutputPath, OutputFileName);
-                Assert.FileExists(result, PublishOutputPath, $"{TestProjectName}.pdb");
-                Assert.FileExists(result, PublishOutputPath, $"{TestProjectName}.Views.dll");
-                Assert.FileExists(result, PublishOutputPath, $"{TestProjectName}.Views.pdb");
-
-                // By default refs and .cshtml files will not be copied on publish
-                Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "refs"), "*.dll");
-                Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "Views"), "*.cshtml");
-            }
-        }
-
-        [Fact]
-        public virtual async Task Build_DoesNotPrintsWarnings_IfProjectFileContainsRazorFiles()
-        {
-            using (CreateTestProject())
-            {
-                File.WriteAllText(Path.Combine(Project.DirectoryPath, "Index.razor"), "Hello world");
-                var result = await DotnetMSBuild("Build");
-
-                Assert.BuildPassed(result);
-                Assert.DoesNotContain("RAZORSDK1005", result.Output);
-            }
-        }
-
-        [Fact]
-        public async Task PublishingProject_CopyToPublishDirectoryItems()
-        {
-            using (CreateTestProject())
-            {
-                // Build
-                var result = await DotnetMSBuild("Publish");
-
-                Assert.BuildPassed(result);
-
-                // refs shouldn't be produced by default
-                Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "refs"), "*.dll");
-
-                // Views shouldn't be produced by default
-                Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "Views"), "*.cshtml");
-            }
-        }
-
-        [Fact]
-        public virtual async Task Publish_IncludesRefAssemblies_WhenCopyRefAssembliesToPublishDirectoryIsSet()
-        {
-            using (CreateTestProject())
-            {
-                var result = await DotnetMSBuild("Publish", "/p:CopyRefAssembliesToPublishDirectory=true");
-
-                Assert.BuildPassed(result);
-                Assert.FileExists(result, PublishOutputPath, "refs", "System.Threading.Tasks.Extensions.dll");
-            }
-        }
-
-        private class Disposable : IDisposable
-        {
-            public void Dispose()
-            {
-                Project.Dispose();
-                Project = null;
-            }
-        }
-    }
-}

+ 0 - 403
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/PackIntegrationTest.cs

@@ -1,403 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.IO;
-using System.Runtime.InteropServices;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class PackIntegrationTest : MSBuildIntegrationTestBase, IClassFixture<BuildServerTestFixture>
-    {
-        private static readonly string TFM = "net6.0";
-
-        public PackIntegrationTest(BuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        [Fact]
-        [InitializeTestProject("ClassLibrary")]
-        public async Task Pack_NoBuild_IncludeRazorContent_IncludesRazorViewContent()
-        {
-            var result = await DotnetMSBuild("Build");
-            Assert.BuildPassed(result);
-
-            result = await DotnetMSBuild("Pack", "/p:NoBuild=true /p:IncludeRazorContentInPack=true");
-            Assert.BuildPassed(result);
-
-            Assert.NuspecContains(
-                result,
-                Path.Combine("obj", Configuration, "ClassLibrary.1.0.0.nuspec"),
-                $@"<files include=""any/{TFM}/Views/Shared/_Layout.cshtml"" buildAction=""Content"" />");
-
-            Assert.NupkgContains(
-                result,
-                Path.Combine("bin", Configuration, "ClassLibrary.1.0.0.nupkg"),
-                Path.Combine("contentFiles", "any", TFM, "Views", "Shared", "_Layout.cshtml"));
-        }
-
-        [Fact]
-        [InitializeTestProject("ClassLibrary")]
-        public async Task Pack_NoBuild_Works_IncludesRazorAssembly()
-        {
-            var result = await DotnetMSBuild("Build");
-            Assert.BuildPassed(result);
-
-            result = await DotnetMSBuild("Pack", "/p:NoBuild=true");
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, OutputPath, "ClassLibrary.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.Views.dll");
-
-            if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
-            {
-                // Travis on OSX produces different full paths in C# and MSBuild
-                Assert.NuspecContains(
-                    result,
-                    Path.Combine("obj", Configuration, "ClassLibrary.1.0.0.nuspec"),
-                    $"<file src=\"{Path.Combine(Project.DirectoryPath, "bin", Configuration, TFM, "ClassLibrary.Views.dll")}\" " +
-                    $"target=\"{Path.Combine("lib", TFM, "ClassLibrary.Views.dll")}\" />");
-
-                Assert.NuspecDoesNotContain(
-                    result,
-                    Path.Combine("obj", Configuration, "ClassLibrary.1.0.0.nuspec"),
-                    $"<file src=\"{Path.Combine(Project.DirectoryPath, "bin", Configuration, TFM, "ClassLibrary.Views.pdb")}\" " +
-                    $"target=\"{Path.Combine("lib", TFM, "ClassLibrary.Views.pdb")}\" />");
-            }
-
-            Assert.NuspecDoesNotContain(
-                result,
-                Path.Combine("obj", Configuration, "ClassLibrary.1.0.0.nuspec"),
-                $@"<files include=""any/{TFM}/Views/Shared/_Layout.cshtml"" buildAction=""Content"" />");
-
-            Assert.NupkgContains(
-                result,
-                Path.Combine("bin", Configuration, "ClassLibrary.1.0.0.nupkg"),
-                Path.Combine("lib", TFM, "ClassLibrary.Views.dll"));
-        }
-
-        [Fact]
-        [InitializeTestProject("ClassLibrary")]
-        public async Task Pack_Works_IncludesRazorAssembly()
-        {
-            var result = await DotnetMSBuild("Pack");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, OutputPath, "ClassLibrary.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.Views.dll");
-
-            if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
-            {
-                // Travis on OSX produces different full paths in C# and MSBuild
-                Assert.NuspecContains(
-                    result,
-                    Path.Combine("obj", Configuration, "ClassLibrary.1.0.0.nuspec"),
-                    $"<file src=\"{Path.Combine(Project.DirectoryPath, "bin", Configuration, TFM, "ClassLibrary.Views.dll")}\" " +
-                    $"target=\"{Path.Combine("lib", TFM, "ClassLibrary.Views.dll")}\" />");
-
-                Assert.NuspecDoesNotContain(
-                    result,
-                    Path.Combine("obj", Configuration, "ClassLibrary.1.0.0.nuspec"),
-                    $"<file src=\"{Path.Combine(Project.DirectoryPath, "bin", Configuration, TFM, "ClassLibrary.Views.pdb")}\" " +
-                    $"target=\"{Path.Combine("lib", TFM, "ClassLibrary.Views.pdb")}\" />");
-            }
-
-            Assert.NuspecDoesNotContain(
-                result,
-                Path.Combine("obj", Configuration, "ClassLibrary.1.0.0.nuspec"),
-                $@"<files include=""any/{TFM}/Views/Shared/_Layout.cshtml"" buildAction=""Content"" />");
-
-            Assert.NupkgContains(
-                result,
-                Path.Combine("bin", Configuration, "ClassLibrary.1.0.0.nupkg"),
-                Path.Combine("lib", TFM, "ClassLibrary.Views.dll"));
-        }
-
-        [Fact]
-        [InitializeTestProject("ClassLibrary")]
-        public async Task Pack_WithIncludeSymbols_IncludesRazorPdb()
-        {
-            var result = await DotnetMSBuild("Pack", "/p:RazorCompileOnBuild=true /p:IncludeSymbols=true");
-
-            Assert.BuildPassed(result);
-
-            if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
-            {
-                // Travis on OSX produces different full paths in C# and MSBuild
-                Assert.NuspecContains(
-                    result,
-                    Path.Combine("obj", Configuration, "ClassLibrary.1.0.0.symbols.nuspec"),
-                    $"<file src=\"{Path.Combine(Project.DirectoryPath, "bin", Configuration, TFM, "ClassLibrary.Views.dll")}\" " +
-                    $"target=\"{Path.Combine("lib", TFM, "ClassLibrary.Views.dll")}\" />");
-
-                Assert.NuspecContains(
-                    result,
-                    Path.Combine("obj", Configuration, "ClassLibrary.1.0.0.symbols.nuspec"),
-                    $"<file src=\"{Path.Combine(Project.DirectoryPath, "bin", Configuration, TFM, "ClassLibrary.Views.pdb")}\" " +
-                    $"target=\"{Path.Combine("lib", TFM, "ClassLibrary.Views.pdb")}\" />");
-            }
-
-            Assert.NupkgContains(
-                result,
-                Path.Combine("bin", Configuration, "ClassLibrary.1.0.0.symbols.nupkg"),
-                Path.Combine("lib", TFM, "ClassLibrary.Views.dll"),
-                Path.Combine("lib", TFM, "ClassLibrary.Views.pdb"));
-        }
-
-        [Fact]
-        [InitializeTestProject("ClassLibrary")]
-        public async Task Pack_IncludesRazorFilesAsContent_WhenIncludeRazorContentInPack_IsSet()
-        {
-            var result = await DotnetMSBuild("Pack", "/p:IncludeRazorContentInPack=true");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, OutputPath, "ClassLibrary.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.Views.dll");
-
-            if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
-            {
-                // Travis on OSX produces different full paths in C# and MSBuild
-                Assert.NuspecContains(
-                    result,
-                    Path.Combine("obj", Configuration, "ClassLibrary.1.0.0.nuspec"),
-                    $"<file src=\"{Path.Combine(Project.DirectoryPath, "bin", Configuration, TFM, "ClassLibrary.Views.dll")}\" " +
-                    $"target=\"{Path.Combine("lib", TFM, "ClassLibrary.Views.dll")}\" />");
-
-                Assert.NuspecContains(
-                    result,
-                    Path.Combine("obj", Configuration, "ClassLibrary.1.0.0.nuspec"),
-                    $@"<files include=""any/{TFM}/Views/Shared/_Layout.cshtml"" buildAction=""Content"" />");
-            }
-
-            Assert.NupkgContains(
-                result,
-                Path.Combine("bin", Configuration, "ClassLibrary.1.0.0.nupkg"),
-                Path.Combine("lib", TFM, "ClassLibrary.Views.dll"));
-        }
-
-        [Fact]
-        [InitializeTestProject("PackageLibraryDirectDependency", additionalProjects: new[] { "PackageLibraryTransitiveDependency" })]
-        public async Task Pack_FailsWhenStaticWebAssetsHaveConflictingPaths()
-        {
-            Project.AddProjectFileContent(@"
-<ItemGroup>
-  <StaticWebAsset Include=""bundle\js\pkg-direct-dep.js"">
-    <SourceType></SourceType>
-    <SourceId>PackageLibraryDirectDependency</SourceId>
-    <ContentRoot>$([MSBuild]::NormalizeDirectory('$(MSBuildProjectDirectory)\bundle\'))</ContentRoot>
-    <BasePath>_content/PackageLibraryDirectDependency</BasePath>
-    <RelativePath>js/pkg-direct-dep.js</RelativePath>
-  </StaticWebAsset>
-</ItemGroup>");
-
-            Directory.CreateDirectory(Path.Combine(Project.DirectoryPath, "bundle", "js"));
-            File.WriteAllText(Path.Combine(Project.DirectoryPath, "bundle", "js", "pkg-direct-dep.js"), "console.log('bundle');");
-
-            var result = await DotnetMSBuild("Pack");
-
-            Assert.BuildFailed(result);
-        }
-
-        // If you modify this test, make sure you also modify the test below this one to assert that things are not included as content.
-        [Fact]
-        [InitializeTestProject("PackageLibraryDirectDependency", additionalProjects: new[] { "PackageLibraryTransitiveDependency" })]
-        public async Task Pack_IncludesStaticWebAssets()
-        {
-            var result = await DotnetMSBuild("Pack");
-
-            Assert.BuildPassed(result, allowWarnings: true);
-
-            Assert.FileExists(result, OutputPath, "PackageLibraryDirectDependency.dll");
-
-            Assert.NupkgContains(
-                result,
-                Path.Combine("..", "TestPackageRestoreSource", "PackageLibraryDirectDependency.1.0.0.nupkg"),
-                filePaths: new[]
-                {
-                    Path.Combine("staticwebassets", "js", "pkg-direct-dep.js"),
-                    Path.Combine("staticwebassets", "css", "site.css"),
-                    Path.Combine("staticwebassets", "PackageLibraryDirectDependency.bundle.scp.css"),
-                    Path.Combine("build", "Microsoft.AspNetCore.StaticWebAssets.props"),
-                    Path.Combine("build", "PackageLibraryDirectDependency.props"),
-                    Path.Combine("buildMultiTargeting", "PackageLibraryDirectDependency.props"),
-                    Path.Combine("buildTransitive", "PackageLibraryDirectDependency.props")
-                });
-        }
-
-        [Fact]
-        [InitializeTestProject("PackageLibraryDirectDependency", additionalProjects: new[] { "PackageLibraryTransitiveDependency" })]
-        public async Task Pack_DoesNotInclude_TransitiveBundleOrScopedCssAsStaticWebAsset()
-        {
-            var result = await DotnetMSBuild("Pack");
-
-            Assert.BuildPassed(result, allowWarnings: true);
-
-            Assert.FileExists(result, OutputPath, "PackageLibraryDirectDependency.dll");
-
-            Assert.NupkgDoesNotContain(
-                result,
-                Path.Combine("..", "TestPackageRestoreSource", "PackageLibraryDirectDependency.1.0.0.nupkg"),
-                filePaths: new[]
-                {
-                    // This is to make sure we don't include the scoped css files on the package when bundling is enabled.
-                    Path.Combine("staticwebassets", "Components", "App.razor.rz.scp.css"),
-                    Path.Combine("staticwebassets", "PackageLibraryDirectDependency.styles.css"),
-                });
-        }
-
-        [Fact]
-        [InitializeTestProject("PackageLibraryDirectDependency", additionalProjects: new[] { "PackageLibraryTransitiveDependency" })]
-        public async Task Pack_DoesNotIncludeStaticWebAssetsAsContent()
-        {
-            var result = await DotnetMSBuild("Pack");
-
-            Assert.BuildPassed(result, allowWarnings: true);
-
-            Assert.FileExists(result, OutputPath, "PackageLibraryDirectDependency.dll");
-
-            Assert.NupkgDoesNotContain(
-                result,
-                Path.Combine("..", "TestPackageRestoreSource", "PackageLibraryDirectDependency.1.0.0.nupkg"),
-                filePaths: new[]
-                {
-                    Path.Combine("content", "js", "pkg-direct-dep.js"),
-                    Path.Combine("content", "css", "site.css"),
-                    Path.Combine("content", "Components", "App.razor.css"),
-                    // This is to make sure we don't include the unscoped css file on the package.
-                    Path.Combine("content", "Components", "App.razor.css"),
-                    Path.Combine("content", "Components", "App.razor.rz.scp.css"),
-                    Path.Combine("contentFiles", "js", "pkg-direct-dep.js"),
-                    Path.Combine("contentFiles", "css", "site.css"),
-                    Path.Combine("contentFiles", "Components", "App.razor.css"),
-                    Path.Combine("contentFiles", "Components", "App.razor.rz.scp.css"),
-                });
-        }
-
-        [Fact]
-        [InitializeTestProject("PackageLibraryDirectDependency", additionalProjects: new[] { "PackageLibraryTransitiveDependency" })]
-        public async Task Pack_StaticWebAssetsEnabledFalse_DoesNotPackAnyStaticWebAssets()
-        {
-            var result = await DotnetMSBuild("Pack", "/p:StaticWebAssetsEnabled=false");
-
-            Assert.BuildPassed(result, allowWarnings: true);
-
-            Assert.FileExists(result, OutputPath, "PackageLibraryDirectDependency.dll");
-
-            Assert.NupkgDoesNotContain(
-                result,
-                Path.Combine("..", "TestPackageRestoreSource", "PackageLibraryDirectDependency.1.0.0.nupkg"),
-                filePaths: new[]
-                {
-                    Path.Combine("staticwebassets", "js", "pkg-direct-dep.js"),
-                    Path.Combine("staticwebassets", "css", "site.css"),
-                    Path.Combine("build", "Microsoft.AspNetCore.StaticWebAssets.props"),
-                    Path.Combine("build", "PackageLibraryDirectDependency.props"),
-                    Path.Combine("buildMultiTargeting", "PackageLibraryDirectDependency.props"),
-                    Path.Combine("buildTransitive", "PackageLibraryDirectDependency.props")
-                });
-        }
-
-        [Fact]
-        [InitializeTestProject("PackageLibraryDirectDependency", additionalProjects: new[] { "PackageLibraryTransitiveDependency" })]
-        public async Task Pack_NoBuild_IncludesStaticWebAssets()
-        {
-            var result = await DotnetMSBuild("Build");
-            Assert.BuildPassed(result, allowWarnings: true);
-
-            var pack = await DotnetMSBuild("Pack", "/p:NoBuild=true");
-            Assert.BuildPassed(pack, allowWarnings: true);
-
-            Assert.FileExists(pack, OutputPath, "PackageLibraryDirectDependency.dll");
-
-            Assert.NupkgContains(
-                pack,
-                Path.Combine("..", "TestPackageRestoreSource", "PackageLibraryDirectDependency.1.0.0.nupkg"),
-                filePaths: new[]
-                {
-                    Path.Combine("staticwebassets", "js", "pkg-direct-dep.js"),
-                    Path.Combine("staticwebassets", "PackageLibraryDirectDependency.bundle.scp.css"),
-                    Path.Combine("staticwebassets", "css", "site.css"),
-                    Path.Combine("build", "Microsoft.AspNetCore.StaticWebAssets.props"),
-                    Path.Combine("build", "PackageLibraryDirectDependency.props"),
-                    Path.Combine("buildMultiTargeting", "PackageLibraryDirectDependency.props"),
-                    Path.Combine("buildTransitive", "PackageLibraryDirectDependency.props")
-                });
-        }
-
-        [Fact]
-        [InitializeTestProject("ComponentLibrary")]
-        public async Task Pack_DoesNotIncludeAnyCustomPropsFiles_WhenNoStaticAssetsAreAvailable()
-        {
-            Project.TargetFramework = "netstandard2.0";
-
-            var result = await DotnetMSBuild("Pack");
-
-            Assert.BuildPassed(result, allowWarnings: true);
-
-            Assert.FileExists(result, OutputPath, "ComponentLibrary.dll");
-
-            Assert.NupkgDoesNotContain(
-                result,
-                Path.Combine("bin", Configuration, "ComponentLibrary.1.0.0.nupkg"),
-                filePaths: new[]
-                {
-                    Path.Combine("build", "Microsoft.AspNetCore.StaticWebAssets.props"),
-                    Path.Combine("build", "ComponentLibrary.props"),
-                    Path.Combine("buildMultiTargeting", "ComponentLibrary.props"),
-                    Path.Combine("buildTransitive", "ComponentLibrary.props")
-                });
-        }
-
-        [Fact]
-        [InitializeTestProject("PackageLibraryTransitiveDependency")]
-        public async Task Pack_Incremental_DoesNotRegenerateCacheAndPropsFiles()
-        {
-            Project.TargetFramework = "netstandard2.0";
-            var result = await DotnetMSBuild("Pack");
-
-            Assert.BuildPassed(result, allowWarnings: true);
-
-            Assert.FileExists(result, OutputPath, "PackageLibraryTransitiveDependency.dll");
-
-            Assert.FileExists(result, IntermediateOutputPath, "staticwebassets", "msbuild.PackageLibraryTransitiveDependency.Microsoft.AspNetCore.StaticWebAssets.props");
-            Assert.FileExists(result, IntermediateOutputPath, "staticwebassets", "msbuild.build.PackageLibraryTransitiveDependency.props");
-            Assert.FileExists(result, IntermediateOutputPath, "staticwebassets", "msbuild.buildMultiTargeting.PackageLibraryTransitiveDependency.props");
-            Assert.FileExists(result, IntermediateOutputPath, "staticwebassets", "msbuild.buildTransitive.PackageLibraryTransitiveDependency.props");
-            Assert.FileExists(result, IntermediateOutputPath, "staticwebassets", "PackageLibraryTransitiveDependency.StaticWebAssets.Pack.cache");
-
-            var directoryPath = Path.Combine(result.Project.DirectoryPath, IntermediateOutputPath, "staticwebassets");
-            var thumbPrints = new Dictionary<string, FileThumbPrint>();
-            var thumbPrintFiles = new[]
-            {
-                Path.Combine(directoryPath, "msbuild.PackageLibraryTransitiveDependency.Microsoft.AspNetCore.StaticWebAssets.props"),
-                Path.Combine(directoryPath, "msbuild.build.PackageLibraryTransitiveDependency.props"),
-                Path.Combine(directoryPath, "msbuild.buildMultiTargeting.PackageLibraryTransitiveDependency.props"),
-                Path.Combine(directoryPath, "msbuild.buildTransitive.PackageLibraryTransitiveDependency.props"),
-                Path.Combine(directoryPath, "PackageLibraryTransitiveDependency.StaticWebAssets.Pack.cache"),
-            };
-
-            foreach (var file in thumbPrintFiles)
-            {
-                var thumbprint = GetThumbPrint(file);
-                thumbPrints[file] = thumbprint;
-            }
-
-            // Act
-            var incremental = await DotnetMSBuild("Pack");
-
-            // Assert
-            Assert.BuildPassed(incremental, allowWarnings: true);
-
-            foreach (var file in thumbPrintFiles)
-            {
-                var thumbprint = GetThumbPrint(file);
-                Assert.Equal(thumbPrints[file], thumbprint);
-            }
-        }
-    }
-}

+ 0 - 469
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/PublishIntegrationTest.cs

@@ -1,469 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using System.Reflection;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class PublishIntegrationTest : MSBuildIntegrationTestBase, IClassFixture<BuildServerTestFixture>
-    {
-        public PublishIntegrationTest(BuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_RazorCompileOnPublish_IsDefault()
-        {
-            var result = await DotnetMSBuild("Publish");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.pdb");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.pdb");
-
-            // Verify assets get published
-            Assert.FileExists(result, PublishOutputPath, "wwwroot", "js", "SimpleMvc.js");
-            Assert.FileExists(result, PublishOutputPath, "wwwroot", "css", "site.css");
-
-            // By default refs and .cshtml files will not be copied on publish
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "refs"), "*.dll");
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "Views"), "*.cshtml");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_PublishesAssemblyAndContent()
-        {
-            var result = await DotnetMSBuild("Publish");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, OutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, OutputPath, "SimpleMvc.pdb");
-            Assert.FileExists(result, OutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, OutputPath, "SimpleMvc.Views.pdb");
-            Assert.FileExists(result, OutputPath, "appsettings.json");
-            Assert.FileExists(result, OutputPath, "appsettings.Development.json");
-
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.pdb");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.pdb");
-            Assert.FileExists(result, PublishOutputPath, "appsettings.json");
-            Assert.FileExists(result, PublishOutputPath, "appsettings.Development.json");
-            Assert.FileDoesNotExist(result, PublishOutputPath, Path.Combine("Properties", "launchSettings.json"));
-
-            // By default refs and .cshtml files will not be copied on publish
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "refs"), "*.dll");
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "Views"), "*.cshtml");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_WithRazorCompileOnPublish_PublishesAssembly()
-        {
-            var result = await DotnetMSBuild("Publish");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.pdb");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.pdb");
-
-            // By default refs and .cshtml files will not be copied on publish
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "refs"), "*.dll");
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "Views"), "*.cshtml");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_WithRazorCompileOnBuildFalse_PublishesAssembly()
-        {
-            // RazorCompileOnBuild is turned off, but RazorCompileOnPublish should still be enabled
-            var result = await DotnetMSBuild("Publish", "/p:RazorCompileOnBuild=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.Views.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.Views.pdb");
-
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.pdb");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.pdb");
-
-            // By default refs and .cshtml files will not be copied on publish
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "refs"), "*.dll");
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "Views"), "*.cshtml");
-        }
-
-        [Fact] // This is an override to force the new toolset
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_WithMvcRazorCompileOnPublish_AndRazorSDK_PublishesAssembly()
-        {
-            var result = await DotnetMSBuild("Publish", "/p:MvcRazorCompileOnPublish=true /p:ResolvedRazorCompileToolset=RazorSDK");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.pdb");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.pdb");
-
-            // By default refs and .cshtml files will not be copied on publish
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "refs"), "*.dll");
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "Views"), "*.cshtml");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_NoopsWithNoFiles()
-        {
-            Directory.Delete(Path.Combine(Project.DirectoryPath, "Views"), recursive: true);
-
-            var result = await DotnetMSBuild("Publish");
-
-            Assert.BuildPassed(result);
-
-            // Everything we do should noop - including building the app.
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.pdb");
-            Assert.FileDoesNotExist(result, PublishOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileDoesNotExist(result, PublishOutputPath, "SimpleMvc.Views.pdb");
-
-            // By default refs will not be copied on publish
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "refs"), "*.dll");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_NoopsWith_RazorCompileOnPublishFalse()
-        {
-            Directory.Delete(Path.Combine(Project.DirectoryPath, "Views"), recursive: true);
-
-            var result = await DotnetMSBuild("Publish", "/p:RazorCompileOnPublish=false");
-
-            Assert.BuildPassed(result);
-
-            // Everything we do should noop - including building the app.
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.pdb");
-            Assert.FileDoesNotExist(result, PublishOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileDoesNotExist(result, PublishOutputPath, "SimpleMvc.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_SkipsCopyingBinariesToOutputDirectory_IfCopyBuildOutputToOutputDirectory_IsUnset()
-        {
-            var result = await DotnetMSBuild("Publish", "/p:CopyBuildOutputToPublishDirectory=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-
-            Assert.FileDoesNotExist(result, PublishOutputPath, "SimpleMvc.dll");
-            Assert.FileDoesNotExist(result, PublishOutputPath, "SimpleMvc.Views.dll");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_SkipsCopyingBinariesToOutputDirectory_IfCopyOutputSymbolsToOutputDirectory_IsUnset()
-        {
-            var result = await DotnetMSBuild("Publish", "/p:CopyOutputSymbolsToPublishDirectory=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.pdb");
-
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileDoesNotExist(result, PublishOutputPath, "SimpleMvc.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_Works_WhenSymbolsAreNotGenerated()
-        {
-            var result = await DotnetMSBuild("Publish", "/p:DebugType=none");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.pdb");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.Views.pdb");
-
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileDoesNotExist(result, PublishOutputPath, "SimpleMvc.pdb");
-            Assert.FileDoesNotExist(result, PublishOutputPath, "SimpleMvc.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_IncludeCshtmlAndRefAssemblies_CopiesFiles()
-        {
-            var result = await DotnetMSBuild("Publish", "/p:CopyRazorGenerateFilesToPublishDirectory=true /p:CopyRefAssembliesToPublishDirectory=true");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.pdb");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.pdb");
-
-            // By default refs and .cshtml files will not be copied on publish
-            Assert.FileExists(result, PublishOutputPath, "refs", "mscorlib.dll");
-            Assert.FileCountEquals(result, 8, Path.Combine(PublishOutputPath, "Views"), "*.cshtml");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_WithCopySettingsInProjectFile_CopiesFiles()
-        {
-            AddProjectFileContent(@"
-            <PropertyGroup>
-                <CopyRefAssembliesToPublishDirectory>true</CopyRefAssembliesToPublishDirectory>
-                <CopyRazorGenerateFilesToPublishDirectory>true</CopyRazorGenerateFilesToPublishDirectory>
-            </PropertyGroup>");
-
-            var result = await DotnetMSBuild("Publish");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.pdb");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.pdb");
-
-            // By default refs and .cshtml files will not be copied on publish
-            Assert.FileExists(result, PublishOutputPath, "refs", "mscorlib.dll");
-            Assert.FileCountEquals(result, 8, Path.Combine(PublishOutputPath, "Views"), "*.cshtml");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_WithPreserveCompilationReferencesSetInProjectFile_CopiesRefs()
-        {
-            // This simulates the behavior of 3.0 with RuntimeCompilation enabled
-            AddProjectFileContent(@"
-            <PropertyGroup>
-                <PreserveCompilationReferences>true</PreserveCompilationReferences>
-            </PropertyGroup>");
-
-            var result = await DotnetMSBuild("Publish");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.pdb");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.pdb");
-
-            // By default refs and .cshtml files will not be copied on publish
-            Assert.FileExists(result, PublishOutputPath, "refs", "mscorlib.dll");
-        }
-
-        [Fact] // Tests old MvcPrecompilation behavior that we support for compat.
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_MvcRazorExcludeFilesFromPublish_False_CopiesFiles()
-        {
-            var result = await DotnetMSBuild("Publish", "/p:MvcRazorExcludeViewFilesFromPublish=false /p:MvcRazorExcludeRefAssembliesFromPublish=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.pdb");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.pdb");
-
-            // By default refs and .cshtml files will not be copied on publish
-            Assert.FileExists(result, PublishOutputPath, "refs", "mscorlib.dll");
-            Assert.FileCountEquals(result, 8, Path.Combine(PublishOutputPath, "Views"), "*.cshtml");
-        }
-
-        [Fact]
-        [InitializeTestProject("AppWithP2PReference", additionalProjects: "ClassLibrary")]
-        public async Task Publish_WithP2P_AndRazorCompileOnBuild_CopiesRazorAssembly()
-        {
-            var result = await DotnetMSBuild("Publish");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, PublishOutputPath, "AppWithP2PReference.dll");
-            Assert.FileExists(result, PublishOutputPath, "AppWithP2PReference.pdb");
-            Assert.FileExists(result, PublishOutputPath, "AppWithP2PReference.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "AppWithP2PReference.Views.pdb");
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary.dll");
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary.pdb");
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("AppWithP2PReference", additionalProjects: "ClassLibrary")]
-        public async Task Publish_WithP2P_AndRazorCompileOnPublish_CopiesRazorAssembly()
-        {
-            var result = await DotnetMSBuild("Publish");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, PublishOutputPath, "AppWithP2PReference.dll");
-            Assert.FileExists(result, PublishOutputPath, "AppWithP2PReference.pdb");
-            Assert.FileExists(result, PublishOutputPath, "AppWithP2PReference.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "AppWithP2PReference.Views.pdb");
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary.dll");
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary.pdb");
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary.Views.pdb");
-
-            // Verify fix for https://github.com/aspnet/Razor/issues/2295. No cshtml files should be published from the app
-            // or the ClassLibrary.
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "refs"), "*.dll");
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "Views"), "*.cshtml");
-        }
-
-        [Fact(Skip = "https://github.com/dotnet/aspnetcore/issues/13303")]
-        [InitializeTestProject("SimpleMvcFSharp", language: "F#")]
-        public async Task Publish_SimpleMvcFSharp_NoopsWithoutFailing()
-        {
-            var result = await DotnetMSBuild("Publish");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvcFSharp.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvcFSharp.pdb");
-
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvcFSharp.Views.dll");
-            Assert.FileDoesNotExist(result, OutputPath, "SimpleMvcFSharp.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_DoesNotPublishCustomRazorGenerateItems()
-        {
-            var additionalProjectContent = @"
-<PropertyGroup>
-    <EnableDefaultRazorGenerateItems>false</EnableDefaultRazorGenerateItems>
-</PropertyGroup>
-<ItemGroup>
-  <RazorGenerate Include=""Views\_ViewImports.cshtml"" />
-  <RazorGenerate Include=""Views\Home\Index.cshtml"" />
-</ItemGroup>
-";
-            AddProjectFileContent(additionalProjectContent);
-            var result = await DotnetMSBuild("Publish");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.pdb");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.pdb");
-
-            // Verify assets get published
-            Assert.FileExists(result, PublishOutputPath, "wwwroot", "js", "SimpleMvc.js");
-            Assert.FileExists(result, PublishOutputPath, "wwwroot", "css", "site.css");
-
-            // By default refs and .cshtml files will not be copied on publish
-            Assert.FileCountEquals(result, 0, Path.Combine(PublishOutputPath, "refs"), "*.dll");
-            // Custom RazorGenerate item does not get published
-            Assert.FileDoesNotExist(result, PublishOutputPath, "Views", "Home", "Home.cshtml");
-            // cshtml Content item that's not part of RazorGenerate gets published.
-            Assert.FileExists(result, PublishOutputPath, "Views", "Home", "About.cshtml");
-        }
-
-        [Fact]
-        [InitializeTestProject("AppWithP2PReference", additionalProjects: new[] { "ClassLibrary", "ClassLibrary2" })]
-        public async Task Publish_WithP2P_WorksWhenBuildProjectReferencesIsDisabled()
-        {
-            // Simulates publishing the same way VS does by setting BuildProjectReferences=false.
-            // With this flag, P2P references aren't resolved during GetCopyToPublishDirectoryItems which would cause
-            // any target that uses References as inputs to not be incremental. This test verifies no Razor Sdk work
-            // is performed at this time.
-            var additionalProjectContent = @"
-<ItemGroup>
-  <ProjectReference Include=""..\ClassLibrary2\ClassLibrary2.csproj"" />
-</ItemGroup>
-";
-            AddProjectFileContent(additionalProjectContent);
-
-            var result = await DotnetMSBuild(target: default);
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, OutputPath, "AppWithP2PReference.dll");
-            Assert.FileExists(result, OutputPath, "AppWithP2PReference.Views.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary.Views.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary2.dll");
-            Assert.FileExists(result, OutputPath, "ClassLibrary2.Views.dll");
-
-            // dotnet msbuild /t:Publish /p:BuildProjectReferences=false
-            result = await DotnetMSBuild(target: "Publish", "/p:BuildProjectReferences=false");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, PublishOutputPath, "AppWithP2PReference.dll");
-            Assert.FileExists(result, PublishOutputPath, "AppWithP2PReference.pdb");
-            Assert.FileExists(result, PublishOutputPath, "AppWithP2PReference.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "AppWithP2PReference.Views.pdb");
-
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary.dll");
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary.pdb");
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary.Views.pdb");
-
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary2.dll");
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary2.pdb");
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary2.Views.dll");
-            Assert.FileExists(result, PublishOutputPath, "ClassLibrary2.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_WithNoBuild_FailsWithoutBuild()
-        {
-            // Publish without building shouldn't succeed.
-            var result = await DotnetMSBuild("Publish", "/p:NoBuild=true");
-
-            Assert.BuildFailed(result);
-            Assert.BuildError(result, "MSB3030"); // Could not copy the file "obj/Debug/net6.0/SimpleMvc.dll because it couldn't be found.
-
-            Assert.FileDoesNotExist(result, PublishOutputPath, "SimpleMvc.dll");
-            Assert.FileDoesNotExist(result, PublishOutputPath, "SimpleMvc.Views.dll");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task Publish_WithNoBuild_CopiesAlreadyCompiledViews()
-        {
-            // Build
-            var result = await DotnetMSBuild("Build", "/p:AssemblyVersion=1.1.1.1");
-
-            Assert.BuildPassed(result);
-            var assemblyPath = Assert.FileExists(result, OutputPath, "SimpleMvc.dll");
-            var viewsAssemblyPath = Assert.FileExists(result, OutputPath, "SimpleMvc.Views.dll");
-            var assemblyVersion = AssemblyName.GetAssemblyName(assemblyPath).Version;
-            var viewsAssemblyVersion = AssemblyName.GetAssemblyName(viewsAssemblyPath).Version;
-
-            // Publish should copy dlls from OutputPath
-            result = await DotnetMSBuild("Publish", "/p:NoBuild=true");
-
-            Assert.BuildPassed(result);
-            var publishAssemblyPath = Assert.FileExists(result, PublishOutputPath, "SimpleMvc.dll");
-            var publishViewsAssemblyPath = Assert.FileExists(result, PublishOutputPath, "SimpleMvc.Views.dll");
-            var publishAssemblyVersion = AssemblyName.GetAssemblyName(publishAssemblyPath).Version;
-            var publishViewsAssemblyVersion = AssemblyName.GetAssemblyName(publishViewsAssemblyPath).Version;
-
-            Assert.Equal(assemblyVersion, publishAssemblyVersion);
-            Assert.Equal(viewsAssemblyVersion, publishViewsAssemblyVersion);
-        }
-    }
-}

+ 0 - 115
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/RazorCompileIntegrationTest.cs

@@ -1,115 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-using System.Linq;
-using System.Reflection;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class RazorCompileIntegrationTest : MSBuildIntegrationTestBase, IClassFixture<BuildServerTestFixture>
-    {
-        public RazorCompileIntegrationTest(BuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorCompile_Success_CompilesAssembly()
-        {
-            var result = await DotnetMSBuild("RazorCompile");
-
-            Assert.BuildPassed(result);
-
-            // RazorGenerate should compile the assembly and pdb.
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.pdb");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorCompile_NoopsWithNoFiles()
-        {
-            Directory.Delete(Path.Combine(Project.DirectoryPath, "Views"), recursive: true);
-
-            var result = await DotnetMSBuild("RazorCompile");
-
-            Assert.BuildPassed(result);
-
-            // Everything we do should noop - including building the app.
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.dll");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.pdb");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.Views.pdb");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorCompile_EmbedRazorGenerateSources_EmbedsCshtmlFiles()
-        {
-            var result = await DotnetMSBuild("RazorCompile", "/p:EmbedRazorGenerateSources=true");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-
-            var assembly = LoadAssemblyFromBytes(result.Project.DirectoryPath, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            var resources = assembly.GetManifestResourceNames();
-
-            Assert.Equal(new string[]
-            {
-                "/Views/Home/About.cshtml",
-                "/Views/Home/Contact.cshtml",
-                "/Views/Home/Index.cshtml",
-                "/Views/Shared/Error.cshtml",
-                "/Views/Shared/_Layout.cshtml",
-                "/Views/Shared/_ValidationScriptsPartial.cshtml",
-                "/Views/_ViewImports.cshtml",
-                "/Views/_ViewStart.cshtml",
-            },
-            resources.OrderBy(r => r, StringComparer.Ordinal));
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorCompile_MvcRazorEmbedViewSources_EmbedsCshtmlFiles()
-        {
-            var result = await DotnetMSBuild("RazorCompile", "/p:EmbedRazorGenerateSources=true");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-
-            var assembly = LoadAssemblyFromBytes(result.Project.DirectoryPath, IntermediateOutputPath, "SimpleMvc.Views.dll");
-            var resources = assembly.GetManifestResourceNames();
-
-            Assert.Equal(new string[]
-            {
-                "/Views/Home/About.cshtml",
-                "/Views/Home/Contact.cshtml",
-                "/Views/Home/Index.cshtml",
-                "/Views/Shared/Error.cshtml",
-                "/Views/Shared/_Layout.cshtml",
-                "/Views/Shared/_ValidationScriptsPartial.cshtml",
-                "/Views/_ViewImports.cshtml",
-                "/Views/_ViewStart.cshtml",
-            },
-            resources.OrderBy(r => r, StringComparer.Ordinal));
-        }
-
-        private Assembly LoadAssemblyFromBytes(params string[] paths)
-        {
-            // We need to load the assembly from bytes to load it without locking the file - and yes, we need to
-            // load the pdb too, or else the CLR will load/lock it based on the path specified in the assembly.
-            var assemblyBytes = File.ReadAllBytes(Path.Combine(paths));
-            var symbolBytes = File.ReadAllBytes(Path.ChangeExtension(Path.Combine(paths), ".pdb"));
-            return Assembly.Load(assemblyBytes, symbolBytes);
-        }
-    }
-}

+ 0 - 358
src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/RazorGenerateIntegrationTest.cs

@@ -1,358 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.IO;
-using System.Runtime.InteropServices;
-using System.Text;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
-{
-    public class RazorGenerateIntegrationTest : MSBuildIntegrationTestBase, IClassFixture<BuildServerTestFixture>
-    {
-        private const string RazorGenerateTarget = "RazorGenerate";
-
-        public RazorGenerateIntegrationTest(BuildServerTestFixture buildServer)
-            : base(buildServer)
-        {
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorGenerate_Success_GeneratesFilesOnDisk()
-        {
-            var result = await DotnetMSBuild(RazorGenerateTarget);
-
-            Assert.BuildPassed(result);
-
-            // RazorGenerate should compile the assembly, but not the views.
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.dll");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-
-            // RazorGenerate should generate correct TagHelper caches
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.TagHelpers.input.cache");
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.TagHelpers.output.cache");
-            Assert.FileContains(
-                result,
-                Path.Combine(IntermediateOutputPath, "SimpleMvc.TagHelpers.output.cache"),
-                @"""Name"":""SimpleMvc.SimpleTagHelper""");
-
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "_ViewImports.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "_ViewStart.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Home", "About.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Home", "Contact.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Home", "Index.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Shared", "_Layout.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Shared", "_ValidationScriptsPartial.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Shared", "Error.cshtml.g.cs");
-            Assert.FileCountEquals(result, 8, RazorIntermediateOutputPath, "*.cshtml.g.cs");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorGenerate_ErrorInRazorFile_ReportsMSBuildError()
-        {
-            // Introducing a syntax error, an unclosed brace
-            ReplaceContent("@{", "Views", "Home", "Index.cshtml");
-
-            var result = await DotnetMSBuild(RazorGenerateTarget);
-
-            Assert.BuildFailed(result);
-
-            // Looks like C:\...\Views\Home\Index.cshtml(1,2): error RZ1006: The code block is missi... [C:\Users\rynowak\AppData\Local\Temp\rwnv03ll.wb0\SimpleMvc.csproj]
-            Assert.BuildError(result, "RZ1006");
-
-            // RazorGenerate should compile the assembly, but not the views.
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.dll");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-
-            // If there's a parser error, the generated file contents is likely incorrect. The file should not be written to disk.
-            Assert.FileDoesNotExist(result, RazorIntermediateOutputPath, "Views", "Home", "Index.cshtml.g.cs");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorGenerate_LotOfErrorsInRazorFile_ReportsFirstHundredErrors()
-        {
-            // Introducing a syntax error, an unclosed brace
-            var content = new StringBuilder().Insert(0, "@{ ", 100).ToString();
-            ReplaceContent(content, "Views", "Home", "Index.cshtml");
-
-            var result = await DotnetMSBuild(RazorGenerateTarget);
-
-            Assert.BuildFailed(result);
-
-            Assert.BuildOutputContainsLine(result, "And 101 more warnings/errors.");
-
-            // RazorGenerate should compile the assembly, but not the views.
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.dll");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorGenerate_BuildsIncrementally()
-        {
-            // Act - 1
-            var result = await DotnetMSBuild(RazorGenerateTarget);
-            var generatedFile = Path.Combine(Project.DirectoryPath, RazorIntermediateOutputPath, "Views", "Home", "About.cshtml.g.cs");
-
-            // Assert - 1
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, generatedFile);
-            var thumbPrint = GetThumbPrint(generatedFile);
-
-            // Act - 2
-            using (var razorGenDirectoryLock = LockDirectory(RazorIntermediateOutputPath))
-            {
-                result = await DotnetMSBuild(RazorGenerateTarget);
-            }
-
-            // Assert - 2
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, generatedFile);
-            var currentThumbPrint = GetThumbPrint(generatedFile);
-            Assert.Equal(thumbPrint, currentThumbPrint);
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorGenerate_Rebuilds_IfSourcesAreUpdated()
-        {
-            // Act - 1
-            var result = await DotnetMSBuild(RazorGenerateTarget);
-            var file = Path.Combine(Project.DirectoryPath, "Views", "Home", "Contact.cshtml");
-            var generatedFile = Path.Combine(RazorIntermediateOutputPath, "Views", "Home", "Contact.cshtml.g.cs");
-
-            // Assert - 1
-            Assert.BuildPassed(result);
-            var fileThumbPrint = GetThumbPrint(generatedFile);
-
-            // Act - 2
-            // Update the source content and build. We should expect the outputs to be regenerated.
-            ReplaceContent("Uodated content", file);
-            result = await DotnetMSBuild(RazorGenerateTarget);
-
-            // Assert - 2
-            Assert.BuildPassed(result);
-            var newThumbPrint = GetThumbPrint(generatedFile);
-            Assert.NotEqual(fileThumbPrint, newThumbPrint);
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorGenerate_Rebuilds_IfOutputFilesAreMissing()
-        {
-            // Act - 1
-            var result = await DotnetMSBuild(RazorGenerateTarget);
-            var file = Path.Combine(Project.DirectoryPath, RazorIntermediateOutputPath, "Views", "Home", "About.cshtml.g.cs");
-
-            // Assert - 1
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, file);
-
-            // Act - 2
-            File.Delete(file);
-            result = await DotnetMSBuild(RazorGenerateTarget);
-
-            // Assert - 2
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, file);
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorGenerate_Rebuilds_IfInputFilesAreRenamed()
-        {
-            // Act - 1
-            var result = await DotnetMSBuild(RazorGenerateTarget);
-            var file = Path.Combine(Project.DirectoryPath, "Views", "Home", "Index.cshtml");
-            var renamed = Path.Combine(Project.DirectoryPath, "Views", "Home", "NewIndex.cshtml");
-            var generated = Path.Combine(RazorIntermediateOutputPath, "Views", "Home", "Index.cshtml.g.cs");
-
-            // Assert - 1
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, file);
-            Assert.FileExists(result, generated);
-
-            // Act - 2
-            File.Move(file, renamed);
-            result = await DotnetMSBuild(RazorGenerateTarget);
-
-            // Assert - 2
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Home", "NewIndex.cshtml.g.cs");
-            Assert.FileDoesNotExist(result, generated);
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorGenerate_Rebuilds_IfInputFilesAreDeleted()
-        {
-            // Act - 1
-            var result = await DotnetMSBuild(RazorGenerateTarget);
-            var file = Path.Combine(Project.DirectoryPath, "Views", "Home", "Index.cshtml");
-            var generatedFile = Path.Combine(RazorIntermediateOutputPath, "Views", "Home", "Index.cshtml.g.cs");
-
-            // Assert - 1
-            Assert.BuildPassed(result);
-            Assert.FileExists(result, generatedFile);
-
-            // Act - 2
-            File.Delete(file);
-            result = await DotnetMSBuild(RazorGenerateTarget);
-
-            // Assert - 2
-            Assert.BuildPassed(result);
-            Assert.FileDoesNotExist(result, generatedFile);
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorGenerate_Noops_WithNoFiles()
-        {
-            Directory.Delete(Path.Combine(Project.DirectoryPath, "Views"), recursive: true);
-
-            var result = await DotnetMSBuild(RazorGenerateTarget);
-
-            Assert.BuildPassed(result);
-
-            // We shouldn't need to look for tag helpers
-            Assert.FileDoesNotExist(result, Path.Combine(IntermediateOutputPath, "SimpleMvc.TagHelpers.input.cache"));
-            Assert.FileDoesNotExist(result, Path.Combine(IntermediateOutputPath, "SimpleMvc.TagHelpers.output.cache"));
-
-            // We shouldn't need to hash the files
-            Assert.FileDoesNotExist(result, Path.Combine(IntermediateOutputPath, "SimpleMvc.RazorCoreGenerate.cache"));
-
-            Assert.FileCountEquals(result, 0, RazorIntermediateOutputPath, "*.cshtml.g.cs");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorGenerate_MvcRazorFilesToCompile_OverridesDefaultItems()
-        {
-            var projectContent = @"
-<ItemGroup>
-  <MvcRazorFilesToCompile Include=""Views/Home/About.cshtml"" />
-</ItemGroup>
-";
-            AddProjectFileContent(projectContent);
-
-            var result = await DotnetMSBuild(RazorGenerateTarget);
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Home", "About.cshtml.g.cs");
-            Assert.FileCountEquals(result, 1, RazorIntermediateOutputPath, "*.cshtml.g.cs");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorGenerate_EnableDefaultRazorGenerateItems_False_OverridesDefaultItems()
-        {
-            var projectContent = @"
- <PropertyGroup>
-   <EnableDefaultRazorGenerateItems>false</EnableDefaultRazorGenerateItems>
- </PropertyGroup>
- <ItemGroup>
-   <RazorGenerate Include=""Views/Home/About.cshtml"" />
- </ItemGroup>
-";
-            AddProjectFileContent(projectContent);
-
-            var result = await DotnetMSBuild(RazorGenerateTarget);
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Home", "About.cshtml.g.cs");
-            Assert.FileCountEquals(result, 1, RazorIntermediateOutputPath, "*.cshtml.g.cs");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc", additionalProjects: "LinkedDir")]
-        public async Task RazorGenerate_WorksWithLinkedFiles()
-        {
-            // Arrange
-            var projectContent = @"
-<ItemGroup>
-  <Content Include=""..\LinkedDir\LinkedFile.cshtml"" />
-  <Content Include=""..\LinkedDir\LinkedFile2.cshtml"" Link=""LinkedFileOut\LinkedFile2.cshtml"" />
-  <Content Include=""..\LinkedDir\LinkedFile3.cshtml"" Link=""LinkedFileOut\LinkedFileWithRename.cshtml"" />
-</ItemGroup>
-";
-            AddProjectFileContent(projectContent);
-
-            var result = await DotnetMSBuild(RazorGenerateTarget, "/t:_IntrospectRazorGenerateWithTargetPath");
-
-            Assert.BuildPassed(result);
-
-            Assert.FileExists(result, RazorIntermediateOutputPath, "LinkedFile.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "LinkedFileOut", "LinkedFile2.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "LinkedFileOut", "LinkedFileWithRename.cshtml.g.cs");
-
-            Assert.BuildOutputContainsLine(result, $@"RazorGenerateWithTargetPath: {Path.Combine("..", "LinkedDir", "LinkedFile.cshtml")} LinkedFile.cshtml {Path.Combine(RazorIntermediateOutputPath, "LinkedFile.cshtml.g.cs")}");
-            Assert.BuildOutputContainsLine(result, $@"RazorGenerateWithTargetPath: {Path.Combine("..", "LinkedDir", "LinkedFile2.cshtml")} LinkedFileOut\LinkedFile2.cshtml {Path.Combine(RazorIntermediateOutputPath, "LinkedFileOut", "LinkedFile2.cshtml.g.cs")}");
-            Assert.BuildOutputContainsLine(result, $@"RazorGenerateWithTargetPath: {Path.Combine("..", "LinkedDir", "LinkedFile3.cshtml")} LinkedFileOut\LinkedFileWithRename.cshtml {Path.Combine(RazorIntermediateOutputPath, "LinkedFileOut", "LinkedFileWithRename.cshtml.g.cs")}");
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc", additionalProjects: "LinkedDir")]
-        public async Task RazorGenerate_PrintsErrorsFromLinkedFiles()
-        {
-            // Arrange
-            var file = @"..\LinkedDir\LinkedErrorFile.cshtml";
-            var projectContent = $@"
-<ItemGroup>
-  <Content Include=""{file}"" Link=""LinkedFileOut\LinkedFile.cshtml"" />
-</ItemGroup>
-";
-            AddProjectFileContent(projectContent);
-
-            var result = await DotnetMSBuild(RazorGenerateTarget);
-
-            Assert.BuildFailed(result);
-            if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
-            {
-                // GetFullPath on OSX doesn't work well in travis. We end up computing a different path than will
-                // end up in the MSBuild logs.
-                var errorLocation = Path.GetFullPath(Path.Combine(Project.DirectoryPath, "..", "LinkedDir", "LinkedErrorFile.cshtml")) + "(1,2)";
-                Assert.BuildError(result, "RZ1006", errorLocation);
-            }
-        }
-
-        [Fact]
-        [InitializeTestProject("SimpleMvc")]
-        public async Task RazorGenerate_FileWithAbsolutePath()
-        {
-            // In preview1 we totally ignore files that are specified with an absolute path
-            var filePath = Path.Combine(Project.SolutionPath, "temp.cshtml");
-            File.WriteAllText(filePath, string.Empty);
-
-            AddProjectFileContent($@"
-<ItemGroup>
-  <Content Include=""{filePath}""/>
-</ItemGroup>");
-
-            var result = await DotnetMSBuild(RazorGenerateTarget, "/t:_IntrospectRazorGenerateWithTargetPath");
-
-            Assert.BuildPassed(result);
-
-            // RazorGenerate should compile the assembly, but not the views.
-            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.dll");
-            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.Views.dll");
-
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "_ViewImports.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "_ViewStart.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Home", "About.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Home", "Contact.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Home", "Index.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Shared", "_Layout.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Shared", "_ValidationScriptsPartial.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "Views", "Shared", "Error.cshtml.g.cs");
-            Assert.FileExists(result, RazorIntermediateOutputPath, "temp.cshtml.g.cs");
-            Assert.FileCountEquals(result, 9, RazorIntermediateOutputPath, "*.cshtml.g.cs");
-            Assert.BuildOutputContainsLine(result, $@"RazorGenerateWithTargetPath: {filePath} temp.cshtml {Path.Combine(RazorIntermediateOutputPath, "temp.cshtml.g.cs")}");
-        }
-    }
-}

Некоторые файлы не были показаны из-за большого количества измененных файлов