private static BuildResult GetBuildResult(string target) { var manager = new Microsoft.Build.Execution.BuildManager(); Project proj = new Project(XmlReader.Create(new StringReader(ProjectContents))); var instance = proj.CreateProjectInstance(); return(manager.Build(new BuildParameters(), new BuildRequestData(instance, new[] { target }))); }
public Assembly CompileProject(string projectFilename, string configuration = "Debug") { var mgr = new BuildManager(); var parms = new BuildParameters(); var proj = new ProjectInstance(projectFilename); var req = new BuildRequestData(proj, new string[] {configuration}); BuildResult result = mgr.Build(parms, req); Console.WriteLine("Overall build result: {0}", result.OverallResult); throw new NotImplementedException("Not fully implemented yet"); }
public bool Build(string[] targets, IEnumerable <ILogger> loggers, IEnumerable <ForwardingLoggerRecord> remoteLoggers, out IDictionary <string, TargetResult> targetOutputs) { var manager = new BuildManager(); var parameters = new BuildParameters(projects) { ForwardingLoggers = remoteLoggers, Loggers = loggers, }; var requestData = new BuildRequestData(this, targets); var result = manager.Build(parameters, requestData); targetOutputs = result.ResultsByTarget; return(result.OverallResult == BuildResultCode.Success); }
public static IEnumerable<string> GetProjectReferences(string projectFullPath) { var projectDirectory = Path.GetDirectoryName(projectFullPath); var project = new ProjectInstance(projectFullPath); var manager = new BuildManager(); var result = manager.Build( new BuildParameters(), new BuildRequestData(project, new[] { GetProjectReferenceBuildTarget })); TargetResult targetResult; if (result.ResultsByTarget.TryGetValue(GetProjectReferenceBuildTarget, out targetResult)) { if (targetResult.ResultCode == TargetResultCode.Success && targetResult.Items.Length > 0) { var taskItem = targetResult.Items[0]; var metadataValue = taskItem.GetMetadata(ProjectReferencesKey); var projectRelativePaths = metadataValue.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (var relativePath in projectRelativePaths) { var resolvedPath = Path.GetFullPath(Path.Combine(projectDirectory, relativePath)); yield return resolvedPath; } } else if (targetResult.Exception != null) { throw targetResult.Exception; } } else if (result.Exception != null) { throw result.Exception; } }
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 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; }
/// <summary> /// Builds the specified target and returns the build result. /// </summary> /// <param name="project">The project to build</param> /// <param name="logger">The build logger to use. If null then a default logger will be used that dumps the build output to the console.</param> /// <param name="targets">Optional list of targets to execute</param> public static BuildResult BuildTargets(ProjectInstance projectInstance, ILogger logger, params string[] targets) { if (projectInstance == null) { throw new ArgumentNullException("projectInstance"); } if (logger == null) { throw new ArgumentNullException("logger"); } BuildParameters parameters = new BuildParameters(); parameters.Loggers = new ILogger[] { logger ?? new BuildLogger() }; parameters.UseSynchronousLogging = true; parameters.ShutdownInProcNodeOnBuildFinish = true; // required, other we can get an "Attempted to access an unloaded AppDomain" exception when the test finishes. BuildRequestData requestData = new BuildRequestData(projectInstance, targets); BuildResult result = null; BuildManager mgr = new BuildManager(); try { result = mgr.Build(parameters, requestData); result.ProjectStateAfterBuild = projectInstance; BuildUtilities.DumpProjectProperties(projectInstance, "Project properties post-build"); } finally { mgr.ShutdownAllNodes(); mgr.ResetCaches(); mgr.Dispose(); } return result; }
public bool Build(IEnumerable<string> ProjectsPath, long VersionId, string OutputDirectory) { var ret = false; try { // Properties passed to MSBUID (the ones of the .target file) var globalProperties = new Dictionary<string, string>(); globalProperties.Add("CodeContractsCacheDirectory", OutputDirectory); globalProperties.Add("CodeContractsCacheAnalysisResults", "true"); globalProperties.Add("CodeContractsCacheVersion", VersionId.ToString()); globalProperties.Add("CodeContractsCacheMaxSize", Int32.MaxValue.ToString()); #if WITH_LOG // It does not work: The log file is empty var logFileName = "build." + VersionId + ".log"; var logger = new FileLogger(); logger.Parameters = "logfile=" + Path.Combine(OutputDirectory, logFileName); logger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Diagnostic; var loggers = new FileLogger[]{ logger }; // with this version, loggers don't work (log files are created but empty), why? #else var loggers = new FileLogger[0]; #endif 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; // 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; }
public void AfterTargetsShouldReportFailedBuild() { // 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(); } string content = @" <Project ToolsVersion='msbuilddefaulttoolsversion' DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Target Name='Build'> <Message Text='Hello'/> </Target> <Target Name='Boo' AfterTargets='build'> <Error Text='Hi in Boo'/> </Target> </Project> "; BuildManager manager = null; try { MockLogger logger = new MockLogger(); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); ProjectCollection collection = new ProjectCollection(); Project project = new Project(XmlReader.Create(new StringReader(content)), (IDictionary<string, string>)null, "4.0", collection); project.FullPath = FileUtilities.GetTemporaryFile(); project.Save(); File.Delete(project.FullPath); BuildParameters parameters = new BuildParameters(collection); parameters.Loggers = loggers; parameters.ShutdownInProcNodeOnBuildFinish = true; BuildRequestData data = new BuildRequestData(project.FullPath, new Dictionary<string, string>(), "4.0", new string[] { }, null); manager = new BuildManager(); BuildResult result = manager.Build(parameters, data); // Make sure the overall result is failed Assert.AreEqual(BuildResultCode.Failure, result.OverallResult); // Expect the build target to pass Assert.IsTrue(result.ResultsByTarget["Build"].ResultCode == TargetResultCode.Success); } finally { // and we should clean up after ourselves, too. if (manager != null) { NodeProviderInProc inProcNodeProvider = ((IBuildComponentHost)manager).GetComponent(BuildComponentType.InProcNodeProvider) as NodeProviderInProc; if (inProcNodeProvider != null) { inProcNodeProvider.Dispose(); } } } }
/// <summary> /// Build user-action with additional BuildManager. /// Most important for our post-build operations with msbuild tool. /// Only for Visual Studio we may safe begin simple from Evaluation.Project.Build(...) /// </summary> /// <param name="manager">Build Manager.</param> /// <param name="request">Configuration.</param> /// <param name="silent"></param> /// <returns></returns> protected bool build(BuildManager manager, BuildRequestData request, bool silent = true) { BuildResult result = manager.Build(new BuildParameters() { //MaxNodeCount = 12, Loggers = new List<ILogger>() { new MSBuildLogger() { Silent = silent } } }, request); return (result.OverallResult == BuildResultCode.Success); }
public void DisposeAfterUse() { string project = FrameworkLocationHelper.PathToDotNetFrameworkV45 + "\\microsoft.common.targets"; var globalProperties = new Dictionary<string, string>(); var targets = new string[0]; var brd = new BuildRequestData(project, globalProperties, null, targets, new HostServices()); using (var bm = new BuildManager()) { bm.Build(new BuildParameters(), brd); } }
public void ShutdownNodesAfterParallelBuild() { ProjectCollection projectCollection = new ProjectCollection(); // Get number of MSBuild processes currently instantiated int numberProcsOriginally = (new List<Process>(Process.GetProcessesByName("MSBuild"))).Count; // Generate a theoretically unique directory to put our dummy projects in. string shutdownProjectDirectory = Path.Combine(Path.GetTempPath(), String.Format(CultureInfo.InvariantCulture, "VSNodeShutdown_{0}_UnitTest", Process.GetCurrentProcess().Id)); // Create the dummy projects we'll be "building" as our excuse to connect to and shut down // all the nodes. ProjectInstance rootProject = this.GenerateDummyProjects(shutdownProjectDirectory, numberProcsOriginally + 4, projectCollection); // Build the projects. BuildParameters buildParameters = new BuildParameters(projectCollection); buildParameters.OnlyLogCriticalEvents = true; buildParameters.MaxNodeCount = numberProcsOriginally + 4; buildParameters.EnableNodeReuse = true; buildParameters.DisableInProcNode = true; // Tell the build manager to not disturb process wide state buildParameters.SaveOperatingEnvironment = false; BuildRequestData requestData = new BuildRequestData(rootProject, new string[] { "Build" }, null); // Use a separate BuildManager for the node shutdown build, so that we don't have // to worry about taking dependencies on whether or not the existing ones have already // disappeared. BuildManager shutdownManager = new BuildManager("IdleNodeShutdown"); shutdownManager.Build(buildParameters, requestData); // Number of nodes after the build has to be greater than the original number int numberProcsAfterBuild = (new List<Process>(Process.GetProcessesByName("MSBuild"))).Count; Assert.IsTrue(numberProcsOriginally < numberProcsAfterBuild); // Shutdown all nodes shutdownManager.ShutdownAllNodes(); // Wait until all processes shut down Thread.Sleep(3000); // Number of nodes after the shutdown has to be smaller or equal the original number int numberProcsAfterShutdown = (new List<Process>(Process.GetProcessesByName("MSBuild"))).Count; Assert.IsTrue(numberProcsAfterShutdown <= numberProcsOriginally); // Delete directory with the dummy project if (Directory.Exists(shutdownProjectDirectory)) { Directory.Delete(shutdownProjectDirectory, true /* recursive delete */); } }
public void Regress251333() { string contents = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <PropertyGroup> <InitialProperty1>InitialProperty1</InitialProperty1> <InitialProperty2>InitialProperty2</InitialProperty2> <InitialProperty3>InitialProperty3</InitialProperty3> </PropertyGroup> <Target Name='test'> <Message Text='[success]'/> </Target> </Project> "); // First a normal build BuildRequestData data = GetBuildRequestData(contents); BuildResult result = _buildManager.Build(_parameters, data); Assert.AreEqual(result.OverallResult, BuildResultCode.Success); // Now a build using a different build manager. using (BuildManager newBuildManager = new BuildManager()) { BuildRequestData data2 = GetBuildRequestData(contents); BuildResult result2 = newBuildManager.Build(_parameters, data); Assert.AreEqual(result2.OverallResult, BuildResultCode.Success); } }
public void BuildParameterLoggersExplicitlyRequired () { string project_xml = @"<Project DefaultTargets='Foo' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets' /> <Target Name='Foo'> <ItemGroup> <Foo Condition='$(X)' Include='foo.txt' /> </ItemGroup> </Target> </Project>"; var xml = XmlReader.Create (new StringReader (project_xml)); var root = ProjectRootElement.Create (xml); root.FullPath = "BuildSubmissionTest.BuildParameterLoggersExplicitlyRequired.proj"; var pc = new ProjectCollection (); var sw = new StringWriter (); pc.RegisterLogger (new ConsoleLogger (LoggerVerbosity.Diagnostic, sw.WriteLine, null, null)); var proj = new ProjectInstance (root); var bm = new BuildManager (); var bp = new BuildParameters (pc); var br = new BuildRequestData (proj, new string [] {"Foo"}); Assert.AreEqual (BuildResultCode.Failure, bm.Build (bp, br).OverallResult, "#1"); // the logger is *ignored* Assert.IsFalse (sw.ToString ().Contains ("$(X)"), "#2"); }
public void BuildCommonResolveAssemblyReferences () { string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Import Project='$(MSBuildToolsPath)\Microsoft.Common.targets' /> <ItemGroup> <Reference Include='System.Core' /> <Reference Include='System.Xml' /> </ItemGroup> </Project>"; var xml = XmlReader.Create (new StringReader (project_xml)); var root = ProjectRootElement.Create (xml); root.FullPath = "BuildManagerTest.BuildCommonResolveAssemblyReferences.proj"; var proj = new ProjectInstance (root); var manager = new BuildManager (); var parameters = new BuildParameters () { Loggers = new ILogger [] {new ConsoleLogger (LoggerVerbosity.Diagnostic)} }; var request = new BuildRequestData (proj, new string [] {"ResolveAssemblyReferences"}); Assert.AreEqual (string.Empty, proj.GetPropertyValue ("TargetFrameworkDirectory"), "#1-1"); var result = manager.Build (parameters, request); Assert.AreNotEqual (string.Empty, proj.GetPropertyValue ("TargetFrameworkDirectory"), "#1-2"); // filled during build. Assert.IsTrue (result.ResultsByTarget.ContainsKey ("GetFrameworkPaths"), "#2-1"); Assert.IsTrue (result.ResultsByTarget.ContainsKey ("PrepareForBuild"), "#2-2"); Assert.IsTrue (result.ResultsByTarget.ContainsKey ("ResolveAssemblyReferences"), "#2-3"); var items = proj.GetItems ("ReferencePath"); Assert.AreEqual (2, items.Count (), "#3"); var syscore = items.FirstOrDefault (i => Path.GetFileName (i.EvaluatedInclude) == "System.Core.dll"); var sysxml = items.FirstOrDefault (i => Path.GetFileName (i.EvaluatedInclude) == "System.Xml.dll"); Assert.IsNotNull (syscore, "#4-1"); Assert.IsNotNull (sysxml, "#4-2"); Assert.IsTrue (File.Exists (syscore.EvaluatedInclude), "#5-1"); Assert.IsTrue (File.Exists (sysxml.EvaluatedInclude), "#5-1"); Assert.AreEqual (BuildResultCode.Success, result.OverallResult, "#6"); }