public void ImportFromExtensionsPathNotFound()
        {
            string extnDir1 = null;
            string mainProjectPath = null;

            try {
                extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), GetExtensionTargetsFileContent1());
                mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());

                var projColln = new ProjectCollection();
                projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", extnDir1, Path.Combine("tmp", "nonexistant")));
                var logger = new MockLogger();
                projColln.RegisterLogger(logger);

                Assert.Throws<InvalidProjectFileException>(() => projColln.LoadProject(mainProjectPath));

                logger.AssertLogContains("MSB4226");
            } finally {
                if (mainProjectPath != null)
                {
                    FileUtilities.DeleteNoThrow(mainProjectPath);
                }
                if (extnDir1 != null)
                {
                    FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
                }
            }
        }
        public void OverrideTaskPathIsRelative()
        {
            //Note Engine's BinPath is distinct from the ToolsVersion's ToolsPath
            ProjectCollection e = new ProjectCollection();
            Toolset t = new Toolset("toolsversionname", "c:\\directory1\\directory2", new PropertyDictionary<ProjectPropertyInstance>(), new ProjectCollection(), new DirectoryGetFiles(this.getFiles), new LoadXmlFromPath(this.loadXmlFromPath), "msbuildoverridetasks", new DirectoryExists(this.directoryExists));

            MockLogger mockLogger = new MockLogger();
            LoggingService service = (LoggingService)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1);
            service.RegisterLogger(mockLogger);

            TaskRegistry taskoverrideRegistry = (TaskRegistry)t.GetOverrideTaskRegistry(service, new BuildEventContext(1, 2, BuildEventContext.InvalidProjectContextId, 4), e.ProjectRootElementCache);
            Assert.IsNotNull(taskoverrideRegistry);
            Assert.IsTrue(taskoverrideRegistry.TaskRegistrations.Count == 0);
            string rootedPathMessage = ResourceUtilities.FormatResourceString("OverrideTaskNotRootedPath", "msbuildoverridetasks");
            mockLogger.AssertLogContains(ResourceUtilities.FormatResourceString("OverrideTasksFileFailure", rootedPathMessage));
        }
Exemple #3
0
        public void TaskReturnsFailureButDoesNotLogError_ContinueOnError_WarnAndContinue()
        {
            using (TestEnvironment env = TestEnvironment.Create(_output))
            {
                TransientTestProjectWithFiles proj = env.CreateTestProjectWithFiles($@"
                <Project>
                    <UsingTask TaskName = ""ReturnFailureWithoutLoggingErrorTask"" AssemblyName=""Microsoft.Build.Engine.UnitTests""/>
                    <Target Name='Build'>
                        <ReturnFailureWithoutLoggingErrorTask
                            ContinueOnError=""WarnAndContinue""/>
                    </Target>
                </Project>");

                MockLogger logger = proj.BuildProjectExpectSuccess();

                logger.WarningCount.ShouldBe(1);

                logger.AssertLogContains("MSB4181");
            }
        }
        public void TasksAreDiscoveredWhenTaskConditionTrue()
        {
            MockLogger logger = new MockLogger();
            string     projectFileContents = ObjectModelHelpers.CleanupFileContents(
                @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                      <Target Name='t'>
                         <NonExistantTask Condition=""'1'=='1'""/>
                         <Message Text='Made it'/>                    
                      </Target>
                      </Project>");

            Project        project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
            List <ILogger> loggers = new List <ILogger>();

            loggers.Add(logger);
            project.Build("t", loggers);

            logger.AssertLogContains("MSB4036");
            logger.AssertLogDoesntContain("Made it");
        }
        public void NullMetadataOnLegacyOutputItems()
        {
            string customTaskPath = Assembly.GetExecutingAssembly().Location;

            string projectContents = @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
  <UsingTask TaskName=`NullMetadataTask` AssemblyFile=`" + customTaskPath + @"` />

  <Target Name=`Build`>
    <NullMetadataTask>
      <Output TaskParameter=`OutputItems` ItemName=`Outputs`/>
    </NullMetadataTask>

    <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` />
  </Target>
</Project>";

            MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents);

            logger.AssertLogContains("[foo: ]");
        }
Exemple #6
0
        public void TaskReturnsFailureAndLogsError_ContinueOnError_WarnAndContinue()
        {
            using (TestEnvironment env = TestEnvironment.Create(_output))
            {
                TransientTestProjectWithFiles proj = env.CreateTestProjectWithFiles($@"
                <Project>
                    <UsingTask TaskName = ""CustomLogAndReturnTask"" AssemblyName=""Microsoft.Build.Engine.UnitTests""/>
                    <UsingTask TaskName = ""ReturnFailureWithoutLoggingErrorTask"" AssemblyName=""Microsoft.Build.Engine.UnitTests""/>
                    <Target Name='Build'>
                        <CustomLogAndReturnTask Return=""false"" ErrorCode=""MSB1234"" ContinueOnError=""WarnAndContinue""/>
                    </Target>
                </Project>");

                MockLogger logger = proj.BuildProjectExpectSuccess();

                // The only warning should be the error->warning logged by the task.
                logger.WarningCount.ShouldBe(1);
                logger.AssertLogContains("MSB1234");
            }
        }
Exemple #7
0
        public void OtherBuiltInMetadataErrors()
        {
            MockLogger logger = new MockLogger();
            string     projectFileContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t'>
 <CreateItem Include='Foo' AdditionalMetadata='RecursiveDir=1'>
   <Output TaskParameter='Include' ItemName='x' />
 </CreateItem>
</Target>
</Project>");

            Project        project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
            List <ILogger> loggers = new List <ILogger>();

            loggers.Add(logger);
            bool result = project.Build("t", loggers);

            Assert.False(result);
            logger.AssertLogContains("MSB3031");
        }
Exemple #8
0
        /// <summary>
        /// Assert that the log file contains the given string.
        /// Case insensitive.
        /// First check if the string is in the log string. If not
        /// than make sure it is also check the MockLogger
        /// </summary>
        /// <param name="contains"></param>
        public void AssertLogContains(string contains)
        {
            if (upperLog == null)
            {
                upperLog = log;
                upperLog = upperLog.ToUpperInvariant();
            }

            // If we do not contain this string than pass it to
            // MockLogger. Since MockLogger is also registered as
            // a logger it may have this string.
            if (!upperLog.Contains
                (
                    contains.ToUpperInvariant()
                )
                )
            {
                Console.WriteLine(log);
                mockLogger.AssertLogContains(contains);
            }
        }
        public void ProjectResolverContextRefersToBuildingProject(string projectFormatString)
        {
            string projectInnerContents = _projectInnerContents;

            File.WriteAllText(_sdkPropsPath, _sdkPropsContent);
            File.WriteAllText(_sdkTargetsPath, _sdkTargetsContent);

            // Use custom SDK resolution to ensure resolver context is logged.
            var mapping = new Dictionary <string, string> {
                { SdkName, _testSdkDirectory }
            };
            var projectOptions = SdkUtilities.CreateProjectOptionsWithResolver(new SdkUtilities.FileBasedMockSdkResolver(mapping));

            // Create a normal project (p1) which imports an SDK style project (p2).
            var projectFolder = _env.CreateFolder().Path;

            var p1 = @"<Project> <Import Project=""p2.proj"" /> </Project>";
            var p2 = string.Format(projectFormatString, SdkName, projectInnerContents);

            var p1Path = Path.Combine(projectFolder, "p1.proj");
            var p2Path = Path.Combine(projectFolder, "p2.proj");

            File.WriteAllText(p1Path, p1);
            File.WriteAllText(p2Path, p2);

            var logger = new MockLogger();
            var pc     = _env.CreateProjectCollection().Collection;

            pc.RegisterLogger(logger);
            ProjectRootElement projectRootElement = ProjectRootElement.Open(p1Path, pc);

            projectOptions.ProjectCollection = pc;

            var project = Project.FromProjectRootElement(projectRootElement, projectOptions);

            // ProjectFilePath should be logged with the path to p1 and not the path to p2.
            logger.AssertLogContains($"ProjectFilePath = {p1Path}");
            logger.AssertLogDoesntContain($"ProjectFilePath = {p2Path}");
        }
        public void SemicolonInPropertyPassedIntoITaskItemParam()
        {
            MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(String.Format(@"

                <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>

                    <UsingTask TaskName=`Microsoft.Build.UnitTests.EscapingInProjects_Tests.MyTestTask` AssemblyFile=`{0}` />

                    <PropertyGroup>
                        <MyPropertyWithSemicolons>abc %3b def %3b ghi</MyPropertyWithSemicolons>
                    </PropertyGroup>

                    <Target Name=`Build`>
                        <MyTestTask TaskItemParam=`123 $(MyPropertyWithSemicolons) 789` />
                    </Target>

                </Project>

                ", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath));

            logger.AssertLogContains("Received TaskItemParam: 123 abc ; def ; ghi 789");
        }
        public void Simple()
        {
            string content = @"
                <Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">

                    <ItemGroup>
                        <AToB Include=""a;b""/>
                    </ItemGroup>

                    <Target Name=""Build"">
                        <CreateItem Include=""%(AToB.Identity)"">
                            <Output ItemName=""AToBBatched"" TaskParameter=""Include""/>
                        </CreateItem>
                        <Message Text=""[AToBBatched: @(AToBBatched)]""/>
                    </Target>

                </Project>
                ";

            MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content);

            log.AssertLogContains("[AToBBatched: a;b]");
        }
Exemple #12
0
        public void ProjectResolverContextRefersToBuildingProject(string projectFormatString)
        {
            string projectInnerContents = @"<PropertyGroup><UsedToTestIfImplicitImportsAreInTheCorrectLocation>null</UsedToTestIfImplicitImportsAreInTheCorrectLocation></PropertyGroup>";

            File.WriteAllText(_sdkPropsPath, "<Project><PropertyGroup><InitialImportProperty>Hello</InitialImportProperty></PropertyGroup></Project>");
            File.WriteAllText(_sdkTargetsPath, "<Project><PropertyGroup><FinalImportProperty>World</FinalImportProperty></PropertyGroup></Project>");

            // Use custom SDK resolution to ensure resolver context is logged.
            var mapping = new Dictionary <string, string> {
                { SdkName, _testSdkDirectory }
            };

            _env.CustomSdkResolution(mapping);

            // Create a normal project (p1) which imports an SDK style project (p2).
            var projectFolder = _env.CreateFolder().FolderPath;

            var p1 = @"<Project> <Import Project=""p2.proj"" /> </Project>";
            var p2 = string.Format(projectFormatString, SdkName, projectInnerContents);

            var p1Path = Path.Combine(projectFolder, "p1.proj");
            var p2Path = Path.Combine(projectFolder, "p2.proj");

            File.WriteAllText(p1Path, p1);
            File.WriteAllText(p2Path, p2);

            var logger = new MockLogger();
            var pc     = new ProjectCollection();

            pc.RegisterLogger(logger);
            ProjectRootElement projectRootElement = ProjectRootElement.Open(p1Path, pc);
            var project = new Project(projectRootElement, null, null, pc);

            // ProjectFilePath should be logged with the path to p1 and not the path to p2.
            logger.AssertLogContains($"ProjectFilePath = {p1Path}");
            logger.AssertLogDoesntContain($"ProjectFilePath = {p2Path}");
        }
Exemple #13
0
        public void OnErrorSeesPropertiesAndItemsFromFirstTarget()
        {
            MockLogger l = new MockLogger();
            Project    p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"

                <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> 

                   <Target Name='Build'>
                      <!-- Create a bunch of items and properties -->
                      <CreateItem Include='a1'>
                        <Output ItemName='i1' TaskParameter='Include'/>
                      </CreateItem> 
                      <ItemGroup>
                        <i1 Include='a2'/>
                      </ItemGroup> 
                      <CreateProperty Value='v1'>
                        <Output PropertyName='p1' TaskParameter='Value'/>
                      </CreateProperty>
                      <PropertyGroup>
                        <p2>v2</p2>
                      </PropertyGroup>

                      <Error Text='This is an error.'/>
                      <OnError ExecuteTargets='ErrorTarget'/>
                   </Target>

                   <Target Name='ErrorTarget'>
                      <Message Text='[@(i1)][$(p1)][$(p2)]'/>
                   </Target>

                </Project>"))));

            p.Build(new string[] { "Build" }, new ILogger[] { l });

            Assert.Equal(1, l.ErrorCount); // "Expected one error because 'Build' failed."
            l.AssertLogContains("[a1;a2][v1][v2]");
        }
Exemple #14
0
        public void Build()
        {
            string projectFileContent = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
                        <UsingTask TaskName='Microsoft.Build.Tasks.Message' AssemblyFile='Microsoft.Build.Tasks.Core.dll'/>
                        <ItemGroup>
                            <i Include='i0'/>
                        </ItemGroup>
                        <Target Name='Build'>
                            <Message Text='Building...'/>
                            <Message Text='Completed!'/>
                        </Target>
                    </Project>";

            ProjectInstance projectInstance = GetProjectInstance(projectFileContent);
            List <ILogger>  loggers         = new List <ILogger>();
            MockLogger      mockLogger      = new MockLogger();

            loggers.Add(mockLogger);
            bool success = projectInstance.Build("Build", loggers);

            Assert.True(success);
            mockLogger.AssertLogContains(new string[] { "Building...", "Completed!" });
        }
Exemple #15
0
        public void NullMetadataOnLegacyOutputItems_InlineTask()
        {
            string projectContents = @"
                    <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
                        <UsingTask TaskName=`NullMetadataTask_v4` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildFrameworkToolsPath)\net.r_eg.IeXod.Tasks.v4.0.dll`>
                            <ParameterGroup>
                               <OutputItems ParameterType=`net.r_eg.IeXod.Framework.ITaskItem[]` Output=`true` />
                            </ParameterGroup>
                            <Task>
                                <Code>
                                <![CDATA[
                                    OutputItems = new ITaskItem[1];

                                    IDictionary<string, string> metadata = new Dictionary<string, string>();
                                    metadata.Add(`a`, null);

                                    OutputItems[0] = new TaskItem(`foo`, (IDictionary)metadata);

                                    return true;
                                ]]>
                                </Code>
                            </Task>
                        </UsingTask>
                      <Target Name=`Build`>
                        <NullMetadataTask_v4>
                          <Output TaskParameter=`OutputItems` ItemName=`Outputs` />
                        </NullMetadataTask_v4>

                        <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` />
                      </Target>
                    </Project>";

            MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput);

            logger.AssertLogContains("[foo: ]");
        }
        // Ignore: Changes to the current directory interfere with the toolset reader.
        public void SolutionDoesntPassSubToolsetToChildProjects()
        {
            try
            {
                string classLibraryContents =
                    @"
                        <Project ToolsVersion=""4.0"" DefaultTargets=""Build"" xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
                            <Target Name='Build'>
                                <Message Text='.[$(VisualStudioVersion)].' />
                                <Message Text='.[[$(MSBuildToolsVersion)]].' />
                            </Target>
                        </Project>
                    ";

                string projectFile = ObjectModelHelpers.CreateFileInTempProjectDirectory("ClassLibrary1.csproj", classLibraryContents);

                string solutionFileContents =
                    @"
                        Microsoft Visual Studio Solution File, Format Version 12.00
                        # Visual Studio Dev11
                        Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""ClassLibrary1"", ""ClassLibrary1.csproj"", ""{6185CC21-BE89-448A-B3C0-D1C27112E595}""
                        EndProject
                        Global
                            GlobalSection(SolutionConfigurationPlatforms) = preSolution
                                Debug|Mixed Platforms = Debug|Mixed Platforms
                                Release|Any CPU = Release|Any CPU
                            EndGlobalSection
                            GlobalSection(ProjectConfigurationPlatforms) = postSolution
                                {6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.ActiveCfg = CSConfig1|Any CPU
                                {6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.Build.0 = CSConfig1|Any CPU
                                {6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Any CPU.ActiveCfg = CSConfig2|Any CPU
                            EndGlobalSection
                        EndGlobal
                    ";

                string solutionFile = ObjectModelHelpers.CreateFileInTempProjectDirectory("Foo.sln", solutionFileContents);

                SolutionFile sp = new SolutionFile();

                sp.FullPath = solutionFile;
                sp.ParseSolutionFile();

                ProjectInstance[] instances = SolutionProjectGenerator.Generate(sp, null, null, new BuildEventContext(0, 0, 0, 0), null);

                Assert.AreEqual(ObjectModelHelpers.MSBuildDefaultToolsVersion, instances[0].ToolsVersion);
                Assert.AreEqual("11.0", instances[0].SubToolsetVersion);
                Assert.AreEqual("11.0", instances[0].GetPropertyValue("VisualStudioVersion"));

                MockLogger logger = new MockLogger();
                List<ILogger> loggers = new List<ILogger>(1);
                loggers.Add(logger);


                instances[0].Build(loggers);
                logger.AssertLogContains(String.Format(".[{0}].", ObjectModelHelpers.MSBuildDefaultToolsVersion));
            }
            finally
            {
                ObjectModelHelpers.DeleteTempProjectDirectory();
            }
        }
        public void CustomToolsVersionIsHonored()
        {
            Environment.SetEnvironmentVariable("MSBUILDTREATALLTOOLSVERSIONSASCURRENT", String.Empty);
            try
            {
                string content = @"<Project ToolsVersion=""14.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
    <Target Name=""a"">
        <Message Text=""[$(MSBUILDTOOLSVERSION)]"" />
    </Target>
</Project>
";
                string projectPath = Path.GetTempFileName();
                File.WriteAllText(projectPath, content);

                ProjectCollection p = new ProjectCollection();
                MockLogger mockLogger = new MockLogger();
                LoggingService service = (LoggingService)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1);
                service.RegisterLogger(mockLogger);

                Toolset source = p.GetToolset("14.0");
                Toolset potato = new Toolset("potato", source.ToolsPath, ProjectCollection.GlobalProjectCollection, source.ToolsPath);
                p.AddToolset(potato);

                bool success = false;
                Project project = p.LoadProject(projectPath, "potato");
                success = project.Build(mockLogger);

                Assert.IsTrue(success);
                mockLogger.AssertLogContains("[potato]");
            }
            finally
            {
                // Nothing
            }
        }
        public void ImportFromExtensionsPathSearchOrder2()
        {
            string extnTargetsFileContent1 = @"
                <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                    <PropertyGroup>
                        <PropertyFromExtn1>FromFirstFile</PropertyFromExtn1>
                    </PropertyGroup>

                    <Target Name='FromExtn'>
                        <Message Text='Running FromExtn'/>
                    </Target>
                </Project>
                ";

            string extnTargetsFileContent2 = @"
                <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                    <PropertyGroup>
                        <PropertyFromExtn1>FromSecondFile</PropertyFromExtn1>
                    </PropertyGroup>

                    <Target Name='FromExtn'>
                        <Message Text='Running FromExtn'/>
                    </Target>
                </Project>
                ";

            // File with the same name available in two different extension paths, but the one from the first
            // directory in MSBuildExtensionsPath environment variable should get loaded
            string extnDir1        = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent1);
            string extnDir2        = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("foo", "extn.proj"), extnTargetsFileContent2);
            string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());

            // MSBuildExtensionsPath* property value has highest priority for the lookups
            try {
                var projColln = new ProjectCollection();
                projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", Path.Combine("tmp", "non-existstant"), extnDir1));
                var logger = new MockLogger();
                projColln.RegisterLogger(logger);
                var project = projColln.LoadProject(mainProjectPath);

                project.SetProperty("MSBuildExtensionsPath", extnDir2);
                project.ReevaluateIfNecessary();
                Assert.True(project.Build());

                logger.AssertLogContains("Running FromExtn");
                logger.AssertLogContains("PropertyFromExtn1: FromSecondFile");
            } finally {
                if (mainProjectPath != null)
                {
                    FileUtilities.DeleteNoThrow(mainProjectPath);
                }
                if (extnDir1 != null)
                {
                    FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
                }
                if (extnDir2 != null)
                {
                    FileUtilities.DeleteDirectoryNoThrow(extnDir2, recursive: true);
                }
            }
        }
Exemple #19
0
        public void FailingTaskStillPublishesOutputs()
        {
            MockLogger l = new MockLogger();

            string resx = Path.Combine(Path.GetTempPath(), "FailingTaskStillPublishesOutputs.resx");

            try
            {
                File.WriteAllText(resx, @"
                    <root>
                      <resheader name=""resmimetype"">
                        <value>text/microsoft-resx</value>
                      </resheader>
                      <resheader name=""version"">
                        <value>2.0</value>
                      </resheader>
                      <resheader name=""reader"">
                        <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
                      </resheader>
                      <resheader name=""writer"">
                        <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
                      </resheader>
                      <data name=""a"">
                        <value>aa</value>
                      </data>
                      <data name=""b"">
                        <value>bb</value>
                      </data>
                    </root>");

                Project project = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"
                    <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> 
                        <Target Name='Build'>
                            
                            <GenerateResource
                                ExecuteAsTool='false'
                                Sources='" + resx + @"'
                                StronglyTypedLanguage='!@:|'>
                                    <Output TaskParameter='FilesWritten' ItemName='FilesWrittenItem'/>
                                    <Output TaskParameter='FilesWritten' PropertyName='FilesWrittenProperty'/>
                            </GenerateResource>
                                               
                            <OnError ExecuteTargets='ErrorTarget'/>
                        </Target>

                        <Target Name='ErrorTarget'>    
                            <Message Text='[@(fileswrittenitem)]'/>
                            <Message Text='[$(fileswrittenproperty)]'/>
                        </Target>
                    </Project>"))));

                ProjectInstance p = project.CreateProjectInstance();
                p.Build(new string[] { "Build" }, new ILogger[] { l });

                string resource = Path.ChangeExtension(resx, ".resources");

                Assert.Equal(1, l.ErrorCount); // "Expected one error because 'Build' failed."
                l.AssertLogContains("[" + resource + "]", "[" + resource + "]");

                // And outputs are visible at the project level
                Assert.Equal(resource, Helpers.MakeList(p.GetItems("FilesWrittenItem"))[0].EvaluatedInclude);
                Assert.Equal(resource, p.GetPropertyValue("FilesWrittenProperty"));

                p = project.CreateProjectInstance();

                // But are gone after resetting of course
                Assert.Empty(Helpers.MakeList(p.GetItems("FilesWrittenItem")));
                Assert.Equal(String.Empty, p.GetPropertyValue("FilesWrittenProperty"));
            }
            finally
            {
                File.Delete(resx);
            }
        }
        public void SkippedTargetsShouldOnlyInferOutputsOnce()
        {
            MockLogger logger = new MockLogger();

            string path = FileUtilities.GetTemporaryFile();

            Thread.Sleep(100);

            string content = String.Format
                (
@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>

  <Target Name='Build' DependsOnTargets='GFA;GFT;DFTA;GAFT'>
        <Message Text='Build: [@(Outs)]' />
  </Target>


  <Target Name='GFA' Inputs='{0}' Outputs='{0}'>
        <Message Text='GFA' />
        <CreateItem Include='GFA'>
        	<Output TaskParameter='Include' ItemName='Outs' />
        </CreateItem>
  </Target>
  <Target Name='GFT'  Inputs='{0}' Outputs='{0}'>
        <CreateItem Include='GFT'>
            <Output TaskParameter='Include' ItemName='Outs' />
        </CreateItem>
        <Message Text='GFT' />
  </Target>
  <Target Name='DFTA'  Inputs='{0}' Outputs='{0}'>
        <CreateItem Include='DFTA'>
            <Output TaskParameter='Include' ItemName='Outs' />
        </CreateItem>
        <Message Text='DFTA' />
  </Target>
  <Target Name='GAFT'  Inputs='{0}' Outputs='{0}' DependsOnTargets='DFTA'>
        <CreateItem Include='GAFT'>
            <Output TaskParameter='Include' ItemName='Outs' />
        </CreateItem>
        <Message Text='GAFT' />
  </Target>
</Project>
            ",
             path
             );

            Project p = new Project(XmlReader.Create(new StringReader(content)));
            p.Build(new string[] { "Build" }, new ILogger[] { logger });

            // There should be no duplicates in the list - if there are, then skipped targets are being inferred multiple times
            logger.AssertLogContains("[GFA;GFT;DFTA;GAFT]");

            File.Delete(path);
        }
Exemple #21
0
        public void VerifyNewLinesAndTabsEvaluateToEmpty()
        {
            MockLogger mockLogger = new MockLogger();

            string projectFileContent = ObjectModelHelpers.CleanupFileContents(@"
                    <Project xmlns='msbuildnamespace'>
                       <PropertyGroup><NewLine>" + Environment.NewLine + Environment.NewLine + "</NewLine></PropertyGroup>" +
                       "<PropertyGroup><Tab>\t\t\t\t</Tab></PropertyGroup>" +
                       "<PropertyGroup><CarriageReturn>\r\r\r\r</CarriageReturn></PropertyGroup>" +
                        @"<PropertyGroup><Message1 Condition =""'$(NewLine)' == ''"">NewLineEvalAsEmpty</Message1></PropertyGroup>
                        <PropertyGroup><Message2 Condition =""'$(Tab)' == ''"">TabEvalAsEmpty</Message2></PropertyGroup>
                        <PropertyGroup><Message3 Condition =""'$(CarriageReturn)' == ''"">CarriageReturnEvalAsEmpty</Message3></PropertyGroup>

                        <Target Name=""BUild"">
                           <Message Text=""$(Message1)"" Importance=""High""/>
                          <Message Text=""$(Message2)"" Importance=""High""/>
                          <Message Text=""$(Message3)"" Importance=""High""/>
                       </Target>                    
                    </Project>");

            ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent)));
            Project project = new Project(xml);
            bool result = project.Build(new ILogger[] { mockLogger });
            Assert.Equal(true, result);
            mockLogger.AssertLogContains("NewLineEvalAsEmpty");
            mockLogger.AssertLogContains("TabEvalAsEmpty");
            mockLogger.AssertLogContains("CarriageReturnEvalAsEmpty");
        }
Exemple #22
0
        public void ImportSelfIgnored()
        {
            string file = null;

            try
            {
                ProjectCollection collection = new ProjectCollection();
                MockLogger logger = new MockLogger();
                collection.RegisterLogger(logger);

                Project project = new Project(collection);
                project.Xml.AddImport("$(MSBuildProjectFullPath)");

                file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                project.Save(file);
                project.ReevaluateIfNecessary();

                logger.AssertLogContains("MSB4210"); // selfimport
            }
            finally
            {
                File.Delete(file);
            }
        }
        public void Build()
        {
            string projectFileContent = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
                        <UsingTask TaskName='Microsoft.Build.Tasks.Message' AssemblyFile='Microsoft.Build.Tasks.Core.dll'/>
                        <ItemGroup>
                            <i Include='i0'/>
                        </ItemGroup>
                        <Target Name='Build'>
                            <Message Text='Building...'/>
                            <Message Text='Completed!'/>
                        </Target>
                    </Project>";

            ProjectInstance projectInstance = GetProjectInstance(projectFileContent);
            List<ILogger> loggers = new List<ILogger>();
            MockLogger mockLogger = new MockLogger(_output);
            loggers.Add(mockLogger);
            bool success = projectInstance.Build("Build", loggers);

            Assert.True(success);
            mockLogger.AssertLogContains(new string[] { "Building...", "Completed!" });
        }
Exemple #24
0
        public void DoNotCrashOnInvalidFormatExpression()
        {
            string content = @"
 <Project DefaultTargets=`t` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
   <UsingTask
     TaskName=`Crash`
     TaskFactory=`CodeTaskFactory`
     AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` >
     <Task>
       <Code Type=`Fragment` Language=`cs`>
         this.Log.LogError(`Correct: {0}`, `[goodone]`);
         this.Log.LogError(`This is a message logged from a task {1} blah blah [crashing].`, `[crasher]`); 

            try
            {
                this.Log.LogError(`Correct: {0}`, 4224);
                this.Log.LogError(`Malformed: {1}`, 42); // Line 13
                throw new InvalidOperationException();
            }
            catch (Exception e)
            {
                this.Log.LogError(`Catching: {0}`, e.GetType().Name);
            }
            finally
            {
                this.Log.LogError(`Finally`);
            }

            try
            {
                this.Log.LogError(`Correct: {0}`, 4224);
                throw new InvalidOperationException();
            }
            catch (Exception e)
            {
                this.Log.LogError(`Catching: {0}`, e.GetType().Name);
                this.Log.LogError(`Malformed: {1}`, 42); // Line 19
            }
            finally
            {
                this.Log.LogError(`Finally`);
            }

            try
            {
                this.Log.LogError(`Correct: {0}`, 4224);
                throw new InvalidOperationException();
            }
            catch (Exception e)
            {
                this.Log.LogError(`Catching: {0}`, e.GetType().Name);
            }
            finally
            {
                this.Log.LogError(`Finally`);
                this.Log.LogError(`Malformed: {1}`, 42); // Line 24
            }

       </Code>
     </Task>
   </UsingTask>

        <Target Name=`t`>
             <Crash />
        </Target>
</Project>
                ";

            MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content);

            log.AssertLogContains("[goodone]");
            log.AssertLogContains("[crashing]");
        }
Exemple #25
0
        public void UndefinedAndEmptyMetadataValues()
        {
            string content = @"
                <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
                    <ItemGroup>
                        <i Include='i1'/>
                        <i Include='i2'>
                            <m></m>
                        </i>
                        <i Include='i3'>
                            <m>m1</m>
                        </i>
                    </ItemGroup>

                    <Target Name='Build'>
                        <Message Text='[@(i) %(i.m)]'/>
                    </Target>

                </Project>
                ";

            Project project = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(content))));
            MockLogger logger = new MockLogger();
            project.Build(logger);

            logger.AssertLogContains("[i1;i2 ]", "[i3 m1]");
        }
Exemple #26
0
        public void OneSubmissionTwoLoggers()
        {
            string projectBody = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
    <Target Name='Test'>
        <Message Text='Foo'/>
        <Error Text='Error'/>
    </Target>
</Project>
");
            ProjectInstance project = (new Project(XmlReader.Create(new StringReader(projectBody)))).CreateProjectInstance();

            BuildManager buildManager = BuildManager.DefaultBuildManager;
            MuxLogger muxLogger = new MuxLogger();
            BuildParameters parameters = new BuildParameters(ProjectCollection.GlobalProjectCollection);
            parameters.Loggers = new ILogger[] { muxLogger };
            MockLogger mockLogger1 = new MockLogger();
            MockLogger mockLogger2 = new MockLogger();
            buildManager.BeginBuild(parameters);
            try
            {
                BuildSubmission submission = buildManager.PendBuildRequest(new BuildRequestData(project, new string[0], null));

                muxLogger.RegisterLogger(submission.SubmissionId, mockLogger1);
                muxLogger.RegisterLogger(submission.SubmissionId, mockLogger2);
                submission.Execute();
            }
            finally
            {
                buildManager.EndBuild();
            }

            mockLogger1.AssertLogContains("Foo");
            mockLogger1.AssertLogContains("Error");
            Assert.Equal(1, mockLogger1.ErrorCount);
            mockLogger1.AssertNoWarnings();

            mockLogger2.AssertLogContains("Foo");
            mockLogger2.AssertLogContains("Error");
            Assert.Equal(1, mockLogger2.ErrorCount);
            mockLogger2.AssertNoWarnings();

            Assert.Equal(mockLogger1.FullLog, mockLogger2.FullLog);
        }
        public void InvalidToolsVersionFromEnvironmentVariable_ProjectInstance()
        {
            string oldDefaultToolsVersion = Environment.GetEnvironmentVariable("MSBUILDDEFAULTTOOLSVERSION");

            try
            {
                Environment.SetEnvironmentVariable("MSBUILDDEFAULTTOOLSVERSION", "foo");
                InternalUtilities.RefreshInternalEnvironmentValues();

                ProjectCollection p = new ProjectCollection();
                MockLogger mockLogger = new MockLogger();
                LoggingService service = (LoggingService)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1);
                service.RegisterLogger(mockLogger);

                bool success = false;
                Project project = new Project(XmlReader.Create(new StringReader(@"<Project ToolsVersion='4.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
                    <Target Name='Foo'>
                    </Target>
                   </Project>")), null /* no global properties */, null /* don't explicitly set the toolsversion */, p);

                ProjectInstance pi = new ProjectInstance(project.Xml, null /* no global properties */, null /* don't explicitly set the toolsversion */, p);
                success = pi.Build(new ILogger[] { mockLogger });

                Assert.IsTrue(success);
                mockLogger.AssertLogContains("ToolsVersion=\"4.0\"");
                // falls back to the current ToolsVersion
                mockLogger.AssertLogContains(ObjectModelHelpers.CleanupFileContents("ToolsVersion=\"msbuilddefaulttoolsversion\""));
            }
            finally
            {
                Environment.SetEnvironmentVariable("MSBUILDDEFAULTTOOLSVERSION", oldDefaultToolsVersion);
                InternalUtilities.RefreshInternalEnvironmentValues();
            }
        }
        public void BatchingConsidersItemDefinitionMetadata()
        {
            string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
  <ItemDefinitionGroup>
    <i>
      <m>m1</m>
    </i>
  </ItemDefinitionGroup>
  <ItemGroup>
    <i Include='a.foo;a.bar'/>
  </ItemGroup>
  <Target Name='t'>
    <Message Text='@(i)/%(m)'/>
  </Target>
</Project>");

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

            MockLogger logger = new MockLogger();
            List<ILogger> loggers = new List<ILogger>() { logger };
            Assert.Equal(true, project.Build(loggers));

            logger.AssertLogContains("a.foo;a.bar/m1");
            logger.AssertNoErrors();
            logger.AssertNoWarnings();
        }
        public void ToolsVersionFallbackIfCurrentToolsVersionDoesNotExist_ProjectInstance()
        {
            ProjectCollection p = new ProjectCollection();
            p.RemoveToolset(ObjectModelHelpers.MSBuildDefaultToolsVersion);

            MockLogger mockLogger = new MockLogger();
            LoggingService service = (LoggingService)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1);
            service.RegisterLogger(mockLogger);

            bool success = false;
            Project project = new Project(XmlReader.Create(new StringReader(@"<Project ToolsVersion='4.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
                    <Target Name='Foo'>
                    </Target>
                   </Project>")), null /* no global properties */, null /* don't explicitly set the toolsversion */, p);

            ProjectInstance pi = new ProjectInstance(project.Xml, null /* no global properties */, null /* don't explicitly set the toolsversion */, p);
            Assert.AreEqual("4.0", pi.ToolsVersion);
            success = pi.Build(new ILogger[] { mockLogger });

            Assert.IsTrue(success);
            mockLogger.AssertLogContains("\"4.0\"");
            mockLogger.AssertLogDoesntContain(ObjectModelHelpers.CleanupFileContents("\"msbuilddefaulttoolsversion\""));
        }
        public void TasksNotDiscoveredWhenTaskConditionFalse()
        {
            MockLogger logger = new MockLogger();
            string projectFileContents = ObjectModelHelpers.CleanupFileContents(
                @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                      <Target Name='t'>
                         <NonExistantTask Condition=""'1'=='2'""/>
                         <Message Text='Made it'/>                    
                      </Target>
                      </Project>");

            Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
            List<ILogger> loggers = new List<ILogger>();
            loggers.Add(logger);
            project.Build("t", loggers);

            logger.AssertLogContains("Made it");
        }
Exemple #31
0
        public void ReservedPropertyProjectCollectionConstructor3()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                Dictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                globalProperties.Add("Target", "x");
                MockLogger logger = new MockLogger();
                List<ILogger> loggers = new List<ILogger>();
                loggers.Add(logger);

                try
                {
                    ProjectCollection collection = new ProjectCollection(globalProperties, loggers, ToolsetDefinitionLocations.None);
                }
                finally
                {
                    logger.AssertLogContains("MSB4177");
                }
            }
           );
        }
        public void OverridePropertiesInInferredCreateProperty()
        {
            string[] files = null;
            try
            {
                files = ObjectModelHelpers.GetTempFiles(2, new DateTime(2005, 1, 1));

                MockLogger logger = new MockLogger();
                string projectFileContents = ObjectModelHelpers.CleanupFileContents(
                    @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                      <ItemGroup>
                        <i Include='" + files[0] + "'><output>" + files[1] + @"</output></i>
                      </ItemGroup> 
                      <ItemGroup>
                         <EmbeddedResource Include='a.resx'>
                        <LogicalName>foo</LogicalName>
                          </EmbeddedResource>
                            <EmbeddedResource Include='b.resx'>
                            <LogicalName>bar</LogicalName>
                        </EmbeddedResource>
                            <EmbeddedResource Include='c.resx'>
                            <LogicalName>barz</LogicalName>
                        </EmbeddedResource>
                        </ItemGroup>
                      <Target Name='t2' DependsOnTargets='t'>
                        <Message Text='final:[$(LinkSwitches)]'/>   
                      </Target>
                      <Target Name='t' Inputs='%(i.Identity)' Outputs='%(i.Output)'>
                        <Message Text='start:[Hello]'/>
                        <CreateProperty Value=""@(EmbeddedResource->'/assemblyresource:%(Identity),%(LogicalName)', ' ')""
                                         Condition=""'%(LogicalName)' != '' "">
                             <Output TaskParameter=""Value"" PropertyName=""LinkSwitches""/>
                        </CreateProperty>
                        <Message Text='end:[hello]'/>                    
                    </Target>
                    </Project>");

                Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
                List<ILogger> loggers = new List<ILogger>();
                loggers.Add(logger);
                project.Build("t2", loggers);

                // We should only see messages from the second target, as the first is only inferred
                logger.AssertLogDoesntContain("start:");
                logger.AssertLogDoesntContain("end:");

                logger.AssertLogContains(new string[] { "final:[/assemblyresource:c.resx,barz]" });
                logger.AssertLogDoesntContain(ResourceUtilities.FormatResourceString("TaskStarted", "CreateProperty"));
                logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceString("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:a.resx,foo", "/assemblyresource:b.resx,bar") });
                logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceString("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:b.resx,bar", "/assemblyresource:c.resx,barz") });
            }
            finally
            {
                ObjectModelHelpers.DeleteTempFiles(files);
            }
        }
Exemple #33
0
        public void DoubleImportIndirectIgnored()
        {
            string file = null;
            string file2 = null;
            string file3 = null;

            try
            {
                ProjectCollection collection = new ProjectCollection();
                MockLogger logger = new MockLogger();
                collection.RegisterLogger(logger);

                file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                file2 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                file3 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();

                Project project = new Project(collection);
                project.Xml.AddImport(file2);
                project.Xml.AddImport(file3);
                project.Save(file);

                Project project2 = new Project(collection);
                project.Xml.AddImport(file3);
                project2.Save(file2);

                Project project3 = new Project(collection);
                project3.Save(file3);

                project.ReevaluateIfNecessary();

                logger.AssertLogContains("MSB4011"); // duplicate import
            }
            finally
            {
                File.Delete(file);
                File.Delete(file2);
                File.Delete(file3);
            }
        }
        public void MSBuildLastTaskResult()
        {
            string projectFileContents = ObjectModelHelpers.CleanupFileContents(@"
<Project DefaultTargets='t2' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
    <Target Name='t'>
        <Message Text='[start:$(MSBuildLastTaskResult)]'/> <!-- Should be blank -->
        <Warning Text='warning'/>
        <Message Text='[0:$(MSBuildLastTaskResult)]'/> <!-- Should be true, only a warning-->
        <!-- task's Execute returns false -->
        <Copy SourceFiles='|' DestinationFolder='c:\' ContinueOnError='true' />
        <PropertyGroup>
           <p>$(MSBuildLastTaskResult)</p>
        </PropertyGroup>                 
        <Message Text='[1:$(MSBuildLastTaskResult)]'/> <!-- Should be false: propertygroup did not reset it -->   
        <Message Text='[p:$(p)]'/> <!-- Should be false as stored earlier -->   
        <Message Text='[2:$(MSBuildLastTaskResult)]'/> <!-- Message succeeded, should now be true -->
    </Target>
    <Target Name='t2' DependsOnTargets='t'>
        <Message Text='[3:$(MSBuildLastTaskResult)]'/> <!-- Should still have true -->
        <!-- check Error task as well -->
        <Error Text='error' ContinueOnError='true' />
        <Message Text='[4:$(MSBuildLastTaskResult)]'/> <!-- Should be false -->
        <!-- trigger OnError target, ContinueOnError is false -->
        <Error Text='error2'/>
        <OnError ExecuteTargets='t3'/>
    </Target>
    <Target Name='t3' >
        <Message Text='[5:$(MSBuildLastTaskResult)]'/> <!-- Should be false -->
    </Target>
</Project>");

            Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
            List<ILogger> loggers = new List<ILogger>();
            MockLogger logger = new MockLogger();
            loggers.Add(logger);
            project.Build("t2", loggers);

            logger.AssertLogContains("[start:]");
            logger.AssertLogContains("[0:true]");
            logger.AssertLogContains("[1:false]");
            logger.AssertLogContains("[p:false]");
            logger.AssertLogContains("[2:true]");
            logger.AssertLogContains("[3:true]");
            logger.AssertLogContains("[4:false]");
            logger.AssertLogContains("[4:false]");
        }
Exemple #35
0
        public void LogWithLoggersOnProjectCollection()
        {
            MockLogger mockLogger = new MockLogger();

            string projectFileContent = ObjectModelHelpers.CleanupFileContents(@"
                    <Project xmlns='msbuildnamespace'>
                      <Target Name=""BUild"">
                           <Message Text=""IHaveBeenLogged"" Importance=""High""/>
                       </Target>                    
                    </Project>");

            ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent)));
            ProjectCollection collection = new ProjectCollection();
            collection.RegisterLogger(mockLogger);
            Project project = new Project(xml, null, null, collection);

            bool result = project.Build();
            Assert.Equal(true, result);
            mockLogger.AssertLogContains("IHaveBeenLogged");
        }
        public void IllegalFileCharsInItemsOutOfTask()
        {
            MockLogger logger = new MockLogger();
            string projectFileContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t'>
 <PropertyGroup>
   <p>||illegal||</p>
 </PropertyGroup>
 <CreateItem Include='$(p)'>
   <Output TaskParameter='Include' ItemName='x' />
 </CreateItem>
 <Message Text='[@(x)]'/>
</Target>
</Project>");

            Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
            List<ILogger> loggers = new List<ILogger>();
            loggers.Add(logger);
            bool result = project.Build("t", loggers);

            Assert.AreEqual(true, result);
            logger.AssertLogContains("[||illegal||]");
        }
Exemple #37
0
        // Ignore: Changes to the current directory interfere with the toolset reader.
        public void SquareBracketEscaping()
        {
            string projectFile = @"
                      <Project ToolsVersion=`msbuilddefaulttoolsversion` DefaultTargets=`XamlTaskFactory` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
                        <UsingTask TaskName=`TestTask` TaskFactory=`XamlTaskFactory` AssemblyName=`Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`>
                          <Task>
                            <![CDATA[
                              <ProjectSchemaDefinitions xmlns=`clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework` xmlns:x=`http://schemas.microsoft.com/winfx/2006/xaml` xmlns:sys=`clr-namespace:System;assembly=mscorlib` xmlns:impl=`clr-namespace:Microsoft.VisualStudio.Project.Contracts.Implementation;assembly=Microsoft.VisualStudio.Project.Contracts.Implementation`>
                                <Rule Name=`TestTask` ToolName=`echoparameters.exe`>
                                  <StringProperty Name=`test` />
                                </Rule>
                              </ProjectSchemaDefinitions>
                            ]]>
                          </Task>
                        </UsingTask>
                        <Target Name=`XamlTaskFactory`>
                          <TestTask CommandLineTemplate=`echo  1) [test]            end` test=`value` />
                          <TestTask CommandLineTemplate=`echo  2) [[[test]           end` test=`value` />
                          <TestTask CommandLineTemplate=`echo  3) [ [test]          end` test=`value` />
                          <TestTask CommandLineTemplate=`echo  4) [ [test] [test]    end` test=`value` />
                          <TestTask CommandLineTemplate=`echo  5) [test]]           end` test=`value` />
                          <TestTask CommandLineTemplate=`echo  6) [[test]]          end` test=`value` />
                          <TestTask CommandLineTemplate=`echo  7) [[[test]]          end` test=`value` />
                          <TestTask CommandLineTemplate=`echo  8) [notaproperty]   end` test=`value` />
                          <TestTask CommandLineTemplate=`echo  9) [[[notaproperty]  end` test=`value` />
                          <TestTask CommandLineTemplate=`echo 10) [ [notaproperty] end` test=`value` />
                          <TestTask CommandLineTemplate=`echo 11) [ [nap] [nap]    end` test=`value` />
                          <TestTask CommandLineTemplate=`echo 12) [notaproperty]]  end` test=`value` />
                          <TestTask CommandLineTemplate=`echo 13) [[notaproperty]]  end` test=`value` />
                          <TestTask CommandLineTemplate=`echo 14) [[[notaproperty]] end` test=`value` />
                        </Target>
                      </Project>";

            Project    p      = ObjectModelHelpers.CreateInMemoryProject(projectFile);
            MockLogger logger = new MockLogger();

            bool success = p.Build(logger);

            Assert.IsTrue(success, "Build should have succeeded");

            logger.AssertLogContains("echo  1) value            end");
            logger.AssertLogContains("echo  2) [value           end");
            logger.AssertLogContains("echo  3) [ value          end");
            logger.AssertLogContains("echo  4) [ value value    end");
            logger.AssertLogContains("echo  5) value]           end");
            logger.AssertLogContains("echo  6) [test]]          end");
            logger.AssertLogContains("echo  7) [value]          end");
            logger.AssertLogContains("echo  8) [notaproperty]   end");
            logger.AssertLogContains("echo  9) [[notaproperty]  end");
            logger.AssertLogContains("echo 10) [ [notaproperty] end");
            logger.AssertLogContains("echo 11) [ [nap] [nap]    end");
            logger.AssertLogContains("echo 12) [notaproperty]]  end");
            logger.AssertLogContains("echo 13) [notaproperty]]  end");
            logger.AssertLogContains("echo 14) [[notaproperty]] end");
        }
        public void OverrideTaskPathHasInvalidChars()
        {
            ProjectCollection e = new ProjectCollection();
            Toolset t = new Toolset("toolsversionname", "c:\\directory1\\directory2", new PropertyDictionary<ProjectPropertyInstance>(), new ProjectCollection(), new DirectoryGetFiles(this.getFiles), new LoadXmlFromPath(this.loadXmlFromPath), "k:\\||^%$#*msbuildoverridetasks", new DirectoryExists(this.directoryExists));

            MockLogger mockLogger = new MockLogger();
            LoggingService service = (LoggingService)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1);
            service.RegisterLogger(mockLogger);

            TaskRegistry taskoverrideRegistry = (TaskRegistry)t.GetOverrideTaskRegistry(service, new BuildEventContext(1, 2, BuildEventContext.InvalidProjectContextId, 4), e.ProjectRootElementCache);
            Assert.IsNotNull(taskoverrideRegistry);
            Assert.IsTrue(taskoverrideRegistry.TaskRegistrations.Count == 0);
            mockLogger.AssertLogContains("MSB4194");
        }
        public void OverridePropertiesInCreateProperty()
        {
            MockLogger logger = new MockLogger();
            string projectFileContents = ObjectModelHelpers.CleanupFileContents(
                @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                      <ItemGroup>
                         <EmbeddedResource Include='a.resx'>
                            <LogicalName>foo</LogicalName>
                         </EmbeddedResource>
                         <EmbeddedResource Include='b.resx'>
                            <LogicalName>bar</LogicalName>
                         </EmbeddedResource>
                         <EmbeddedResource Include='c.resx'>
                            <LogicalName>barz</LogicalName>
                         </EmbeddedResource>
                      </ItemGroup>
                      <Target Name='t'>
                         <CreateProperty Value=""@(EmbeddedResource->'/assemblyresource:%(Identity),%(LogicalName)', ' ')""
                                         Condition=""'%(LogicalName)' != '' "">
                             <Output TaskParameter=""Value"" PropertyName=""LinkSwitches""/>
                         </CreateProperty>
                         <Message Text='final:[$(LinkSwitches)]'/>                    
                      </Target>
                      </Project>");

            Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
            List<ILogger> loggers = new List<ILogger>();
            loggers.Add(logger);
            project.Build("t", loggers);

            logger.AssertLogContains(new string[] { "final:[/assemblyresource:c.resx,barz]" });
            logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceString("TaskStarted", "CreateProperty") });
            logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceString("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:a.resx,foo", "/assemblyresource:b.resx,bar") });
            logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceString("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:b.resx,bar", "/assemblyresource:c.resx,barz") });
        }
        public void ExpandExtensionsPathFallbackInErrorMessage()
        {
            string extnTargetsFileContentTemplate = @"
                <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                    <Target Name='FromExtn'>
                        <Message Text='Running FromExtn'/>
                    </Target>
                    <Import Project='$(MSBuildExtensionsPath)\\foo\\extn2.proj' Condition=""Exists('$(MSBuildExtensionsPath)\foo\extn.proj')"" />
                </Project>";

            var configFileContents = @"
                 <configuration>
                   <configSections>
                     <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
                   </configSections>
                   <msbuildToolsets default=""14.1"">
                     <toolset toolsVersion=""14.1"">
                       <property name=""MSBuildToolsPath"" value="".""/>
                       <property name=""MSBuildBinPath"" value="".""/>
                       <projectImportSearchPaths>
                         <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
                           <property name=""MSBuildExtensionsPath"" value=""$(FallbackExpandDir1)"" />
                         </searchPaths>
                       </projectImportSearchPaths>
                      </toolset>
                   </msbuildToolsets>
                 </configuration>";

            string extnDir1        = null;
            string mainProjectPath = null;

            try
            {
                extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"),
                                                             extnTargetsFileContentTemplate);

                mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj",
                                                                                      GetMainTargetFileContent());

                ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents);
                var reader = GetStandardConfigurationReader();

                var projectCollection = new ProjectCollection(new Dictionary <string, string> {
                    ["FallbackExpandDir1"] = extnDir1
                });

                projectCollection.ResetToolsetsForTests(reader);
                var logger = new MockLogger();
                projectCollection.RegisterLogger(logger);

                Assert.Throws <InvalidProjectFileException>(() => projectCollection.LoadProject(mainProjectPath));

                // Expanded $(FallbackExpandDir) will appear in quotes in the log
                logger.AssertLogContains("\"" + extnDir1 + "\"");
            }
            finally
            {
                FileUtilities.DeleteNoThrow(mainProjectPath);
                FileUtilities.DeleteDirectoryNoThrow(extnDir1, true);
            }
        }
        public void TaskOutputBatching()
        {
            MockLogger logger = new MockLogger();
            string projectFileContents = ObjectModelHelpers.CleanupFileContents(@"
                <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
                    <ItemGroup>
                        <TaskParameterItem Include=""foo"">
                            <ParameterName>Value</ParameterName>
                            <ParameterName2>Include</ParameterName2>
                            <PropertyName>MetadataProperty</PropertyName>
                            <ItemType>MetadataItem</ItemType>
                        </TaskParameterItem>
                    </ItemGroup>
                    <Target Name='Build'>
                        <CreateProperty Value=""@(TaskParameterItem)"">
                            <Output TaskParameter=""Value"" PropertyName=""Property1""/>
                        </CreateProperty> 
                        <Message Text='Property1=[$(Property1)]' />

                        <CreateProperty Value=""@(TaskParameterItem)"">
                            <Output TaskParameter=""%(TaskParameterItem.ParameterName)"" PropertyName=""Property2""/>
                        </CreateProperty> 
                        <Message Text='Property2=[$(Property2)]' />

                        <CreateProperty Value=""@(TaskParameterItem)"">
                            <Output TaskParameter=""Value"" PropertyName=""%(TaskParameterItem.PropertyName)""/>
                        </CreateProperty> 
                        <Message Text='MetadataProperty=[$(MetadataProperty)]' />

                        <CreateItem Include=""@(TaskParameterItem)"">
                            <Output TaskParameter=""Include"" ItemName=""TestItem1""/>
                        </CreateItem>
                        <Message Text='TestItem1=[@(TestItem1)]' />

                        <CreateItem Include=""@(TaskParameterItem)"">
                            <Output TaskParameter=""%(TaskParameterItem.ParameterName2)"" ItemName=""TestItem2""/>
                        </CreateItem>
                        <Message Text='TestItem2=[@(TestItem2)]' />

                        <CreateItem Include=""@(TaskParameterItem)"">
                            <Output TaskParameter=""Include"" ItemName=""%(TaskParameterItem.ItemType)""/>
                        </CreateItem>
                        <Message Text='MetadataItem=[@(MetadataItem)]' />
                    </Target>
                </Project>");

            Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
            List<ILogger> loggers = new List<ILogger>();
            loggers.Add(logger);
            project.Build(loggers);

            logger.AssertLogContains("Property1=[foo]");
            logger.AssertLogContains("Property2=[foo]");
            logger.AssertLogContains("MetadataProperty=[foo]");
            logger.AssertLogContains("TestItem1=[foo]");
            logger.AssertLogContains("TestItem2=[foo]");
            logger.AssertLogContains("MetadataItem=[foo]");
        }
        public void BadFrameworkMonkierExpectBuildToFail2()
        {
            string tmpFileName = FileUtilities.GetTemporaryFile();
            File.Delete(tmpFileName);
            string projectFilePath = tmpFileName + ".sln";

            string solutionFileContents =
                            @"Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project('{E24C65DC-7377-472B-9ABA-BC803B73C61A}') = 'WebSite1', '..\WebSite1\', '{6B8F98F2-C976-4029-9321-5CCD73A174DA}'
	ProjectSection(WebsiteProperties) = preProject
		TargetFrameworkMoniker = 'Oscar the grouch'
		Debug.AspNetCompiler.VirtualPath = '/WebSite1'
		Debug.AspNetCompiler.PhysicalPath = '..\WebSite1\'
		Debug.AspNetCompiler.TargetPath = 'PrecompiledWeb\WebSite1\'
		Debug.AspNetCompiler.Updateable = 'true'
		Debug.AspNetCompiler.ForceOverwrite = 'true'
		Debug.AspNetCompiler.FixedNames = 'false'
		Debug.AspNetCompiler.Debug = 'True'
		Release.AspNetCompiler.VirtualPath = '/WebSite1'
		Release.AspNetCompiler.PhysicalPath = '..\WebSite1\'
		Release.AspNetCompiler.TargetPath = 'PrecompiledWeb\WebSite1\'
		Release.AspNetCompiler.Updateable = 'true'
		Release.AspNetCompiler.ForceOverwrite = 'true'
		Release.AspNetCompiler.FixedNames = 'false'
		Release.AspNetCompiler.Debug = 'False'
		VWDPort = '45602'
		DefaultWebSiteLanguage = 'Visual Basic'
	EndProjectSection
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{6B8F98F2-C976-4029-9321-5CCD73A174DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{6B8F98F2-C976-4029-9321-5CCD73A174DA}.Debug|Any CPU.Build.0 = Debug|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal
                ";

            BuildManager buildManager = null;

            try
            {
                // Since we're creating our own BuildManager, we need to make sure that the default 
                // one has properly relinquished the inproc node
                NodeProviderInProc nodeProviderInProc = ((IBuildComponentHost)BuildManager.DefaultBuildManager).GetComponent(BuildComponentType.InProcNodeProvider) as NodeProviderInProc;
                if (nodeProviderInProc != null)
                {
                    nodeProviderInProc.Dispose();
                }

                File.WriteAllText(projectFilePath, solutionFileContents.Replace('\'', '"'));
                MockLogger logger = new MockLogger();

                BuildParameters parameters = new BuildParameters();
                parameters.Loggers = new ILogger[] { logger };
                parameters.EnableNodeReuse = false;
                parameters.ShutdownInProcNodeOnBuildFinish = true;
                buildManager = new BuildManager();


                Dictionary<string, string> globalProperties = new Dictionary<string, string>();
                globalProperties["Configuration"] = "Release";

                BuildRequestData request = new BuildRequestData(projectFilePath, globalProperties, ObjectModelHelpers.MSBuildDefaultToolsVersion, new string[0], null);
                BuildResult result = buildManager.Build(parameters, request);
                Assert.AreEqual(BuildResultCode.Failure, result.OverallResult);
                // Build should complete successfully even with an invalid solution config if SkipInvalidConfigurations is true
                logger.AssertLogContains("MSB4204");
            }
            finally
            {
                File.Delete(projectFilePath);

                if (buildManager != null)
                {
                    NodeProviderInProc nodeProviderInProc = ((IBuildComponentHost)buildManager).GetComponent(BuildComponentType.InProcNodeProvider) as NodeProviderInProc;
                    nodeProviderInProc.Dispose();
                }
            }
        }
        public void OtherBuiltInMetadataErrors2()
        {
            MockLogger logger = new MockLogger();
            string projectFileContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t'>
 <CreateItem Include='Foo' AdditionalMetadata='Extension=1'/>
</Target>
</Project>");

            Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
            List<ILogger> loggers = new List<ILogger>();
            loggers.Add(logger);
            bool result = project.Build("t", loggers);

            Assert.AreEqual(false, result);
            logger.AssertLogContains("MSB3031");
        }
        public void TestTargetFrameworkVersionGreaterThan4()
        {
            string tmpFileName = FileUtilities.GetTemporaryFile();
            File.Delete(tmpFileName);
            string projectFilePath = tmpFileName + ".sln";

            string solutionFileContents =
               @"
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project('{E24C65DC-7377-472B-9ABA-BC803B73C61A}') = 'WebSite1', '..\WebSite1\', '{6B8F98F2-C976-4029-9321-5CCD73A174DA}'
	ProjectSection(WebsiteProperties) = preProject
		TargetFrameworkMoniker = '.NETFramework,Version=v4.34'
		Debug.AspNetCompiler.VirtualPath = '/WebSite1'
		Debug.AspNetCompiler.PhysicalPath = '..\WebSite1\'
		Debug.AspNetCompiler.TargetPath = 'PrecompiledWeb\WebSite1\'
		Debug.AspNetCompiler.Updateable = 'true'
		Debug.AspNetCompiler.ForceOverwrite = 'true'
		Debug.AspNetCompiler.FixedNames = 'false'
		Debug.AspNetCompiler.Debug = 'True'
		Release.AspNetCompiler.VirtualPath = '/WebSite1'
		Release.AspNetCompiler.PhysicalPath = '..\WebSite1\'
		Release.AspNetCompiler.TargetPath = 'PrecompiledWeb\WebSite1\'
		Release.AspNetCompiler.Updateable = 'true'
		Release.AspNetCompiler.ForceOverwrite = 'true'
		Release.AspNetCompiler.FixedNames = 'false'
		Release.AspNetCompiler.Debug = 'False'
		VWDPort = '45602'
		DefaultWebSiteLanguage = 'Visual Basic'
	EndProjectSection
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{6B8F98F2-C976-4029-9321-5CCD73A174DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{6B8F98F2-C976-4029-9321-5CCD73A174DA}.Debug|Any CPU.Build.0 = Debug|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal
                ";

            try
            {
                MockLogger logger = new MockLogger();

                Dictionary<string, string> globalProperties = new Dictionary<string, string>();
                globalProperties["Configuration"] = "Release";
                globalProperties["SkipInvalidConfigurations"] = "true";

                SolutionFile solution = SolutionFile_Tests.ParseSolutionHelper(solutionFileContents.Replace('\'', '"'));
                ProjectCollection collection = new ProjectCollection();
                collection.RegisterLogger(logger);

                ProjectInstance[] instances = SolutionProjectGenerator.Generate(solution, globalProperties, null, BuildEventContext.Invalid, collection.LoggingService);

                Version ver = new Version("4.34");
                string message = ResourceUtilities.FormatResourceString("AspNetCompiler.TargetingHigherFrameworksDefaultsTo40", solution.ProjectsInOrder[0].ProjectName, ver.ToString());
                logger.AssertLogContains(message);
            }
            finally
            {
                File.Delete(projectFilePath);
            }
        }
        /// <summary>
        /// Executes an STA task test.
        /// </summary>
        private void TestSTATask(bool requireSTA, bool failTask, bool throwException)
        {
            MockLogger logger = new MockLogger();
            logger.AllowTaskCrashes = throwException;

            string taskAssemblyName = null;
            Project project = CreateSTATestProject(requireSTA, failTask, throwException, out taskAssemblyName);

            List<ILogger> loggers = new List<ILogger>();
            loggers.Add(logger);

            BuildParameters parameters = new BuildParameters();
            parameters.Loggers = new ILogger[] { logger };
            BuildResult result = BuildManager.DefaultBuildManager.Build(parameters, new BuildRequestData(project.CreateProjectInstance(), new string[] { "Foo" }));
            if (requireSTA)
            {
                logger.AssertLogContains("STA");
            }
            else
            {
                logger.AssertLogContains("MTA");
            }

            if (throwException)
            {
                logger.AssertLogContains("EXCEPTION");
                Assert.AreEqual(BuildResultCode.Failure, result.OverallResult);
                return;
            }
            else
            {
                logger.AssertLogDoesntContain("EXCEPTION");
            }

            if (failTask)
            {
                logger.AssertLogContains("FAIL");
                Assert.AreEqual(BuildResultCode.Failure, result.OverallResult);
            }
            else
            {
                logger.AssertLogDoesntContain("FAIL");
            }

            if (!throwException && !failTask)
            {
                Assert.AreEqual(BuildResultCode.Success, result.OverallResult);
            }
        }
        // Ignore: Changes to the current directory interfere with the toolset reader.
        public void SolutionPassesSubToolsetToChildProjects2()
        {
            string classLibraryContentsToolsV4 = ObjectModelHelpers.CleanupFileContents(
                    @"
                        <Project ToolsVersion=""4.0"" DefaultTargets=""Build"" xmlns='msbuildnamespace'>
                            <Target Name='Build'>
                                <Message Text='.[$(VisualStudioVersion)]. .[$(MSBuildToolsVersion)].' />
                            </Target>
                        </Project>
                    ");

            string classLibraryContentsToolsV12 = ObjectModelHelpers.CleanupFileContents(
                    @"
                        <Project ToolsVersion=""msbuilddefaulttoolsversion"" DefaultTargets=""Build"" xmlns='msbuildnamespace'>
                            <Target Name='Build'>
                                <Message Text='.[$(VisualStudioVersion)]. .[$(MSBuildToolsVersion)].' />
                            </Target>
                        </Project>
                    ");

            string solutionFilePreambleV11 =
                    @"
                        Microsoft Visual Studio Solution File, Format Version 12.00
                        # Visual Studio Dev11
                     ";

            string solutionFilePreambleV12 =
                    @"
                        Microsoft Visual Studio Solution File, Format Version 12.00
                        # Visual Studio Dev11
                        VisualStudioVersion = 12.0.20311.0 VSPRO_PLATFORM
                        MinimumVisualStudioVersion = 10.0.40219.1
                     ";

            string solutionBodySingleProjectContents =
                    @"

                        Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""ClassLibrary1"", ""ClassLibrary1.csproj"", ""{6185CC21-BE89-448A-B3C0-D1C27112E595}""
                        EndProject
                        Global
                            GlobalSection(SolutionConfigurationPlatforms) = preSolution
                                Debug|Mixed Platforms = Debug|Mixed Platforms
                                Release|Any CPU = Release|Any CPU
                            EndGlobalSection
                            GlobalSection(ProjectConfigurationPlatforms) = postSolution
                                {6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.ActiveCfg = CSConfig1|Any CPU
                                {6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.Build.0 = CSConfig1|Any CPU
                                {6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Any CPU.ActiveCfg = CSConfig2|Any CPU
                            EndGlobalSection
                        EndGlobal
                    ";

            string solutionBodyMultipleProjectsContents =
                @"
                    Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""ClassLibrary1"", ""ClassLibrary1.csproj"", ""{A437DBE9-DCAA-46D8-9D80-A50EDB2244FD}""
                    EndProject
                    Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""ClassLibrary2"", ""ClassLibrary2.csproj"", ""{84AA5584-4B0F-41DE-95AA-589E1447EDA0}""
                    EndProject
                    Global
	                    GlobalSection(SolutionConfigurationPlatforms) = preSolution
		                    Debug|Any CPU = Debug|Any CPU
		                    Release|Any CPU = Release|Any CPU
	                    EndGlobalSection
	                    GlobalSection(ProjectConfigurationPlatforms) = postSolution
		                    {A437DBE9-DCAA-46D8-9D80-A50EDB2244FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		                    {A437DBE9-DCAA-46D8-9D80-A50EDB2244FD}.Debug|Any CPU.Build.0 = Debug|Any CPU
		                    {A437DBE9-DCAA-46D8-9D80-A50EDB2244FD}.Release|Any CPU.ActiveCfg = Release|Any CPU
		                    {A437DBE9-DCAA-46D8-9D80-A50EDB2244FD}.Release|Any CPU.Build.0 = Release|Any CPU
		                    {84AA5584-4B0F-41DE-95AA-589E1447EDA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		                    {84AA5584-4B0F-41DE-95AA-589E1447EDA0}.Debug|Any CPU.Build.0 = Debug|Any CPU
		                    {84AA5584-4B0F-41DE-95AA-589E1447EDA0}.Release|Any CPU.ActiveCfg = Release|Any CPU
		                    {84AA5584-4B0F-41DE-95AA-589E1447EDA0}.Release|Any CPU.Build.0 = Release|Any CPU
	                    EndGlobalSection
	                    GlobalSection(SolutionProperties) = preSolution
		                    HideSolutionNode = FALSE
	                    EndGlobalSection
                    EndGlobal
                ";


            string solutionFileContentsDev11 = solutionFilePreambleV11 + solutionBodySingleProjectContents;
            string solutionFileContentsDev12 = solutionFilePreambleV12 + solutionBodySingleProjectContents;

            string[] solutions = { solutionFileContentsDev11, solutionFileContentsDev12, solutionFileContentsDev12 };
            string[] projects = { classLibraryContentsToolsV4, classLibraryContentsToolsV4, classLibraryContentsToolsV12 };
            string[] logoutputs = { ".[11.0]. .[4.0].", ".[11.0]. .[4.0].", String.Format(".[{0}]. .[{0}].", ObjectModelHelpers.MSBuildDefaultToolsVersion) };

            string previousLegacyEnvironmentVariable = Environment.GetEnvironmentVariable("MSBUILDLEGACYDEFAULTTOOLSVERSION");

            try
            {
                Environment.SetEnvironmentVariable("MSBUILDLEGACYDEFAULTTOOLSVERSION", "1");
                InternalUtilities.RefreshInternalEnvironmentValues();

                for (int i = 0; i < solutions.Length; i++)
                {
                    string solutionFile = ObjectModelHelpers.CreateFileInTempProjectDirectory("Foo.sln", solutions[i]);
                    string projectFile = ObjectModelHelpers.CreateFileInTempProjectDirectory("ClassLibrary1.csproj", projects[i]);
                    SolutionFile sp = new SolutionFile();

                    sp.FullPath = solutionFile;
                    sp.ParseSolutionFile();

                    ProjectInstance[] instances = SolutionProjectGenerator.Generate(sp, null, null, new BuildEventContext(0, 0, 0, 0), null);

                    MockLogger logger = new MockLogger();
                    List<ILogger> loggers = new List<ILogger>(1);
                    loggers.Add(logger);

                    instances[0].Build(loggers);
                    logger.AssertLogContains(logoutputs[i]);
                }

                // Test Dev 12 sln and mixed v4.0 and v12.0 projects
                string solutionFileContentsDev12MultipleProjects = solutionFilePreambleV12 + solutionBodyMultipleProjectsContents;

                string solutionFileMultipleProjects = ObjectModelHelpers.CreateFileInTempProjectDirectory("Foo.sln", solutionFileContentsDev12MultipleProjects);
                string projectFileV4 = ObjectModelHelpers.CreateFileInTempProjectDirectory("ClassLibrary1.csproj", classLibraryContentsToolsV4);
                string projectFileV12 = ObjectModelHelpers.CreateFileInTempProjectDirectory("ClassLibrary2.csproj", classLibraryContentsToolsV12);

                SolutionFile sp1 = new SolutionFile();

                sp1.FullPath = solutionFileMultipleProjects;
                sp1.ParseSolutionFile();
                ProjectInstance[] instances1 = SolutionProjectGenerator.Generate(sp1, null, null, new BuildEventContext(0, 0, 0, 0), null);

                MockLogger logger1 = new MockLogger();
                List<ILogger> loggers1 = new List<ILogger>(1);
                loggers1.Add(logger1);

                instances1[0].Build(loggers1);
                logger1.AssertLogContains(".[11.0]. .[4.0].");
                logger1.AssertLogContains(String.Format(".[{0}]. .[{0}].", ObjectModelHelpers.MSBuildDefaultToolsVersion));
            }
            finally
            {
                Environment.SetEnvironmentVariable("MSBUILDLEGACYDEFAULTTOOLSVERSION", previousLegacyEnvironmentVariable);
                InternalUtilities.RefreshInternalEnvironmentValues();
            }
        }
        public void ImportFromExtensionsPathAnd32And64()
        {
            string extnTargetsFileContentTemplate = @"
                <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                    <Target Name='FromExtn{0}' DependsOnTargets='{1}'>
                        <Message Text='Running FromExtn{0}'/>
                    </Target>
                    {2}
                </Project>
                ";

            var configFileContents = @"
                 <configuration>
                   <configSections>
                     <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
                   </configSections>
                   <msbuildToolsets default=""14.1"">
                     <toolset toolsVersion=""14.1"">
                       <property name=""MSBuildToolsPath"" value="".""/>
                       <property name=""MSBuildBinPath"" value=""" + /*v4Folder*/ "." + @"""/>
                       <projectImportSearchPaths>
                         <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
                           <property name=""MSBuildExtensionsPath"" value=""{0}"" />
                           <property name=""MSBuildExtensionsPath32"" value=""{1}"" />
                           <property name=""MSBuildExtensionsPath64"" value=""{2}"" />
                         </searchPaths>
                       </projectImportSearchPaths>
                      </toolset>
                   </msbuildToolsets>
                 </configuration>";

            string extnDir1 = null, extnDir2 = null, extnDir3 = null;
            string mainProjectPath = null;

            try {
                extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"),
                                                             String.Format(extnTargetsFileContentTemplate, String.Empty, "FromExtn2", "<Import Project='$(MSBuildExtensionsPath32)\\bar\\extn2.proj' />"));
                extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("bar", "extn2.proj"),
                                                             String.Format(extnTargetsFileContentTemplate, 2, "FromExtn3", "<Import Project='$(MSBuildExtensionsPath64)\\xyz\\extn3.proj' />"));
                extnDir3 = GetNewExtensionsPathAndCreateFile("extensions3", Path.Combine("xyz", "extn3.proj"),
                                                             String.Format(extnTargetsFileContentTemplate, 3, String.Empty, String.Empty));

                mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());

                var configFilePath = ToolsetConfigurationReaderTestHelper.WriteConfigFile(String.Format(configFileContents, extnDir1, extnDir2, extnDir3));
                var reader         = GetStandardConfigurationReader();

                var projColln = new ProjectCollection();
                projColln.ResetToolsetsForTests(reader);
                var logger = new MockLogger();
                projColln.RegisterLogger(logger);

                var project = projColln.LoadProject(mainProjectPath);
                Assert.True(project.Build("Main"));
                logger.AssertLogContains("Running FromExtn3");
                logger.AssertLogContains("Running FromExtn2");
                logger.AssertLogContains("Running FromExtn");
            } finally {
                if (mainProjectPath != null)
                {
                    FileUtilities.DeleteNoThrow(mainProjectPath);
                }
                if (extnDir1 != null)
                {
                    FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
                }
                if (extnDir2 != null)
                {
                    FileUtilities.DeleteDirectoryNoThrow(extnDir2, recursive: true);
                }
                if (extnDir3 != null)
                {
                    FileUtilities.DeleteDirectoryNoThrow(extnDir3, recursive: true);
                }
            }
        }
        public void ToolsVersionFromEnvironmentVariable()
        {
            string oldDefaultToolsVersion = Environment.GetEnvironmentVariable("MSBUILDDEFAULTTOOLSVERSION");

            try
            {
                Environment.SetEnvironmentVariable("MSBUILDDEFAULTTOOLSVERSION", "foo");
                InternalUtilities.RefreshInternalEnvironmentValues();

                ProjectCollection p = new ProjectCollection();
                p.AddToolset(new Toolset("foo", @"c:\foo", p, @"c:\foo\override"));
                MockLogger mockLogger = new MockLogger();
                LoggingService service = (LoggingService)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1);
                service.RegisterLogger(mockLogger);

                bool success = false;
                Project project = new Project(XmlReader.Create(new StringReader(@"<Project ToolsVersion='4.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
                    <Target Name='Foo'>
                    </Target>
                   </Project>")), null /* no global properties */, null /* don't explicitly set the toolsversion */, p);
                success = project.Build(mockLogger);

                Assert.IsTrue(success);
                mockLogger.AssertLogContains("ToolsVersion=\"4.0\"");
                mockLogger.AssertLogContains("ToolsVersion=\"foo\"");
            }
            finally
            {
                Environment.SetEnvironmentVariable("MSBUILDDEFAULTTOOLSVERSION", oldDefaultToolsVersion);
                InternalUtilities.RefreshInternalEnvironmentValues();
            }
        }
        public void FallbackImportWithUndefinedProperty()
        {
            string mainTargetsFileContent = @"
               <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                   <Import Project='$(UndefinedProperty)\file.props' Condition=""Exists('$(UndefinedProperty)\file.props')"" />
                   <Target Name='Main' DependsOnTargets='FromExtn' />
               </Project>";

            string extnTargetsFileContentTemplate = @"
               <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                   <Target Name='FromExtn'>
                       <Message Text='Running FromExtn'/>
                   </Target>
               </Project>";

            var configFileContents = @"
                <configuration>
                  <configSections>
                    <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
                  </configSections>
                  <msbuildToolsets default=""14.1"">
                    <toolset toolsVersion=""14.1"">
                      <property name=""MSBuildToolsPath"" value="".""/>
                      <property name=""MSBuildBinPath"" value="".""/>
                      <projectImportSearchPaths>
                        <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
                          <property name=""UndefinedProperty"" value=""$(FallbackExpandDir1)"" />
                        </searchPaths>
                      </projectImportSearchPaths>
                     </toolset>
                  </msbuildToolsets>
                </configuration>";

            string extnDir1        = null;
            string mainProjectPath = null;

            try
            {
                extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("file.props"),
                                                             extnTargetsFileContentTemplate);

                mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent);

                ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents);
                var reader = GetStandardConfigurationReader();

                var projectCollection = new ProjectCollection(new Dictionary <string, string> {
                    ["FallbackExpandDir1"] = extnDir1
                });

                projectCollection.ResetToolsetsForTests(reader);
                var logger = new MockLogger();
                projectCollection.RegisterLogger(logger);

                var project = projectCollection.LoadProject(mainProjectPath);
                Assert.True(project.Build("Main"));
                logger.AssertLogContains("Running FromExtn");
            }
            finally
            {
                FileUtilities.DeleteNoThrow(mainProjectPath);
                FileUtilities.DeleteDirectoryNoThrow(extnDir1, true);
            }
        }
        public void TestSkipInvalidConfigurationsCase()
        {
            string tmpFileName = FileUtilities.GetTemporaryFile();
            File.Delete(tmpFileName);
            string projectFilePath = tmpFileName + ".sln";

            string solutionContents =
                @"
                Microsoft Visual Studio Solution File, Format Version 11.00
                # Visual Studio 2005
                Project('{E24C65DC-7377-472B-9ABA-BC803B73C61A}') = 'C:\solutions\WebSite2\', '..\..\solutions\WebSite2\', '{F90528C4-6989-4D33-AFE8-F53173597CC2}'
                    ProjectSection(WebsiteProperties) = preProject
                        Debug.AspNetCompiler.VirtualPath = '/WebSite2'
                        Debug.AspNetCompiler.PhysicalPath = '..\..\solutions\WebSite2\'
                        Debug.AspNetCompiler.TargetPath = 'PrecompiledWeb\WebSite2\'
                        Debug.AspNetCompiler.Updateable = 'true'
                        Debug.AspNetCompiler.ForceOverwrite = 'true'
                        Debug.AspNetCompiler.FixedNames = 'true'
                        Debug.AspNetCompiler.Debug = 'True'
                        Release.AspNetCompiler.VirtualPath = '/WebSite2'
                        Release.AspNetCompiler.PhysicalPath = '..\..\solutions\WebSite2\'
                        Release.AspNetCompiler.TargetPath = 'PrecompiledWeb\WebSite2\'
                        Release.AspNetCompiler.Updateable = 'true'
                        Release.AspNetCompiler.ForceOverwrite = 'true'
                        Release.AspNetCompiler.FixedNames = 'true'
                        Release.AspNetCompiler.Debug = 'False'
                        VWDPort = '2776'
                        DefaultWebSiteLanguage = 'Visual C#'
                    EndProjectSection
                EndProject
                Global
                    GlobalSection(SolutionConfigurationPlatforms) = preSolution
                        Debug|Any CPU = Debug|Any CPU
                    EndGlobalSection
                    GlobalSection(ProjectConfigurationPlatforms) = postSolution
                        {F90528C4-6989-4D33-AFE8-F53173597CC2}.Debug|Any CPU.ActiveCfg = Debug|.NET
                        {F90528C4-6989-4D33-AFE8-F53173597CC2}.Debug|Any CPU.Build.0 = Debug|.NET
                    EndGlobalSection
                EndGlobal";

            try
            {
                MockLogger logger = new MockLogger();

                Dictionary<string, string> globalProperties = new Dictionary<string, string>();
                globalProperties["Configuration"] = "Nonexistent";
                globalProperties["SkipInvalidConfigurations"] = "true";

                SolutionFile solution = SolutionFile_Tests.ParseSolutionHelper(solutionContents.Replace('\'', '"'));
                ProjectInstance[] instances = SolutionProjectGenerator.Generate(solution, globalProperties, null, BuildEventContext.Invalid, null);
                ProjectInstance msbuildProject = instances[0];

                // Build should complete successfully even with an invalid solution config if SkipInvalidConfigurations is true
                Assert.AreEqual(true, msbuildProject.Build(new ILogger[] { logger }));

                // We should get the invalid solution configuration warning
                Assert.AreEqual(1, logger.Warnings.Count);
                BuildWarningEventArgs warning = logger.Warnings[0];

                // Don't look at warning.Code here -- it may be null if PseudoLoc has messed
                // with our resource strings. The code will still be in the log -- it just wouldn't get
                // pulled out into the code field.
                logger.AssertLogContains("MSB4126");

                // No errors expected
                Assert.AreEqual(0, logger.Errors.Count);
            }
            finally
            {
                File.Delete(projectFilePath);
            }
        }