/// <summary> /// Builds a project. /// </summary> /// <param name="projectPath">The absolute path to the project.</param> /// <param name="targetsToBuild">The targets to build. If not specified, the project's default target will be invoked.</param> /// <param name="properties">The optional global properties to pass to the project. May come from the <see cref="MSBuild.Properties"/> static class.</param> /// <returns>A task whose result is the result of the build.</returns> public static async Task<BuildResultAndLogs> ExecuteAsync(string projectPath, string[] targetsToBuild = null, IDictionary<string, string> properties = null, ITestOutputHelper testLogger = null) { targetsToBuild = targetsToBuild ?? new string[0]; var logger = new EventLogger(); var logLines = new List<string>(); var parameters = new BuildParameters { Loggers = new List<ILogger> { new ConsoleLogger(LoggerVerbosity.Detailed, logLines.Add, null, null), new ConsoleLogger(LoggerVerbosity.Minimal, v => testLogger?.WriteLine(v.TrimEnd()), null, null), logger, }, }; BuildResult result; using (var buildManager = new BuildManager()) { buildManager.BeginBuild(parameters); try { var requestData = new BuildRequestData(projectPath, properties ?? Properties.Default, null, targetsToBuild, null); var submission = buildManager.PendBuildRequest(requestData); result = await submission.ExecuteAsync(); } finally { buildManager.EndBuild(); } } return new BuildResultAndLogs(result, logger.LogEvents, logLines); }
public void GetProjectInstanceForBuildEmptyFullPath () { var proj = GetDummyProject (); proj.FullPath = ""; var manager = new BuildManager (); manager.GetProjectInstanceForBuild (proj); }
/// <summary> /// Process for specified event. /// </summary> /// <param name="evt">Configured event.</param> /// <returns>Result of handling.</returns> public override bool process(ISolutionEvent evt) { string command = ((IModeTargets)evt.Mode).Command; ProjectRootElement root = getXml(parse(evt, command)); BuildRequestData request = new BuildRequestData( new ProjectInstance(root, propertiesByDefault(evt), root.ToolsVersion, ProjectCollection.GlobalProjectCollection), new string[] { ENTRY_POINT }, new HostServices() ); // holy hedgehogs... #if !NET_40 // Using of BuildManager from Microsoft.Build.dll, v4.0.0.0 - .NETFramework\v4.5\Microsoft.Build.dll // you should see IDisposable, and of course you can see CA1001 for block as in #else section below. using(BuildManager manager = new BuildManager(Settings.APP_NAME_SHORT)) { return build(manager, request, evt.Process.Hidden); } #else // Using of BuildManager from Microsoft.Build.dll, v4.0.30319 - .NETFramework\v4.0\Microsoft.Build.dll // It doesn't implement IDisposable, and voila: // https://ci.appveyor.com/project/3Fs/vssolutionbuildevent/build/build-103 return build(new BuildManager(Settings.APP_NAME_SHORT), request, evt.Process.Hidden); #endif }
public BackgroundBuild2(DTE dte, OutputWindowPane pane) { _dte = dte; _pane = pane; _mainThread = SynchronizationContext.Current; BuildManager = new BuildManager(); }
public BuildNodeManager (BuildManager buildManager) { BuildManager = buildManager; new Thread (RunLoop) { IsBackground = true, Name = "xbuild request handler" }.Start (); }
/// <summary> /// TearDown /// </summary> public void Dispose() { Environment.SetEnvironmentVariable("MSBUILDINPROCENVCHECK", null); if (_buildManager != null) { _buildManager.Dispose(); _buildManager = null; } }
public void GetProjectInstanceForBuild () { string empty_project_xml = "<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' />"; var path = "file://localhost/foo.xml"; var xml = XmlReader.Create (new StringReader(empty_project_xml), null, path); var root = ProjectRootElement.Create (xml); root.FullPath = path; var proj = new Project (root); var manager = new BuildManager (); var inst = manager.GetProjectInstanceForBuild (proj); Assert.AreEqual (inst, manager.GetProjectInstanceForBuild (proj), "#1"); }
public void ResultBeforeExecute () { string empty_project_xml = "<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' />"; var path = "file://localhost/foo.xml"; var xml = XmlReader.Create (new StringReader (empty_project_xml), null, path); var root = ProjectRootElement.Create (xml); var proj = new ProjectInstance (root); var bm = new BuildManager (); bm.BeginBuild (new BuildParameters ()); var sub = bm.PendBuildRequest (new BuildRequestData (proj, new string [0])); Assert.IsNull (sub.BuildResult, "#1"); }
private static Task <MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildManager buildManager, MSB.Execution.BuildParameters parameters, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken) { var taskSource = new TaskCompletionSource <MSB.Execution.BuildResult>(); buildManager.BeginBuild(parameters); // enable cancellation of build CancellationTokenRegistration registration = default(CancellationTokenRegistration); if (cancellationToken.CanBeCanceled) { registration = cancellationToken.Register(() => { try { buildManager.CancelAllSubmissions(); buildManager.EndBuild(); registration.Dispose(); } finally { taskSource.TrySetCanceled(); } }); } // execute build async try { buildManager.PendBuildRequest(requestData).ExecuteAsync(sub => { // when finished try { var result = sub.BuildResult; buildManager.EndBuild(); registration.Dispose(); taskSource.TrySetResult(result); } catch (Exception e) { taskSource.TrySetException(e); } }, null); } catch (Exception e) { taskSource.SetException(e); } return(taskSource.Task); }
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"); }
/// <summary> /// Constructor /// </summary> internal BuildSubmission(BuildManager buildManager, int submissionId, BuildRequestData requestData, bool legacyThreadingSemantics) { ErrorUtilities.VerifyThrowArgumentNull(buildManager, "buildManager"); ErrorUtilities.VerifyThrowArgumentNull(requestData, "requestData"); BuildManager = buildManager; SubmissionId = submissionId; BuildRequestData = requestData; _completionEvent = new ManualResetEvent(false); _loggingCompleted = false; _completionInvoked = 0; _legacyThreadingSemantics = legacyThreadingSemantics; }
public void SetUp() { // Ensure that any previous tests which may have been using the default BuildManager do not conflict with us. BuildManager.DefaultBuildManager.Dispose(); _logger = new MockLogger(); _parameters = new BuildParameters(); _parameters.ShutdownInProcNodeOnBuildFinish = true; _parameters.Loggers = new ILogger[] { _logger }; _parameters.EnableNodeReuse = false; _buildManager = new BuildManager(); _projectCollection = new ProjectCollection(); Environment.SetEnvironmentVariable("MSBUILDINPROCENVCHECK", "1"); }
public MSBuild12Project(HarvesterCore harvesterCore, string configuration, string platform) : base(null, null, null, null) { this.buildParameters = new BuildParameters(); try { HarvestLogger logger = new HarvestLogger(); logger.HarvesterCore = harvesterCore; List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); this.buildParameters.Loggers = loggers; // MSBuild can't handle storing operating environments for nested builds. if (Util.RunningInMsBuild) { this.buildParameters.SaveOperatingEnvironment = false; } } catch (Exception e) { if (harvesterCore != null) { harvesterCore.OnMessage(VSWarnings.NoLogger(e.Message)); } } this.buildManager = new BuildManager(); if (configuration != null || platform != null) { Dictionary<string, string> globalVariables = new Dictionary<string, string>(); if (configuration != null) { globalVariables.Add("Configuration", configuration); } if (platform != null) { globalVariables.Add("Platform", platform); } this.projectCollection = new ProjectCollection(globalVariables); } else { this.projectCollection = new ProjectCollection(); } }
/// <summary> /// Check if project compiles locally /// </summary> public static bool LocalCompile() { // Save Files to Project in QC bool success; // Compile Locally Microsoft.Build.Execution.BuildManager buildSolution = new Microsoft.Build.Execution.BuildManager(); Solution4 soln = (Solution4)QCPluginPackage.ApplicationObject.Solution; soln.SolutionBuild.Build(true); if (soln.SolutionBuild.LastBuildInfo != 0) { success = false; } else { success = true; } return(success); }
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(); }
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 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 BuildEnvironment(BuildManager manager) { if (manager == null) throw new ArgumentNullException("manager"); m_Manager = manager; }
static IDisposable beginBuild(BuildManager buildManager, BuildParameters parameters) { buildManager.BeginBuild(parameters); return new DisposeAction(buildManager.EndBuild); }
// Enumerate all the projects the BuildManager built while building the projects we asked it to build. // This will allow us to identify any secondary outputs (like XNB files). private static BuiltItem[] ExtractChildProjectResults (BuildManager manager) { var resultsCache = GetField(manager, "resultsCache", BindingFlags.Instance | BindingFlags.NonPublic); var tResultsCache = resultsCache.GetType(); var pResultsDictionary = tResultsCache.GetProperty("ResultsDictionary", BindingFlags.NonPublic | BindingFlags.Instance); var oResultsDictionary = pResultsDictionary.GetValue(resultsCache, null); IDictionary<int, Microsoft.Build.Execution.BuildResult> resultsDictionary = oResultsDictionary as Dictionary<int, Microsoft.Build.Execution.BuildResult>; if (resultsDictionary == null) resultsDictionary = oResultsDictionary as ConcurrentDictionary<int, Microsoft.Build.Execution.BuildResult>; if (resultsDictionary == null) throw new Exception("Unsupported version of MSBuild"); var result = new List<BuiltItem>(); foreach (var projectResult in resultsDictionary.Values) { foreach (var kvp in projectResult.ResultsByTarget) { result.AddRange( from taskItem in kvp.Value.Items select new BuiltItem(kvp.Key, taskItem) ); } } return result.ToArray(); }
public void EndBuildWaitsForSubmissionCompletion () { // Windows does not have useful sleep or alternative, so skip it bool is_windows = true; switch (Environment.OSVersion.Platform) { case PlatformID.Unix: case PlatformID.MacOSX: is_windows = false; break; } string project_xml = string.Format (@"<Project DefaultTargets='Wait1Sec' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Target Name='Wait1Sec'> <Exec Command='{0}' /> </Target> </Project>", is_windows ? "powershell -command \"Start-Sleep -s 1\"" : "/bin/sleep 1"); var xml = XmlReader.Create (new StringReader (project_xml)); var root = ProjectRootElement.Create (xml); root.FullPath = "BuildSubmissionTest.EndBuildWaitsForSubmissionCompletion.proj"; var proj = new ProjectInstance (root); var bm = new BuildManager (); bm.BeginBuild (new BuildParameters ()); DateTime waitDone = DateTime.MinValue; DateTime beforeExec = DateTime.Now; var sub = bm.PendBuildRequest (new BuildRequestData (proj, new string [] { "Wait1Sec" })); sub.ExecuteAsync (delegate { waitDone = DateTime.Now; }, null); bm.EndBuild (); Assert.IsTrue (sub.BuildResult.OverallResult == BuildResultCode.Success, "#1"); DateTime endBuildDone = DateTime.Now; Assert.IsTrue (endBuildDone - beforeExec >= TimeSpan.FromSeconds (1), "#2"); Assert.IsTrue (endBuildDone > waitDone, "#3"); }
internal BuildSubmission (BuildManager build, BuildRequestData requestData) { BuildManager = build; this.request = requestData; SubmissionId = rnd.Next (); }
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; }
/// <summary> /// Builds a project. /// </summary> /// <param name="projectInstance">The project to build.</param> /// <param name="targetsToBuild">The targets to build. If not specified, the project's default target will be invoked.</param> /// <returns>A task whose result is the result of the build.</returns> public static async Task<BuildResultAndLogs> ExecuteAsync(ProjectInstance projectInstance, params string[] targetsToBuild) { targetsToBuild = (targetsToBuild == null || targetsToBuild.Length == 0) ? projectInstance.DefaultTargets.ToArray() : targetsToBuild; var logger = new EventLogger(); var logLines = new List<string>(); var parameters = new BuildParameters { Loggers = new List<ILogger> { new ConsoleLogger(LoggerVerbosity.Detailed, logLines.Add, null, null), logger, }, }; BuildResult result; using (var buildManager = new BuildManager()) { buildManager.BeginBuild(parameters); try { var brdFlags = BuildRequestDataFlags.ProvideProjectStateAfterBuild; var requestData = new BuildRequestData(projectInstance, targetsToBuild, null, brdFlags); var submission = buildManager.PendBuildRequest(requestData); result = await submission.ExecuteAsync(); } finally { buildManager.EndBuild(); } } return new BuildResultAndLogs(result, logger.LogEvents, logLines); }
public void VerifyNoOverCreationOfNodesWithBuildLoop() { // 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(); } _host = new MockHost(); _host.BuildParameters.MaxNodeCount = 3; _scheduler = new Scheduler(); _scheduler.InitializeComponent(_host); _parameters = new BuildParameters(); _parameters.ShutdownInProcNodeOnBuildFinish = true; _buildManager = new BuildManager(); CreateConfiguration(99, "parent.proj"); _defaultParentRequest = CreateBuildRequest(99, 99, new string[] { }, null); CreateConfiguration(1, "foo.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }, NodeAffinity.OutOfProc, _defaultParentRequest); CreateConfiguration(2, "foo2.proj"); BuildRequest request2 = CreateBuildRequest(2, 2, new string[] { "bar" }, NodeAffinity.OutOfProc, _defaultParentRequest); CreateConfiguration(3, "foo3.proj"); BuildRequest request3 = CreateBuildRequest(3, 3, new string[] { "bar" }, NodeAffinity.InProc, _defaultParentRequest); List<ScheduleResponse> responses = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, new BuildRequestBlocker(-1, new string[] { }, new BuildRequest[] { _defaultParentRequest, request1, request2, request3 }))); int nextNodeId = 1; bool inProcNodeExists = false; MockPerformSchedulingActions(responses, ref nextNodeId, ref inProcNodeExists); Assert.Equal(4, nextNodeId); // 3 nodes }
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(); } } }
// The only way to actually specify a solution configuration/platform is by messing around with internal/private types! // Using the normal globalProperties method to set configuration/platform will break all the projects inside the // solution by forcibly overriding their configuration/platform. MSBuild is garbage. public static ProjectInstance[] ParseSolutionFile ( string solutionFile, string buildConfiguration, string buildPlatform, Dictionary<string, string> globalProperties, BuildManager manager ) { var asmBuild = manager.GetType().Assembly; // Find the types used internally by MSBuild to convert .sln files into MSBuild projects. var tSolutionParser = asmBuild.GetType("Microsoft.Build.Construction.SolutionParser", true); var tProjectGenerator = asmBuild.GetType("Microsoft.Build.Construction.SolutionProjectGenerator", true); // Create an instance of the solution parser. The ctor is internal, hence the second arg. var solutionParser = Activator.CreateInstance(tSolutionParser, true); const BindingFlags fieldFlags = BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public; Func<object, string, object> getField = (target, fieldName) => GetField(target, fieldName, fieldFlags); Action<object, string, object> setField = (target, fieldName, value) => SetField(target, fieldName, fieldFlags, value); // Point the solution parser instance to the solution file. setField(solutionParser, "solutionFile", solutionFile); // Parse the solution file. The generator will use the parsed information later. solutionParser.GetType().InvokeMember( "ParseSolutionFile", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, solutionParser, new object[0] ); // Override the configuration and platform that may have been selected when parsing the solution // file. if (buildConfiguration != null) setField(solutionParser, "defaultConfigurationName", buildConfiguration); if (buildPlatform != null) setField(solutionParser, "defaultPlatformName", buildPlatform); // Forces the solution parser to scan project dependencies and select the configuration/platform // that we provided above. if ((buildConfiguration != null) || (buildPlatform != null)) setField(solutionParser, "solutionContainsWebDeploymentProjects", true); // The generator needs a logging service and build context. var loggingService = manager.GetType().InvokeMember( "Microsoft.Build.BackEnd.IBuildComponentHost.get_LoggingService", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, manager, new object[0] ); var context = new BuildEventContext(0, 0, 0, 0); // Convert the parsed solution into one or more project instances that we can build. var result = tProjectGenerator.InvokeMember( "Generate", BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, null, new object[] { solutionParser, globalProperties, null, context, loggingService } ); return (ProjectInstance[])result; }
public void VerifyRequestOrderingDoesNotAffectNodeCreationCountWithInProcAndAnyRequests() { // 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(); } _host = new MockHost(); _host.BuildParameters.MaxNodeCount = 3; _scheduler = new Scheduler(); _scheduler.InitializeComponent(_host); _logger = new MockLogger(); _parameters = new BuildParameters(); _parameters.Loggers = new ILogger[] { _logger }; _parameters.ShutdownInProcNodeOnBuildFinish = true; _buildManager = new BuildManager(); CreateConfiguration(99, "parent.proj"); _defaultParentRequest = CreateBuildRequest(99, 99, new string[] { }, null); CreateConfiguration(1, "foo.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }, NodeAffinity.Any, _defaultParentRequest); BuildRequest request2 = CreateBuildRequest(2, 1, new string[] { "bar" }, NodeAffinity.InProc, _defaultParentRequest); BuildRequest request3 = CreateBuildRequest(3, 1, new string[] { "bar" }, NodeAffinity.InProc, _defaultParentRequest); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, new BuildRequestBlocker(-1, new string[] { }, new BuildRequest[] { _defaultParentRequest, request1, request2, request3 }))); Assert.Equal(1, response.Count); Assert.Equal(ScheduleActionType.CreateNode, response[0].Action); Assert.Equal(NodeAffinity.InProc, response[0].RequiredNodeType); Assert.Equal(1, response[0].NumberOfNodesToCreate); List<NodeInfo> nodeInfos = new List<NodeInfo>(new NodeInfo[] { new NodeInfo(1, NodeProviderType.InProc) }); List<ScheduleResponse> moreResponses = new List<ScheduleResponse>(_scheduler.ReportNodesCreated(nodeInfos)); Assert.Equal(2, moreResponses.Count); Assert.Equal(ScheduleActionType.ScheduleWithConfiguration, moreResponses[0].Action); Assert.Equal(ScheduleActionType.CreateNode, moreResponses[1].Action); Assert.Equal(NodeAffinity.OutOfProc, moreResponses[1].RequiredNodeType); Assert.Equal(1, moreResponses[1].NumberOfNodesToCreate); }
// Enumerate all the projects the BuildManager built while building the projects we asked it to build. // This will allow us to identify any secondary outputs (like XNB files). private static BuiltItem[] ExtractChildProjectResults(BuildManager manager) { var resultsCache = GetField(manager, "resultsCache", BindingFlags.Instance | BindingFlags.NonPublic); var tResultsCache = resultsCache.GetType(); var pResultsDictionary = tResultsCache.GetProperty("ResultsDictionary", BindingFlags.NonPublic | BindingFlags.Instance); var oResultsDictionary = pResultsDictionary.GetValue(resultsCache, null); var resultsDictionary = (Dictionary<int, BuildResult>) oResultsDictionary; return resultsDictionary.Values.SelectMany( (result) => result.ResultsByTarget.SelectMany( (kvp) => kvp.Value.Items ) ).Select( (taskItem) => new BuiltItem(taskItem) ).ToArray(); }
/// <summary> /// Set up /// </summary> public Scheduler_Tests() { // 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(); } _host = new MockHost(); _scheduler = new Scheduler(); _scheduler.InitializeComponent(_host); CreateConfiguration(99, "parent.proj"); _defaultParentRequest = CreateBuildRequest(99, 99, new string[] { }, null); // Set up the scheduler with one node to start with. _scheduler.ReportNodesCreated(new NodeInfo[] { new NodeInfo(1, NodeProviderType.InProc) }); _scheduler.ReportRequestBlocked(1, new BuildRequestBlocker(-1, new string[] { }, new BuildRequest[] { _defaultParentRequest })); _logger = new MockLogger(); _parameters = new BuildParameters(); _parameters.Loggers = new ILogger[] { _logger }; _parameters.ShutdownInProcNodeOnBuildFinish = true; _buildManager = new BuildManager(); }
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(); } } } }