private void Build(string target) { if (!internalProject.Build(target)) { // If the build fails, re-run this build with a logger attached. internalProject.Build(target, new[] { new ConsoleLogger(LoggerVerbosity.Quiet) }); Process.Start(WorkingDirectory); throw new ApplicationException("Build of project [" + this + ":" + target + "] failed!"); } }
public bool IsPackagingTargetsInstalled(string projectFilePath) { var loggers = new IMSBuildLogger[] { new ConsoleLogger(LoggerVerbosity.Quiet) }; var project = new MSBuild.Project(projectFilePath); if (!project.Build("Restore", loggers)) { Console.Error.WriteLine($"Failed to restore '{Path.GetFileName(projectFilePath)}'. Please run dotnet restore, and try again."); return(false); } var projectAssetsPath = project.GetPropertyValue("ProjectAssetsFile"); // NuGet has a LockFileUtilities.GetLockFile API which provides direct access to this file format, // but loading NuGet in the same process as MSBuild creates dependency conflicts. LockFile lockFile = null; using (StreamReader reader = File.OpenText(projectAssetsPath)) using (JsonReader jsonReader = new JsonTextReader(reader)) { JsonSerializer serializer = new JsonSerializer(); lockFile = serializer.Deserialize <LockFile>(jsonReader); } if (!lockFile.Libraries.Any(l => l.Key.StartsWith("Packaging.Targets/"))) { Console.Error.WriteLine($"The project '{Path.GetFileName(projectFilePath)}' doesn't have a PackageReference to Packaging.Targets."); Console.Error.WriteLine($"Please run 'dotnet {this.commandName} install', and try again."); return(false); } return(true); }
public void Hello () { string project_xml = @"<Project ToolsVersion='4.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <UsingTask TaskName='DoNothing' TaskFactory='CodeTaskFactory' AssemblyFile='$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll' > <ParameterGroup /> <Task> <Code Type='Fragment' Language='cs'> <![CDATA[ // Display ""Hello, world!"" Log.LogWarning(""Hello, world!""); ]]> </Code> </Task> </UsingTask> <Target Name='default'> <DoNothing /> </Target> </Project>"; var root = ProjectRootElement.Create (XmlReader.Create (new StringReader (project_xml))); root.FullPath = "CodeTaskFactoryTest.Hello.proj"; var project = new Project (root); Assert.IsTrue (project.Build (new ConsoleLogger (LoggerVerbosity.Diagnostic)), "Build"); }
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"); }
public static bool Compile(Project project, string logfile, Log log) { try { if (project != null) { var doLog = false; var logErrorFile = Path.Combine(Directories.LogsDir, ("Error - " + Path.GetFileName(logfile))); if (File.Exists(logErrorFile)) { File.Delete(logErrorFile); } if (!string.IsNullOrWhiteSpace(logfile)) { var logDir = Path.GetDirectoryName(logfile); if (!string.IsNullOrWhiteSpace(logDir)) { doLog = true; if (!Directory.Exists(logDir)) { Directory.CreateDirectory(logDir); } var fileLogger = new FileLogger { Parameters = @"logfile=" + logfile, ShowSummary = true }; ProjectCollection.GlobalProjectCollection.RegisterLogger(fileLogger); } } var result = project.Build(); ProjectCollection.GlobalProjectCollection.UnregisterAllLoggers(); ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); Utility.Log( result ? LogStatus.Ok : LogStatus.Error, "Compiler", result ? string.Format("Compile - {0}", project.FullPath) : string.Format("Compile - Check ./logs/ for details - {0}", project.FullPath), log); if (!result && doLog && File.Exists(logfile)) { var pathDir = Path.GetDirectoryName(logfile); if (!string.IsNullOrWhiteSpace(pathDir)) { File.Move( logfile, Path.Combine(Directories.LogsDir, ("Error - " + Path.GetFileName(logfile)))); } } else if (result && File.Exists(logfile)) { File.Delete(logfile); } return result; } } catch (Exception ex) { Utility.Log(LogStatus.Error, "Compiler", ex.Message, log); } return false; }
private static void AssertBuildsProject(Microsoft.Build.Evaluation.Project proj, string target) { var logger = new StringLogger(); if (!proj.Build(target, new StringLogger[] { logger })) { Assert.Fail(logger.ToString()); } }
protected override void DoRun() { Environment.CurrentDirectory = _fileInfo.DirectoryName; List<string> targets = _targets.ConvertAll(prop => prop.Name); _project = _projects.LoadProject(_fileInfo.FullName); _project.Build(targets.ToArray(), _loggers); //SetTargetFramework(); }
private static bool CompileLibMooNet(string libmoonetPath) { Console.WriteLine("Compiling LibMoonet..."); if (File.Exists(Program.madcowINI)) { IConfigSource source = new IniConfigSource(Program.madcowINI); String Src = source.Configs["Balloons"].Get("ShowBalloons"); if (Src.Contains("1")) { Form1.GlobalAccess.MadCowTrayIcon.ShowBalloonTip(1000, "MadCow", "Compiling LibMoonet...", ToolTipIcon.Info); } } var libmoonetProject = new Project(libmoonetPath); return libmoonetProject.Build(new Microsoft.Build.Logging.FileLogger()); }
static void Main(string[] args) { //SolutionFile solutionFile = SolutionFile.Parse(); //Microsoft.Build.Evaluation.Project project = new Microsoft.Build.Evaluation.Project(); //SolutionParser parser = new SolutionParser(); //parser.SolutionFile = @"D:\Projects\WFAppsHelper\TestProjectSolution\TestProjectSolution.sln"; //parser.ParseSolutionFile(); ProjectRootElement rootElement = ProjectRootElement.Open(@"D:\Projects\WFAppsHelper\TestProjectSolution\TestProjectSolution\TestProjectSolution.csproj"); Project project = new Project(rootElement); project.ProjectCollection.RegisterLogger(new ConsoleLogger()); project.ProjectCollection.SetGlobalProperty("EnableNuGetPackageRestore", "true"); project.Build(); Console.Read(); }
public void BuildProject(string projectName) { var globalProperties = new Dictionary<string, string>(){ {"Configuration", "Debug"}, {"SolutionDir", SolutionDir}, {"OutputPath", OutputPath}, //{"VSToolsPath", @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v12.0"} //{"VSToolsPath", @"c:\program files (x86)MSBuild\Microsoft\Microsoft\VisualStudio\v12.0"} }; var project = new Project(Path.Combine(TestProjectsDir, projectName, projectName + ".csproj"), globalProperties, "12.0"); var logger = new ConsoleLogger(LoggerVerbosity.Diagnostic); Assert.IsTrue(project.Build(logger)); ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); }
public static bool Compile(Project project, string logfile, Log log) { try { if (project != null) { bool doLog = false; if (!string.IsNullOrWhiteSpace(logfile)) { string logDir = Path.GetDirectoryName(logfile); if (!string.IsNullOrWhiteSpace(logDir)) { doLog = true; if (!Directory.Exists(logDir)) { Directory.CreateDirectory(logDir); } var fileLogger = new FileLogger { Parameters = @"logfile=" + logfile, ShowSummary = true }; ProjectCollection.GlobalProjectCollection.RegisterLogger(fileLogger); } } bool result = project.Build(); ProjectCollection.GlobalProjectCollection.UnregisterAllLoggers(); Utility.Log(result ? LogStatus.Ok : LogStatus.Error, string.Format("Compile - {0}", project.FullPath), log); if (!result && doLog && File.Exists(logfile)) { string pathDir = Path.GetDirectoryName(logfile); if (!string.IsNullOrWhiteSpace(pathDir)) { File.Move(logfile, Path.Combine(pathDir, ("Error - " + Path.GetFileName(logfile)))); } } return(result); } } catch (Exception ex) { Utility.Log(LogStatus.Error, ex.Message, log); } return(false); }
public void BuildSolutions(List<string> solutionFiles) { foreach (string solution in solutionFiles) { buildLog.AppendLine("Preparing to build " + solution); Project project = new Project(solution); try { project.Build(); buildLog.AppendLine("Solution built."); } catch (Exception e) { buildLog.AppendLine(e.Message); } ProjectCollection.GlobalProjectCollection.UnloadProject(project); } }
/// <summary> /// Creates a DecisionTreeClassifier.exe from a decision tree, returning the file path of the new exe /// </summary> public static string CompileClassifier(TreeNode decisionTree) { var assemblyLocation = Assembly.GetExecutingAssembly().Location; var assemblyDirectory = new FileInfo(assemblyLocation).DirectoryName ?? ""; var classifierDir = Path.Combine(assemblyDirectory, "DecisionTreeClassifier"); var projFullPath = Path.Combine(classifierDir, "DecisionTreeClassifier.csproj"); var mainFullPath = Path.Combine(classifierDir, "Program.cs"); ReplaceSerializedTreeLine(mainFullPath, decisionTree); // load up the classifier project var proj = new Project(projFullPath); // set project to compile special DecisionTree config proj.SetProperty("Configuration", "DecisionTree"); // set the output path proj.SetProperty("DecisionTreeOutputPath", assemblyDirectory); // make a logger to catch possible build errors var logger = new SimpleBuildLogger(); // if we failed to build the classifier, we're screwed if (!proj.Build(logger)) { var sb = new StringBuilder(); sb.AppendLine("***************************************"); sb.AppendLine("**** Failed To Compile Classifier! ****"); sb.AppendLine("***************************************"); foreach (var error in logger.Errors) { sb.AppendLine(error.Message + " " + error.File + ": " + error.LineNumber); } throw new Exception(sb.ToString()); } // return the executable name var exeFileName = proj.GetProperty("AssemblyName").EvaluatedValue + ".exe"; return Path.Combine(assemblyDirectory, exeFileName); }
public bool IsPackagingTargetsInstalled() { var projectFilePath = Directory.GetFiles(Environment.CurrentDirectory, "*.csproj").SingleOrDefault(); if (projectFilePath == null) { Console.Error.WriteLine($"Failed to find a .csproj file in '{Environment.CurrentDirectory}'. dotnet {this.commandName} only works if"); Console.Error.WriteLine($"you have exactly one .csproj file in your directory. For advanced scenarios, please use 'dotnet msbuild /t:{this.msbuildTarget}'"); return(false); } var loggers = new IMSBuildLogger[] { new ConsoleLogger(LoggerVerbosity.Quiet) }; var project = new MSBuild.Project(projectFilePath); if (!project.Build("Restore", loggers)) { Console.Error.WriteLine($"Failed to restore '{Path.GetFileName(projectFilePath)}'. Please run dotnet restore, and try again."); return(false); } var projectAssetsPath = project.GetPropertyValue("ProjectAssetsFile"); // NuGet has a LockFileUtilities.GetLockFile API which provides direct access to this file format, // but loading NuGet in the same process as MSBuild creates dependency conflicts. LockFile lockFile = null; using (StreamReader reader = File.OpenText(projectAssetsPath)) using (JsonReader jsonReader = new JsonTextReader(reader)) { JsonSerializer serializer = new JsonSerializer(); lockFile = serializer.Deserialize <LockFile>(jsonReader); } if (!lockFile.Libraries.Any(l => l.Key.StartsWith("Packaging.Targets/"))) { Console.Error.WriteLine($"The project '{Path.GetFileName(projectFilePath)}' doesn't have a PackageReference to Packaging.Targets."); Console.Error.WriteLine($"Please run 'dotnet {this.commandName} install', and try again."); return(false); } return(true); }
public void Basic() { MockLogger l = new MockLogger(); Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@" <Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='CleanUp'> <Message Text='CleanUp-was-called.'/> </Target> <Target Name='Build'> <Error Text='This is an error.'/> <OnError ExecuteTargets='CleanUp'/> </Target> </Project>")))); p.Build(new string[] { "Build" }, new ILogger[] { l }); Assert.Equal(1, l.ErrorCount); // "Expected one error because 'Build' failed." Assert.True((l.FullLog.IndexOf("CleanUp-was-called") != -1)); // "The CleanUp target should have been called." }
public static void AddProjectFiles(FilePath ProjectFile, IReadOnlyList <FilePath> files, bool build = false) { var project = new MSEV.Project(ProjectFile); var projectFolder = ProjectFile.Folder; foreach (var file in files) { var itemType = StandardItemTypes.InferItemType(file.FileName); var relativePath = file.Value.Replace(projectFolder.FullPath, String.Empty); if (relativePath.StartsWith("\\")) { relativePath = relativePath.Substring(1); } project.AddItem(itemType, relativePath); } project.Save(); if (build) { project.Build(); } }
public void EmptyItemSpecInTargetInputs() { MockLogger ml = new MockLogger(); Project p = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <MyFile Include='a.cs; b.cs; c.cs'/> </ItemGroup> <Target Name='Build' Inputs=""@(MyFile->'%(NonExistentMetadata)')"" Outputs='foo.exe'> <Message Text='Running Build target' Importance='High'/> </Target> </Project>")))); bool success = p.Build(new string[] { "Build" }, new ILogger[] { ml }); Assert.True(success); // It should have actually skipped the "Build" target since there were no inputs. ml.AssertLogDoesntContain("Running Build target"); }
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"); }
public void TestRunPythonCommand() { var expectedSearchPath = string.Format("['{0}', '{1}']", TestData.GetPath(@"TestData").Replace("\\", "\\\\"), TestData.GetPath(@"TestData\HelloWorld").Replace("\\", "\\\\") ); var proj = new Project(TestData.GetPath(@"TestData\Targets\Commands4.pyproj")); foreach (var version in PythonPaths.Versions) { var verStr = version.Version.ToVersion().ToString(); proj.SetProperty("InterpreterId", version.Id.ToString("B")); proj.SetProperty("InterpreterVersion", verStr); proj.RemoveItems(proj.ItemsIgnoringCondition.Where(i => i.ItemType == "InterpreterReference").ToArray()); proj.AddItem("InterpreterReference", string.Format("{0:B}\\{1}", version.Id, verStr)); proj.Save(); proj.ReevaluateIfNecessary(); var log = new StringLogger(LoggerVerbosity.Minimal); Assert.IsTrue(proj.Build("CheckCode", new ILogger[] { new ConsoleLogger(LoggerVerbosity.Detailed), log })); Console.WriteLine(); Console.WriteLine("Output from {0:B} {1}", version.Id, version.Version.ToVersion()); foreach (var line in log.Lines) { Console.WriteLine("* {0}", line.TrimEnd('\r', '\n')); } var logLines = log.Lines.Last().Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); Assert.AreEqual(2, logLines.Length); Assert.AreEqual(version.Version.ToVersion().ToString(), logLines[0].Trim()); Assert.AreEqual(expectedSearchPath, logLines[1].Trim()); } }
public void Load(string path_project) { //BuildResult result = null; using (ProjectCollection collection = new ProjectCollection()) { /* * result = BuildManager.DefaultBuildManager.Build( * new BuildParameters(pc) { Loggers = new[] { new ConsoleLogger() } }, * // Change this path to your .sln file instead of the .csproj. * // (It won't work with the .csproj.) * new BuildRequestData(@"c:\projects\Sample.sln", * // Change the parameters as you need them, * // e.g. if you want to just Build the Debug (not Rebuild the Release). * new Dictionary<string, string> * { * { "Configuration", "Release" }, * { "Platform", "Any CPU" } * }, null, new[] { "Rebuild" }, null)); * * if (result.OverallResult == BuildResultCode.Failure) * { * } */ /* * collection. * Microsoft.Build.Evaluation.Project proj = collection.LoadProject(path_project); // <-- exception * * proj.Build("Build"); */ collection.DefaultToolsVersion = "15.0"; Microsoft.Build.Evaluation.Project p = null; Microsoft.Build.Construction.ProjectRootElement pre = null; pre = Microsoft.Build.Construction.ProjectRootElement.Open(path_project); //p = collection.LoadProject //( // path_project, // new Dictionary<string, string>(), // "15.0", // new ProjectCollection() //); p = new Microsoft.Build.Evaluation.Project(pre); //( // path_project, // new Dictionary<string, string>(), // "15.0", // new ProjectCollection() //); p.ProjectCollection.RegisterLogger(new ConsoleLogger()); p.ProjectCollection.SetGlobalProperty("EnableNuGetPackageRestore", "true"); p.Build(); if (!p.Build()) { Console.ReadLine(); } //MsBuildProject return; } }
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||]"); }
public void TasksCanAddRecursiveDirBuiltInMetadata() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <CreateItem Include='$(programfiles)\reference assemblies\**\*.dll;'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> <Message Text='@(x)'/> <Message Text='[%(x.RecursiveDir)]'/> </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.AssertLogDoesntContain("[]"); logger.AssertLogDoesntContain("MSB4118"); logger.AssertLogDoesntContain("MSB3031"); }
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 BuildEvaluationUsesCustomLoggers() { string importProjectContent = ObjectModelHelpers.CleanupFileContents(@"<Project xmlns='msbuildnamespace'> </Project>"); string importFileName = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile() + ".proj"; File.WriteAllText(importFileName, importProjectContent); string projectContent = ObjectModelHelpers.CleanupFileContents(@"<Project xmlns='msbuildnamespace'> <Import Project=""" + importFileName + @"""/> <Import Project=""" + importFileName + @"""/> <ItemGroup> <Compile Include='a.cs' /> </ItemGroup> <Target Name=""Build"" /> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectContent))); project.MarkDirty(); MockLogger collectionLogger = new MockLogger(); project.ProjectCollection.RegisterLogger(collectionLogger); MockLogger mockLogger = new MockLogger(); bool result; try { result = project.Build(new ILogger[] { mockLogger }); } catch { throw; } finally { project.ProjectCollection.UnregisterAllLoggers(); } Assert.Equal(true, result); Assert.Equal(0, mockLogger.WarningCount); // "Log should not contain MSB4011 because the build logger will not receive evaluation messages." Assert.Equal(collectionLogger.Warnings[0].Code, "MSB4011"); // "Log should contain MSB4011 because the project collection logger should have been used for evaluation." }
public void BuildNonExistentTarget() { Project project = new Project(); MockLogger logger = new MockLogger(); bool result = project.Build(new string[] { "nonexistent" }, new List<ILogger>() { logger }); Assert.Equal(false, result); Assert.Equal(1, logger.ErrorCount); }
public void BuildCSharpTargetBuild () { string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <AssemblyName>Foo</AssemblyName> </PropertyGroup> <Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets' /> </Project>"; var xml = XmlReader.Create (new StringReader (project_xml)); var root = ProjectRootElement.Create (xml); root.FullPath = "ProjectTest.BuildCSharpTargetBuild.proj"; var proj = new Project (root, null, "4.0"); Assert.IsFalse (proj.Build ("Build", new ILogger [] {/*new ConsoleLogger (LoggerVerbosity.Diagnostic)*/})); // missing mandatory properties }
public bool Build(IEnumerable<string> ProjectsPath, string versionName, string outputPrefix) { var ret = false; try { // Properties passed to MSBUILD (the ones of the .target file) var globalProperties = new Dictionary<string, string>(); // INFERENCE off globalProperties.Add("CodeContractsInferRequires", "false"); globalProperties.Add("CodeContractsInferEnsures", "false"); globalProperties.Add("CodeContractsInferObjectInvariants", "false"); // SUGGESTIONS off globalProperties.Add("CodeContractsSuggestAssumptions", "false"); globalProperties.Add("CodeContractsSuggestRequires", "false"); globalProperties.Add("CodeContractsSuggestEnsures", "false"); globalProperties.Add("CodeContractsSuggestObjectInvariants", "false"); // WARNINGS globalProperties.Add("CodeContractsRunCodeAnalysis", "true"); globalProperties.Add("CodeContractsAnalysisWarningLevel", "3"); globalProperties.Add("CodeContractsNonNullObligations", "true"); globalProperties.Add("CodeContractsBoundsObligations", "true"); globalProperties.Add("CodeContractsArithmeticObligations", "true"); globalProperties.Add("CodeContractsEnumObligations", "true"); globalProperties.Add("CodeContractsRedundantAssumptions", "false"); globalProperties.Add("CodeContractsMissingPublicRequiresAsWarnings", "false"); globalProperties.Add("CodeContractsRunInBackground", "false"); // get output globalProperties.Add("CodeContractsEnableRuntimeChecking", "false"); // speedup globalProperties.Add("CodeContractsReferenceAssembly", "Build"); // make sure we have it //globalProperties.Add("CodeContractsUseBaseLine", "true"); //globalProperties.Add("CodeContractsBaseLineFile", "base.xml"); //globalProperties.Add("CodeContractsExtraAnalysisOptions", "-repro"); globalProperties.Add("CodeContractsCacheAnalysisResults", "true"); globalProperties.Add("CodeContractsSQLServerOption", "cloudotserver"); var extraOptions = this.ExtraOptions == null ? "" : this.ExtraOptions; extraOptions += " -sortwarns:false -stats:perMethod -show:progress -trace:cache"; if (this.SaveSemanticBaseline) { extraOptions += String.Format(" -saveSemanticBaseline:{0}", versionName); } else { extraOptions += String.Format(" -useSemanticBaseline:{0}", versionName); } globalProperties.Add("CodeContractsExtraAnalysisOptions", extraOptions); //globalProperties.Add("CodeContractsCacheVersion", VersionId.ToString()); //globalProperties.Add("CodeContractsCacheMaxSize", Int32.MaxValue.ToString()); globalProperties.Add("DeployExtension", "false"); // avoid vsix deployment // It does not work: The log file is empty var logFileName = "buildlog." + versionName + "." + outputPrefix + (this.SaveSemanticBaseline ? ".save.txt" : ".use.txt"); var fileLogger = new FileLogger(); fileLogger.Parameters = "logfile=" + Path.Combine(this.SourceDirectory, logFileName); fileLogger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Normal; var consoleLogger = new ConsoleLogger(); consoleLogger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Normal; var overallLoggers = new[] { fileLogger, consoleLogger }; // with this version, loggers don't work (log files are created but empty), why? var loggers = new FileLogger[0]; using (var projectCollection = new ProjectCollection(globalProperties, loggers, ToolsetDefinitionLocations.Registry)) { // The only way to communicate to msbuild is to create an xml file, and pass it to msbuild XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003"; var xmlTarget = new XElement(ns + "Target", new XAttribute("Name", "Build")); var properties = ""; foreach (var projectPath in ProjectsPath) { Contract.Assert(projectPath != null); xmlTarget.Add(new XElement(ns + "MSBuild", new XAttribute("Projects", Path.Combine(this.SourceDirectory, projectPath)), new XAttribute("Targets", "Rebuild"), // ensures the project will be rebuilt from scratch (is it needed?) new XAttribute("UseResultsCache", "false"), new XAttribute("UnloadProjectsOnCompletion", "true"), new XAttribute("ContinueOnError", "true"), new XAttribute("StopOnFirstFailure", "false"), new XAttribute("Properties", properties))); } // create the project var xmlProject = new XElement(ns + "Project", xmlTarget); // now read the project var project = projectCollection.LoadProject(xmlProject.CreateReader()); // create an instance of the project var projectInstance = project.CreateProjectInstance(); // create the parameters for the build var buildParameters = new BuildParameters(projectCollection); buildParameters.EnableNodeReuse = false; buildParameters.ResetCaches = true; buildParameters.Loggers = overallLoggers; buildParameters.MaxNodeCount = Environment.ProcessorCount; // Ask a build on this project var buildRequestData = new BuildRequestData(projectInstance, new string[] { "Build" }); // we need to create a new BuildManager each time, otherwise it wrongly caches project files var buildManager = new BuildManager(); // now do the build! var buildResult = buildManager.Build(buildParameters, buildRequestData); ret = buildResult.OverallResult == BuildResultCode.Success; #if WITH_LOG logger.Shutdown(); #endif // now cleanup - it seems it does not improve projectCollection.UnregisterAllLoggers(); projectCollection.UnloadAllProjects(); } #region Version using the default BuildManager (disabled) #if false // First version. It does not work, because msbuild keeps a cache of the projects, and so it compiles the new files with the old project // The Log works Microsoft.Build.Execution.BuildManager.DefaultBuildManager.ResetCaches(); // ensures MSBuild doesn't use cached version of project files (it handles very badly versions changing!), not sure it works XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003"; var xmlTarget = new XElement(ns + "Target", new XAttribute("Name", "Build")); var properties = ""; properties += ";CodeContractsCacheDirectory=" + OutputDirectory; properties += ";CodeContractsCacheAnalysisResults=true"; properties += ";CodeContractsCacheVersion=" + VersionId; foreach (var projectPath in ProjectsPath) { Contract.Assume(projectPath != null); xmlTarget.Add(new XElement(ns + "MSBuild", new XAttribute("Projects", Path.Combine(this.WorkingDirectory, projectPath)), new XAttribute("Targets", "Rebuild"), // ensures the project will be rebuilt from scratch (is it needed?) new XAttribute("UseResultsCache", "false"), new XAttribute("UnloadProjectsOnCompletion", "true"), new XAttribute("ContinueOnError", "true"), new XAttribute("StopOnFirstFailure", "false"), new XAttribute("Properties", properties))); } var xmlProject = new XElement(ns + "Project", xmlTarget); var project = new Project(xmlProject.CreateReader()); var logFileName = "build." + VersionId + ".log"; var logger = new Microsoft.Build.Logging.FileLogger(); logger.Parameters = "logfile=" + Path.Combine(OutputDirectory, logFileName); ret = project.Build(logger); #endif #endregion } catch { ret = false; } return ret; }
private async Task <string> RunExecuteAsync(object sender, EventArgs e) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var textView = Utils.GetCurrentViewHost(owner)?.TextView; if (textView == null) { return("textView == null"); } SnapshotPoint caretPosition = textView.Caret.Position.BufferPosition; var roslynDocument = GetRoslynDocument(); if (roslynDocument == null) { //owner.ShowMessage("This element is not analyzable in current view."); return("roslynDocument == null"); } var ast = await roslynDocument.GetSyntaxRootAsync().ConfigureAwait(false); var model = await roslynDocument.GetSemanticModelAsync().ConfigureAwait(false); var node = ast.FindNode(new TextSpan(caretPosition.Position, 0), false, true); if (node == null) { //owner.ShowMessage(OLEMSGICON.OLEMSGICON_WARNING, "Can't show ILSpy for this code element!"); return("node == null"); } bool isstatic = false; bool ispublic = false; if (node is Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax) { Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax mdy = node as Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax; foreach (var modifier in mdy.Modifiers) { Debug.WriteLine(modifier.Text);//public static if ("public" == modifier.Text.ToLower()) { ispublic = true; } if ("static" == modifier.Text.ToLower()) { isstatic = true; } } } else { //owner.ShowMessage(OLEMSGICON.OLEMSGICON_WARNING, "只支持c#,请针对方法!"); return("只支持c#,请针对方法!"); } if (false == ispublic) { //owner.ShowMessage(OLEMSGICON.OLEMSGICON_WARNING, "只支持public方法!"); return("只支持public方法!"); } var symbol = GetSymbolResolvableByILSpy(model, node); if (symbol == null) { //owner.ShowMessage(OLEMSGICON.OLEMSGICON_WARNING, "Can't show ILSpy for this code element!"); return("symbol == null"); } Debug.WriteLine(symbol.MetadataName); // Run Debug.WriteLine(symbol.ContainingAssembly); // console, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null Debug.WriteLine(symbol.ContainingModule); // console.dll Debug.WriteLine(symbol.ContainingNamespace); // fgq.console Debug.WriteLine(symbol.ContainingSymbol); // fgq.console.MemoryLeakDemo1 Debug.WriteLine(symbol.ContainingType); // fgq.console.MemoryLeakDemo1 Debug.WriteLine(symbol.Name); // Run var roslynProject = roslynDocument.Project; var refsmap = GetReferences(roslynProject); var symbolAssemblyName = symbol.ContainingAssembly?.Identity?.Name; // Add our own project as well (not among references) var project = FindProject(owner.DTE.Solution.Projects.OfType <EnvDTE.Project>(), roslynProject.FilePath); if (project == null) { //owner.ShowMessage(OLEMSGICON.OLEMSGICON_WARNING, "Can't show ILSpy for this code element!"); return("project == null"); } string assemblyName = roslynDocument.Project.AssemblyName; string projectOutputPath = Utils.GetProjectOutputAssembly(project, roslynProject); //Debug.WriteLine("fgq" + nameof(assemblyName) + ":" + assemblyName); //Debug.WriteLine("fgq" + nameof(projectOutputPath) + ":" + projectOutputPath); //Debug.WriteLine("fgq project.name" + ":" + project.Name); //Debug.WriteLine("fgq project.FileName" + ":" + project.FileName); //Debug.WriteLine("fgq project.FullName" + ":" + project.FullName); try { using (ProjectCollection projectCollection = new ProjectCollection()) { Microsoft.Build.Definition.ProjectOptions projectOptions = new Microsoft.Build.Definition.ProjectOptions(); Microsoft.Build.Evaluation.Project buildproject = projectCollection.LoadProject(project.FullName); bool isNetCoreProject = IsNetCoreProject(buildproject); bool buildresult = buildproject.Build(); Debug.WriteLine(buildresult); Assembly assembly = Assembly.LoadFile(projectOutputPath); Debug.WriteLine("System.Reflection.Assembly.GetEntryAssembly().FullName:" + Assembly.GetEntryAssembly()?.FullName); Debug.WriteLine("System.Reflection.Assembly.GetExecutingAssembly().FullName:" + Assembly.GetExecutingAssembly()?.FullName); string cmdPath = GetCmdPath(isNetCoreProject); Debug.WriteLine(cmdPath); VSOutput("--------------------------start invoke--------------------------------------------"); Type type = assembly.GetType(symbol.ContainingType.ToString(), false, true); Object o = assembly.CreateInstance(symbol.ContainingType.Name); ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.UseShellExecute = false;; processStartInfo.RedirectStandardError = true; processStartInfo.RedirectStandardInput = true; processStartInfo.RedirectStandardOutput = true; processStartInfo.Arguments = string.Format("{0} {1} {2} {3}", projectOutputPath, symbol.ContainingType.ToString(), symbol.Name, isstatic.ToString()); processStartInfo.FileName = cmdPath; Process process = Process.Start(processStartInfo); TextReader textReader = process.StandardOutput; process.WaitForExit(); //while (false == process.HasExited) //{ //} Debug.WriteLine(process.ExitCode); string output = await textReader.ReadToEndAsync(); VSOutput(output); } } catch (Exception ex) { Debug.WriteLine(ex); return(ex.ToString()); } return(""); }
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 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); } }
public static void Compile(string projFilePath) { Microsoft.Build.Evaluation.Project p = new Microsoft.Build.Evaluation.Project(projFilePath); p.Build("C:\\"); }
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]"); }
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 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 TestCircularDependencyInCallTarget() { string projectContents = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name=""t1""> <CallTarget Targets=""t3""/> </Target> <Target Name=""t2"" DependsOnTargets=""t1""> </Target> <Target Name=""t3"" DependsOnTargets=""t2""> </Target> </Project> "; StringReader reader = new StringReader(projectContents); Project project = new Project(new XmlTextReader(reader), null, null); bool success = project.Build(_mockLogger); Assert.False(success); }
public void BuildCSharpTargetGetFrameworkPaths () { string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets' /> </Project>"; var xml = XmlReader.Create (new StringReader (project_xml)); var root = ProjectRootElement.Create (xml); var proj = new Project (root); root.FullPath = "ProjectTest.BuildCSharpTargetGetFrameworkPaths.proj"; Assert.IsTrue (proj.Build ("GetFrameworkPaths", new ILogger [] {/*new ConsoleLogger ()*/})); }
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); }
public void SameNameTargets () { string project_xml = @"<Project DefaultTargets='Foo' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Target Name='Foo'><Message Text='This should not be written' /></Target> <Target Name='Foo'><Message Text='This will be written' /></Target> </Project>"; var xml = XmlReader.Create (new StringReader (project_xml)); var root = ProjectRootElement.Create (xml); var proj = new Project (root, null, "4.0"); var sw = new StringWriter (); proj.Build (new ConsoleLogger (LoggerVerbosity.Diagnostic, sw.WriteLine, null, null)); Assert.IsTrue (sw.ToString ().Contains ("This will be written"), "#1"); Assert.IsFalse (sw.ToString ().Contains ("This should not be written"), "#2"); }
public void BuildDisabled() { Project project = new Project(); project.Xml.AddTarget("t"); project.IsBuildEnabled = false; MockLogger mockLogger = new MockLogger(); ProjectCollection.GlobalProjectCollection.RegisterLogger(mockLogger); bool result = project.Build(); Assert.Equal(false, result); Assert.Equal(mockLogger.Errors[0].Code, "MSB4112"); // "Security message about disabled targets need to have code MSB4112, because code in the VS Core project system depends on this. See DesignTimeBuildFeedback.cpp." }