Esempio n. 1
0
        public static LockFileTarget GetTargetAndReturnNullIfNotFound(this LockFile lockFile, string frameworkAlias, string runtimeIdentifier)
        {
            LockFileTarget lockFileTarget = lockFile.GetTarget(frameworkAlias, runtimeIdentifier);

            if (lockFileTarget == null &&
                lockFile.PackageSpec.TargetFrameworks.All(tfi => string.IsNullOrEmpty(tfi.TargetAlias)))
            {
                var nuGetFramework = NuGetUtils.ParseFrameworkName(frameworkAlias);
                lockFileTarget = lockFile.GetTarget(nuGetFramework, runtimeIdentifier);
            }

            return(lockFileTarget);
        }
Esempio n. 2
0
        public void It_restores_multitargeted_net_framework_project_successfully()
        {
            var testProject = new TestProject()
            {
                Name = "ProjectWithoutTargetingPackRef",
                TargetFrameworks = "net471;net472;netcoreapp3.0",
                IsSdkProject = true,
            };

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            string projectAssetsJsonPath = Path.Combine(
                testAsset.Path,
                testProject.Name,
                "obj",
                "project.assets.json");

            var restoreCommand =
                testAsset.GetRestoreCommand(Log, relativePath: testProject.Name);
            restoreCommand.Execute().Should().Pass();

            LockFile lockFile = LockFileUtilities.GetLockFile(
                projectAssetsJsonPath,
                NullLogger.Instance);

            var net471FrameworkLibrary = lockFile.GetTarget(NuGetFramework.Parse(".NETFramework,Version=v4.7.1"), null).Libraries.FirstOrDefault((file) => file.Name.Contains("net471"));
            if (TestProject.ReferenceAssembliesAreInstalled(TargetDotNetFrameworkVersion.Version471))
            {
                net471FrameworkLibrary.Should().BeNull();
            }
            else
            {
                net471FrameworkLibrary.Name.Should().Be("Microsoft.NETFramework.ReferenceAssemblies.net471");
                net471FrameworkLibrary.Type.Should().Be("package");
            }

            var net472FrameworkLibrary = lockFile.GetTarget(NuGetFramework.Parse(".NETFramework,Version=v4.7.2"), null).Libraries.FirstOrDefault((file) => file.Name.Contains("net472"));

            if (TestProject.ReferenceAssembliesAreInstalled(TargetDotNetFrameworkVersion.Version472))
            {
                net472FrameworkLibrary.Should().BeNull();
            }
            else
            {
                net472FrameworkLibrary.Name.Should().Be("Microsoft.NETFramework.ReferenceAssemblies.net472");
                net472FrameworkLibrary.Type.Should().Be("package");
            }
        }
Esempio n. 3
0
        public static ProjectContext CreateProjectContext(
            this LockFile lockFile,
            NuGetFramework framework,
            string runtime,
            string platformLibraryName)
        {
            if (lockFile == null)
            {
                throw new ArgumentNullException(nameof(lockFile));
            }
            if (framework == null)
            {
                throw new ArgumentNullException(nameof(framework));
            }

            LockFileTarget lockFileTarget = lockFile.GetTarget(framework, runtime);

            if (lockFileTarget == null)
            {
                string frameworkString = framework.DotNetFrameworkName;
                string targetMoniker   = string.IsNullOrEmpty(runtime) ?
                                         frameworkString :
                                         $"{frameworkString}/{runtime}";

                throw new BuildErrorException(Strings.AssetsFileMissingTarget, lockFile.Path, targetMoniker, framework.GetShortFolderName(), runtime);
            }

            return(new ProjectContext(lockFile, lockFileTarget, platformLibraryName));
        }
Esempio n. 4
0
        private static void InitializePackageDependencies(
            LockFile assetsFile,
            Dictionary <NuGetFramework, HashSet <LibraryDependency> > dependenciesByFramework,
            ISet <NuGetFramework> frameworkWithSuppressedDependencies)
        {
            // From the package spec, we know the direct package dependencies of this project.
            foreach (var framework in assetsFile.PackageSpec.TargetFrameworks)
            {
                if (frameworkWithSuppressedDependencies.Contains(framework.FrameworkName))
                {
                    continue;
                }

                // First, add each of the generic package dependencies to the framework-specific list.
                var packageDependencies = assetsFile
                                          .PackageSpec
                                          .Dependencies
                                          .Concat(framework.Dependencies);

                HashSet <LibraryDependency> dependencies;
                if (!dependenciesByFramework.TryGetValue(framework.FrameworkName, out dependencies))
                {
                    dependencies = new HashSet <LibraryDependency>();
                    dependenciesByFramework[framework.FrameworkName] = dependencies;
                }

                // Add each package dependency.
                foreach (var packageDependency in packageDependencies)
                {
                    // If we have a floating package dependency like 1.2.3-xyz-*, we
                    // use the version of the package that restore resolved it to.
                    if (packageDependency.LibraryRange.VersionRange.IsFloating)
                    {
                        var lockFileTarget = assetsFile.GetTarget(framework.FrameworkName, runtimeIdentifier: null);
                        var package        = lockFileTarget.Libraries.First(
                            library =>
                            string.Equals(library.Name, packageDependency.Name, StringComparison.OrdinalIgnoreCase));
                        if (package != null)
                        {
                            if (packageDependency.LibraryRange.VersionRange.HasUpperBound)
                            {
                                packageDependency.LibraryRange.VersionRange = new VersionRange(
                                    minVersion: package.Version,
                                    includeMinVersion: packageDependency.LibraryRange.VersionRange.IsMinInclusive,
                                    maxVersion: packageDependency.LibraryRange.VersionRange.MaxVersion,
                                    includeMaxVersion: packageDependency.LibraryRange.VersionRange.IsMaxInclusive);
                            }
                            else
                            {
                                packageDependency.LibraryRange.VersionRange = new VersionRange(
                                    minVersion: package.Version,
                                    includeMinVersion: packageDependency.LibraryRange.VersionRange.IsMinInclusive);
                            }
                        }
                    }

                    PackCommandRunner.AddLibraryDependency(packageDependency, dependencies);
                }
            }
        }
Esempio n. 5
0
        public static ProjectContext CreateProjectContext(
            this LockFile lockFile,
            NuGetFramework framework,
            string runtime,
            string platformLibraryName)
        {
            if (lockFile == null)
            {
                throw new ArgumentNullException(nameof(lockFile));
            }
            if (framework == null)
            {
                throw new ArgumentNullException(nameof(framework));
            }

            LockFileTarget lockFileTarget = lockFile.GetTarget(framework, runtime);

            if (lockFileTarget == null)
            {
                string frameworkString = framework.DotNetFrameworkName;
                string targetMoniker   = string.IsNullOrEmpty(runtime) ?
                                         frameworkString :
                                         $"{frameworkString}/{runtime}";

                throw new ReportUserErrorException($"Assets file '{lockFile.Path}' doesn't have a target for '{targetMoniker}'." +
                                                   $" Ensure you have restored this project for TargetFramework='{framework.GetShortFolderName()}'" +
                                                   $" and RuntimeIdentifier='{runtime}'.");
            }

            return(new ProjectContext(lockFile, lockFileTarget, platformLibraryName));
        }
        public void It_uses_MicrosoftNETCoreApp20x_as_the_implicit_version_for_NetCoreApp20()
        {
            const string testProjectName = "NetCoreApp2";
            var          project         = new TestProject
            {
                Name             = testProjectName,
                TargetFrameworks = "netcoreapp2.0",
                IsSdkProject     = true
            };

            var testAsset = _testAssetsManager
                            .CreateTestProject(project);

            string projectAssetsJsonPath = Path.Combine(
                testAsset.Path,
                project.Name,
                "obj",
                "project.assets.json");

            var restoreCommand =
                testAsset.GetRestoreCommand(Log, relativePath: testProjectName);

            restoreCommand.Execute().Should().Pass();

            LockFile lockFile = LockFileUtilities.GetLockFile(
                projectAssetsJsonPath,
                NullLogger.Instance);

            var target =
                lockFile.GetTarget(NuGetFramework.Parse(".NetCoreApp,Version=v2.0"), null);
            var netStandardLibrary =
                target.Libraries.Single(l => l.Name == "Microsoft.NETCore.App");

            netStandardLibrary.Version.ToString().Should().Be("2.0.0");
        }
Esempio n. 7
0
        public static LockFileTarget GetTargetAndThrowIfNotFound(this LockFile lockFile, NuGetFramework framework, string runtime)
        {
            LockFileTarget lockFileTarget = lockFile.GetTarget(framework, runtime);

            if (lockFileTarget == null)
            {
                string frameworkString = framework.DotNetFrameworkName;
                string targetMoniker   = string.IsNullOrEmpty(runtime) ?
                                         frameworkString :
                                         $"{frameworkString}/{runtime}";

                string message;
                if (string.IsNullOrEmpty(runtime))
                {
                    message = string.Format(Strings.AssetsFileMissingTarget, lockFile.Path, targetMoniker, framework.GetShortFolderName());
                }
                else
                {
                    message = string.Format(Strings.AssetsFileMissingRuntimeIdentifier, lockFile.Path, targetMoniker, framework.GetShortFolderName(), runtime);
                }

                throw new BuildErrorException(message);
            }

            return(lockFileTarget);
        }
        public void The_RuntimeFrameworkVersion_can_float()
        {
            var testProject = new TestProject()
            {
                Name                    = "RuntimeFrameworkVersionFloat",
                TargetFrameworks        = "netcoreapp2.0",
                RuntimeFrameworkVersion = "2.0.*",
                IsSdkProject            = true,
                IsExe                   = true
            };

            var testAsset = _testAssetsManager.CreateTestProject(testProject)
                            .Restore(Log, testProject.Name);

            var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name));

            buildCommand
            .Execute()
            .Should()
            .Pass();

            LockFile lockFile = LockFileUtilities.GetLockFile(Path.Combine(buildCommand.ProjectRootPath, "obj", "project.assets.json"), NullLogger.Instance);

            var target            = lockFile.GetTarget(NuGetFramework.Parse(testProject.TargetFrameworks), null);
            var netCoreAppLibrary = target.Libraries.Single(l => l.Name == "Microsoft.NETCore.App");

            //  Test that the resolved version is greater than or equal to the latest runtime patch
            //  we know about, so that when a new runtime patch is released the test doesn't
            //  immediately start failing
            var minimumExpectedVersion = new NuGetVersion(TestContext.LatestRuntimePatchForNetCoreApp2_0);

            netCoreAppLibrary.Version.CompareTo(minimumExpectedVersion).Should().BeGreaterOrEqualTo(0,
                                                                                                    "the version resolved from a RuntimeFrameworkVersion of '{0}' should be at least {1}",
                                                                                                    testProject.RuntimeFrameworkVersion, TestContext.LatestRuntimePatchForNetCoreApp2_0);
        }
Esempio n. 9
0
        private void It_targets_the_right_framework(
            string testIdentifier,
            string targetFramework,
            string runtimeFrameworkVersion,
            bool selfContained,
            bool isExe,
            string expectedPackageVersion,
            string expectedRuntimeVersion,
            string extraMSBuildArguments = null)
        {
            string runtimeIdentifier = null;

            if (selfContained)
            {
                runtimeIdentifier = EnvironmentInfo.GetCompatibleRid(targetFramework);
            }

            var testProject = new TestProject()
            {
                Name                    = "FrameworkTargetTest",
                TargetFrameworks        = targetFramework,
                RuntimeFrameworkVersion = runtimeFrameworkVersion,
                IsSdkProject            = true,
                IsExe                   = isExe,
                RuntimeIdentifier       = runtimeIdentifier
            };

            var extraArgs = extraMSBuildArguments?.Split(' ') ?? Array.Empty <string>();

            var testAsset = _testAssetsManager.CreateTestProject(testProject, testIdentifier)
                            .Restore(Log, testProject.Name, extraArgs);

            var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name));

            buildCommand
            .Execute(extraArgs)
            .Should()
            .Pass();

            var outputDirectory = buildCommand.GetOutputDirectory(targetFramework, runtimeIdentifier: runtimeIdentifier);

            //  Self-contained apps don't write a framework version to the runtimeconfig, so only check this for framework-dependent apps
            if (isExe && !selfContained)
            {
                string  runtimeConfigFile     = Path.Combine(outputDirectory.FullName, testProject.Name + ".runtimeconfig.json");
                string  runtimeConfigContents = File.ReadAllText(runtimeConfigFile);
                JObject runtimeConfig         = JObject.Parse(runtimeConfigContents);

                string actualRuntimeFrameworkVersion = ((JValue)runtimeConfig["runtimeOptions"]["framework"]["version"]).Value <string>();
                actualRuntimeFrameworkVersion.Should().Be(expectedRuntimeVersion);
            }

            LockFile lockFile = LockFileUtilities.GetLockFile(Path.Combine(buildCommand.ProjectRootPath, "obj", "project.assets.json"), NullLogger.Instance);

            var target            = lockFile.GetTarget(NuGetFramework.Parse(targetFramework), null);
            var netCoreAppLibrary = target.Libraries.Single(l => l.Name == "Microsoft.NETCore.App");

            netCoreAppLibrary.Version.ToString().Should().Be(expectedPackageVersion);
        }
Esempio n. 10
0
        string ResolveRuntimeAssemblyForReferenceAssembly(LockFile lockFile, string assemblyPath)
        {
            if (string.IsNullOrEmpty(TargetMoniker))
            {
                return(null);
            }

            var framework = NuGetFramework.Parse(TargetMoniker);

            if (framework == null)
            {
                LogCodedWarning("XA0118", Properties.Resources.XA0118_Parse, TargetMoniker);
                return(null);
            }
            var target = lockFile.GetTarget(framework, string.Empty);

            if (target == null)
            {
                LogCodedWarning("XA0118", Properties.Resources.XA0118_Target, TargetMoniker);
                return(null);
            }
            foreach (var folder in lockFile.PackageFolders)
            {
                var path = assemblyPath.Replace(folder.Path, string.Empty);
                if (path.StartsWith($"{Path.DirectorySeparatorChar}"))
                {
                    path = path.Substring(1);
                }
                var libraryPath = lockFile.Libraries.FirstOrDefault(x => path.StartsWith(x.Path.Replace('/', Path.DirectorySeparatorChar), StringComparison.OrdinalIgnoreCase));
                if (libraryPath == null)
                {
                    continue;
                }
                var library = target.Libraries.FirstOrDefault(x => String.Compare(x.Name, libraryPath.Name, StringComparison.OrdinalIgnoreCase) == 0);
                if (libraryPath == null)
                {
                    continue;
                }
                var runtime = library.RuntimeAssemblies.FirstOrDefault();
                if (runtime == null)
                {
                    continue;
                }
                path = Path.Combine(folder.Path, libraryPath.Path, runtime.Path).Replace('/', Path.DirectorySeparatorChar);
                if (!File.Exists(path))
                {
                    continue;
                }
                // _._ means its provided by the framework. However if we get here
                // its NOT. So lets use what we got in the first place.
                if (Path.GetFileName(path) == "_._")
                {
                    return(assemblyPath);
                }
                return(path);
            }
            return(null);
        }
Esempio n. 11
0
        public void It_targets_the_right_shared_framework(string targetFramework, string runtimeFrameworkVersion, string netCoreAppPackageVersion,
                                                          string expectedPackageVersion, string expectedRuntimeVersion)
        {
            var testProject = new TestProject()
            {
                Name             = "SharedFrameworkTest",
                TargetFrameworks = targetFramework,
                IsSdkProject     = true,
                IsExe            = true
            };

            string testIdentifier = string.Join("_", targetFramework, runtimeFrameworkVersion ?? "null", netCoreAppPackageVersion ?? "null");

            var testAsset = _testAssetsManager.CreateTestProject(testProject, nameof(It_targets_the_right_shared_framework), testIdentifier);

            testAsset = testAsset.WithProjectChanges(project =>
            {
                var ns            = project.Root.Name.Namespace;
                var propertyGroup = new XElement(ns + "PropertyGroup");
                project.Root.Add(propertyGroup);

                if (runtimeFrameworkVersion != null)
                {
                    propertyGroup.Add(new XElement(ns + "RuntimeFrameworkVersion", runtimeFrameworkVersion));
                }

                if (netCoreAppPackageVersion != null)
                {
                    propertyGroup.Add(new XElement(ns + "NetCoreAppImplicitPackageVersion", netCoreAppPackageVersion));
                }
            });

            testAsset = testAsset.Restore(testProject.Name);

            var buildCommand = new BuildCommand(Stage0MSBuild, Path.Combine(testAsset.TestRoot, testProject.Name));

            buildCommand
            .Execute()
            .Should()
            .Pass();

            var     outputDirectory       = buildCommand.GetOutputDirectory(targetFramework);
            string  runtimeConfigFile     = Path.Combine(outputDirectory.FullName, testProject.Name + ".runtimeconfig.json");
            string  runtimeConfigContents = File.ReadAllText(runtimeConfigFile);
            JObject runtimeConfig         = JObject.Parse(runtimeConfigContents);

            string actualRuntimeFrameworkVersion = ((JValue)runtimeConfig["runtimeOptions"]["framework"]["version"]).Value <string>();

            actualRuntimeFrameworkVersion.Should().Be(expectedRuntimeVersion);

            LockFile lockFile = LockFileUtilities.GetLockFile(Path.Combine(buildCommand.ProjectRootPath, "obj", "project.assets.json"), NullLogger.Instance);

            var target            = lockFile.GetTarget(NuGetFramework.Parse(targetFramework), null);
            var netCoreAppLibrary = target.Libraries.Single(l => l.Name == "Microsoft.NETCore.App");

            netCoreAppLibrary.Version.ToString().Should().Be(expectedPackageVersion);
        }
Esempio n. 12
0
        public DependencyContext Build(
            SingleProjectInfo mainProjectInfo,
            CompilationOptions compilationOptions,
            LockFile lockFile,
            NuGetFramework framework,
            string runtime)
        {
            bool includeCompilationLibraries = compilationOptions != null;

            LockFileTarget lockFileTarget = lockFile.GetTarget(framework, runtime);

            IEnumerable <LockFileTargetLibrary> runtimeExports     = lockFileTarget.GetRuntimeLibraries();
            IEnumerable <LockFileTargetLibrary> compilationExports =
                includeCompilationLibraries ?
                lockFileTarget.GetCompileLibraries() :
                Enumerable.Empty <LockFileTargetLibrary>();

            var dependencyLookup = compilationExports
                                   .Concat(runtimeExports)
                                   .Distinct()
                                   .Select(library => new Dependency(library.Name, library.Version.ToString()))
                                   .ToDictionary(dependency => dependency.Name, StringComparer.OrdinalIgnoreCase);

            var libraryLookup = lockFile.Libraries.ToDictionary(l => l.Name, StringComparer.OrdinalIgnoreCase);

            var runtimeSignature = GenerateRuntimeSignature(runtimeExports);

            IEnumerable <RuntimeLibrary> runtimeLibraries =
                GetLibraries(runtimeExports, libraryLookup, dependencyLookup, runtime: true).Cast <RuntimeLibrary>();

            IEnumerable <CompilationLibrary> compilationLibraries;

            if (includeCompilationLibraries)
            {
                CompilationLibrary projectCompilationLibrary = GetProjectCompilationLibrary(
                    mainProjectInfo,
                    lockFile,
                    lockFileTarget,
                    dependencyLookup);
                compilationLibraries = new[] { projectCompilationLibrary }
                .Concat(
                    GetLibraries(compilationExports, libraryLookup, dependencyLookup, runtime: false)
                    .Cast <CompilationLibrary>());
            }
            else
            {
                compilationLibraries = Enumerable.Empty <CompilationLibrary>();
            }

            return(new DependencyContext(
                       new TargetInfo(framework.DotNetFrameworkName, runtime, runtimeSignature, lockFileTarget.IsPortable()),
                       compilationOptions ?? CompilationOptions.Default,
                       compilationLibraries,
                       runtimeLibraries,
                       new RuntimeFallbacks[] { }));
        }
Esempio n. 13
0
        static NuGetVersion GetLibraryVersion(TestProject testProject, BuildCommand buildCommand, string libraryName)
        {
            LockFile lockFile = LockFileUtilities.GetLockFile(
                Path.Combine(buildCommand.GetBaseIntermediateDirectory().FullName, "project.assets.json"),
                NullLogger.Instance);

            var target          = lockFile.GetTarget(NuGetFramework.Parse(testProject.TargetFrameworks), testProject.RuntimeIdentifier);
            var lockFileLibrary = target.Libraries.Single(l => l.Name == libraryName);

            return(lockFileLibrary.Version);
        }
        AssemblyDefinition ResolveRuntimeAssemblyForReferenceAssembly(LockFile lockFile, DirectoryAssemblyResolver resolver, string assemblyPath)
        {
            if (string.IsNullOrEmpty(TargetMoniker))
            {
                return(null);
            }

            var framework = NuGetFramework.Parse(TargetMoniker);

            if (framework == null)
            {
                LogCodedWarning("XA0118", $"Could not parse '{TargetMoniker}'");
                return(null);
            }
            var target = lockFile.GetTarget(framework, string.Empty);

            if (target == null)
            {
                LogCodedWarning("XA0118", $"Could not resolve target for '{TargetMoniker}'");
                return(null);
            }
            foreach (var folder in lockFile.PackageFolders)
            {
                var path        = assemblyPath.Replace(folder.Path, string.Empty);
                var libraryPath = lockFile.Libraries.FirstOrDefault(x => path.StartsWith(x.Path.Replace('/', Path.DirectorySeparatorChar), StringComparison.OrdinalIgnoreCase));
                if (libraryPath == null)
                {
                    continue;
                }
                var library = target.Libraries.FirstOrDefault(x => String.Compare(x.Name, libraryPath.Name, StringComparison.OrdinalIgnoreCase) == 0);
                if (libraryPath == null)
                {
                    continue;
                }
                var runtime = library.RuntimeAssemblies.FirstOrDefault();
                if (runtime == null)
                {
                    continue;
                }
                path = Path.Combine(folder.Path, libraryPath.Path, runtime.Path).Replace('/', Path.DirectorySeparatorChar);
                if (!File.Exists(path))
                {
                    continue;
                }
                LogDebugMessage($"Attempting to load {path}");
                return(resolver.Load(path, forceLoad: true));
            }
            return(null);
        }
Esempio n. 15
0
        public void It_restores_net_framework_project_with_existing_references()
        {
            var targetFramework = "net471";
            var testProject     = new TestProject()
            {
                Name             = "ProjectWithoutTargetingPackRef",
                TargetFrameworks = targetFramework,
                IsSdkProject     = true,
            };

            // Add explicit reference to assembly packs
            var testAsset = _testAssetsManager.CreateTestProject(testProject).WithProjectChanges(project =>
            {
                var ns        = project.Root.Name.Namespace;
                var itemGroup = project.Root.Elements(ns + "ItemGroup").FirstOrDefault();
                itemGroup.Add(new XElement(ns + "PackageReference",
                                           new XAttribute("Include", $"Newtonsoft.Json"),
                                           new XAttribute("Version", $"11.0.2")));
                itemGroup.Add(new XElement(ns + "PackageReference",
                                           new XAttribute("Include", $"sqlite"),
                                           new XAttribute("Version", $"3.13.0")));
                itemGroup.Add(new XElement(ns + "PackageReference",
                                           new XAttribute("Include", $"Microsoft.NETFramework.ReferenceAssemblies"),
                                           new XAttribute("Version", $"1.0.0")));
            });

            string projectAssetsJsonPath = Path.Combine(
                testAsset.Path,
                testProject.Name,
                "obj",
                "project.assets.json");

            var restoreCommand =
                testAsset.GetRestoreCommand(Log, relativePath: testProject.Name);

            restoreCommand.Execute()
            .Should()
            .Pass()
            .And
            .NotHaveStdOutContaining("NETSDK1023");

            LockFile lockFile            = LockFileUtilities.GetLockFile(projectAssetsJsonPath, NullLogger.Instance);
            var      netFrameworkLibrary = lockFile.GetTarget(NuGetFramework.Parse(".NETFramework,Version=v4.7.1"), null).Libraries.FirstOrDefault((file) => file.Name.Contains(targetFramework));

            netFrameworkLibrary.Name.Should().Be("Microsoft.NETFramework.ReferenceAssemblies." + targetFramework);
            netFrameworkLibrary.Type.Should().Be("package");
            netFrameworkLibrary.Version.ToFullString().Should().Be("1.0.0");
        }
Esempio n. 16
0
        AssemblyDefinition ResolveRuntimeAssemblyForReferenceAssembly(LockFile lockFile, DirectoryAssemblyResolver resolver, AssemblyNameDefinition assemblyNameDefinition)
        {
            if (string.IsNullOrEmpty(TargetMoniker) || string.IsNullOrEmpty(NuGetPackageRoot) || !Directory.Exists(NuGetPackageRoot))
            {
                return(null);
            }

            var framework = NuGetFramework.Parse(TargetMoniker);

            if (framework == null)
            {
                LogWarning($"Could not parse '{TargetMoniker}'");
                return(null);
            }
            var target = lockFile.GetTarget(framework, string.Empty);

            if (target == null)
            {
                LogWarning($"Could not resolve target for '{TargetMoniker}'");
                return(null);
            }
            var libraryPath = lockFile.Libraries.FirstOrDefault(x => x.Name == assemblyNameDefinition.Name);

            if (libraryPath == null)
            {
                return(null);
            }
            var library = target.Libraries.FirstOrDefault(x => x.Name == assemblyNameDefinition.Name);

            if (library == null)
            {
                return(null);
            }
            var runtime = library.RuntimeAssemblies.FirstOrDefault();

            if (runtime == null)
            {
                return(null);
            }
            var path = Path.Combine(NuGetPackageRoot, libraryPath.Path, runtime.Path);

            LogDebugMessage($"Attempting to load {path}");
            return(resolver.Load(path, forceLoad: true));
        }
        public void It_fails_without_assembly_pack_reference()
        {
            var targetFramework = "net472";
            var testProject     = new TestProject()
            {
                Name             = "ProjectWithoutTargetingPackRef",
                TargetFrameworks = targetFramework,
                IsSdkProject     = true,
            };

            testProject.AdditionalProperties["AutomaticallyUseReferenceAssemblyPackages"] = "false";

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name));

            if (TestProject.ReferenceAssembliesAreInstalled(TargetDotNetFrameworkVersion.Version472))
            {
                buildCommand.Execute()
                .Should()
                .Pass();

                string projectAssetsJsonPath = Path.Combine(
                    testAsset.Path,
                    testProject.Name,
                    "obj",
                    "project.assets.json");
                LockFile lockFile = LockFileUtilities.GetLockFile(
                    projectAssetsJsonPath,
                    NullLogger.Instance);
                lockFile.GetTarget(NuGetFramework.Parse(".NETFramework,Version=v4.7.2"), null).Libraries.FirstOrDefault((file) => file.Name.Contains("net472"))
                .Should()
                .BeNull();
            }
            else
            {
                buildCommand.Execute()
                .Should()
                .Fail();
            }
        }
Esempio n. 18
0
        public void Implicit_NetCoreApp_reference_can_be_overridden(bool disableImplicitFrameworkReferences)
        {
            var testProject = new TestProject()
            {
                Name             = "OverrideNetCoreApp",
                TargetFrameworks = "netcoreapp2.0",
                IsSdkProject     = true,
                IsExe            = true
            };

            if (disableImplicitFrameworkReferences)
            {
                testProject.AdditionalProperties["DisableImplicitFrameworkReferences"] = "true";
            }

            string explicitPackageVersion = "2.0.3";

            testProject.PackageReferences.Add(new TestPackageReference("Microsoft.NETCore.App", explicitPackageVersion));

            var testAsset = _testAssetsManager.CreateTestProject(testProject, identifier: disableImplicitFrameworkReferences.ToString())
                            .Restore(Log, testProject.Name);

            var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name));

            buildCommand
            .Execute()
            .Should()
            .Pass()
            .And
            .NotHaveStdOutContaining("NETSDK1071");
            ;

            LockFile lockFile = LockFileUtilities.GetLockFile(Path.Combine(buildCommand.ProjectRootPath, "obj", "project.assets.json"), NullLogger.Instance);

            var target            = lockFile.GetTarget(NuGetFramework.Parse(testProject.TargetFrameworks), null);
            var netCoreAppLibrary = target.Libraries.Single(l => l.Name == "Microsoft.NETCore.App");

            netCoreAppLibrary.Version.ToString().Should().Be(explicitPackageVersion);
        }
        string GetRollForwardNetCoreAppVersion()
        {
            var testProject = new TestProject()
            {
                Name             = nameof(GetRollForwardNetCoreAppVersion),
                TargetFrameworks = "netcoreapp2.2",
                IsExe            = true
            };

            testProject.AdditionalProperties.Add("TargetLatestRuntimePatch", "true");

            var testAsset = _testAssetsManager.CreateTestProject(testProject)
                            .Restore(Log, testProject.Name);

            LockFile lockFile = LockFileUtilities.GetLockFile(Path.Combine(testAsset.TestRoot, testProject.Name,
                                                                           "obj", "project.assets.json"), NullLogger.Instance);

            var target            = lockFile.GetTarget(NuGetFramework.Parse(testProject.TargetFrameworks), null);
            var netCoreAppLibrary = target.Libraries.Single(l => l.Name == "Microsoft.NETCore.App");

            return(netCoreAppLibrary.Version.ToString());
        }
Esempio n. 20
0
        public void It_restores_net_framework_project_successfully(string version)
        {
            var targetFrameworkVersion = (TargetDotNetFrameworkVersion)System.Enum.Parse(typeof(TargetDotNetFrameworkVersion), "Version" + string.Join("", version.Split('.')));
            var targetFramework        = "net" + string.Join("", version.Split('.'));
            var testProject            = new TestProject()
            {
                Name             = "ProjectWithoutTargetingPackRef",
                TargetFrameworks = targetFramework,
                IsSdkProject     = true,
            };

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            string projectAssetsJsonPath = Path.Combine(
                testAsset.Path,
                testProject.Name,
                "obj",
                "project.assets.json");

            var restoreCommand =
                testAsset.GetRestoreCommand(Log, relativePath: testProject.Name);

            restoreCommand.Execute().Should().Pass();

            LockFile lockFile            = LockFileUtilities.GetLockFile(projectAssetsJsonPath, NullLogger.Instance);
            var      netFrameworkLibrary = lockFile.GetTarget(NuGetFramework.Parse(".NETFramework,Version=v" + version), null).Libraries.FirstOrDefault((file) => file.Name.Contains(targetFramework));

            if (TestProject.ReferenceAssembliesAreInstalled(targetFrameworkVersion))
            {
                netFrameworkLibrary.Should().BeNull();
            }
            else
            {
                netFrameworkLibrary.Name.Should().Be("Microsoft.NETFramework.ReferenceAssemblies." + targetFramework);
                netFrameworkLibrary.Type.Should().Be("package");
            }
        }
Esempio n. 21
0
        private static void InitializeProjectDependencies(
            LockFile assetsFile,
            IDictionary <NuGetFramework, HashSet <LibraryDependency> > dependenciesByFramework,
            IDictionary <string, string> projectRefToVersionMap,
            ISet <NuGetFramework> frameworkWithSuppressedDependencies)
        {
            // From the package spec, all we know is each absolute path to the project reference the the target
            // framework that project reference applies to.

            if (assetsFile.PackageSpec.RestoreMetadata == null)
            {
                return;
            }

            // Using the libraries section of the assets file, the library name and version for the project path.
            var projectPathToLibraryIdentities = assetsFile
                                                 .Libraries
                                                 .Where(library => library.MSBuildProject != null)
                                                 .ToLookup(
                library => Path.GetFullPath(Path.Combine(
                                                Path.GetDirectoryName(assetsFile.PackageSpec.RestoreMetadata.ProjectPath),
                                                PathUtility.GetPathWithDirectorySeparator(library.MSBuildProject))),
                library => new PackageIdentity(library.Name, library.Version),
                PathUtility.GetStringComparerBasedOnOS());

            // Consider all of the project references, grouped by target framework.
            foreach (var framework in assetsFile.PackageSpec.RestoreMetadata.TargetFrameworks)
            {
                var target = assetsFile.GetTarget(framework.FrameworkName, runtimeIdentifier: null);
                if (target == null || frameworkWithSuppressedDependencies.Contains(framework.FrameworkName))
                {
                    continue;
                }

                HashSet <LibraryDependency> dependencies;
                if (!dependenciesByFramework.TryGetValue(framework.FrameworkName, out dependencies))
                {
                    dependencies = new HashSet <LibraryDependency>();
                    dependenciesByFramework[framework.FrameworkName] = dependencies;
                }

                // For the current target framework, create a map from library identity to library model. This allows
                // us to be sure we have picked the correct library (name and version) for this target framework.
                var libraryIdentityToTargetLibrary = target
                                                     .Libraries
                                                     .ToLookup(library => new PackageIdentity(library.Name, library.Version));

                foreach (var projectReference in framework.ProjectReferences)
                {
                    var libraryIdentities = projectPathToLibraryIdentities[projectReference.ProjectPath];

                    var targetLibrary = libraryIdentities
                                        .Select(identity => libraryIdentityToTargetLibrary[identity].FirstOrDefault())
                                        .FirstOrDefault(library => library != null);

                    if (targetLibrary == null)
                    {
                        continue;
                    }

                    var versionToUse = new VersionRange(targetLibrary.Version);

                    // Use the project reference version obtained at build time if it exists, otherwise fallback to the one in assets file.
                    if (projectRefToVersionMap.TryGetValue(projectReference.ProjectPath, out var projectRefVersion))
                    {
                        versionToUse = VersionRange.Parse(projectRefVersion, allowFloating: false);
                    }
                    // TODO: Implement <TreatAsPackageReference>false</TreatAsPackageReference>
                    //   https://github.com/NuGet/Home/issues/3891
                    //
                    // For now, assume the project reference is a package dependency.
                    var projectDependency = new LibraryDependency
                    {
                        LibraryRange = new LibraryRange(
                            targetLibrary.Name,
                            versionToUse,
                            LibraryDependencyTarget.All),
                        IncludeType    = projectReference.IncludeAssets & ~projectReference.ExcludeAssets,
                        SuppressParent = projectReference.PrivateAssets
                    };

                    PackCommandRunner.AddLibraryDependency(projectDependency, dependencies);
                }
            }
        }
Esempio n. 22
0
        protected IEnumerable <RuntimeLibrary> GetNugetReferences(string projectFilePath, Project project)
        {
            Logger.WriteInfo("Adding nuget references.");

            ICollection <RuntimeLibrary> runtimeLibraries = new List <RuntimeLibrary>();

            LockFileFormat lockFileFormat = new LockFileFormat();

            string lockFileFilePath = Path.Combine(Path.GetDirectoryName(projectFilePath),
                                                   project.GetPropertyValue(PropertyNames.ProjectAssetsFile));

            if (!File.Exists(lockFileFilePath))
            {
                Logger.WriteError($"Lock file {lockFileFilePath} not found. Run dotnet restore before executing Automaty.");

                throw new AutomatyException();
            }

            LockFile lockFile = lockFileFormat.Read(lockFileFilePath);

            string targetFramework = project.GetPropertyValue(PropertyNames.TargetFramework);

            if (string.IsNullOrEmpty(targetFramework))
            {
                Logger.WriteDebug("Multi targeting project assembly detected.");
                targetFramework = GetSuitableTargetFramework(project.GetPropertyValue(PropertyNames.TargetFrameworks));
                Logger.WriteDebug($"Using target framework {targetFramework}.");
            }

            LockFileTarget lockFileTarget = lockFile.GetTarget(NuGetUtils.ParseFrameworkName(targetFramework), string.Empty);

            NuGetPackageResolver nuGetPackageResolver =
                NuGetPackageResolver.CreateResolver(lockFile, Path.GetDirectoryName(projectFilePath));

            // Add nuget references
            foreach (LockFileTargetLibrary library in lockFileTarget.Libraries)
            {
                if (library.Type != LibraryType.Package)
                {
                    continue;
                }

                string packageDirectory = nuGetPackageResolver.GetPackageDirectory(library.Name, library.Version);

                foreach (LockFileItem file in library.RuntimeAssemblies.Where(file => !NuGetUtils.IsPlaceholderFile(file.Path)))
                {
                    string filePath = Path.GetFullPath(Path.Combine(packageDirectory, file.Path));

                    Logger.WriteDebug($"Adding \"{filePath}\".");

                    runtimeLibraries.Add(new RuntimeLibrary
                    {
                        Name          = library.Name,
                        DirectoryName = Path.GetDirectoryName(filePath),
                        FileName      = Path.GetFileName(filePath)
                    });
                }
            }

            return(runtimeLibraries);
        }
Esempio n. 23
0
        public void It_restores_multitargeted_net_framework_project_successfully(bool includeExplicitReference)
        {
            var testProject = new TestProject()
            {
                Name             = "ProjectWithoutTargetingPackRef",
                TargetFrameworks = "net471;net472;netcoreapp3.0",
            };

            TestAsset testAsset = null;

            if (includeExplicitReference)
            {
                // Add explicit reference to assembly packs
                testAsset = _testAssetsManager.CreateTestProject(testProject, identifier: includeExplicitReference.ToString()).WithProjectChanges(project =>
                {
                    var ns        = project.Root.Name.Namespace;
                    var itemGroup = project.Root.Elements(ns + "ItemGroup").FirstOrDefault();
                    itemGroup.Add(new XElement(ns + "PackageReference",
                                               new XAttribute("Include", $"Microsoft.NETFramework.ReferenceAssemblies"),
                                               new XAttribute("Version", $"1.0.0-preview.2")));
                });
            }
            else
            {
                testAsset = _testAssetsManager.CreateTestProject(testProject);
            }

            string projectAssetsJsonPath = Path.Combine(
                testAsset.Path,
                testProject.Name,
                "obj",
                "project.assets.json");

            var restoreCommand = testAsset.GetRestoreCommand(Log, relativePath: testProject.Name);

            restoreCommand.Execute()
            .Should()
            .Pass()
            .And
            .NotHaveStdOutContaining("NETSDK1023");

            LockFile lockFile = LockFileUtilities.GetLockFile(
                projectAssetsJsonPath,
                NullLogger.Instance);

            var net471FrameworkLibrary = lockFile.GetTarget(NuGetFramework.Parse(".NETFramework,Version=v4.7.1"), null).Libraries.FirstOrDefault((file) => file.Name.Contains("net471"));

            if (TestProject.ReferenceAssembliesAreInstalled(TargetDotNetFrameworkVersion.Version471) && !includeExplicitReference)
            {
                net471FrameworkLibrary.Should().BeNull();
            }
            else
            {
                net471FrameworkLibrary.Name.Should().Be("Microsoft.NETFramework.ReferenceAssemblies.net471");
                net471FrameworkLibrary.Type.Should().Be("package");
            }

            var net472FrameworkLibrary = lockFile.GetTarget(NuGetFramework.Parse(".NETFramework,Version=v4.7.2"), null).Libraries.FirstOrDefault((file) => file.Name.Contains("net472"));

            if (TestProject.ReferenceAssembliesAreInstalled(TargetDotNetFrameworkVersion.Version472) && !includeExplicitReference)
            {
                net472FrameworkLibrary.Should().BeNull();
            }
            else
            {
                net472FrameworkLibrary.Name.Should().Be("Microsoft.NETFramework.ReferenceAssemblies.net472");
                net472FrameworkLibrary.Type.Should().Be("package");
            }
        }
        private void InitializePackageDependencies(
            LockFile assetsFile,
            Dictionary <NuGetFramework, HashSet <LibraryDependency> > dependenciesByFramework,
            ISet <NuGetFramework> frameworkWithSuppressedDependencies)
        {
            var packageSpecificNoWarnProperties = new Dictionary <string, HashSet <(NuGetLogCode, NuGetFramework)> >(StringComparer.OrdinalIgnoreCase);

            // From the package spec, we know the direct package dependencies of this project.
            foreach (TargetFrameworkInformation framework in assetsFile.PackageSpec.TargetFrameworks)
            {
                if (frameworkWithSuppressedDependencies.Contains(framework.FrameworkName))
                {
                    continue;
                }

                IEnumerable <LibraryDependency> centralTransitiveDependencies = assetsFile
                                                                                .CentralTransitiveDependencyGroups
                                                                                .Where(centralTDG => centralTDG.FrameworkName.Equals(framework.FrameworkName.ToString(), StringComparison.OrdinalIgnoreCase))
                                                                                .SelectMany(centralTDG => centralTDG.TransitiveDependencies);

                // First, add each of the generic package dependencies to the framework-specific list.
                var packageDependencies = assetsFile
                                          .PackageSpec
                                          .Dependencies
                                          .Concat(framework.Dependencies)
                                          .Concat(centralTransitiveDependencies);

                HashSet <LibraryDependency> dependencies;
                if (!dependenciesByFramework.TryGetValue(framework.FrameworkName, out dependencies))
                {
                    dependencies = new HashSet <LibraryDependency>();
                    dependenciesByFramework[framework.FrameworkName] = dependencies;
                }

                // Add each package dependency.
                foreach (var packageDependency in packageDependencies)
                {
                    // If we have a floating package dependency like 1.2.3-xyz-*, we
                    // use the version of the package that restore resolved it to.
                    if (packageDependency.LibraryRange.VersionRange.IsFloating)
                    {
                        var lockFileTarget = assetsFile.GetTarget(framework.FrameworkName, runtimeIdentifier: null);
                        var package        = lockFileTarget.Libraries.First(
                            library =>
                            string.Equals(library.Name, packageDependency.Name, StringComparison.OrdinalIgnoreCase));
                        if (package != null)
                        {
                            if (packageDependency.LibraryRange.VersionRange.HasUpperBound)
                            {
                                packageDependency.LibraryRange.VersionRange = new VersionRange(
                                    minVersion: package.Version,
                                    includeMinVersion: packageDependency.LibraryRange.VersionRange.IsMinInclusive,
                                    maxVersion: packageDependency.LibraryRange.VersionRange.MaxVersion,
                                    includeMaxVersion: packageDependency.LibraryRange.VersionRange.IsMaxInclusive);
                            }
                            else
                            {
                                packageDependency.LibraryRange.VersionRange = new VersionRange(
                                    minVersion: package.Version,
                                    includeMinVersion: packageDependency.LibraryRange.VersionRange.IsMinInclusive);
                            }
                        }
                    }

                    if (packageDependency.NoWarn.Count > 0)
                    {
                        HashSet <(NuGetLogCode, NuGetFramework)> nowarnProperties = null;

                        if (!packageSpecificNoWarnProperties.TryGetValue(packageDependency.Name, out nowarnProperties))
                        {
                            nowarnProperties = new HashSet <(NuGetLogCode, NuGetFramework)>();
                        }

                        nowarnProperties.AddRange(packageDependency.NoWarn.Select(n => (n, framework.FrameworkName)));
                        packageSpecificNoWarnProperties[packageDependency.Name] = nowarnProperties;
                    }

                    PackCommandRunner.AddLibraryDependency(packageDependency, dependencies);
                }
            }

            if (packageSpecificNoWarnProperties.Keys.Count > 0)
            {
                _packageSpecificWarningProperties = PackageSpecificWarningProperties.CreatePackageSpecificWarningProperties(packageSpecificNoWarnProperties);
            }
        }
        /// <summary>
        /// Creates an MSBuild properties file that specifies the full closure of packages with locked versions.
        /// </summary>
        /// <returns>A <see cref="ProjectRootElement"/> object that can be saved.</returns>
        internal bool TryCreateProject(out ProjectRootElement project)
        {
            project = null;

            if (!File.Exists(ProjectAssetsFile))
            {
                Log.LogError($"NuGet assets file '{ProjectAssetsFile}' does not exist.");
                return(false);
            }

            // should item group be conditioned or items or metadata?  Perhaps item condition should be considered and compared as well as an item could be conditioned.  Consider the below scenarios.  Since we are only parsing the assets file we need to consider the project file entries.
            // <PackageReference Include="foo" Version="1.2.3" Condition="bar"/>
            // <PackageReference Include="foo">
            //    <version>1.2.3</version>
            //    <version Condition="bar">1.2.3</version>
            // </PackageReference>
            // What about dependencies of packages that are conditioned? they should be conditioned as well.

            HashSet <string> packagesToExclude = new HashSet <string>(PackagesToExclude?.Select(i => i.ItemSpec).Distinct() ?? Enumerable.Empty <string>(), StringComparer.OrdinalIgnoreCase);

            project = ProjectRootElement.Create();

            project.ToolsVersion = String.Empty;

            ProjectPropertyElement wasImportedPropertyElement = project.AddProperty("NuGetDeterministicPropsWasImported", "true");

            LockFile lockFile = LockFileUtilities.GetLockFile(ProjectAssetsFile, NullLogger.Instance);

            bool crossTargeting = lockFile.PackageSpec.TargetFrameworks.Count > 1;

            foreach (TargetFrameworkInformation targetFramework in lockFile.PackageSpec.TargetFrameworks)
            {
                HashSet <LockFileLibrary> addedLibraries = new HashSet <LockFileLibrary>();

                ProjectItemGroupElement itemGroupElement = project.AddItemGroup();

                if (crossTargeting)
                {
                    itemGroupElement.Condition = $" '$(TargetFramework)' == '{targetFramework.FrameworkName.GetShortFolderName()}' ";
                }

                LockFileTarget target = lockFile.GetTarget(targetFramework.FrameworkName, runtimeIdentifier: null);

                bool addedImplicitReference = false;

                foreach (LibraryDependency libraryDependency in targetFramework.Dependencies.Where(i => !packagesToExclude.Contains(i.Name)))
                {
                    if (libraryDependency.AutoReferenced)
                    {
                        if (ExcludeImplicitReferences)
                        {
                            continue;
                        }
                        addedImplicitReference = true;
                    }

                    LockFileLibrary library = lockFile.GetLibrary(libraryDependency);

                    if (library.Type.Equals("project", StringComparison.OrdinalIgnoreCase))
                    {
                        // if a csproj name matches a package id then nuget swaps in the csproj output instead of the package.  Because of this we should skip adding the package as a locked package because it provides no value.
                        continue;
                    }

                    if (addedLibraries.Contains(library))
                    {
                        continue;
                    }

                    addedLibraries.Add(library);

                    LockFileTargetLibrary targetLibrary = target.GetTargetLibrary(libraryDependency.Name);

                    itemGroupElement.AddItem("PackageReference", targetLibrary.Name, GetPackageReferenceItemMetadata(library, libraryDependency));

                    foreach (LockFileLibrary dependency in targetLibrary.ResolveDependencies(lockFile, target).Where(i => !addedLibraries.Contains(i) && !packagesToExclude.Contains(i.Name)))
                    {
                        addedLibraries.Add(dependency);

                        itemGroupElement.AddItem("PackageReference", dependency.Name, GetPackageReferenceItemMetadata(dependency));
                    }
                }

                if (addedImplicitReference)
                {
                    ProjectPropertyElement disableImplicitFrameworkReferencesPropertyElement = project.AddProperty("DisableImplicitFrameworkReferences", "true");

                    if (crossTargeting)
                    {
                        disableImplicitFrameworkReferencesPropertyElement.Condition = $" '$(TargetFramework)' == '{targetFramework.FrameworkName.GetShortFolderName()}' ";
                    }
                }
            }

            ProjectImportElement beforeImportElement = project.CreateImportElement("Before.$(MSBuildThisFile)");

            project.InsertAfterChild(beforeImportElement, wasImportedPropertyElement.Parent);
            beforeImportElement.Condition = $"Exists('{beforeImportElement.Project}')";

            ProjectImportElement afterImportElement = project.AddImport("After.$(MSBuildThisFile)");

            afterImportElement.Condition = $"Exists('{afterImportElement.Project}')";

            return(true);
        }
        private void It_targets_the_right_framework(
            string testIdentifier,
            string targetFramework,
            string runtimeFrameworkVersion,
            bool selfContained,
            bool isExe,
            string expectedPackageVersion,
            string expectedRuntimeVersion,
            string extraMSBuildArguments = null)
        {
            string runtimeIdentifier = null;

            if (selfContained)
            {
                runtimeIdentifier = EnvironmentInfo.GetCompatibleRid(targetFramework);
            }

            var testProject = new TestProject()
            {
                Name                    = "FrameworkTargetTest",
                TargetFrameworks        = targetFramework,
                RuntimeFrameworkVersion = runtimeFrameworkVersion,
                IsSdkProject            = true,
                IsExe                   = isExe,
                RuntimeIdentifier       = runtimeIdentifier
            };

            var extraArgs = extraMSBuildArguments?.Split(' ') ?? Array.Empty <string>();

            var testAsset = _testAssetsManager.CreateTestProject(testProject, testIdentifier)
                            .Restore(Log, testProject.Name, extraArgs);

            NuGetConfigWriter.Write(testAsset.TestRoot, NuGetConfigWriter.DotnetCoreBlobFeed);

            var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name));

            buildCommand
            .Execute(extraArgs)
            .Should()
            .Pass();

            var outputDirectory = buildCommand.GetOutputDirectory(targetFramework, runtimeIdentifier: runtimeIdentifier);

            if (isExe)
            {
                //  Self-contained apps don't write a framework version to the runtimeconfig, so only check this for framework-dependent apps
                if (!selfContained)
                {
                    string  runtimeConfigFile     = Path.Combine(outputDirectory.FullName, testProject.Name + ".runtimeconfig.json");
                    string  runtimeConfigContents = File.ReadAllText(runtimeConfigFile);
                    JObject runtimeConfig         = JObject.Parse(runtimeConfigContents);

                    string actualRuntimeFrameworkVersion = ((JValue)runtimeConfig["runtimeOptions"]["framework"]["version"]).Value <string>();
                    actualRuntimeFrameworkVersion.Should().Be(expectedRuntimeVersion);
                }

                var runtimeconfigDevFileName = testProject.Name + ".runtimeconfig.dev.json";
                outputDirectory.Should()
                .HaveFile(runtimeconfigDevFileName);

                string  devruntimeConfigContents = File.ReadAllText(Path.Combine(outputDirectory.FullName, runtimeconfigDevFileName));
                JObject devruntimeConfig         = JObject.Parse(devruntimeConfigContents);

                var additionalProbingPaths = ((JArray)devruntimeConfig["runtimeOptions"]["additionalProbingPaths"]).Values <string>();
                // can't use Path.Combine on segments with an illegal `|` character
                var expectedPath = $"{Path.Combine(FileConstants.UserProfileFolder, ".dotnet", "store")}{Path.DirectorySeparatorChar}|arch|{Path.DirectorySeparatorChar}|tfm|";
                additionalProbingPaths.Should().Contain(expectedPath);
            }

            LockFile lockFile = LockFileUtilities.GetLockFile(Path.Combine(buildCommand.ProjectRootPath, "obj", "project.assets.json"), NullLogger.Instance);

            var target            = lockFile.GetTarget(NuGetFramework.Parse(targetFramework), null);
            var netCoreAppLibrary = target.Libraries.Single(l => l.Name == "Microsoft.NETCore.App");

            netCoreAppLibrary.Version.ToString().Should().Be(expectedPackageVersion);
        }