public void BuildAndAnalyze() { var globalProps = new Dictionary <string, string> { { "VisualStudioVersion", "12.0" } }; pc = new ProjectCollection(globalProps); var diagLogger = new DiagnosticXmlLogger(this); diagLogger.LogFile = _logFilepath; project = pc.LoadProject(_projectFilepath, "12.0"); projInst = project.CreateProjectInstance(); buildManager = new BuildManager(); var buildParams = new BuildParameters(); buildParams.Loggers = new ILogger[] { diagLogger }; buildManager.BeginBuild(buildParams); var brd = new BuildRequestData(projInst, _targets, null, BuildRequestDataFlags.ReplaceExistingProjectInstance); submission = buildManager.PendBuildRequest(brd); buildResult = submission.Execute(); buildManager.EndBuild(); }
private static BuildResult Build(BuildRequestData buildRequestData, IEnumerable <ILogger> loggers) { lock (LockObject) { BuildParameters buildParameters = new BuildParameters { EnableNodeReuse = false, MaxNodeCount = Environment.ProcessorCount, ResetCaches = true, Loggers = loggers, }; BuildManager.DefaultBuildManager.BeginBuild(buildParameters); try { BuildSubmission buildSubmission = BuildManager.DefaultBuildManager.PendBuildRequest(buildRequestData); SetCurrentHost(BuildManager.DefaultBuildManager); BuildResult buildResult = buildSubmission.Execute(); if (buildResult.Exception != null) { throw buildResult.Exception; } return(buildResult); } finally { BuildManager.DefaultBuildManager.EndBuild(); } } }
public bool Build(string solutionDirectory, string outputPath) { string projectFilePath = Path.Combine(solutionDirectory); ProjectCollection pc = new ProjectCollection(); // THERE ARE A LOT OF PROPERTIES HERE, THESE MAP TO THE MSBUILD CLI PROPERTIES Dictionary <string, string> globalProperty = new Dictionary <string, string>(); globalProperty.Add("OutputPath", outputPath); globalProperty.Add("Configuration", "Debug"); globalProperty.Add("Platform", "Any CPU"); BuildParameters bp = new BuildParameters(pc); bp.Loggers = new[] { new FileLogger { Verbosity = LoggerVerbosity.Detailed, ShowSummary = true, SkipProjectStartedText = true } }; BuildManager.DefaultBuildManager.BeginBuild(bp); BuildRequestData BuildRequest = new BuildRequestData(projectFilePath, globalProperty, "4.7", new string[] { "Build" }, null); BuildSubmission BuildSubmission = BuildManager.DefaultBuildManager.PendBuildRequest(BuildRequest); BuildSubmission.Execute(); BuildManager.DefaultBuildManager.EndBuild(); return(BuildSubmission.BuildResult.OverallResult == BuildResultCode.Success ? true : false); }
public override bool Build(string projectFileName, string[] targetNames, IDictionary targetOutputs) { try { this.buildManager.BeginBuild(this.buildParameters); BuildRequestData buildRequestData = new BuildRequestData(this.currentProjectInstance, targetNames, null, BuildRequestDataFlags.ReplaceExistingProjectInstance); BuildSubmission submission = this.buildManager.PendBuildRequest(buildRequestData); BuildResult buildResult = submission.Execute(); bool buildSucceeded = buildResult.OverallResult == BuildResultCode.Success; this.buildManager.EndBuild(); // Fill in empty lists for each target so that heat will look at the item group later. foreach (string target in targetNames) { targetOutputs.Add(target, new List <object>()); } return(buildSucceeded); } catch (Exception e) { throw new WixException(VSErrors.CannotBuildProject(projectFileName, e.Message)); } }
private void Build(string[] targets, BuildOutput buildOutput, out bool result, out IDictionary <string, TargetResult> targetOutputs) { lock (BuildManager.DefaultBuildManager) { BuildRequestData restoreRequest = new BuildRequestData( ProjectInstance, targetsToBuild: targets ?? ProjectInstance.DefaultTargets.ToArray(), hostServices: null, flags: BuildRequestDataFlags.ReplaceExistingProjectInstance); BuildParameters buildParameters = new BuildParameters { Loggers = new List <Framework.ILogger>(ProjectCollection.Loggers.Concat(buildOutput.AsEnumerable())), }; BuildManager.DefaultBuildManager.BeginBuild(buildParameters); try { BuildSubmission buildSubmission = BuildManager.DefaultBuildManager.PendBuildRequest(restoreRequest); BuildResult buildResult = buildSubmission.Execute(); result = buildResult.OverallResult == BuildResultCode.Success; targetOutputs = buildResult.ResultsByTarget; } finally { BuildManager.DefaultBuildManager.EndBuild(); } } }
public void BuildWithMuxLoggerEquivalentToNormalLogger() { string projectBody = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='Test'> <Message Text='Foo'/> <Error Text='Error'/> </Target> </Project> "); BuildManager buildManager = BuildManager.DefaultBuildManager; // Build with a 'normal' logger MockLogger mockLogger2 = new MockLogger(); mockLogger2.LogBuildFinished = false; ProjectCollection projectCollection = new ProjectCollection(); ProjectInstance project = (new Project(XmlReader.Create(new StringReader(projectBody)), null, "4.0", projectCollection)).CreateProjectInstance(); BuildParameters parameters = new BuildParameters(projectCollection); parameters.Loggers = new ILogger[] { mockLogger2 }; buildManager.Build(parameters, new BuildRequestData(project, new string[0], null)); // Build with the mux logger MuxLogger muxLogger = new MuxLogger(); muxLogger.Verbosity = LoggerVerbosity.Normal; projectCollection = new ProjectCollection(); project = (new Project(XmlReader.Create(new StringReader(projectBody)), null, "4.0", projectCollection)).CreateProjectInstance(); parameters = new BuildParameters(projectCollection); parameters.Loggers = new ILogger[] { muxLogger }; buildManager.BeginBuild(parameters); MockLogger mockLogger = new MockLogger(); mockLogger.LogBuildFinished = false; try { BuildSubmission submission = buildManager.PendBuildRequest(new BuildRequestData(project, new string[0], null)); muxLogger.RegisterLogger(submission.SubmissionId, mockLogger); submission.Execute(); } finally { buildManager.EndBuild(); } Assert.True(mockLogger2.BuildFinishedEvents.Count > 0); Assert.Equal(mockLogger2.BuildFinishedEvents.Count, mockLogger.BuildFinishedEvents.Count); Assert.Equal(mockLogger2.BuildFinishedEvents[0].Succeeded, mockLogger.BuildFinishedEvents[0].Succeeded); Assert.Equal(mockLogger2.FullLog, mockLogger.FullLog); }
/// <summary> /// Attempts to run the Restore target for the current project with a unique evaluation context. /// </summary> /// <param name="result">A value indicating the result of the restore.</param> /// <param name="buildOutput">A <see cref="BuildOutput"/> object that captured the logging from the restore.</param> /// <param name="targetOutputs">A <see cref="IDictionary{String,TargetResult}" /> containing the target outputs.</param> /// <returns>The current <see cref="ProjectCreator"/>.</returns> public ProjectCreator TryRestore(out bool result, out BuildOutput buildOutput, out IDictionary <string, TargetResult> targetOutputs) { Save(); buildOutput = BuildOutput.Create(); lock (BuildManager.DefaultBuildManager) { BuildRequestData restoreRequest = new BuildRequestData( FullPath, new Dictionary <string, string> { ["ExcludeRestorePackageImports"] = "true", ["MSBuildRestoreSessionId"] = Guid.NewGuid().ToString("D"), }, ProjectCollection.DefaultToolsVersion, targetsToBuild: new[] { "Restore" }, hostServices: null, flags: BuildRequestDataFlags.ClearCachesAfterBuild | BuildRequestDataFlags.SkipNonexistentTargets | BuildRequestDataFlags.IgnoreMissingEmptyAndInvalidImports); BuildParameters buildParameters = new BuildParameters { Loggers = new List <Framework.ILogger> { buildOutput, }, }; BuildManager.DefaultBuildManager.BeginBuild(buildParameters); try { BuildSubmission buildSubmission = BuildManager.DefaultBuildManager.PendBuildRequest(restoreRequest); BuildResult buildResult = buildSubmission.Execute(); result = buildResult.OverallResult == BuildResultCode.Success; targetOutputs = buildResult.ResultsByTarget; } finally { BuildManager.DefaultBuildManager.EndBuild(); } } Project.MarkDirty(); Project.ReevaluateIfNecessary(); return(this); }
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); }
private bool BuildProject(Project buildProject) { OnError("Compiling project..."); // Create and submit a new asynchronous build request. BuildParameters buildParameters = new BuildParameters(ProjectCollection.GlobalProjectCollection) { Loggers = new ILogger[] { new ErrorLogger(OnError) } }; BuildManager.DefaultBuildManager.BeginBuild(buildParameters); BuildRequestData request = new BuildRequestData(buildProject.CreateProjectInstance(), new string[0]); BuildSubmission submission = BuildManager.DefaultBuildManager.PendBuildRequest(request); BuildResult result = submission.Execute(); BuildManager.DefaultBuildManager.EndBuild(); OnError("Project compilation complete."); return(result.OverallResult == BuildResultCode.Success); }
public override async Task <bool> Process(Resource resource) { var solution = Path.Combine(resource.Path, resource.Info["clr_solution"]); // set global properties var globalProperties = new Dictionary <string, string>(); globalProperties["Configuration"] = "Release"; globalProperties["OutputPath"] = Path.GetFullPath(Path.Combine(Path.Combine(Program.RootDirectory, "cache/resource_bin"), resource.Name)) + "/"; globalProperties["IntermediateOutputPath"] = Path.GetFullPath(Path.Combine(Path.Combine(Program.RootDirectory, "cache/resource_obj"), resource.Name)) + "/"; globalProperties["OutDir"] = globalProperties["OutputPath"]; // for Mono? try { // prepare the project file var projectRoot = ProjectRootElement.Open(Path.GetFullPath(solution)); // disable any Citizen profiles foreach (var property in projectRoot.Properties) { if (property.Name == "TargetFrameworkProfile") { property.Value = ""; } } // we don't want the system mscorlib projectRoot.AddProperty("NoStdLib", "true"); // add hint paths for all references Func <string, string> getPath = a => Path.GetFullPath(Path.Combine(Path.Combine(Program.RootDirectory, "system/clrcore"), a + ".dll")); foreach (var item in projectRoot.Items) { if (item.ItemType == "Reference") { // remove existing hint paths item.Metadata.Where(a => a.Name == "HintPath").ToList().ForEach(a => item.RemoveChild(a)); item.AddMetadata("HintPath", getPath(item.Include)); item.AddMetadata("Private", "false"); } } // add our own mscorlib projectRoot.AddItem("Reference", "mscorlib", new Dictionary <string, string>() { { "HintPath", getPath("mscorlib") }, { "Private", "false" } }); // create an instance and build request var projectInstance = new ProjectInstance(projectRoot, globalProperties, "4.0", ProjectCollection.GlobalProjectCollection); var buildRequest = new BuildRequestData(projectInstance, new[] { "Build" }, null); BuildSubmission buildSubmission = null; // run this in a separate task await Task.Run(() => { // building is mutually-exclusive thanks to MSBuild working directory affinity lock (_compileLock) { // set the working directory var oldDirectory = Environment.CurrentDirectory; Environment.CurrentDirectory = Path.GetFullPath(Path.GetDirectoryName(solution)); // set the build parameters var buildParameters = new BuildParameters(); buildParameters.Loggers = new[] { this }; BuildManager.DefaultBuildManager.BeginBuild(buildParameters); // create a build submission and execute buildSubmission = BuildManager.DefaultBuildManager.PendBuildRequest(buildRequest); buildSubmission.Execute(); // end building BuildManager.DefaultBuildManager.EndBuild(); // put the current directory back Environment.CurrentDirectory = oldDirectory; } }); this.Log().Info("Build for {0} complete - result: {1}", resource.Name, buildSubmission.BuildResult.OverallResult); var success = (buildSubmission.BuildResult.OverallResult == BuildResultCode.Success); if (success) { // the targets producing 'interesting' items (resource_bin/*.dll) var targetList = new[] { "Build", "CoreBuild" }; // CoreBuild is needed on Mono // callback to run on each target Action <TargetResult> iterateResult = buildResult => { if (buildResult.Items != null) { foreach (var item in buildResult.Items) { var baseName = Path.GetFileName(item.ItemSpec); resource.ExternalFiles[string.Format("bin/{0}", baseName)] = new FileInfo(item.ItemSpec); } } }; // loop through the targets foreach (var target in targetList) { TargetResult result; // if it's a resulting target if (buildSubmission.BuildResult.ResultsByTarget.TryGetValue(target, out result)) { iterateResult(result); } } } else { foreach (var logItem in m_logDump) { this.Log().Error(logItem); } } m_logDump.Clear(); // unload the project so it will not get cached ProjectCollection.GlobalProjectCollection.UnloadProject(projectRoot); return(success); } catch (Exception e) { this.Log().Error(() => "Building assembly failed: " + e.Message, e); return(false); } }
/// <summary> /// Performs a synchronous build of all content items that have been /// added to the content system. /// </summary> /// <returns>True if the build succeeded, false otherwise.</returns> public Boolean Build() { BuildSubmission build = null; try { if (!Directory.Exists(BuildDirectory)) { Directory.CreateDirectory(BuildDirectory); } String projectPath = Path.Combine(BuildDirectory, "Content.contentproj"); String outputPath = Path.Combine(BuildDirectory, "bin"); if (File.Exists(projectPath)) { File.Delete(projectPath); } ProjectCollection projectCollection = ProjectCollection.GlobalProjectCollection; Project project = ConstructStandardProject(projectPath, outputPath); project.SetProperty("XnaCompressContent", _compressContent.ToString()); foreach (QueuedContentFile q in _files.Values) { ProjectItem item = project.AddItem("Compile", q.Filename)[0]; // you'd think the item would need to be added to the project, but this API is weird. // this just ends up mutating objects that the build system creates instead. item.SetMetadataValue("Link", Path.GetFileName(q.Filename)); item.SetMetadataValue("Name", q.ContentName); if (q.ImporterType != null) { item.SetMetadataValue("Importer", q.ImporterType.Name); } if (q.ProcessorType != null) { item.SetMetadataValue("Processor", q.ProcessorType.Name); } } ErrorLogger logger = new ErrorLogger(); BuildParameters parameters = new BuildParameters(projectCollection) { Loggers = new[] { logger } }; if (BuildStarted != null) { BuildStarted(project, parameters); } if (File.Exists(projectPath)) { File.Delete(projectPath); } BuildManager.DefaultBuildManager.BeginBuild(parameters); BuildRequestData request = new BuildRequestData(project.CreateProjectInstance(), new String[0]); build = BuildManager.DefaultBuildManager.PendBuildRequest(request); // build.ExecuteAsync(submission => { // if (submission.BuildResult.OverallResult == BuildResultCode.Success && BuildFinished != null) // { // BuildFinished(BuildDirectory, OutputDirectory, submission); // ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); // } // else if (submission.BuildResult.OverallResult == BuildResultCode.Failure && BuildErrored != null) // { // BuildErrored(submission, logger.Errors, null); // ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); // } // }, null); build.Execute(); CleanUpOldTempDirectories(); Boolean success = build.BuildResult.OverallResult == BuildResultCode.Success; BuildManager.DefaultBuildManager.EndBuild(); if (success && BuildFinished != null) { BuildFinished(BuildDirectory, OutputDirectory, build); } else if (BuildErrored != null) { BuildErrored(build, logger.Errors, null); } ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); ProjectCollection.GlobalProjectCollection.UnregisterAllLoggers(); return(success); } catch (Exception ex) { if (BuildErrored != null) { BuildErrored(build, new String[0], ex); } return(false); } }
public void TwoSubmissionsWithSeparateLoggers() { string projectBody1 = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='Test'> <Message Text='Foo'/> <Error Text='Error'/> </Target> </Project> "); string projectBody2 = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='Test'> <Message Text='Bar'/> <Warning Text='Warning'/> </Target> </Project> "); ProjectInstance project1 = (new Project(XmlReader.Create(new StringReader(projectBody1)))).CreateProjectInstance(); ProjectInstance project2 = (new Project(XmlReader.Create(new StringReader(projectBody2)))).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 submission1 = buildManager.PendBuildRequest(new BuildRequestData(project1, new string[0], null)); muxLogger.RegisterLogger(submission1.SubmissionId, mockLogger1); submission1.Execute(); BuildSubmission submission2 = buildManager.PendBuildRequest(new BuildRequestData(project2, new string[0], null)); muxLogger.RegisterLogger(submission2.SubmissionId, mockLogger2); submission2.Execute(); } finally { buildManager.EndBuild(); } mockLogger1.AssertLogContains("Foo"); mockLogger1.AssertLogContains("Error"); mockLogger1.AssertLogDoesntContain("Bar"); mockLogger1.AssertLogDoesntContain("Warning"); Assert.AreEqual(1, mockLogger1.ErrorCount); Assert.AreEqual(0, mockLogger1.WarningCount); mockLogger2.AssertLogDoesntContain("Foo"); mockLogger2.AssertLogDoesntContain("Error"); mockLogger2.AssertLogContains("Bar"); mockLogger2.AssertLogContains("Warning"); Assert.AreEqual(0, mockLogger2.ErrorCount); Assert.AreEqual(1, mockLogger2.WarningCount); }