Ejemplo n.º 1
0
        public void SaveToNonexistentDirectoryRelativePath()
        {
            ProjectRootElement project   = ProjectRootElement.Create();
            string             directory = null;

            try
            {
                Environment.CurrentDirectory = Path.GetTempPath(); // should be used for project.DirectoryPath; it must exist

                string file = @"bar\foo.proj";
                string path = Path.Combine(Path.GetTempPath(), file);
                directory = Path.Combine(Path.GetTempPath(), "bar");

                project.Save(file); // relative path: file and a single directory only; should create the "bar" part

                Assert.True(File.Exists(file));
                Assert.Equal(path, project.FullPath);
                Assert.Equal(directory, project.DirectoryPath);
            }
            finally
            {
                Directory.Delete(directory, true);
            }
        }
        public async Task ProjectLoadedAsync_AddsNewProjectWithDocument()
        {
            // Arrange
            var projectRootElement     = ProjectRootElement.Create("/project/project.csproj");
            var intermediateOutputPath = "/project/obj";

            projectRootElement.AddProperty(MSBuildProjectManager.IntermediateOutputPathPropertyName, intermediateOutputPath);
            var projectInstance       = new ProjectInstance(projectRootElement);
            var hostDocument          = new OmniSharpHostDocument("file.razor", "file.razor", FileKinds.Component);
            var projectConfiguration  = new ProjectConfiguration(CustomConfiguration, new[] { hostDocument }, "TestRootNamespace");
            var configurationProvider = new Mock <ProjectConfigurationProvider>(MockBehavior.Strict);

            configurationProvider.Setup(provider => provider.TryResolveConfiguration(It.IsAny <ProjectConfigurationProviderContext>(), out projectConfiguration))
            .Returns(true);
            var projectChangePublisher = new Mock <ProjectChangePublisher>(MockBehavior.Strict);

            projectChangePublisher.Setup(p => p.SetPublishFilePath(It.IsAny <string>(), It.IsAny <string>())).Verifiable();
            var msbuildProjectManager = new MSBuildProjectManager(
                new[] { configurationProvider.Object },
                CreateProjectInstanceEvaluator(),
                projectChangePublisher.Object,
                Dispatcher,
                LoggerFactory);
            var projectManager = CreateProjectSnapshotManager();

            msbuildProjectManager.Initialize(projectManager);
            var args = new ProjectLoadedEventArgs(
                id: null,
                project: null,
                sessionId: Guid.NewGuid(),
                projectInstance,
                diagnostics: Enumerable.Empty <MSBuildDiagnostic>().ToImmutableArray(),
                isReload: false,
                projectIdIsDefinedInSolution: false,
                sourceFiles: Enumerable.Empty <string>().ToImmutableArray(),
                sdkVersion: default);
Ejemplo n.º 3
0
        /// <summary>
        /// Creates a temporary MSBuild content project in memory.
        /// </summary>
        void CreateBuildProject()
        {
            string projectPath = Path.Combine(buildDirectory, "content.contentproj");
            //string outputPath = Path.Combine(buildDirectory, "bin");
            string CurrentDirectory = Directory.GetCurrentDirectory();
            string outputPath       = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;

            // Create the build project.
            projectRootElement = ProjectRootElement.Create(outputPath + "\\Content");

            // Include the standard targets file that defines how to build XNA Framework content.

            /*projectRootElement.AddImport("$(MSBuildExtensionsPath)\\Microsoft\\XNA Game Studio\\" +
             *                           "v4.0\\Microsoft.Xna.GameStudio.ContentPipeline.targets");*/
            projectRootElement.AddImport(CurrentDirectory + "\\Microsoft.Xna.GameStudio.ContentPipeline.targets");

            buildProject = new Project(projectRootElement);

            buildProject.SetProperty("XnaPlatform", "Windows");
            buildProject.SetProperty("XnaProfile", "Reach");
            buildProject.SetProperty("XnaFrameworkVersion", "v4.0");
            buildProject.SetProperty("Configuration", "Release");
            buildProject.SetProperty("OutputPath", outputPath);

            // Register any custom importers or processors.
            foreach (string pipelineAssembly in pipelineAssemblies)
            {
                buildProject.AddItem("Reference", pipelineAssembly);
            }

            // Hook up our custom error logger.
            errorLogger = new ErrorLogger();

            buildParameters         = new BuildParameters(ProjectCollection.GlobalProjectCollection);
            buildParameters.Loggers = new ILogger[] { errorLogger };
        }
        public void SkipOtherProjectTypes()
        {
            string             projectFile        = Path.Combine(_rootDir, @"src\project.csproj");
            ProjectRootElement projectRootElement = ProjectRootElement.Create(projectFile);

            projectRootElement.AddProperty(GetCopyToPublishDirectoryItemsGraphPredictor.PublishDirPropertyName, @"bin\Publish");

            ProjectRootElement service1 = CreateServiceProject("service1");
            ProjectRootElement service2 = CreateServiceProject("service2");
            ProjectRootElement service3 = CreateServiceProject("service3");

            projectRootElement.AddItem("ProjectReference", @"..\service1\service1.csproj");
            projectRootElement.AddItem("ProjectReference", @"..\service2\service2.csproj");
            projectRootElement.AddItem("ProjectReference", @"..\service3\service3.csproj");

            projectRootElement.Save();
            service1.Save();
            service2.Save();
            service3.Save();

            new ServiceFabricPackageRootFilesGraphPredictor()
            .GetProjectPredictions(projectFile)
            .AssertNoPredictions();
        }
        public void ReadBasic()
        {
            string content = @"
                    <Project>
                        <ItemDefinitionGroup Condition='c'>
                            <i1/>
                        </ItemDefinitionGroup>
                        <ItemDefinitionGroup>
                            <i2/>
                            <i3/>
                        </ItemDefinitionGroup>
                    </Project>
                ";

            ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));

            var itemDefinitionGroups = Helpers.MakeList(project.ItemDefinitionGroups);

            Assert.Equal(2, itemDefinitionGroups.Count);

            Assert.Equal(1, Helpers.Count(itemDefinitionGroups[0].ItemDefinitions));
            Assert.Equal(2, Helpers.Count(itemDefinitionGroups[1].ItemDefinitions));
            Assert.Equal("c", itemDefinitionGroups[0].Condition);
        }
Ejemplo n.º 6
0
        public void MigratingProjectWithFullFrameworkTFMsOnlyAddsARuntimeIdentifierWin7x86WhenNoRuntimesExistAlready()
        {
            var testDirectory = Temp.CreateDirectory().Path;
            var testPJ        = new ProjectJsonBuilder(TestAssets)
                                .FromTestAssetBase("TestAppWithMultipleFullFrameworksOnly")
                                .SaveToDisk(testDirectory);

            var projectContexts = ProjectContext.CreateContextForEachFramework(testDirectory);
            var mockProj        = ProjectRootElement.Create();

            var migrationSettings =
                MigrationSettings.CreateMigrationSettingsTestHook(testDirectory, testDirectory, mockProj);
            var migrationInputs = new MigrationRuleInputs(
                projectContexts,
                mockProj,
                mockProj.AddItemGroup(),
                mockProj.AddPropertyGroup());

            new MigrateTFMRule().Apply(migrationSettings, migrationInputs);

            mockProj.Properties.Count(p => p.Name == "RuntimeIdentifiers").Should().Be(0);
            mockProj.Properties.Where(p => p.Name == "RuntimeIdentifier").Should().HaveCount(1);
            mockProj.Properties.Single(p => p.Name == "RuntimeIdentifier").Value.Should().Be("win7-x86");
        }
        public void Project_dependencies_are_migrated_to_ProjectReference()
        {
            var solutionDirectory =
                TestAssetsManager.CreateTestInstance("TestAppWithLibrary", callingMethod: "p").Path;

            var appDirectory = Path.Combine(solutionDirectory, "TestApp");

            var projectContext = ProjectContext.Create(appDirectory, FrameworkConstants.CommonFrameworks.NetCoreApp10);
            var mockProj       = ProjectRootElement.Create();
            var testSettings   = new MigrationSettings(appDirectory, appDirectory, "1.0.0", mockProj, null);
            var testInputs     = new MigrationRuleInputs(new[] { projectContext }, mockProj, mockProj.AddItemGroup(),
                                                         mockProj.AddPropertyGroup());

            new MigrateProjectDependenciesRule().Apply(testSettings, testInputs);

            var projectReferences = mockProj.Items.Where(item => item.ItemType.Equals("ProjectReference", StringComparison.Ordinal));

            projectReferences.Count().Should().Be(1);

            var projectReference = projectReferences.First();

            projectReference.Include.Should().Be(Path.Combine("..", "TestLibrary", "TestLibrary.csproj"));
            projectReference.Parent.Condition.Should().BeEmpty();
        }
Ejemplo n.º 8
0
        public void UpdateMetadataImported()
        {
            string file = null;

            try
            {
                file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                ProjectRootElement import = ProjectRootElement.Create(file);
                import.AddItemDefinitionGroup().AddItemDefinition("i").AddMetadata("m", "m0");
                import.Save();

                ProjectRootElement main    = ProjectRootElement.Create();
                Project            project = new Project(main);
                main.AddImport(file);
                project.ReevaluateIfNecessary();

                ProjectItemDefinition definition = project.ItemDefinitions["i"];
                definition.SetMetadataValue("m", "m1");
            }
            finally
            {
                File.Delete(file);
            }
        }
Ejemplo n.º 9
0
        public void AddMetadataExistingItemDefinitionGroup()
        {
            ProjectRootElement xml = ProjectRootElement.Create();

            xml.AddItemDefinitionGroup().AddItemDefinition("i").AddMetadata("m", "m0");

            Project project = new Project(xml);

            project.ItemDefinitions["i"].SetMetadataValue("n", "n0");

            string expected = ObjectModelHelpers.CleanupFileContents(
                @"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
  <ItemDefinitionGroup>
    <i>
      <m>m0</m>
    </i>
    <i>
      <n>n0</n>
    </i>
  </ItemDefinitionGroup>
</Project>");

            Helpers.VerifyAssertProjectContent(expected, project.Xml);
        }
Ejemplo n.º 10
0
        public void MultipleCodeElements()
        {
            string project_xml = @"<Project ToolsVersion='4.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
  <UsingTask
    TaskName='DoNothing'
    TaskFactory='CodeTaskFactory'
    AssemblyFile='$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll' >
    <ParameterGroup />
    <Task>
      <Code Type='Fragment' Language='cs'></Code>
      <Code Type='Fragment' Language='cs'></Code>
    </Task>
  </UsingTask>
  <Target Name='default'>
    <DoNothing />
  </Target>
</Project>";
            var    root        = ProjectRootElement.Create(XmlReader.Create(new StringReader(project_xml)));

            root.FullPath = "CodeTaskFactoryTest.MultipleCodeElements.proj";
            var project = new Project(root);

            Assert.IsFalse(project.Build(), "Build");
        }
        public void FindItems()
        {
            ProjectRootElement projectRootElement = ProjectRootElement.Create();

            projectRootElement.AddItem(RefAssemblyPredictor.IntermediateRefAssemblyItemName, @"obj\ref\Foo.dll");
            projectRootElement.AddProperty(RefAssemblyPredictor.TargetRefPathPropertyName, @"bin\ref\Foo.dll");

            ProjectInstance projectInstance = TestHelpers.CreateProjectInstanceFromRootElement(projectRootElement);

            var expectedOutputFiles = new[]
            {
                new PredictedItem(@"obj\ref\Foo.dll", nameof(RefAssemblyPredictor)),
                new PredictedItem(@"bin\ref\Foo.dll", nameof(RefAssemblyPredictor)),
            };

            new RefAssemblyPredictor()
            .GetProjectPredictions(projectInstance)
            .AssertPredictions(
                projectInstance,
                null,
                null,
                expectedOutputFiles,
                null);
        }
Ejemplo n.º 12
0
    private ProjectRootElement CreateProjectRootElement(string projectDirectory, string projectName)
    {
        var pre = ProjectRootElement.Create(this.projectCollection);

        pre.FullPath = Path.Combine(projectDirectory, projectName);

        pre.AddProperty("RootNamespace", "TestNamespace");
        pre.AddProperty("AssemblyName", "TestAssembly");
        pre.AddProperty("AssemblyTitle", "TestAssembly");
        pre.AddProperty("AssemblyProduct", "TestProduct");
        pre.AddProperty("AssemblyCompany", "TestCompany");
        pre.AddProperty("AssemblyCopyright", "TestCopyright");
        pre.AddProperty("AssemblyConfiguration", "TestConfiguration");
        pre.AddProperty("TargetFrameworkVersion", "v4.5");
        pre.AddProperty("OutputType", "Library");
        pre.AddProperty("OutputPath", @"bin\");

        pre.AddItem("Reference", "System");

        pre.AddImport(@"$(MSBuildToolsPath)\Microsoft.CSharp.targets");
        pre.AddImport(Path.Combine(this.RepoPath, GitVersioningTargetsFileName));

        return(pre);
    }
        private ProjectRootElement MigrateProject(
            string solution,
            string project,
            NuGetFramework targetFramework)
        {
            var solutionDirectory =
                TestAssetsManager.CreateTestInstance(solution, callingMethod: "p").Path;

            var appDirectory = Path.Combine(solutionDirectory, project);

            var projectContext = ProjectContext.Create(appDirectory, targetFramework);
            var mockProj       = ProjectRootElement.Create();
            var testSettings   = new MigrationSettings(appDirectory, appDirectory, "1.0.0", mockProj, null);
            var testInputs     = new MigrationRuleInputs(new[] { projectContext }, mockProj, mockProj.AddItemGroup(),
                                                         mockProj.AddPropertyGroup());

            new MigrateProjectDependenciesRule().Apply(testSettings, testInputs);

            var s = mockProj.Items.Select(p => $"ItemType = {p.ItemType}, Include = {p.Include}");

            Console.WriteLine(string.Join(Environment.NewLine, s));

            return(mockProj);
        }
Ejemplo n.º 14
0
        public void SaveUnmodifiedWithNewEncoding()
        {
            ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"
<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
</Project>"))));

            project.FullPath = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
            string projectFullPath = project.FullPath;

            try
            {
                project.Save();
                project = null;

                // We haven't made any changes to the project, but we want to save it using various encodings.
                SaveProjectWithEncoding(projectFullPath, Encoding.Unicode);
                SaveProjectWithEncoding(projectFullPath, Encoding.ASCII);
                SaveProjectWithEncoding(projectFullPath, Encoding.UTF8);
            }
            finally
            {
                File.Delete(projectFullPath);
            }
        }
        public void It_migrates_csproj_ProjectReference_in_xproj_including_condition_on_ProjectReference_parent_and_item()
        {
            var projectReference    = "some/to.csproj";
            var xproj               = ProjectRootElement.Create();
            var csprojReferenceItem = xproj.AddItem("ProjectReference", projectReference);

            csprojReferenceItem.Parent.Condition = " '$(Foo)' == 'bar' ";
            csprojReferenceItem.Condition        = " '$(Bar)' == 'foo' ";

            var projectReferenceName = Path.GetFileNameWithoutExtension(projectReference);

            var projectJson = @"
                {
                    ""dependencies"": {" +
                              $"\"{projectReferenceName}\"" + @": {
                            ""target"" : ""project""
                        }
                    }
                }
            ";

            var testDirectory = Temp.CreateDirectory().Path;
            var migratedProj  = TemporaryProjectFileRuleRunner.RunRules(new IMigrationRule[]
            {
                new MigrateProjectDependenciesRule()
            }, projectJson, testDirectory, xproj);

            var migratedProjectReferenceItems = migratedProj.Items.Where(i => i.ItemType == "ProjectReference");

            migratedProjectReferenceItems.Should().HaveCount(1);

            var migratedProjectReferenceItem = migratedProjectReferenceItems.First();

            migratedProjectReferenceItem.Include.Should().Be(projectReference);
            migratedProjectReferenceItem.Condition.Should().Be(" '$(Bar)' == 'foo'  and  '$(Foo)' == 'bar' ");
        }
Ejemplo n.º 16
0
        public void UpdateMetadataValueAsAttributeWithSpecialCharacters(string projectContents, string updatedProject)
        {
            ProjectRootElement projectElement = ProjectRootElement.Create(XmlReader.Create(
                                                                              new StringReader(ObjectModelHelpers.CleanupFileContents(projectContents))),
                                                                          ProjectCollection.GlobalProjectCollection,
                                                                          preserveFormatting: true);
            ProjectItemGroupElement itemGroup = (ProjectItemGroupElement)projectElement.AllChildren.FirstOrDefault(c => c is ProjectItemGroupElement);

            var project = new Project(projectElement);

            var items = Helpers.MakeList(itemGroup.Items);

            Assert.Equal(1, items.Count);
            Assert.Equal(1, items[0].Metadata.Count);

            var metadata = items[0].Metadata.First();

            Assert.Equal("m1", metadata.Name);
            Assert.Equal("v1", metadata.Value);
            Assert.True(metadata.ExpressedAsAttribute);

            metadata.Value = @"<&>""";

            Assert.True(project.IsDirty);
            Assert.True(metadata.ExpressedAsAttribute);

            StringWriter writer = new StringWriter();

            project.Save(writer);

            string expected = @"<?xml version=""1.0"" encoding=""utf-16""?>" +
                              ObjectModelHelpers.CleanupFileContents(updatedProject);
            string actual = writer.ToString();

            VerifyAssertLineByLine(expected, actual);
        }
Ejemplo n.º 17
0
        public void ItHasErrorWhenMigratingADeprecatedNamedResourceOptionProjectJson()
        {
            var testProjectDirectory = TestAssets
                                       .GetProjectJson(TestAssetKinds.NonRestoredTestProjects, "PJDeprecatedNamedResource")
                                       .CreateInstance()
                                       .WithSourceFiles()
                                       .Root
                                       .FullName;

            var mockProj     = ProjectRootElement.Create();
            var testSettings = MigrationSettings.CreateMigrationSettingsTestHook(
                testProjectDirectory,
                testProjectDirectory,
                mockProj);

            var projectMigrator = new ProjectMigrator(new FakeEmptyMigrationRule());
            var report          = projectMigrator.Migrate(testSettings);

            var projectReport = report.ProjectMigrationReports.First();
            var errorMessage  = projectReport.Errors.First().GetFormattedErrorMessage();

            errorMessage.Should().Contain("MIGRATE1011::Deprecated Project:");
            errorMessage.Should().Contain("The 'namedResource' option is deprecated. Use 'embed' in 'buildOptions' instead. (line: 3, file:");
        }
Ejemplo n.º 18
0
        public void ProjectRemoveItemFormatting()
        {
            string content = ObjectModelHelpers.CleanupFileContents(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
  <ItemGroup>
    <Compile Include=""Class1.cs"" />
    <Compile Include=""Class2.cs""/>
    <Compile Include=""Program.cs""/>
  </ItemGroup>
</Project>");

            ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)),
                                                               ProjectCollection.GlobalProjectCollection,
                                                               preserveFormatting: true);
            Project project = new Project(xml);

            var itemToRemove = project.GetItems("Compile").Single(item => item.EvaluatedInclude == "Class2.cs");

            project.RemoveItem(itemToRemove);

            StringWriter writer = new StringWriter();

            project.Save(writer);

            string expected = ObjectModelHelpers.CleanupFileContents(@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
  <ItemGroup>
    <Compile Include=""Class1.cs"" />
    <Compile Include=""Program.cs"" />
  </ItemGroup>
</Project>");

            string actual = writer.ToString();

            VerifyAssertLineByLine(expected, actual);
        }
Ejemplo n.º 19
0
        public void ProjectInstanceBuildLoggersExplicitlyRequired()
        {
            string project_xml = @"<Project DefaultTargets='Foo' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
  <Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets' />
  <Target Name='Foo'>
    <ItemGroup>
      <Foo Condition='$(X)' Include='foo.txt' />
    </ItemGroup>
  </Target>
</Project>";
            var    xml         = XmlReader.Create(new StringReader(project_xml));
            var    root        = ProjectRootElement.Create(xml);

            root.FullPath = "BuildSubmissionTest.TaskOutputsToLoggers.proj";
            var pc = new ProjectCollection();
            var sw = new StringWriter();

            pc.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Diagnostic, sw.WriteLine, null, null));
            var proj = new ProjectInstance(root);

            Assert.IsFalse(proj.Build(), "#1");
            // the logger is *ignored* again
            Assert.IsFalse(sw.ToString().Contains("$(X)"), "#2");
        }
        public void ReadBasic()
        {
            string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <ItemDefinitionGroup Condition='c'>
                            <i1/>
                        </ItemDefinitionGroup>
                        <ItemDefinitionGroup>
                            <i2/>
                            <i3/>
                        </ItemDefinitionGroup>
                    </Project>
                ";

            ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));

            var itemDefinitionGroups = Helpers.MakeList(project.ItemDefinitionGroups);

            Assert.Equal(2, itemDefinitionGroups.Count);

            Assert.Equal(1, Helpers.Count(itemDefinitionGroups[0].ItemDefinitions));
            Assert.Equal(2, Helpers.Count(itemDefinitionGroups[1].ItemDefinitions));
            Assert.Equal("c", itemDefinitionGroups[0].Condition);
        }
Ejemplo n.º 21
0
        public void FindItems()
        {
            ProjectRootElement projectRootElement = ProjectRootElement.Create();

            projectRootElement.AddItem(DocumentationFilePredictor.DocFileItemItemName, @"obj\Foo.xml");
            projectRootElement.AddItem(DocumentationFilePredictor.FinalDocFileItemName, @"bin\Foo.xml");

            ProjectInstance projectInstance = TestHelpers.CreateProjectInstanceFromRootElement(projectRootElement);

            var expectedOutputFiles = new[]
            {
                new PredictedItem(@"obj\Foo.xml", nameof(DocumentationFilePredictor)),
                new PredictedItem(@"bin\Foo.xml", nameof(DocumentationFilePredictor)),
            };

            new DocumentationFilePredictor()
            .GetProjectPredictions(projectInstance)
            .AssertPredictions(
                projectInstance,
                null,
                null,
                expectedOutputFiles,
                null);
        }
Ejemplo n.º 22
0
        public void TestAndroidAarResourceMergeModifyInPlaceAndStampFile()
        {
            var engine = new ProjectCollection();
            var prel   = ProjectRootElement.Create(Path.Combine(TempDir, "project.csproj"), engine);

            var intermediateDir = Path.Combine(TempDir, "obj");

            var asm = AssemblyDefinition.CreateAssembly(
                new AssemblyNameDefinition("Xamarin.Android.Support.v7.CardView", new System.Version(1, 0, 0, 0)),
                "Main",
                ModuleKind.Dll
                );
            var dll = Path.Combine(TempDir, "Xamarin.Android.Support.v7.CardView.dll");

            asm.Write(dll);
            prel.AddItem("ReferencePath", dll);

            var originalAsmDate = File.GetLastWriteTimeUtc(dll);


            var unpackDir = GetTempPath("unpacked");

            prel.SetProperty("XamarinBuildDownloadDir", unpackDir);
            prel.SetProperty("TargetFrameworkIdentifier", "MonoAndroid");
            prel.SetProperty("TargetFrameworkVersion", "v7.0");
            prel.SetProperty("OutputType", "Exe");
            prel.SetProperty("IntermediateOutputPath", intermediateDir);

            prel.AddItem(
                "XamarinBuildDownloadPartialZip", "androidsupport-25.0.0/cardview.v7", new Dictionary <string, string> {
                { "Url", "https://dl-ssl.google.com/android/repository/android_m2repository_r40.zip" },
                { "ToFile", "cardview.v7.aar" },
                { "RangeStart", "196438127" },
                { "RangeEnd", "196460160" },
                { "Md5", "b44eb88f7cc621ae616744c6646f5b64" }
            });


            const string resourceName = "__AndroidLibraryProjects__.zip";
            var          aarPath      = "$(XamarinBuildDownloadDir)androidsupport-25.0.0\\cardview.v7\\cardview.v7.aar";

            prel.AddItem(
                "XamarinBuildDownloadRestoreAssemblyAar",
                aarPath,
                new Dictionary <string, string> {
                { "AssemblyName", "Xamarin.Android.Support.v7.CardView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" },
                { "LogicalName", resourceName }
            }
                );

            AddCoreTargets(prel);

            var project = new ProjectInstance(prel);
            var log     = new MSBuildTestLogger();

            //var success = BuildProject (engine, project, "_XamarinBuildDownload", log);
            var success = BuildProject(engine, project, "_XamarinAndroidBuildAarRestore", log);

//			AssertNoMessagesOrWarnings (log);
            Assert.IsTrue(success);
            //Assert.IsTrue (File.Exists (Path.Combine (unpackDir, "androidsupport-25.0.1", "cardview.v7", "cardview.v7.aar")));

            success = BuildProject(engine, project, "_XamarinAndroidBuildAarRestore", log);

            Assert.IsTrue(File.Exists(Path.Combine(intermediateDir, "XbdMerge", "Xamarin.Android.Support.v7.CardView.dll.stamp")));

            Assert.IsTrue(File.GetLastWriteTimeUtc(dll) > originalAsmDate);
        }
Ejemplo n.º 23
0
        public void TestAndroidAarManifestFixup()
        {
            var engine = new ProjectCollection();
            var prel   = ProjectRootElement.Create(Path.Combine(TempDir, "project.csproj"), engine);

            var intermediateDir = Path.Combine(TempDir, "obj");

            var asm = AssemblyDefinition.CreateAssembly(
                new AssemblyNameDefinition("Xamarin.GooglePlayServices.Auth", new System.Version(1, 0, 0, 0)),
                "Main",
                ModuleKind.Dll
                );
            var dll = Path.Combine(TempDir, "Xamarin.GooglePlayServices.Auth.dll");

            asm.Write(dll);
            prel.AddItem("ReferencePath", dll);

            var originalAsmDate = File.GetLastWriteTimeUtc(dll);


            var unpackDir = GetTempPath("unpacked");

            prel.SetProperty("XamarinBuildDownloadDir", unpackDir);
            prel.SetProperty("TargetFrameworkIdentifier", "MonoAndroid");
            prel.SetProperty("TargetFrameworkVersion", "v7.0");
            prel.SetProperty("OutputType", "Exe");
            prel.SetProperty("IntermediateOutputPath", intermediateDir);

            prel.AddItem(
                "XamarinBuildDownloadPartialZip", "playservices-10.2.1/playservicesauth", new Dictionary <string, string> {
                { "Url", "https://dl-ssl.google.com/android/repository/google_m2repository_gms_v9_1_rc07_wear_2_0_1_rc3.zip" },
                { "ToFile", "play-services-auth-10.2.1.aar" },
                { "RangeStart", "12694130" },
                { "RangeEnd", "12770642" },
                { "Md5", "f4d814a0a434c09577a9b5a9d62da1f6" }
            });


            const string resourceName = "__AndroidLibraryProjects__.zip";
            var          aarPath      = "$(XamarinBuildDownloadDir)playservices-10.2.1\\playservicesauth\\play-services-auth-10.2.1.aar";

            prel.AddItem(
                "XamarinBuildDownloadRestoreAssemblyAar",
                aarPath,
                new Dictionary <string, string> {
                { "AssemblyName", "Xamarin.GooglePlayServices.Auth, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" },
                { "LogicalName", resourceName }
            }
                );

            AddCoreTargets(prel);

            var project = new ProjectInstance(prel);
            var log     = new MSBuildTestLogger();

            var success = BuildProject(engine, project, "_XamarinAndroidBuildAarRestore", log);

            Assert.IsTrue(success);

            //check the assembly has the processed resource
            var processedAsm = AssemblyDefinition.ReadAssembly(dll);
            var resource     = processedAsm.MainModule.Resources.FirstOrDefault() as EmbeddedResource;

            Assert.NotNull(resource);
            Assert.AreEqual(resourceName, resource.Name);

            // Check the embedded .aar to see if all the manifest entries were fixed up
            using (var zip = new ZipArchive(resource.GetResourceStream())) {
                var manifestEntry = zip.Entries.FirstOrDefault(ze => ze.Name.EndsWith("AndroidManifest.xml", StringComparison.OrdinalIgnoreCase));

                Assert.IsNotNull(manifestEntry);

                // android: namespace
                XNamespace xns = "http://schemas.android.com/apk/res/android";

                using (var xmlReader = System.Xml.XmlReader.Create(manifestEntry.Open())) {
                    var xdoc = XDocument.Load(xmlReader);

                    var anyUnfixed = xdoc.Document.Descendants()
                                     .Any(elem => elem.Attribute(xns + "name")?.Value?.StartsWith(".", StringComparison.Ordinal) ?? false);

                    Assert.IsFalse(anyUnfixed);
                }
            }
        }
Ejemplo n.º 24
0
        public void TestResourcesAdded()
        {
            var engine = new ProjectCollection();
            var prel   = ProjectRootElement.Create(Path.Combine(TempDir, "project.csproj"), engine);

            var asm = AssemblyDefinition.CreateAssembly(
                new AssemblyNameDefinition("Foo", new System.Version(1, 0, 0, 0)),
                "Main",
                ModuleKind.Dll
                );
            var dll = Path.Combine(TempDir, "Foo.dll");

            asm.Write(dll);

            var unpackDir = GetTempPath("unpacked");

            prel.SetProperty("XamarinBuildDownloadDir", unpackDir);
            prel.SetProperty("TargetFrameworkIdentifier", "Xamarin.iOS");
            prel.SetProperty("OutputType", "Exe");
            prel.SetProperty("IntermediateOutputPath", Path.Combine(TempDir, "obj"));

            prel.AddItem(
                "XamarinBuildDownload", "AppInvites-1.0.2", new Dictionary <string, string> {
                { "Url", "https://www.gstatic.com/cpdc/278f79fcd3b365e3-AppInvites-1.0.2.tar.gz" },
                { "Kind", "Tgz" }
            });

            prel.AddItem(
                "ReferencePath",
                dll
                );

            var plist = Path.Combine(unpackDir, "AppInvites-1.0.2", "Frameworks", "GINInvite.framework", "Versions", "A", "Resources", "GINInviteResources.bundle", "Info.plist");

            const string resourceName = "monotouch_content_GINInviteResources.bundle_fInfo.plist";

            prel.AddItem(
                "RestoreAssemblyResource",
                plist,
                new Dictionary <string, string> {
                { "AssemblyName", "Foo" },
                { "LogicalName", resourceName }
            }
                );

            AddCoreTargets(prel);

            var project = new ProjectInstance(prel);
            var log     = new MSBuildTestLogger();

            var success = BuildProject(engine, project, "_XamariniOSBuildResourceRestore", log);

            AssertNoMessagesOrWarnings(log);
            Assert.IsTrue(success);

            Assert.IsTrue(File.Exists(plist));

            //check the referencepath has been replaced by the processed one
            var items = project.GetItems("ReferencePath");

            var mergedItem = items.FirstOrDefault(i => !string.IsNullOrEmpty(i.EvaluatedInclude) && i.EvaluatedInclude != dll);

            Assert.IsTrue(mergedItem != null);

            var itemPath = mergedItem.EvaluatedInclude;

            Assert.AreNotEqual(dll, itemPath);

            //check the assembly has the processed resource
            var processedAsm = AssemblyDefinition.ReadAssembly(itemPath);
            var resource     = processedAsm.MainModule.Resources.FirstOrDefault() as EmbeddedResource;

            Assert.NotNull(resource);
            Assert.AreEqual(resourceName, resource.Name);
            var ps = PObject.FromStream(resource.GetResourceStream()) as PDictionary;

            Assert.IsFalse(ps.ContainsKey("CFBundleExecutable"));
            Assert.Greater(ps.Count, 0);
            var processedAsmMtime = File.GetLastWriteTime(itemPath);

            // check incremental build works
            project = new ProjectInstance(prel);
            log     = new MSBuildTestLogger();
            var newSuccess = BuildProject(engine, project, "_XamariniOSBuildResourceRestore", log);

            AssertNoMessagesOrWarnings(log);
            Assert.IsTrue(success);

            var newItems    = project.GetItems("ReferencePath");
            var newItem     = newItems.FirstOrDefault(i => !string.IsNullOrEmpty(i.EvaluatedInclude) && i.EvaluatedInclude != dll);
            var newItemPath = newItem.EvaluatedInclude;

            Assert.AreEqual(itemPath, newItemPath);
            Assert.AreEqual(processedAsmMtime, File.GetLastWriteTime(newItemPath));
        }
Ejemplo n.º 25
0
        public void testAndroidAarAdded(bool useAndroidSdk)
        {
            var engine = new ProjectCollection();
            var prel   = ProjectRootElement.Create(Path.Combine(TempDir, "project.csproj"), engine);

            var asm = AssemblyDefinition.CreateAssembly(
                new AssemblyNameDefinition("Xamarin.Android.Support.v7.CardView", new System.Version(1, 0, 0, 0)),
                "Main",
                ModuleKind.Dll
                );
            var dll = Path.Combine(TempDir, "Xamarin.Android.Support.v7.CardView.dll");

            asm.Write(dll);

            var unpackDir = GetTempPath("unpacked");

            prel.SetProperty("XamarinBuildDownloadDir", unpackDir);
            prel.SetProperty("TargetFrameworkIdentifier", "MonoAndroid");
            prel.SetProperty("TargetFrameworkVersion", "v7.0");

            var aarPathInSdk = "$(AndroidSdkPath)\\extras\\android\\m2repository\\com\\android\\support\\cardview-v7\\25.0.0\\cardview-v7-25.0.0.aar";

            if (useAndroidSdk)
            {
                prel.SetProperty("AndroidSdkPath", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Library", "Developer", "Xamarin", "android-sdk-mac_x86"));
            }

            prel.SetProperty("OutputType", "Exe");
            prel.SetProperty("IntermediateOutputPath", Path.Combine(TempDir, "obj"));

            var item = prel.AddItem(
                "XamarinBuildDownload", "androidsupport-25.0.0", new Dictionary <string, string> {
                { "Url", "https://dl-ssl.google.com/android/repository/android_m2repository_r39.zip" },
                { "Kind", "Zip" },
                { "Sha1", "89ad37d67a1018c42be36933cec3d7712141d42c" },
            });

            if (useAndroidSdk)
            {
                item.Condition = "!Exists('" + aarPathInSdk + "')";
            }

            prel.AddItem(
                "ReferencePath",
                dll
                );

            const string resourceName = "__AndroidLibraryProjects__.zip";
            var          aarPath      = "$(XamarinBuildDownloadDir)androidsupport-25.0.0\\m2repository\\com\\android\\support\\cardview-v7\\25.0.0\\cardview-v7-25.0.0.aar";

            prel.AddItem(
                "XamarinBuildDownloadRestoreAssemblyAar",
                useAndroidSdk ? aarPathInSdk : aarPath,
                new Dictionary <string, string> {
                { "AssemblyName", "Xamarin.Android.Support.v7.CardView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" },
                { "LogicalName", resourceName }
            }
                );

            AddCoreTargets(prel);

            var project = new ProjectInstance(prel);
            var log     = new MSBuildTestLogger();

            log.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Diagnostic;

            var success = BuildProject(engine, project, "_XamarinAndroidBuildAarRestore", log);

            AssertNoMessagesOrWarnings(log);
            Assert.IsTrue(success);

            //Assert.IsTrue (File.Exists (aar));

            //check the referencepath has been replaced by the processed one
            var items = project.GetItems("ReferencePath");

            var mergedItem = items.FirstOrDefault(i => !string.IsNullOrEmpty(i.EvaluatedInclude) && i.EvaluatedInclude != dll);

            Assert.IsTrue(mergedItem != null);

            var itemPath = mergedItem.EvaluatedInclude;

            //check the assembly has the processed resource
            var processedAsm = AssemblyDefinition.ReadAssembly(itemPath);
            var resource     = processedAsm.MainModule.Resources.FirstOrDefault() as EmbeddedResource;

            Assert.NotNull(resource);
            Assert.AreEqual(resourceName, resource.Name);

            // Check that the embedded .aar has an appropriate prefix for each entry's path
            var hasWrongEntryNames = false;

            using (var zip = new ZipArchive(resource.GetResourceStream())) {
                hasWrongEntryNames = zip.Entries.Any(ze => !ze.FullName.StartsWith("library_project_imports", System.StringComparison.InvariantCulture));
            }
            Assert.IsFalse(hasWrongEntryNames);

            var processedAsmMtime = File.GetLastWriteTime(itemPath);

            // check incremental build works
            project       = new ProjectInstance(prel);
            log           = new MSBuildTestLogger();
            log.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Diagnostic;
            var newSuccess = BuildProject(engine, project, "_XamarinAndroidBuildAarRestore", log);

            AssertNoMessagesOrWarnings(log);
            Assert.IsTrue(newSuccess);

            var newItems = project.GetItems("ReferencePath");
            var newItem  = newItems.FirstOrDefault(i => !string.IsNullOrEmpty(i.EvaluatedInclude) && i.EvaluatedInclude != dll);

            Assert.IsTrue(newItem != null);
            var newItemPath = newItem.EvaluatedInclude;

            Assert.AreEqual(itemPath, newItemPath);
            Assert.AreEqual(processedAsmMtime, File.GetLastWriteTime(newItemPath));
        }
Ejemplo n.º 26
0
        internal static void WriteProjectXml(
            IInterpreterRegistryService service,
            TextWriter writer,
            string projectPath,
            string sourcePath,
            string filters,
            string searchPaths,
            string startupFile,
            PythonInterpreterView selectedInterpreter,
            ProjectCustomization customization,
            bool detectVirtualEnv
            )
        {
            var projectHome = PathUtils.GetRelativeDirectoryPath(Path.GetDirectoryName(projectPath), sourcePath);

            var project = ProjectRootElement.Create();

            project.DefaultTargets = "Build";
            project.ToolsVersion   = "4.0";

            var globals = project.AddPropertyGroup();

            globals.AddProperty("Configuration", "Debug").Condition = " '$(Configuration)' == '' ";
            globals.AddProperty("SchemaVersion", "2.0");
            globals.AddProperty("ProjectGuid", Guid.NewGuid().ToString("B"));
            globals.AddProperty("ProjectHome", projectHome);
            if (PathUtils.IsValidPath(startupFile))
            {
                globals.AddProperty("StartupFile", startupFile);
            }
            else
            {
                globals.AddProperty("StartupFile", "");
            }
            globals.AddProperty("SearchPath", searchPaths);
            globals.AddProperty("WorkingDirectory", ".");
            globals.AddProperty("OutputPath", ".");

            globals.AddProperty("ProjectTypeGuids", "{888888a0-9f3d-457c-b088-3a5042f75d52}");
            globals.AddProperty("LaunchProvider", DefaultLauncherProvider.DefaultLauncherName);

            var interpreterId = globals.AddProperty(PythonConstants.InterpreterId, "");

            if (selectedInterpreter != null && !String.IsNullOrWhiteSpace(selectedInterpreter.Id))
            {
                interpreterId.Value = selectedInterpreter.Id;
            }

            // VS requires property groups with conditions for Debug
            // and Release configurations or many COMExceptions are
            // thrown.
            var debugGroup   = project.AddPropertyGroup();
            var releaseGroup = project.AddPropertyGroup();

            debugGroup.Condition   = "'$(Configuration)' == 'Debug'";
            releaseGroup.Condition = "'$(Configuration)' == 'Release'";


            var folders         = new HashSet <string>();
            var virtualEnvPaths = detectVirtualEnv ? new List <string>() : null;

            foreach (var unescapedFile in EnumerateAllFiles(sourcePath, filters, virtualEnvPaths))
            {
                var file     = ProjectCollection.Escape(unescapedFile);
                var ext      = Path.GetExtension(file);
                var fileType = "Content";
                if (PythonConstants.FileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase) ||
                    PythonConstants.WindowsFileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase))
                {
                    fileType = "Compile";
                }
                folders.Add(Path.GetDirectoryName(file));

                project.AddItem(fileType, file);
            }

            foreach (var folder in folders.Where(s => !string.IsNullOrWhiteSpace(s)).OrderBy(s => s))
            {
                project.AddItem("Folder", folder);
            }

            if (selectedInterpreter != null && !String.IsNullOrWhiteSpace(selectedInterpreter.Id))
            {
                project.AddItem(
                    MSBuildConstants.InterpreterReferenceItem,
                    selectedInterpreter.Id
                    );
            }
            if (virtualEnvPaths != null && virtualEnvPaths.Any() && service != null)
            {
                foreach (var path in virtualEnvPaths)
                {
                    var shortId = PathUtils.GetFileOrDirectoryName(path);
                    var longId  = MSBuildProjectInterpreterFactoryProvider.GetInterpreterId("$(MSBuildProjectFullPath)", shortId);
                    var config  = VirtualEnv.FindInterpreterConfiguration(longId, path, service);
                    if (config != null)
                    {
                        AddVirtualEnvironment(project, sourcePath, shortId, config);

                        if (string.IsNullOrEmpty(interpreterId.Value))
                        {
                            interpreterId.Value = longId;
                        }
                    }
                }
            }

            var imports = project.AddPropertyGroup();

            imports.AddProperty("VisualStudioVersion", "10.0").Condition = " '$(VisualStudioVersion)' == '' ";

            (customization ?? DefaultProjectCustomization.Instance).Process(
                sourcePath,
                project,
                new Dictionary <string, ProjectPropertyGroupElement> {
                { "Globals", globals },
                { "Imports", imports },
                { "Debug", debugGroup },
                { "Release", releaseGroup }
            }
                );

            project.Save(writer);
        }
Ejemplo n.º 27
0
        public override bool Execute()
        {
            var fileVersions = new Dictionary <string, FileVersionData>(StringComparer.OrdinalIgnoreCase);

            foreach (var file in Files)
            {
                var targetPath = file.GetMetadata("TargetPath");

                if (!targetPath.StartsWith("runtimes/"))
                {
                    continue;
                }

                if (file.GetMetadata("IsSymbolFile").Equals("true", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                var fileName = Path.GetFileName(file.ItemSpec);

                var current = GetFileVersionData(file);

                FileVersionData existing;

                if (fileVersions.TryGetValue(fileName, out existing))
                {
                    if (current.AssemblyVersion != null)
                    {
                        if (existing.AssemblyVersion == null)
                        {
                            fileVersions[fileName] = current;
                            continue;
                        }
                        else if (current.AssemblyVersion != existing.AssemblyVersion)
                        {
                            if (current.AssemblyVersion > existing.AssemblyVersion)
                            {
                                fileVersions[fileName] = current;
                            }
                            continue;
                        }
                    }

                    if (current.FileVersion != null &&
                        existing.FileVersion != null)
                    {
                        if (current.FileVersion > existing.FileVersion)
                        {
                            fileVersions[fileName] = current;
                        }
                    }
                }
                else
                {
                    fileVersions[fileName] = current;
                }
            }

            var props     = ProjectRootElement.Create();
            var itemGroup = props.AddItemGroup();

            // set the platform manifest when the platform is not being published as part of the app
            itemGroup.Condition = "'$(RuntimeIdentifier)' == '' or '$(SelfContained)' != 'true'";

            var manifestFileName = Path.GetFileName(PlatformManifestFile);

            itemGroup.AddItem(PlatformManifestsItem, $"$(MSBuildThisFileDirectory){manifestFileName}");

            using (var manifestWriter = File.CreateText(PlatformManifestFile))
            {
                foreach (var fileData in fileVersions)
                {
                    var name            = fileData.Key;
                    var versions        = fileData.Value;
                    var assemblyVersion = versions.AssemblyVersion?.ToString() ?? String.Empty;
                    var fileVersion     = versions.FileVersion?.ToString() ?? String.Empty;

                    manifestWriter.WriteLine($"{name}|{PackageId}|{assemblyVersion}|{fileVersion}");
                }
            }

            var propertyGroup = props.AddPropertyGroup();

            propertyGroup.AddProperty(PreferredPackagesProperty, PreferredPackages);

            var versionPropertyName = $"_{PackageId.Replace(".", "_")}_Version";

            propertyGroup.AddProperty(versionPropertyName, PackageVersion);

            props.Save(PropsFile);

            return(!Log.HasLoggedErrors);
        }
Ejemplo n.º 28
0
        public void ReadNone()
        {
            ProjectRootElement project = ProjectRootElement.Create();

            Assert.Null(project.UsingTasks.GetEnumerator().Current);
        }
Ejemplo n.º 29
0
        public string CreateTemplate()
        {
            var root = ProjectRootElement.Create();

            root.ToolsVersion   = "14.0";
            root.DefaultTargets = "Build";

            var group = root.AddPropertyGroup();

            group.AddProperty("Configuration", "Debug").Condition = " '$(Configuration)' == '' ";
            group.AddProperty("Platform", "AnyCPU").Condition     = " '$(Platform)' == '' ";
            group.AddProperty("ProjectGuid", $"{{{Project.Id}}}");
            group.AddProperty("OutputType", "Exe");
            group.AddProperty("AppDesignerFolder", "Properties");
            group.AddProperty("RootNamespace", $"{Project.Name}");
            group.AddProperty("AssemblyName", $"{Project.Name}");
            group.AddProperty("TargetFrameworkVersion", Project.TargetFrameworkVersion());
            group.AddProperty("FileAlignment", "512");
            group.AddProperty("TargetFrameworkProfile", "");

            group           = root.AddPropertyGroup();
            group.Condition = " '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ";
            group.AddProperty("DebugSymbols", "true");
            group.AddProperty("DebugType", "full");
            group.AddProperty("Optimize", "false");
            group.AddProperty("OutputPath", "bin\\Debug\\");
            group.AddProperty("DefineConstants", "DEBUG;TRACE");
            group.AddProperty("ErrorReport", "prompt");
            group.AddProperty("WarningLevel", "4");

            group           = root.AddPropertyGroup();
            group.Condition = " '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ";
            group.AddProperty("DebugType", "pdbonly");
            group.AddProperty("Optimize", "true");
            group.AddProperty("OutputPath", "bin\\Release\\");
            group.AddProperty("DefineConstants", "TRACE");
            group.AddProperty("ErrorReport", "prompt");
            group.AddProperty("WarningLevel", "4");

            var itemGroup = AddItems(root, "Reference",
                                     "Microsoft.CSharp"
                                     , "System"
                                     , "System.Core"
                                     , "System.Data.DataSetExtensions"
                                     , "System.Data"
                                     , "System.Xml"
                                     , "System.Xml.Linq");

            foreach (var reference in Project.References())
            {
                AddReference(itemGroup, reference);
            }

            foreach (var dependency in Project.Dependencies())
            {
                AddItem(itemGroup, "ProjectReference", string.Format("..\\{0}\\{0}.csproj", dependency.Name),
                        new[]
                {
                    new KeyValuePair <string, string>("Project", $"{{{dependency.Id}}}"),
                    new KeyValuePair <string, string>("Name", $"{dependency.Name}"),
                });
            }

            root.AddImport("$(MSBuildToolsPath)\\Microsoft.CSharp.targets");

            return(root.RawXml.Replace("utf-16", "utf-8"));
        }
Ejemplo n.º 30
0
        public void ImportedProjectsSdkImportsAreInPreprocessedOutput()
        {
            using (TestEnvironment env = TestEnvironment.Create())
            {
                string sdk1 = env.CreateFolder().FolderPath;
                string sdk2 = env.CreateFolder().FolderPath;

                var projectOptions = SdkUtilities.CreateProjectOptionsWithResolver(new SdkUtilities.FileBasedMockSdkResolver(new Dictionary <string, string>
                {
                    { "MSBuildUnitTestSdk1", sdk1 },
                    { "MSBuildUnitTestSdk2", sdk2 },
                }));

                string sdkPropsPath1   = Path.Combine(sdk1, "Sdk.props");
                string sdkTargetsPath1 = Path.Combine(sdk1, "Sdk.targets");

                File.WriteAllText(sdkPropsPath1, @"<Project>
    <PropertyGroup>
        <SdkProps1Imported>true</SdkProps1Imported>
    </PropertyGroup>
</Project>");
                File.WriteAllText(sdkTargetsPath1, @"<Project>
    <PropertyGroup>
        <SdkTargets1Imported>true</SdkTargets1Imported>
    </PropertyGroup>
</Project>");

                string sdkPropsPath2   = Path.Combine(sdk2, "Sdk.props");
                string sdkTargetsPath2 = Path.Combine(sdk2, "Sdk.targets");

                File.WriteAllText(sdkPropsPath2, @"<Project>
    <PropertyGroup>
        <SdkProps2Imported>true</SdkProps2Imported>
    </PropertyGroup>
</Project>");
                File.WriteAllText(sdkTargetsPath2, @"<Project>
    <PropertyGroup>
        <SdkTargets2Imported>true</SdkTargets2Imported>
    </PropertyGroup>
</Project>");


                TransientTestProjectWithFiles import = env.CreateTestProjectWithFiles(@"<Project Sdk='MSBuildUnitTestSdk2'>
    <PropertyGroup>
        <MyImportWasImported>true</MyImportWasImported>
    </PropertyGroup>
</Project>");
                string importPath = Path.GetFullPath(import.ProjectFile);
                string content    = $@"<Project Sdk='MSBuildUnitTestSdk1'>
  <Import Project='{importPath}' />
  <PropertyGroup>
    <p>v1</p>
  </PropertyGroup>
</Project>";

                Project project = Project.FromProjectRootElement(
                    ProjectRootElement.Create(XmlReader.Create(new StringReader(content))),
                    projectOptions);

                StringWriter writer = new StringWriter();

                project.SaveLogicalProject(writer);

                string expected = ObjectModelHelpers.CleanupFileContents(
                    $@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project>
  <!--
============================================================================================================================================
  <Import Project=""Sdk.props"" Sdk=""MSBuildUnitTestSdk1"">
  This import was added implicitly because the Project element's Sdk attribute specified ""MSBuildUnitTestSdk1"".

{sdkPropsPath1.Replace("--", "__")}
============================================================================================================================================
-->
  <PropertyGroup>
    <SdkProps1Imported>true</SdkProps1Imported>
  </PropertyGroup>
  <!--
============================================================================================================================================
  </Import>


============================================================================================================================================
-->
  <!--
============================================================================================================================================
  <Import Project=""{importPath.Replace("--", "__")}"">

{importPath.Replace("--", "__")}
============================================================================================================================================
-->
  <!--
============================================================================================================================================
  <Import Project=""Sdk.props"" Sdk=""MSBuildUnitTestSdk2"">
  This import was added implicitly because the Project element's Sdk attribute specified ""MSBuildUnitTestSdk2"".

{sdkPropsPath2.Replace("--", "__")}
============================================================================================================================================
-->
  <PropertyGroup>
    <SdkProps2Imported>true</SdkProps2Imported>
  </PropertyGroup>
  <!--
============================================================================================================================================
  </Import>

{importPath.Replace("--", "__")}
============================================================================================================================================
-->
  <PropertyGroup>
    <MyImportWasImported>true</MyImportWasImported>
  </PropertyGroup>
  <!--
============================================================================================================================================
  <Import Project=""Sdk.targets"" Sdk=""MSBuildUnitTestSdk2"">
  This import was added implicitly because the Project element's Sdk attribute specified ""MSBuildUnitTestSdk2"".

{sdkTargetsPath2.Replace("--", "__")}
============================================================================================================================================
-->
  <PropertyGroup>
    <SdkTargets2Imported>true</SdkTargets2Imported>
  </PropertyGroup>
  <!--
============================================================================================================================================
  </Import>

{importPath.Replace("--", "__")}
============================================================================================================================================
-->
  <!--
============================================================================================================================================
  </Import>


============================================================================================================================================
-->
  <PropertyGroup>
    <p>v1</p>
  </PropertyGroup>
  <!--
============================================================================================================================================
  <Import Project=""Sdk.targets"" Sdk=""MSBuildUnitTestSdk1"">
  This import was added implicitly because the Project element's Sdk attribute specified ""MSBuildUnitTestSdk1"".

{sdkTargetsPath1.Replace("--", "__")}
============================================================================================================================================
-->
  <PropertyGroup>
    <SdkTargets1Imported>true</SdkTargets1Imported>
  </PropertyGroup>
  <!--
============================================================================================================================================
  </Import>


============================================================================================================================================
-->
</Project>");
                Helpers.VerifyAssertLineByLine(expected, writer.ToString());
            }
        }