From 075612b98831ee91ed9dff255e66c77bb1abc03d Mon Sep 17 00:00:00 2001
From: Nate McMaster <natemcmaster@users.noreply.github.com>
Date: Wed, 6 Feb 2019 11:20:49 -0800
Subject: [PATCH] Install the .NET Core SDK into the repo root instead of
 UserProfile and 'install' copy of AspNetCore shared framework (#7293)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This is required to workaround several limitations in the way the .NET Core SDK finds shared frameworks and targeting packs. It allow tests to use shared frameworks and targeting packs.

It also matches the patterns established in other aspnet and dotnet repos. This should reduce the friction required to adopt Arcade SDK.

## Changes

* This moves the default location of the .NET Core SDK installation into `$repoRoot/.dotnet`. This location was already in use for CI builds.
* Update the build step for Microsoft.AspNetCore.App to install the shared framework into the local copy of the .NET Core SDK

## Recommendations

* Use the "startvs.cmd" script to launch Visual Studio. This will set required environment variables to make VS happier than if you just double click the .sln file.
* Use "activate.sh/ps1" if you want to run `dotnet build`, `dotnet test` and other dotnet commands. These will set required environment variables, including PATH.
* I recommend removing %USERPROFILE%/.dotnet to your PATH variable if you had added it manually before. This will no longer match what build tools will install.
* `git clean -xfd -e .dotnet/` preserves the folder so you don’t have to re-download the SDK again.
---
 Directory.Build.props                         |  8 +++
 activate.ps1                                  | 57 +++++++++++++++
 activate.sh                                   | 69 +++++++++++++++++++
 build.ps1                                     |  8 +--
 build.sh                                      |  6 +-
 build/repo.props                              |  2 +-
 docs/BuildFromSource.md                       | 46 ++++++++-----
 src/Framework/src/SharedFx.targets            | 69 +++++++++++++++----
 src/ProjectTemplates/build.cmd                |  2 +-
 .../test/ProjectTemplates.Tests.csproj        |  1 +
 .../test/RazorComponentsTemplateTest.cs       | 11 ---
 src/Servers/IIS/build/testsite.props          |  3 +-
 startvs.cmd                                   |  6 +-
 13 files changed, 225 insertions(+), 63 deletions(-)
 create mode 100644 activate.ps1
 create mode 100644 activate.sh

diff --git a/Directory.Build.props b/Directory.Build.props
index 406abcec72b..a67c0adcf57 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -118,6 +118,14 @@
     <IntermediateOutputPath Condition=" '$(PlatformName)' != 'AnyCPU' ">$(BaseIntermediateOutputPath)$(PlatformName)\$(Configuration)\</IntermediateOutputPath>
   </PropertyGroup>
 
+  <!-- The location of the local installation of the .NET Core shared framework. -->
+  <PropertyGroup>
+    <LocalDotNetRoot Condition="'$(TargetOSName)' == 'win'">$(RepositoryRoot).dotnet\$(TargetArchitecture)\</LocalDotNetRoot>
+    <LocalDotNetRoot Condition="'$(TargetOSName)' != 'win'">$(RepositoryRoot).dotnet\</LocalDotNetRoot>
+    <!-- Override the SDK default and point to local .dotnet folder. -->
+    <NetCoreTargetingPackRoot>$(LocalDotNetRoot)packs\</NetCoreTargetingPackRoot>
+  </PropertyGroup>
+
   <!-- Defines project type conventions. -->
   <PropertyGroup>
     <RepoRelativeProjectDir>$([MSBuild]::MakeRelative($(RepositoryRoot), $(MSBuildProjectDirectory)))</RepoRelativeProjectDir>
diff --git a/activate.ps1 b/activate.ps1
new file mode 100644
index 00000000000..78e8557fc8b
--- /dev/null
+++ b/activate.ps1
@@ -0,0 +1,57 @@
+#
+# This file must be used by invoking ". .\activate.ps1" from the command line.
+# You cannot run it directly.
+# To exit from the environment this creates, execute the 'deactivate' function.
+#
+
+function deactivate ([switch]$init) {
+
+    # reset old environment variables
+    if (Test-Path variable:_OLD_PATH) {
+        $env:PATH = $_OLD_PATH
+        Remove-Item variable:_OLD_PATH
+    }
+
+    if (test-path function:_old_prompt) {
+        Set-Item Function:prompt -Value $function:_old_prompt -ea ignore
+        remove-item function:_old_prompt
+    }
+
+    Remove-Item env:DOTNET_ROOT -ea ignore
+    Remove-Item env:DOTNET_MULTILEVEL_LOOKUP -ea ignore
+    if (-not $init) {
+        # Remove the deactivate function
+        Remove-Item function:deactivate
+    }
+}
+
+# Cleanup the environment
+deactivate -init
+
+$_OLD_PATH = $env:PATH
+# Tell dotnet where to find itself
+$env:DOTNET_ROOT = "$PSScriptRoot\.dotnet\x64"
+# Tell dotnet not to look beyond the DOTNET_ROOT folder for more dotnet things
+$env:DOTNET_MULTILEVEL_LOOKUP = 0
+# Put dotnet first on PATH
+$env:PATH = "${env:DOTNET_ROOT};${env:PATH}"
+
+# Set the shell prompt
+if (-not $env:DISABLE_CUSTOM_PROMPT) {
+    $function:_old_prompt = $function:prompt
+    function dotnet_prompt {
+        # Add a prefix to the current prompt, but don't discard it.
+        write-host "($( split-path $PSScriptRoot -leaf )) " -nonewline
+        & $function:_old_prompt
+    }
+
+    Set-Item Function:prompt -Value $function:dotnet_prompt -ea ignore
+}
+
+Write-Host -f Magenta "Enabled the .NET Core environment. Execute 'deactivate' to exit."
+if (-not (Test-Path "${env:DOTNET_ROOT}\dotnet.exe")) {
+    Write-Host -f Yellow ".NET Core has not been installed yet. Run $PSScriptRoot\restore.cmd to install it."
+}
+else {
+    Write-Host "dotnet = ${env:DOTNET_ROOT}\dotnet.exe"
+}
diff --git a/activate.sh b/activate.sh
new file mode 100644
index 00000000000..894479a8b99
--- /dev/null
+++ b/activate.sh
@@ -0,0 +1,69 @@
+#
+# This file must be used by invoking "source activate.sh" from the command line.
+# You cannot run it directly.
+# To exit from the environment this creates, execute the 'deactivate' function.
+
+_MAGENTA="\033[0;95m"
+_YELLOW="\033[0;33m"
+_RESET="\033[0m"
+
+deactivate () {
+
+    # reset old environment variables
+    if [ ! -z "${_OLD_PATH:-}" ] ; then
+        export PATH="$_OLD_PATH"
+        unset _OLD_PATH
+    fi
+
+    if [ ! -z "${_OLD_PS1:-}" ] ; then
+        export PS1="$_OLD_PS1"
+        unset _OLD_PS1
+    fi
+
+    # This should detect bash and zsh, which have a hash command that must
+    # be called to get it to forget past commands.  Without forgetting
+    # past commands the $PATH changes we made may not be respected
+    if [ -n "${BASH:-}" ] || [ -n "${ZSH_VERSION:-}" ] ; then
+        hash -r 2>/dev/null
+    fi
+
+    unset DOTNET_ROOT
+    unset DOTNET_MULTILEVEL_LOOKUP
+    if [ ! "${1:-}" = "init" ] ; then
+        # Remove the deactivate function
+        unset -f deactivate
+    fi
+}
+
+# Cleanup the environment
+deactivate init
+
+DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+_OLD_PATH="$PATH"
+# Tell dotnet where to find itself
+export DOTNET_ROOT="$DIR/.dotnet"
+# Tell dotnet not to look beyond the DOTNET_ROOT folder for more dotnet things
+export DOTNET_MULTILEVEL_LOOKUP=0
+# Put dotnet first on PATH
+export PATH="$DOTNET_ROOT:$PATH"
+
+# Set the shell prompt
+if [ -z "${DISABLE_CUSTOM_PROMPT:-}" ] ; then
+    _OLD_PS1="$PS1"
+    export PS1="(`basename \"$DIR\"`) $PS1"
+fi
+
+# This should detect bash and zsh, which have a hash command that must
+# be called to get it to forget past commands.  Without forgetting
+# past commands the $PATH changes we made may not be respected
+if [ -n "${BASH:-}" ] || [ -n "${ZSH_VERSION:-}" ] ; then
+    hash -r 2>/dev/null
+fi
+
+echo "${_MAGENTA}Enabled the .NET Core environment. Execute 'deactivate' to exit.${_RESET}"
+
+if [ ! -f "$DOTNET_ROOT/dotnet" ]; then
+    echo "${_YELLOW}.NET Core has not been installed yet. Run $DIR/restore.sh to install it.${_RESET}"
+else
+    echo "dotnet = $DOTNET_ROOT/dotnet"
+fi
diff --git a/build.ps1 b/build.ps1
index 578129a9acf..859ae10cfec 100644
--- a/build.ps1
+++ b/build.ps1
@@ -234,12 +234,7 @@ if (Test-Path $ConfigFile) {
     }
 }
 
-$DotNetHome = if ($env:DOTNET_HOME) { $env:DOTNET_HOME } `
-    elseif ($CI) { Join-Path $PSScriptRoot '.dotnet' } `
-    elseif ($env:USERPROFILE) { Join-Path $env:USERPROFILE '.dotnet'} `
-    elseif ($env:HOME) {Join-Path $env:HOME '.dotnet'}`
-    else { Join-Path $PSScriptRoot '.dotnet'}
-
+$DotNetHome = Join-Path $PSScriptRoot '.dotnet'
 $env:DOTNET_HOME = $DotNetHome
 
 # Execute
@@ -310,4 +305,5 @@ try {
 }
 finally {
     Remove-Module 'KoreBuild' -ErrorAction Ignore
+    Remove-Item env:DOTNET_HOME
 }
diff --git a/build.sh b/build.sh
index bf5e54e8b01..4499355155d 100755
--- a/build.sh
+++ b/build.sh
@@ -236,9 +236,6 @@ while [[ $# -gt 0 ]]; do
             ;;
         --ci|-[Cc][Ii])
             ci=true
-            if [[ -z "${DOTNET_HOME:-}" ]]; then
-                DOTNET_HOME="$DIR/.dotnet"
-            fi
             ;;
         --verbose|-[Vv]erbose)
             verbose=true
@@ -286,8 +283,7 @@ if [ -f "$config_file" ]; then
     [ ! -z "${config_tools_source:-}" ] && tools_source="$config_tools_source"
 fi
 
-[ -z "${DOTNET_HOME:-}" ] && DOTNET_HOME="$HOME/.dotnet"
-export DOTNET_HOME="$DOTNET_HOME"
+export DOTNET_HOME="$DIR/.dotnet"
 
 get_korebuild
 
diff --git a/build/repo.props b/build/repo.props
index 397e3d471d3..d6ed427f9fa 100644
--- a/build/repo.props
+++ b/build/repo.props
@@ -58,6 +58,7 @@
                       $(RepositoryRoot)src\SignalR\clients\ts\**\node_modules\**\*.*proj;
                       $(RepositoryRoot)src\Components\Blazor\Templates\src\content\**\*.*proj;
                       $(RepositoryRoot)src\ProjectTemplates\Web.ProjectTemplates\content\**\*.csproj;
+                      $(RepositoryRoot)src\ProjectTemplates\Web.ProjectTemplates\content\**\*.fsproj;
                       $(RepositoryRoot)src\ProjectTemplates\Web.Spa.ProjectTemplates\content\**\*.csproj;
                       " />
 
@@ -159,7 +160,6 @@
                           $(RepositoryRoot)src\SignalR\**\*.csproj;
                           $(RepositoryRoot)src\Components\**\*.csproj;
                           $(RepositoryRoot)src\ProjectTemplates\*\*.csproj;
-                          $(RepositoryRoot)src\ProjectTemplates\test\*.csproj;
                           $(RepositoryRoot)src\ProjectTemplates\testassets\*\*.csproj;
                           "
                         Exclude="
diff --git a/docs/BuildFromSource.md b/docs/BuildFromSource.md
index ef3bf330a11..267b48331a7 100644
--- a/docs/BuildFromSource.md
+++ b/docs/BuildFromSource.md
@@ -53,7 +53,7 @@ To update an existing copy, run:
 git submodule update --init --recursive
 ```
 
-## Building in Visual Studio / Code
+## Building in Visual Studio
 
 Before opening our .sln files in Visual Studio or VS Code, you need to perform the following actions.
 
@@ -95,30 +95,22 @@ Or you can use this script to automatically traverse the project reference graph
 
     ./eng/scripts/AddAllProjectRefsToSolution.ps1 -WorkingDir src/Mvc/
 
-#### PATH
+## Building with Visual Studio Code
 
-For VS Code and Visual Studio and `dotnet` commands to work correctly, you must place the following location in your PATH.
-Use the following commands to update the PATH variable in a command line window.
+Using Visual Studio Code with this repo requires setting environment variables on command line first.
+Use these command to launch VS Code with the right settings.
 
-Windows (Command Prompt)
-
-```batch
-set PATH=%USERPROFILE%\.dotnet\x64;%PATH%
+On Windows (requires PowerShell):
 ```
-
-Windows (Powershell)
-
-```ps1
-$env:PATH="$env:USERPROFILE\.dotnet\x64;$env:PATH"
+. activate.ps1
+code .
 ```
 
-Linux/macOS:
-
-```sh
-export PATH="$HOME/.dotnet:$PATH"
+On macOS/Linux:
+```
+source activate.sh
+code .
 ```
-
-On Windows, we recommend using the `startvs.cmd` command to launch Visual Studio.
 
 ## Building on command-line
 
@@ -134,6 +126,22 @@ On macOS/Linux:
 ./build.sh
 ```
 
+### Using `dotnet` on command line in this repo
+
+Because we are using pre-release versions of .NET Core, you have to set a handful of environment variables
+to make the .NET Core command line tool work well. You can set these environment variables like this
+
+On Windows (requires PowerShell):
+
+```ps1
+. .\activate.ps1
+```
+
+On macOS/Linux:
+```bash
+source ./activate.sh
+```
+
 ## Running tests on command-line
 
 Tests are not run by default. Use the `-test` option to run tests in addition to building.
diff --git a/src/Framework/src/SharedFx.targets b/src/Framework/src/SharedFx.targets
index 0de8d1dcdb4..4bf154064ff 100644
--- a/src/Framework/src/SharedFx.targets
+++ b/src/Framework/src/SharedFx.targets
@@ -22,15 +22,12 @@ This targets file should only be imported by .shfxproj files.
       CollectSharedFxOutput;
       PostBuildEvent;
       GetTargetPath;
+      PrepareForRun;
     </CoreBuildDependsOn>
 
-    <CollectOutputSharedFxDependsOn Condition=" '$(CrossGenOutput)' != 'false' ">
+    <CollectOutputSharedFxDependsOn>
       PrepareForCrossGen;
       CrossGenAssemblies;
-    </CollectOutputSharedFxDependsOn>
-
-    <CollectOutputSharedFxDependsOn Condition=" '$(CrossgenSymbolsOutput)' != 'false' ">
-      $(CollectOutputSharedFxDependsOn);
       CrossGenSymbols;
     </CollectOutputSharedFxDependsOn>
 
@@ -46,6 +43,12 @@ This targets file should only be imported by .shfxproj files.
       AfterResolveReferences
     </ResolveReferencesDependsOn>
 
+    <PrepareForRunDependsOn>
+      CollectSharedFxOutput;
+      GetCopyToSharedFrameworkItems;
+      InstallFrameworkIntoLocalDotNet;
+    </PrepareForRunDependsOn>
+
     <!-- The name of the shared framework. -->
     <SharedFxName Condition=" '$(SharedFxName)' == '' ">$(MSBuildProjectName)</SharedFxName>
 
@@ -71,6 +74,7 @@ This targets file should only be imported by .shfxproj files.
     <SymbolsOutputPath Condition="'$(SymbolsOutputPath)' == ''">$(OutputPath)symbols\</SymbolsOutputPath>
     <NativeAssetsOutputPath Condition="'$(NativeAssetsOutputPath)' == ''">$(OutputPath)native\</NativeAssetsOutputPath>
     <RuntimeAssetsOutputPath Condition="'$(RuntimeAssetsOutputPath)' == ''">$(OutputPath)lib\$(TargetFramework)\</RuntimeAssetsOutputPath>
+    <LocalInstallationOutputPath>$(LocalDotNetRoot)shared\$(SharedFxName)\$(SharedFxVersion)\</LocalInstallationOutputPath>
 
     <CrossGenToolDir>$(IntermediateOutputPath)crossgen\</CrossGenToolDir>
     <!-- Crossgen executable name -->
@@ -100,6 +104,12 @@ This targets file should only be imported by .shfxproj files.
     <PlatformManifestOutputPath>$(ManifestOutputDir)$(SharedFxName).PlatformManifest.txt</PlatformManifestOutputPath>
   </PropertyGroup>
 
+  <ItemGroup>
+    <CopyToSharedFramework Include="$(SharedFxDepsFilePath)" OutputPath="$(LocalInstallationOutputPath)$(SharedFxName).deps.json" />
+    <CopyToSharedFramework Include="$(VersionFileOutputPath)" OutputPath="$(LocalInstallationOutputPath).version" />
+    <CopyToSharedFramework Include="$(PublishRuntimeConfigFilePath)" OutputPath="$(LocalInstallationOutputPath)$(SharedFxName).runtimeconfig.json" />
+  </ItemGroup>
+
   <ItemDefinitionGroup>
     <TargetPathWithTargetPlatformMoniker>
       <!--
@@ -155,7 +165,7 @@ This targets file should only be imported by .shfxproj files.
   </Target>
 
   <Target Name="PrepareOutputPaths">
-    <MakeDir Directories="$(MetadataOutputPath);$(SymbolsOutputPath);$(NativeAssetsOutputPath);$(RuntimeAssetsOutputPath)" />
+    <MakeDir Directories="$(MetadataOutputPath);$(SymbolsOutputPath);$(NativeAssetsOutputPath);$(RuntimeAssetsOutputPath);$(LocalInstallationOutputPath)" />
   </Target>
 
   <!-- Generates the .version file in the shared framework -->
@@ -192,7 +202,9 @@ This targets file should only be imported by .shfxproj files.
   </Target>
 
   <!-- Prepare the project to run crossgen. -->
-  <Target Name="CopySharedFxToOutput" DependsOnTargets="RunResolvePackageDependencies;RunResolvePublishAssemblies">
+  <Target Name="CopySharedFxToOutput" DependsOnTargets="_GetCopyToOutputItems;_BatchCopyToOutputIfNewer" />
+
+  <Target Name="_GetCopyToOutputItems" DependsOnTargets="RunResolvePackageDependencies;RunResolvePublishAssemblies">
     <ItemGroup>
       <NativeAssetsToPublish Include="@(ResolvedAssembliesToPublish)" Condition="'%(AssetType)' == 'native' " />
       <ResourceAssetsToPublish Include="@(ResolvedAssembliesToPublish)" Condition="'%(AssetType)' == 'resources'" />
@@ -202,13 +214,27 @@ This targets file should only be imported by .shfxproj files.
 
     <Error Text="Unaccounted shared framework assemblies found: @(OtherAssemblies). These files have an unknown asset type." Condition="'@(OtherAssemblies)' != ''" />
 
-    <Copy Condition=" '$(CrossGenOutput)' != 'true' "
-          SourceFiles="@(RuntimeAssetsToPublish)" DestinationFiles="@(RuntimeAssetsToPublish->'$(RuntimeAssetsOutputPath)%(DestinationSubPath)')" />
-    <Copy SourceFiles="@(NativeAssetsToPublish)" DestinationFiles="@(NativeAssetsToPublish->'$(NativeAssetsOutputPath)%(DestinationSubPath)')" />
-    <Copy SourceFiles="@(ResourceAssetsToPublish)" DestinationFiles="@(ResourceAssetsToPublish->'$(RuntimeAssetsOutputPath)%(DestinationSubPath)')" />
+    <ItemGroup>
+      <CopyToOutputItem Condition=" '$(CrossGenOutput)' != 'true' "
+            Include="@(RuntimeAssetsToPublish)" OutputPath="$(RuntimeAssetsOutputPath)%(RuntimeAssetsToPublish.DestinationSubPath)" />
+      <CopyToSharedFramework Condition=" '$(CrossGenOutput)' != 'true' "
+            Include="@(RuntimeAssetsToPublish)" OutputPath="$(LocalInstallationOutputPath)%(RuntimeAssetsToPublish.DestinationSubPath)" />
+      <CopyToOutputItem Include="@(NativeAssetsToPublish)" OutputPath="$(NativeAssetsOutputPath)%(NativeAssetsToPublish.DestinationSubPath)" />
+      <CopyToSharedFramework Include="@(NativeAssetsToPublish)" OutputPath="$(LocalInstallationOutputPath)%(NativeAssetsToPublish.DestinationSubPath)" />
+      <CopyToOutputItem Include="@(ResourceAssetsToPublish)" OutputPath="$(RuntimeAssetsOutputPath)%(ResourceAssetsToPublish.DestinationSubPath)" />
+      <CopyToSharedFramework Include="@(ResourceAssetsToPublish)" OutputPath="$(LocalInstallationOutputPath)%(ResourceAssetsToPublish.DestinationSubPath)" />
+    </ItemGroup>
+  </Target>
+
+  <Target Name="_BatchCopyToOutputIfNewer"
+          Inputs="@(CopyToOutputItem)"
+          Outputs="@(CopyToOutputItem->'%(OutputPath)')">
+    <Copy SourceFiles="@(CopyToOutputItem)"
+          DestinationFiles="@(CopyToOutputItem->'%(OutputPath)')"
+          UseHardlinksIfPossible="true" />
   </Target>
 
-  <Target Name="PrepareForCrossGen" DependsOnTargets="RunResolvePackageDependencies;RunResolvePublishAssemblies">
+  <Target Name="PrepareForCrossGen" DependsOnTargets="RunResolvePackageDependencies;RunResolvePublishAssemblies" Condition=" '$(CrossGenOutput)' != 'false' ">
     <MakeDir Directories="$(CrossGenToolDir)" />
 
     <PropertyGroup>
@@ -246,8 +272,10 @@ This targets file should only be imported by .shfxproj files.
         <SymbolsRsp>$(IntermediateOutputPath)%(RecursiveDir)%(Filename).symbols.rsp</SymbolsRsp>
         <SymbolsOutputPath>$(SymbolsOutputPath)%(RecursiveDir)%(Filename).ni.pdb</SymbolsOutputPath>
         <Destination>$(RuntimeAssetsOutputPath)%(RecursiveDir)%(Filename)%(Extension)</Destination>
+        <DestinationSubPath>%(RecursiveDir)%(Filename)%(Extension)</DestinationSubPath>
         <Symbols>$(SymbolsOutputPath)%(RecursiveDir)</Symbols>
       </AssembliesToCrossgen>
+      <CopyToSharedFramework Include="%(AssembliesToCrossgen.Destination)" OutputPath="$(LocalInstallationOutputPath)%(AssembliesToCrossgen.DestinationSubPath)" />
     </ItemGroup>
   </Target>
 
@@ -255,7 +283,7 @@ This targets file should only be imported by .shfxproj files.
     Run the crossgen tool.
     This uses .rsp files to get around OS limitations in the maximum number of characters that can be passed in on command-line.
   -->
-  <Target Name="CrossGenAssemblies"
+  <Target Name="CrossGenAssemblies" Condition=" '$(CrossGenOutput)' != 'false' "
     DependsOnTargets="CopySharedFxToOutput;ResolveReferences"
     Inputs="@(AssembliesToCrossgen)"
     Outputs="%(AssembliesToCrossgen.Destination)">
@@ -294,7 +322,7 @@ This targets file should only be imported by .shfxproj files.
           StandardOutputImportance="Normal" />
   </Target>
 
-  <Target Name="CrossGenSymbols"
+  <Target Name="CrossGenSymbols" Condition=" '$(CrossgenSymbolsOutput)' != 'false' "
     DependsOnTargets="CrossGenAssemblies"
     Inputs="@(AssembliesToCrossgen)"
     Outputs="%(AssembliesToCrossgen.SymbolsOutputPath)">
@@ -345,4 +373,17 @@ This targets file should only be imported by .shfxproj files.
       </NuspecProperties>
     </PropertyGroup>
   </Target>
+
+  <Target Name="PrepareForRun" DependsOnTargets="$(PrepareForRunDependsOn)" />
+
+  <Target Name="GetCopyToSharedFrameworkItems" DependsOnTargets="PrepareForCrossGen;CopySharedFxToOutput" />
+
+  <!-- Required to workaround https://github.com/dotnet/core-setup/issues/4809. This copies the shared framework into the $reporoot/.dotnet folder so tests can run against the shared framework. -->
+  <Target Name="InstallFrameworkIntoLocalDotNet"
+          Inputs="@(CopyToSharedFramework)"
+          Outputs="@(CopyToSharedFramework->'%(OutputPath)')">
+    <Copy SourceFiles="@(CopyToSharedFramework)"
+          DestinationFiles="@(CopyToSharedFramework->'%(OutputPath)')"
+          UseHardlinksIfPossible="true" />
+  </Target>
 </Project>
diff --git a/src/ProjectTemplates/build.cmd b/src/ProjectTemplates/build.cmd
index 033fe6f6146..bf383703263 100644
--- a/src/ProjectTemplates/build.cmd
+++ b/src/ProjectTemplates/build.cmd
@@ -1,3 +1,3 @@
 @ECHO OFF
 SET RepoRoot=%~dp0..\..
-%RepoRoot%\build.cmd -projects %~dp0\**\*.*proj %*
+%RepoRoot%\build.cmd -projects %~dp0\**\*.*proj -pack /t:BuildSharedFx /t:Build %*
diff --git a/src/ProjectTemplates/test/ProjectTemplates.Tests.csproj b/src/ProjectTemplates/test/ProjectTemplates.Tests.csproj
index 6e32f19f695..a8cd236f3de 100644
--- a/src/ProjectTemplates/test/ProjectTemplates.Tests.csproj
+++ b/src/ProjectTemplates/test/ProjectTemplates.Tests.csproj
@@ -6,6 +6,7 @@
     <SignAssembly>false</SignAssembly>
 
     <!-- Workaround until https://github.com/aspnet/AspNetCore/issues/4321 is resolved. -->
+    <RunTemplateTests Condition="'$(OS)' != 'Windows_NT'">true</RunTemplateTests>
     <SkipTests Condition="'$(RunTemplateTests)' != 'true'">true</SkipTests>
   </PropertyGroup>
 
diff --git a/src/ProjectTemplates/test/RazorComponentsTemplateTest.cs b/src/ProjectTemplates/test/RazorComponentsTemplateTest.cs
index 220361e2d66..eeed2796f78 100644
--- a/src/ProjectTemplates/test/RazorComponentsTemplateTest.cs
+++ b/src/ProjectTemplates/test/RazorComponentsTemplateTest.cs
@@ -23,17 +23,6 @@ namespace Templates.Test
         {
             RunDotNetNew("razorcomponents");
 
-            // We don't want the Directory.Build.props/targets interfering
-            File.WriteAllText(
-                Path.Combine(TemplateOutputDir, "Directory.Build.props"),
-                "<Project />");
-            File.WriteAllText(
-                Path.Combine(TemplateOutputDir, "Directory.Build.targets"),
-                @"<Project> <ItemGroup Condition=""'$(TargetFramework)' != 'netstandard2.0'"" >
-    <FrameworkReference Include = ""Microsoft.AspNetCore.App"" />
-  </ItemGroup>
-</Project>");
-
             // Run the "server" project
             ProjectName += ".Server";
             TemplateOutputDir = Path.Combine(TemplateOutputDir, ProjectName);
diff --git a/src/Servers/IIS/build/testsite.props b/src/Servers/IIS/build/testsite.props
index c0bdaf0e0da..6da7d1c8249 100644
--- a/src/Servers/IIS/build/testsite.props
+++ b/src/Servers/IIS/build/testsite.props
@@ -33,7 +33,8 @@
     <IISArguments>-h "$(IISAppHostConfig)"</IISArguments>
 
     <AncmInProcessRHPath>aspnetcorev2_inprocess.dll</AncmInProcessRHPath>
-    <DotNetPath>$(userprofile)\.dotnet\$(NativePlatform)\dotnet.exe</DotNetPath>
+    <!-- TODO: use LocalDotNetRoot instead to find dotnet.exe (see reporoot/Directory.Build.props). Requires a fix to https://github.com/aspnet/AspNetCore/issues/7196 -->
+    <DotNetPath>$(RepositoryRoot).dotnet\$(NativePlatform)\dotnet.exe</DotNetPath>
   </PropertyGroup>
 
   <Target Name="CopyLaunchSettings" AfterTargets="CoreBuild">
diff --git a/startvs.cmd b/startvs.cmd
index f3fa9216a3a..d15843640b0 100644
--- a/startvs.cmd
+++ b/startvs.cmd
@@ -2,12 +2,8 @@
 
 :: This command launches a Visual Studio solution with environment variables required to use a local version of the .NET Core SDK.
 
-IF "%DOTNET_HOME%"=="" (
-    set DOTNET_HOME=%USERPROFILE%\.dotnet
-)
-
 :: This tells .NET Core to use the same dotnet.exe that build scripts use
-SET DOTNET_ROOT=%DOTNET_HOME%\x64
+SET DOTNET_ROOT=%~dp0.dotnet\x64
 
 :: This tells .NET Core not to go looking for .NET Core in other places
 SET DOTNET_MULTILEVEL_LOOKUP=0
-- 
GitLab