public async Task DotnetRestore_ProjectMovedDoesNotRunRestore()
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                var tfm           = "net472";
                var testDirectory = pathContext.SolutionRoot;
                var pkgX          = new SimpleTestPackageContext("x", "1.0.0");
                pkgX.Files.Clear();
                pkgX.AddFile($"lib/{tfm}/x.dll", tfm);

                await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, pkgX);

                var projectName      = "ClassLibrary1";
                var projectDirectory = Path.Combine(testDirectory, projectName);
                var movedDirectory   = Path.Combine(testDirectory, projectName + "-new");

                var projectFile1     = Path.Combine(projectDirectory, $"{projectName}.csproj");
                var movedProjectFile = Path.Combine(movedDirectory, $"{projectName}.csproj");

                _msbuildFixture.CreateDotnetNewProject(testDirectory, projectName, "classlib");

                using (var stream = File.Open(projectFile1, FileMode.Open, FileAccess.ReadWrite))
                {
                    var xml = XDocument.Load(stream);
                    ProjectFileUtils.SetTargetFrameworkForProject(xml, "TargetFrameworks", tfm);

                    var attributes = new Dictionary <string, string>()
                    {
                        { "Version", "1.0.0" }
                    };

                    ProjectFileUtils.AddItem(
                        xml,
                        "PackageReference",
                        "x",
                        tfm,
                        new Dictionary <string, string>(),
                        attributes);

                    ProjectFileUtils.WriteXmlToFile(xml, stream);
                }


                // Act
                var result = _msbuildFixture.RunDotnet(projectDirectory, $"build {projectFile1} {$"--source \"{pathContext.PackageSource}\""}", ignoreExitCode: true);


                // Assert
                Assert.True(result.ExitCode == 0, result.AllOutput);
                Assert.Contains("Restore completed", result.AllOutput);

                Directory.Move(projectDirectory, movedDirectory);

                result = _msbuildFixture.RunDotnet(movedDirectory, $"build {movedProjectFile} --no-restore", ignoreExitCode: true);

                // Assert
                Assert.True(result.ExitCode == 0, result.AllOutput);
                Assert.DoesNotContain("Restore completed", result.AllOutput);
            }
        }
Example #2
0
        public async Task DotnetToolTests_ToolRestoreWithFallback_SucceedsAsync()
        {
            using (var testDirectory = _msbuildFixture.CreateTestDirectory())
            {
                var actualTfm        = "netcoreapp2.0";
                var fallbackTfm      = "net46";
                var projectName      = "ToolRestoreProject";
                var workingDirectory = Path.Combine(testDirectory, projectName);
                var source           = Path.Combine(testDirectory, "packageSource");
                var rid            = "win-x64";
                var packageName    = string.Join("ToolPackage-", fallbackTfm, rid);
                var packageVersion = NuGetVersion.Parse("1.0.0");
                var packages       = new List <PackageIdentity>()
                {
                    new PackageIdentity(packageName, packageVersion)
                };

                var package = new SimpleTestPackageContext(packageName, packageVersion.OriginalVersion);
                package.Files.Clear();
                package.AddFile($"tools/{fallbackTfm}/{rid}/a.dll");
                package.AddFile($"tools/{fallbackTfm}/{rid}/Settings.json");

                package.PackageType = PackageType.DotnetTool;
                package.UseDefaultRuntimeAssemblies = false;
                package.PackageTypes.Add(PackageType.DotnetTool);
                await SimpleTestPackageUtility.CreatePackagesAsync(source, package);

                _msbuildFixture.CreateDotnetToolProject(solutionRoot: testDirectory.Path,
                                                        projectName: projectName, targetFramework: actualTfm, rid: rid,
                                                        source: source, packages: packages);

                using (var stream = File.Open(Path.Combine(workingDirectory, projectName + ".csproj"), FileMode.Open, FileAccess.ReadWrite))
                {
                    var xml = XDocument.Load(stream);
                    ProjectFileUtils.AddProperty(
                        xml,
                        "AssetTargetFallback",
                        fallbackTfm);

                    ProjectFileUtils.WriteXmlToFile(xml, stream);
                }

                // Act
                var result = _msbuildFixture.RestoreToolProject(workingDirectory, projectName, string.Empty);

                // Assert
                Assert.True(result.Item1 == 0, result.AllOutput);
                // Verify the assets file
                var lockFile = LockFileUtilities.GetLockFile(Path.Combine(testDirectory, projectName, "project.assets.json"), NullLogger.Instance);
                Assert.NotNull(lockFile);
                Assert.Equal(2, lockFile.Targets.Count);
                var ridTargets = lockFile.Targets.Where(e => e.RuntimeIdentifier != null ? e.RuntimeIdentifier.Equals(rid, StringComparison.CurrentCultureIgnoreCase) : false);
                Assert.Equal(1, ridTargets.Count());
                var toolsAssemblies = ridTargets.First().Libraries.First().ToolsAssemblies;
                Assert.Equal(2, toolsAssemblies.Count);
                Assert.True(toolsAssemblies.Contains($"tools/{fallbackTfm}/{rid}/a.dll"));
                Assert.True(toolsAssemblies.Contains($"tools/{fallbackTfm}/{rid}/Settings.json"));
            }
        }
Example #3
0
 private static void CreateXmlFile(string configFilePath, string nugetConfigString)
 {
     using (var stream = File.OpenWrite(configFilePath))
     {
         var nugetConfigXDoc = XDocument.Parse(nugetConfigString);
         ProjectFileUtils.WriteXmlToFile(nugetConfigXDoc, stream);
     }
 }
Example #4
0
        public GameObject GetForgelightObject(ForgelightGame forgelightGame, string model)
        {
            //By default, models are appended with a .dme extension.
            string modelName    = Path.GetFileNameWithoutExtension(model) + ".obj";
            string baseModelDir = ProjectFileUtils.GetProjectRelativePathFromFullPath(forgelightGame.GameInfo.FullResourceDirectory + Path.DirectorySeparatorChar + "Models");
            string modelPath    = baseModelDir + Path.DirectorySeparatorChar + modelName;

            return(AssetDatabase.LoadAssetAtPath <GameObject>(modelPath));
        }
        public async Task DotnetRestore_WithTargetFrameworksProperty_StaticGraphAndRegularRestore_AreEquivalent()
        {
            using (var pathContext = _msbuildFixture.CreateSimpleTestPathContext())
            {
                var testDirectory = pathContext.SolutionRoot;
                var pkgX          = new SimpleTestPackageContext("x", "1.0.0");
                await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, pkgX);

                var projectName1      = "ClassLibrary1";
                var workingDirectory1 = Path.Combine(testDirectory, projectName1);
                var projectFile1      = Path.Combine(workingDirectory1, $"{projectName1}.csproj");
                _msbuildFixture.CreateDotnetNewProject(testDirectory, projectName1, " classlib");

                using (var stream = File.Open(projectFile1, FileMode.Open, FileAccess.ReadWrite))
                {
                    var xml = XDocument.Load(stream);
                    ProjectFileUtils.SetTargetFrameworkForProject(xml, "TargetFrameworks", "net472");

                    ProjectFileUtils.AddItem(
                        xml,
                        "PackageReference",
                        "x",
                        framework: "net472",
                        new Dictionary <string, string>(),
                        new Dictionary <string, string>()
                    {
                        { "Version", "1.0.0" }
                    });

                    ProjectFileUtils.WriteXmlToFile(xml, stream);
                }

                // Preconditions
                var command = $"restore {projectFile1} {$"--source \"{pathContext.PackageSource}\" /p:AutomaticallyUseReferenceAssemblyPackages=false"}";
                var result  = _msbuildFixture.RunDotnet(pathContext.SolutionRoot, command, ignoreExitCode: true);

                result.ExitCode.Should().Be(0, because: result.AllOutput);
                var assetsFilePath = Path.Combine(workingDirectory1, "obj", "project.assets.json");
                File.Exists(assetsFilePath).Should().BeTrue(because: "The assets file needs to exist");
                var            assetsFile = new LockFileFormat().Read(assetsFilePath);
                LockFileTarget target     = assetsFile.Targets.Single(e => e.TargetFramework.Equals(NuGetFramework.Parse("net472")) && string.IsNullOrEmpty(e.RuntimeIdentifier));
                target.Libraries.Should().ContainSingle(e => e.Name.Equals("x"));

                // Act static graph restore
                result = _msbuildFixture.RunDotnet(pathContext.SolutionRoot, command + " /p:RestoreUseStaticGraphEvaluation=true", ignoreExitCode: true);

                // Ensure static graph restore no-ops
                result.ExitCode.Should().Be(0, because: result.AllOutput);
                result.AllOutput.Should().Contain("All projects are up-to-date for restore.");
            }
        }
Example #6
0
        /// <summary>
        /// Appelé après la création d'un nouveau fichier.
        /// </summary>
        /// <param name="fileName">Nom du fichier.</param>
        protected override void FinishFile(string fileName)
        {
            if (string.IsNullOrEmpty(_sqlprojFileName))
            {
                return;
            }

            /* Chemin relatif au csproj */
            string localFileName = ProjectFileUtils.GetProjectRelativeFileName(fileName, _sqlprojFileName);

            /* Met à jour le fichier csproj. */
            new ProjectUpdater()
            .AddItem(_sqlprojFileName, new ProjectItem {
                ItemPath = localFileName, BuildAction = _buildAction
            });
        }
Example #7
0
        public void DotnetRestore_WithAuthorSignedPackage_Succeeds()
        {
            using (var packageSourceDirectory = TestDirectory.Create())
                using (var testDirectory = TestDirectory.Create())
                {
                    var packageFile = new FileInfo(Path.Combine(packageSourceDirectory.Path, "TestPackage.AuthorSigned.1.0.0.nupkg"));
                    var package     = GetResource(packageFile.Name);

                    File.WriteAllBytes(packageFile.FullName, package);

                    var projectName      = "ClassLibrary1";
                    var workingDirectory = Path.Combine(testDirectory, projectName);
                    var projectFile      = Path.Combine(workingDirectory, $"{projectName}.csproj");

                    _msbuildFixture.CreateDotnetNewProject(testDirectory.Path, projectName, " classlib");

                    using (var stream = File.Open(projectFile, FileMode.Open, FileAccess.ReadWrite))
                    {
                        var xml = XDocument.Load(stream);

                        ProjectFileUtils.SetTargetFrameworkForProject(xml, "TargetFrameworks", "netstandard1.3");

                        var attributes = new Dictionary <string, string>()
                        {
                            { "Version", "1.0.0" }
                        };

                        ProjectFileUtils.AddItem(
                            xml,
                            "PackageReference",
                            "TestPackage.AuthorSigned",
                            "netstandard1.3",
                            new Dictionary <string, string>(),
                            attributes);

                        ProjectFileUtils.WriteXmlToFile(xml, stream);
                    }

                    var args = $"--source \"{packageSourceDirectory.Path}\" ";

                    _msbuildFixture.RestoreProject(workingDirectory, projectName, args);
                }
        }
Example #8
0
        /// <summary>
        /// Appelé après la création d'un nouveau fichier.
        /// </summary>
        /// <param name="fileName">Nom du fichier.</param>
        protected override void FinishFile(string fileName)
        {
            /* Ajoute le fichier dans TFS */
            base.FinishFile(fileName);

            if (string.IsNullOrEmpty(_csprojFileName) || GeneratorParameters.IsNewCsproj)
            {
                return;
            }

            /* Chemin relatif au csproj */
            string localFileName = ProjectFileUtils.GetProjectRelativeFileName(fileName, _csprojFileName);

            /* Met à jour le fichier csproj. */
            new ProjectUpdater()
            .AddItem(_csprojFileName, new ProjectItem {
                ItemPath = localFileName, BuildAction = BuildActions.Compile
            });
        }
Example #9
0
        /// <summary>
        /// Appelé après la création d'un nouveau fichier.
        /// </summary>
        /// <param name="fileName">Nom du fichier.</param>
        protected override void FinishFile(string fileName)
        {
            /* Ajoute le fichier dans TFS */
            base.FinishFile(fileName);

            if (string.IsNullOrEmpty(_sqlprojFileName))
            {
                return;
            }

            /* Chemin relatif au csproj */
            string localFileName = ProjectFileUtils.GetProjectRelativeFileName(fileName, _sqlprojFileName);

            /* Met à jour le fichier csproj. */
            ProjectUpdater
            .Create(TfsManager.Client)
            .AddItem(_sqlprojFileName, new ProjectItem {
                ItemPath = localFileName, BuildAction = _buildAction
            });
        }
Example #10
0
        public void RestoreCommand_DisplaysCPVMInPreviewMessageIfCPVMEnabled()
        {
            using (var testDirectory = _msbuildFixture.CreateTestDirectory())
            {
                // Arrange
                var projectName      = "ClassLibrary1";
                var workingDirectory = Path.Combine(testDirectory, projectName);
                var projectFile      = Path.Combine(workingDirectory, $"{projectName}.csproj");

                _msbuildFixture.CreateDotnetNewProject(testDirectory.Path, projectName, " classlib", 60000);

                using (var stream = new FileStream(projectFile, FileMode.Open, FileAccess.ReadWrite))
                {
                    var xml = XDocument.Load(stream);
                    ProjectFileUtils.AddProperty(
                        xml,
                        "ManagePackageVersionsCentrally",
                        "true");

                    ProjectFileUtils.WriteXmlToFile(xml, stream);
                }

                // The test depends on the presence of these packages and their versions.
                // Change to Directory.Packages.props when new cli that supports NuGet.props will be downloaded
                var directoryPackagesPropsName    = Path.Combine(workingDirectory, $"Directory.Build.props");
                var directoryPackagesPropsContent = @"<Project>                    
                        <PropertyGroup>
                            <CentralPackageVersionsFileImported>true</CentralPackageVersionsFileImported>
                        </PropertyGroup>
                    </Project>";
                File.WriteAllText(directoryPackagesPropsName, directoryPackagesPropsContent);

                // Act
                var result = _msbuildFixture.RunDotnet(workingDirectory, "restore /v:n");

                // Assert
                Assert.True(result.Output.Contains($"The project {projectFile} is using CentralPackageVersionManagement, a NuGet preview feature."));
            }
        }
Example #11
0
        public void DotnetRestore_WithAuthorSignedPackage_Succeeds()
        {
            using (var pathContext = _msbuildFixture.CreateSimpleTestPathContext())
            {
                var packageFile = new FileInfo(Path.Combine(pathContext.PackageSource, "TestPackage.AuthorSigned.1.0.0.nupkg"));
                var package     = GetResource(packageFile.Name);

                File.WriteAllBytes(packageFile.FullName, package);

                var projectName      = "ClassLibrary1";
                var workingDirectory = Path.Combine(pathContext.SolutionRoot, projectName);
                var projectFile      = Path.Combine(workingDirectory, $"{projectName}.csproj");

                _msbuildFixture.CreateDotnetNewProject(pathContext.SolutionRoot, projectName, "classlib -f netstandard2.0");

                using (var stream = File.Open(projectFile, FileMode.Open, FileAccess.ReadWrite))
                {
                    var xml = XDocument.Load(stream);

                    var attributes = new Dictionary <string, string>()
                    {
                        { "Version", "1.0.0" }
                    };

                    ProjectFileUtils.AddItem(
                        xml,
                        "PackageReference",
                        "TestPackage.AuthorSigned",
                        string.Empty,
                        new Dictionary <string, string>(),
                        attributes);

                    ProjectFileUtils.WriteXmlToFile(xml, stream);
                }

                _msbuildFixture.RestoreProject(workingDirectory, projectName, args: string.Empty);
            }
        }
Example #12
0
        public async Task DotnetRestore_OneLinePerRestore()
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                var testDirectory = pathContext.SolutionRoot;
                var pkgX          = new SimpleTestPackageContext("x", "1.0.0");
                await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, pkgX);

                var projectName1      = "ClassLibrary1";
                var workingDirectory1 = Path.Combine(testDirectory, projectName1);
                var projectFile1      = Path.Combine(workingDirectory1, $"{projectName1}.csproj");
                _msbuildFixture.CreateDotnetNewProject(testDirectory, projectName1, " classlib");

                using (var stream = File.Open(projectFile1, FileMode.Open, FileAccess.ReadWrite))
                {
                    var xml = XDocument.Load(stream);
                    ProjectFileUtils.SetTargetFrameworkForProject(xml, "TargetFrameworks", "net45");

                    var attributes = new Dictionary <string, string>()
                    {
                        { "Version", "1.0.0" }
                    };

                    ProjectFileUtils.AddItem(
                        xml,
                        "PackageReference",
                        "x",
                        "netstandard1.3",
                        new Dictionary <string, string>(),
                        attributes);

                    ProjectFileUtils.WriteXmlToFile(xml, stream);
                }

                var slnContents = @"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27330.1
MinimumVisualStudioVersion = 10.0.40219.1
Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""ClassLibrary1"", ""ClassLibrary1\ClassLibrary1.csproj"", ""{216FF388-8C16-4AF4-87A8-9094030692FA}""
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{216FF388-8C16-4AF4-87A8-9094030692FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{216FF388-8C16-4AF4-87A8-9094030692FA}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{216FF388-8C16-4AF4-87A8-9094030692FA}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{216FF388-8C16-4AF4-87A8-9094030692FA}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
	GlobalSection(ExtensibilityGlobals) = postSolution
		SolutionGuid = {9A6704E2-6E77-4FF4-9E54-B789D88829DD}
	EndGlobalSection
EndGlobal";

                var slnPath = Path.Combine(pathContext.SolutionRoot, "proj.sln");
                File.WriteAllText(slnPath, slnContents);

                // Act
                var result = _msbuildFixture.RunDotnet(pathContext.SolutionRoot, $"restore proj.sln {$"--source \"{pathContext.PackageSource}\""}", ignoreExitCode: true);

                // Assert
                Assert.True(result.ExitCode == 0);
                Assert.True(1 == result.AllOutput.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).Length, result.AllOutput);

                // Act - make sure no-op does the same thing.
                result = _msbuildFixture.RunDotnet(pathContext.SolutionRoot, $"restore proj.sln {$"--source \"{pathContext.PackageSource}\""}", ignoreExitCode: true);

                // Assert
                Assert.True(result.ExitCode == 0);
                Assert.True(1 == result.AllOutput.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).Length, result.AllOutput);
            }
        }
Example #13
0
        public void DotnetRestore_WithAuthorSignedPackageAndSignatureValidationModeAsRequired_Succeeds()
        {
            using (var pathContext = _msbuildFixture.CreateSimpleTestPathContext())
            {
                var packageFile = new FileInfo(Path.Combine(pathContext.PackageSource, "TestPackage.AuthorSigned.1.0.0.nupkg"));
                var package     = GetResource(packageFile.Name);

                File.WriteAllBytes(packageFile.FullName, package);

                var projectName      = "ClassLibrary1";
                var workingDirectory = Path.Combine(pathContext.SolutionRoot, projectName);
                var projectFile      = Path.Combine(workingDirectory, $"{projectName}.csproj");

                _msbuildFixture.CreateDotnetNewProject(pathContext.SolutionRoot, projectName, "classlib -f netstandard2.0");

                using (var stream = File.Open(projectFile, FileMode.Open, FileAccess.ReadWrite))
                {
                    var xml = XDocument.Load(stream);

                    var attributes = new Dictionary <string, string>()
                    {
                        { "Version", "1.0.0" }
                    };

                    ProjectFileUtils.AddItem(
                        xml,
                        "PackageReference",
                        "TestPackage.AuthorSigned",
                        string.Empty,
                        new Dictionary <string, string>(),
                        attributes);

                    ProjectFileUtils.WriteXmlToFile(xml, stream);
                }

                var projectDir = Path.GetDirectoryName(workingDirectory);
                //Directory.CreateDirectory(projectDir);
                var configPath = Path.Combine(projectDir, "NuGet.Config");

                //set nuget.config properties
                var doc           = new XDocument();
                var configuration = new XElement(XName.Get("configuration"));
                doc.Add(configuration);

                var config = new XElement(XName.Get("config"));
                configuration.Add(config);

                var trustedSigners = new XElement(XName.Get("trustedSigners"));
                configuration.Add(trustedSigners);

                var signatureValidationMode = new XElement(XName.Get("add"));
                signatureValidationMode.Add(new XAttribute(XName.Get("key"), "signatureValidationMode"));
                signatureValidationMode.Add(new XAttribute(XName.Get("value"), "require"));
                config.Add(signatureValidationMode);

                //add trusted signers
                var author = new XElement(XName.Get("author"));
                author.Add(new XAttribute(XName.Get("name"), "microsoft"));
                trustedSigners.Add(author);

                var certificate = new XElement(XName.Get("certificate"));
                certificate.Add(new XAttribute(XName.Get("fingerprint"), "3F9001EA83C560D712C24CF213C3D312CB3BFF51EE89435D3430BD06B5D0EECE"));
                certificate.Add(new XAttribute(XName.Get("hashAlgorithm"), "SHA256"));
                certificate.Add(new XAttribute(XName.Get("allowUntrustedRoot"), "false"));
                author.Add(certificate);

                var repository = new XElement(XName.Get("repository"));
                repository.Add(new XAttribute(XName.Get("name"), "nuget.org"));
                repository.Add(new XAttribute(XName.Get("serviceIndex"), "https://api.nuget.org/v3/index.json"));
                trustedSigners.Add(repository);

                var rcertificate = new XElement(XName.Get("certificate"));
                rcertificate.Add(new XAttribute(XName.Get("fingerprint"), "0E5F38F57DC1BCC806D8494F4F90FBCEDD988B46760709CBEEC6F4219AA6157D"));
                rcertificate.Add(new XAttribute(XName.Get("hashAlgorithm"), "SHA256"));
                rcertificate.Add(new XAttribute(XName.Get("allowUntrustedRoot"), "false"));
                repository.Add(rcertificate);

                var owners = new XElement(XName.Get("owners"));
                owners.Add("dotnetframework;microsoft");
                repository.Add(owners);

                File.WriteAllText(configPath, doc.ToString());

                _msbuildFixture.RestoreProject(workingDirectory, projectName, args: string.Empty);
            }
        }
Example #14
0
        public async Task DotnetRestore_WithUnSignedPackageAndSignatureValidationModeAsRequired_Fails()
        {
            using (var pathContext = _msbuildFixture.CreateSimpleTestPathContext())
            {
                //Setup packages and feed
                var packageX = new SimpleTestPackageContext()
                {
                    Id      = "x",
                    Version = "1.0.0"
                };
                packageX.Files.Clear();
                packageX.AddFile("lib/netcoreapp2.0/x.dll");
                packageX.AddFile("ref/netcoreapp2.0/x.dll");
                packageX.AddFile("lib/net472/x.dll");
                packageX.AddFile("ref/net472/x.dll");

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    pathContext.PackageSource,
                    PackageSaveMode.Defaultv3,
                    packageX);

                // Set up solution, and project
                var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);

                var projectName      = "ClassLibrary1";
                var workingDirectory = Path.Combine(pathContext.SolutionRoot, projectName);
                var projectFile      = Path.Combine(workingDirectory, $"{projectName}.csproj");

                _msbuildFixture.CreateDotnetNewProject(pathContext.SolutionRoot, projectName, "classlib");

                using (var stream = File.Open(projectFile, FileMode.Open, FileAccess.ReadWrite))
                {
                    var xml = XDocument.Load(stream);

                    var attributes = new Dictionary <string, string>()
                    {
                        { "Version", "1.0.0" }
                    };

                    ProjectFileUtils.AddItem(
                        xml,
                        "PackageReference",
                        packageX.Id,
                        string.Empty,
                        new Dictionary <string, string>(),
                        attributes);

                    ProjectFileUtils.WriteXmlToFile(xml, stream);
                }

                //set nuget.config properties
                var doc           = new XDocument();
                var configuration = new XElement(XName.Get("configuration"));
                doc.Add(configuration);

                var config = new XElement(XName.Get("config"));
                configuration.Add(config);

                var signatureValidationMode = new XElement(XName.Get("add"));
                signatureValidationMode.Add(new XAttribute(XName.Get("key"), "signatureValidationMode"));
                signatureValidationMode.Add(new XAttribute(XName.Get("value"), "require"));
                config.Add(signatureValidationMode);

                File.WriteAllText(Path.Combine(workingDirectory, "NuGet.Config"), doc.ToString());

                // Act
                var result = _msbuildFixture.RunDotnet(workingDirectory, "restore", ignoreExitCode: true);

                result.AllOutput.Should().Contain($"error NU3004: Package '{packageX.Id} {packageX.Version}' from source '{pathContext.PackageSource}': signatureValidationMode is set to require, so packages are allowed only if signed by trusted signers; however, this package is unsigned.");
                result.Success.Should().BeFalse();
                result.ExitCode.Should().Be(1, because: "error text should be displayed as restore failed");
            }
        }
        public async Task DotnetRestore_MultiTargettingWithAliases_Succeeds()
        {
            using (var pathContext = _msbuildFixture.CreateSimpleTestPathContext())
            {
                var testDirectory = pathContext.SolutionRoot;
                var pkgX          = new SimpleTestPackageContext("x", "1.0.0");
                await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, pkgX);

                var latestNetFrameworkAlias    = "latestnetframework";
                var notLatestNetFrameworkAlias = "notlatestnetframework";
                var projectName1      = "ClassLibrary1";
                var workingDirectory1 = Path.Combine(testDirectory, projectName1);
                var projectFile1      = Path.Combine(workingDirectory1, $"{projectName1}.csproj");
                _msbuildFixture.CreateDotnetNewProject(testDirectory, projectName1, " classlib");

                using (var stream = File.Open(projectFile1, FileMode.Open, FileAccess.ReadWrite))
                {
                    var xml = XDocument.Load(stream);
                    ProjectFileUtils.SetTargetFrameworkForProject(xml, "TargetFrameworks", $"{latestNetFrameworkAlias};{notLatestNetFrameworkAlias}");

                    var attributes = new Dictionary <string, string>()
                    {
                        { "Version", "1.0.0" }
                    };

                    ProjectFileUtils.AddItem(
                        xml,
                        "PackageReference",
                        "x",
                        notLatestNetFrameworkAlias,
                        new Dictionary <string, string>(),
                        attributes);

                    var latestNetFrameworkProps = new Dictionary <string, string>();
                    latestNetFrameworkProps.Add("TargetFrameworkIdentifier", ".NETFramework");
                    latestNetFrameworkProps.Add("TargetFrameworkVersion", "v4.7.2");

                    ProjectFileUtils.AddProperties(xml, latestNetFrameworkProps, $" '$(TargetFramework)' == '{latestNetFrameworkAlias}' ");

                    var notLatestNetFrameworkProps = new Dictionary <string, string>();
                    notLatestNetFrameworkProps.Add("TargetFrameworkIdentifier", ".NETFramework");
                    notLatestNetFrameworkProps.Add("TargetFrameworkVersion", "v4.6.3");
                    ProjectFileUtils.AddProperties(xml, notLatestNetFrameworkProps, $" '$(TargetFramework)' == '{notLatestNetFrameworkAlias}' ");

                    ProjectFileUtils.WriteXmlToFile(xml, stream);
                }

                // Act
                var result = _msbuildFixture.RunDotnet(pathContext.SolutionRoot, $"restore {projectFile1} {$"--source \"{pathContext.PackageSource}\" /p:AutomaticallyUseReferenceAssemblyPackages=false"}", ignoreExitCode: true);

                // Assert
                result.ExitCode.Should().Be(0, because: result.AllOutput);
                var assetsFilePath = Path.Combine(workingDirectory1, "obj", "project.assets.json");
                File.Exists(assetsFilePath).Should().BeTrue(because: "The assets file needs to exist");
                var            assetsFile      = new LockFileFormat().Read(assetsFilePath);
                LockFileTarget nonLatestTarget = assetsFile.Targets.Single(e => e.TargetFramework.Equals(CommonFrameworks.Net463) && string.IsNullOrEmpty(e.RuntimeIdentifier));
                nonLatestTarget.Libraries.Should().ContainSingle(e => e.Name.Equals("x"));
                LockFileTarget latestTarget = assetsFile.Targets.Single(e => e.TargetFramework.Equals(NuGetFramework.Parse("net472")) && string.IsNullOrEmpty(e.RuntimeIdentifier));
                latestTarget.Libraries.Should().NotContain(e => e.Name.Equals("x"));
            }
        }