Beispiel #1
0
        protected async Task <BuildInfo> BuildAsync(string taskName, MSB.Framework.ITaskHost taskHost, CancellationToken cancellationToken)
        {
            // create a project instance to be executed by build engine.
            // The executed project will hold the final model of the project after execution via msbuild.
            var executedProject = _loadedProject.CreateProjectInstance();

            if (!executedProject.Targets.ContainsKey("Compile"))
            {
                return(new BuildInfo(executedProject, null));
            }

            var hostServices = new Microsoft.Build.Execution.HostServices();

            // connect the host "callback" object with the host services, so we get called back with the exact inputs to the compiler task.
            hostServices.RegisterHostObject(_loadedProject.FullPath, "CoreCompile", taskName, taskHost);

            var buildParameters = new MSB.Execution.BuildParameters(_loadedProject.ProjectCollection);

            var buildRequestData = new MSB.Execution.BuildRequestData(executedProject, new string[] { "Compile" }, hostServices);

            BuildResult result = await this.BuildAsync(buildParameters, buildRequestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);

            if (result.OverallResult == BuildResultCode.Failure)
            {
                return(new BuildInfo(executedProject, result.Exception?.Message ?? ""));
            }
            else
            {
                return(new BuildInfo(executedProject, null));
            }
        }
Beispiel #2
0
        public static string[] Build(string solutionFile)
        {
            Console.Error.Write("// Building '{0}'... ", Path.GetFileName(solutionFile));

            var pc = new ProjectCollection();
            var parms = new BuildParameters(pc);
            var globalProperties = new Dictionary<string, string>();
            var request = new BuildRequestData(solutionFile, globalProperties, null, new string[] { "Build" }, null);

            parms.Loggers = new[] {
                new ConsoleLogger(LoggerVerbosity.Quiet)
            };

            var result = BuildManager.DefaultBuildManager.Build(parms, request);
            var resultFiles = new HashSet<string>();

            Console.Error.WriteLine("done.");

            foreach (var kvp in result.ResultsByTarget) {
                var targetResult = kvp.Value;

                if (targetResult.Exception != null)
                    Console.Error.WriteLine("// Compilation failed for target '{0}':\r\n{1}", kvp.Key, targetResult.Exception.Message);
                else {
                    foreach (var filename in targetResult.Items)
                        resultFiles.Add(filename.ItemSpec);
                }
            }

            return resultFiles.ToArray();
        }
    internal static async Task<BuildResult> BuildAsync(this BuildManager buildManager, ITestOutputHelper logger, ProjectCollection projectCollection, ProjectRootElement project, string target, IDictionary<string, string> globalProperties = null, LoggerVerbosity logVerbosity = LoggerVerbosity.Detailed, ILogger[] additionalLoggers = null)
    {
        Requires.NotNull(buildManager, nameof(buildManager));
        Requires.NotNull(projectCollection, nameof(projectCollection));
        Requires.NotNull(project, nameof(project));

        globalProperties = globalProperties ?? new Dictionary<string, string>();
        var projectInstance = new ProjectInstance(project, globalProperties, null, projectCollection);
        var brd = new BuildRequestData(projectInstance, new[] { target }, null, BuildRequestDataFlags.ProvideProjectStateAfterBuild);

        var parameters = new BuildParameters(projectCollection);

        var loggers = new List<ILogger>();
        loggers.Add(new ConsoleLogger(logVerbosity, s => logger.WriteLine(s.TrimEnd('\r', '\n')), null, null));
        loggers.AddRange(additionalLoggers);
        parameters.Loggers = loggers.ToArray();

        buildManager.BeginBuild(parameters);

        var result = await buildManager.BuildAsync(brd);

        buildManager.EndBuild();

        return result;
    }
Beispiel #4
0
        /// <summary>
        /// Constructor
        /// </summary>
        public MockHost(BuildParameters buildParameters)
        {
            _buildParameters = buildParameters;

            _buildParameters.ProjectRootElementCache = new ProjectRootElementCache(false);

            _configCache = new ConfigCache();
            ((IBuildComponent)_configCache).InitializeComponent(this);

            // We are a logging service
            _loggingService = this;

            _legacyThreadingData = new LegacyThreadingData();

            _requestEngine = new BuildRequestEngine();
            ((IBuildComponent)_requestEngine).InitializeComponent(this);

            _resultsCache = new ResultsCache();
            ((IBuildComponent)_resultsCache).InitializeComponent(this);

            _requestBuilder = new Microsoft.Build.UnitTests.BackEnd.BuildRequestEngine_Tests.MockRequestBuilder();
            ((IBuildComponent)_requestBuilder).InitializeComponent(this);

            _targetBuilder = new TestTargetBuilder();
            ((IBuildComponent)_targetBuilder).InitializeComponent(this);
        }
Beispiel #5
0
		public BuildResult Build (BuildParameters parameters, BuildRequestData requestData)
		{
			BeginBuild (parameters);
			var ret = BuildRequest (requestData);
			EndBuild ();
			return ret;
		}
        private BuildResult Build(IEnumerable<ILogger> loggers)
        {
            // 1) Clean previous deployment.
            // 2) Do a build of the website project with the "Package" target. This will copy all
            //    the necessary website files into a directory similar to the following:
            //    MyProject/obj/Test/Package/PackageTmp

            var parameters = new BuildParameters { Loggers = loggers };
            var projectFilePath = Path.Combine(_siteRoot, _projectFileName);
            var globalProperties = new Dictionary<string, string> {
                { "Configuration", "Test" }
            };

            if (!string.IsNullOrWhiteSpace(_solutionDir))
                globalProperties.Add("SolutionDir", _solutionDir);

            if (!string.IsNullOrWhiteSpace(_projectDir))
                globalProperties.Add("ProjectDir", _projectDir);

            var requestData = new BuildRequestData(
                projectFilePath, globalProperties, null, _targets,
                null);

            return BuildManager.DefaultBuildManager.Build(parameters, requestData);
        }
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("LiteDevelop MSBuild");

                var arguments = CommandLineArguments.Parse(args);

                if (!File.Exists(arguments.InputFile))
                    throw new ArgumentException("File does not exist.");

                var buildParameters = new BuildParameters();
                buildParameters.DetailedSummary = arguments.DetailedSummary;
                buildParameters.Loggers = new ILogger[] 
                { 
                    new ConsoleLogger() { Verbosity = arguments.Verbosity }
                };

                Dictionary<string, string> properties = new Dictionary<string, string>();

                var buildRequest = new BuildRequestData(arguments.InputFile, properties, null, new string[] { arguments.Target.ToString() }, null);
                
              //  Microsoft.Build.Execution.BuildManager.DefaultBuildManager.
                var results = Microsoft.Build.Execution.BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest);

            }
            catch (Exception ex)
            {
                Console.WriteLine("error: line=0 column=0 file=\"LiteDevelop.MSBuild.exe\" => " + ex.Message);
                Console.WriteLine("This program should only be executed by LiteDevelop itself. If you believe this is a bug, please report the issue.");
            }
        }
Beispiel #8
0
    public static BuildResult Build(string projectOrSolution, string targets, Dictionary<string, string> properties = null, ILogger logger = null)
    {
        if (!Path.IsPathRooted(projectOrSolution))
            projectOrSolution = Path.Combine(ModuleInitializer.BaseDirectory, projectOrSolution);

        if (!File.Exists(projectOrSolution))
            throw new FileNotFoundException($"Project or solution to build {projectOrSolution} was not found.", projectOrSolution);

        // Without this, builds end up running in process and colliding with each other,
        // especially around the current directory used to resolve relative paths in projects.
        Environment.SetEnvironmentVariable("MSBUILDNOINPROCNODE", "1");
        using (var manager = new BuildManager(Guid.NewGuid().ToString()))
        {
            properties = properties ?? new Dictionary<string, string>();

            // If file is not a solution, build up a fake solution configuration so P2P references just work
            if (Path.GetExtension(projectOrSolution) != ".sln")
                AddSolutionConfiguration(projectOrSolution, properties);

            var request = new BuildRequestData(projectOrSolution, properties, "14.0", targets.Split(','), null);
            var parameters = new BuildParameters
            {
                GlobalProperties = properties,
            };

            if (logger != null)
                parameters.Loggers = new[] { logger };

            return manager.Build(parameters, request);
        }
    }
        public BuildResult Build(GenerateResult generateResult, ILogger logger, Benchmark benchmark)
        {
            lock (buildLock)
            {
                var projectFileName = Path.Combine(generateResult.DirectoryPath, ClassicGenerator.MainClassName + ".csproj");
                var exeFilePath = Path.Combine(generateResult.DirectoryPath, ClassicGenerator.MainClassName + ".exe");
                var consoleLogger = new MsBuildConsoleLogger(logger);
                var globalProperties = new Dictionary<string, string>();
                var buildRequest = new BuildRequestData(projectFileName, globalProperties, null, new[] { "Build" }, null);
                var buildParameters = new BuildParameters(new ProjectCollection()) { DetailedSummary = false, Loggers = new Microsoft.Build.Framework.ILogger[] { consoleLogger } };
                var buildResult = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest);

                if (buildResult.OverallResult != BuildResultCode.Success && !File.Exists(exeFilePath))
                {
                    logger.WriteLineInfo("BuildManager.DefaultBuildManager can't build this project. =(");
                    logger.WriteLineInfo("Let's try to build it via BuildBenchmark.bat!");
                    var buildProcess = new Process
                    {
                        StartInfo =
                        {
                            FileName = Path.Combine(generateResult.DirectoryPath, "BuildBenchmark.bat"),
                            WorkingDirectory = generateResult.DirectoryPath,
                            UseShellExecute = false,
                            RedirectStandardOutput = false,
                        }
                    };
                    buildProcess.Start();
                    buildProcess.WaitForExit();
                    if (File.Exists(exeFilePath))
                        return new BuildResult(generateResult, true, null, exeFilePath);
                }

                return new BuildResult(generateResult, buildResult.OverallResult == BuildResultCode.Success, buildResult.Exception, exeFilePath);
            }
        }
		public void PropertiesDefault ()
		{
			var bp = new BuildParameters ();
			Assert.IsTrue (bp.EnableNodeReuse, "#1");
			Assert.IsTrue (bp.EnvironmentProperties.Count > 0, "#2");
			Assert.AreEqual (CultureInfo.CurrentCulture, bp.Culture, "#3");
		}
Beispiel #11
0
        public void Execute(WebsiteContext context)
        {
            Logger.Log("Building the solution...");

            var solutionFilePath = Directory.GetFiles(context.CurrentDirectory).FirstOrDefault(x => x.EndsWith(".sln"));
            var properties = new Dictionary<string, string> {
                {"Configuration", "Debug"}
            };

            var buildParameters = new BuildParameters();
            var buildLoggger = new InMemoryBuildLogger();
            buildParameters.Loggers = new[] {buildLoggger};
            var buildRequest = new BuildRequestData(solutionFilePath, properties, null, new[] { "Build" }, null);
            var buildResult = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest);

            if (buildResult.OverallResult == BuildResultCode.Failure) {
                Logger.Error("Failed to build the solution!");
                Logger.Space();

                foreach (var buildError in buildLoggger.BuildErrors) {
                    Logger.Error(buildError);
                }
                Logger.Space();
            }
            else
                Logger.Success("Solution successfully built.");
        }
Beispiel #12
0
        private static void Main()
        {
            try
            {
                // Run this in debug otherwise the files in CreateInstallers will be locked. :)
                const string projectFileName = @"..\..\..\wix-custom-ba-issue.sln";
                var pc = new ProjectCollection();
                var globalProperty = new Dictionary<string, string> {{"Configuration", "Release"}};

                var buildRequestData = new BuildRequestData(projectFileName, globalProperty, null, new[] {"Rebuild"},
                    null);

                var buildParameters = new BuildParameters(pc)
                {
                    DetailedSummary = true,
                    Loggers = new List<ILogger> {new ConsoleLogger()}
                };

                foreach (var version in new List<string> {"0.0.6.0", "1.0.0.0"})
                    BuildExamples(version, buildParameters, buildRequestData);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed!", e);
                Console.WriteLine(e.ToString());
            }
        }
Beispiel #13
0
        private static void BuildExamples(string versionString, BuildParameters buildParameters,
            BuildRequestData buildRequestData)
        {
            const string versionFileName = @"..\..\..\.config\VersionInfo.txt";
            File.WriteAllText(versionFileName, versionString);

            var buildResult = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequestData);

            if (buildResult.OverallResult == BuildResultCode.Success)
            {
                var output =
                    buildResult.ResultsByTarget["Rebuild"].Items.First(x => x.ItemSpec.Contains("Bootstrapper"))
                        .ItemSpec;

                var temp = Path.GetTempPath();
                var productName = Path.GetFileNameWithoutExtension(output);
                var fileName = Path.GetFileName(output);

                if (productName != null)
                {
                    var directory = Path.Combine(temp, productName, versionString);

                    if (Directory.Exists(directory))
                        Directory.Delete(directory, true);

                    Directory.CreateDirectory(directory);

                    if (fileName != null)
                        File.Copy(output, Path.Combine(directory, fileName));
                }
            }
        }
Beispiel #14
0
        /// <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);
        }
Beispiel #15
0
        private MSB.Execution.BuildResult Build(MSB.Execution.BuildParameters parameters, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
        {
            using (buildManagerLock.DisposableWait())
            {
                var buildManager = MSB.Execution.BuildManager.DefaultBuildManager;

                buildManager.BeginBuild(parameters);

                // enable cancellation of build
                CancellationTokenRegistration registration = default(CancellationTokenRegistration);
                if (cancellationToken.CanBeCanceled)
                {
                    registration = cancellationToken.Register(() =>
                    {
                        buildManager.CancelAllSubmissions();
                    });
                }

                // execute build sync
                try
                {
                    return(buildManager.BuildRequest(requestData));
                }
                finally
                {
                    if (registration != default(CancellationTokenRegistration))
                    {
                        registration.Dispose();
                    }

                    buildManager.EndBuild();
                }
            }
        }
Beispiel #16
0
        bool Compile(params string[] targets)
        {
            using (var t = new ChangingOutput("Compiling target(s) {0} . . .", string.Join(", ", targets)))
            {
                t.FinishLine();

                var logger = new ConsoleLogger(LoggerVerbosity.Quiet);

                logger.SkipProjectStartedText = true;

                var props = new Dictionary<string, string>
                {
                    {"Configuration", _release ? "Release" : "Debug"},
                };

                var request = new BuildRequestData(_slnPath, props, null, targets, null);
                var p = new BuildParameters()
                {
                    Loggers = new[] {logger},
                    GlobalProperties = props
                };

                var result = BuildManager.DefaultBuildManager.Build(p, request);

                t.PrintResult(result.OverallResult == BuildResultCode.Success);

                return result.OverallResult == BuildResultCode.Success;
            }
        }
Beispiel #17
0
        protected async Task <BuildResult> BuildAsync(string taskName, MSB.Framework.ITaskHost taskHost, CancellationToken cancellationToken)
        {
            // prepare for building
            var buildTargets = new BuildTargets(loadedProject, "Compile");

            // Don't execute this one. It will build referenced projects.
            // Even when DesignTimeBuild is defined above, it will still add the referenced project's output to the references list
            // which we don't want.
            buildTargets.Remove("ResolveProjectReferences");

            // don't execute anything after CoreCompile target, since we've
            // already done everything we need to compute compiler inputs by then.
            buildTargets.RemoveAfter("CoreCompile", includeTargetInRemoval: false);

            // create a project instance to be executed by build engine.
            // The executed project will hold the final model of the project after execution via msbuild.
            var executedProject = loadedProject.CreateProjectInstance();

            var hostServices = new Microsoft.Build.Execution.HostServices();

            // connect the host "callback" object with the host services, so we get called back with the exact inputs to the compiler task.
            hostServices.RegisterHostObject(this.loadedProject.FullPath, "CoreCompile", taskName, taskHost);

            var buildParameters = new MSB.Execution.BuildParameters(loadedProject.ProjectCollection);

            var buildRequestData = new MSB.Execution.BuildRequestData(executedProject, buildTargets.Targets, hostServices);

            var result = await this.BuildAsync(buildParameters, buildRequestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);

            return(new BuildResult(result, executedProject));
        }
Beispiel #18
0
 private bool BuildSolution_VS()
 {
     if (_SolutionPath == "") return false;
     try
     {
         string projectFilePath = Path.Combine(_SolutionPath);
         _OutputPath = _SolutionPath.Replace(Path.GetFileName(_SolutionPath), "") + "\\bin\\" + BuildInterface_Configuration.Text + "\\";
         ProjectCollection pc = new ProjectCollection();
         Dictionary<string, string> globalProperty = new Dictionary<string, string>();
         globalProperty.Add("OutputPath", _OutputPath);
         BuildParameters bp = new BuildParameters(pc);
         BuildRequestData buildRequest = new BuildRequestData(projectFilePath, globalProperty, "4.0", new string[] { "Build" }, null);
         BuildResult buildResult = BuildManager.DefaultBuildManager.Build(bp, buildRequest);
         if (buildResult.OverallResult == BuildResultCode.Success)
         {
             return true;
         }
         else
         {
             MessageBox.Show("There Are Errors", "Error");
         }
     }
     catch
     {
         MessageBox.Show("Build Failed Unexpectedly", "Error");
     }
     return false;
 }
        void CreateBuildProject()
        {
            string projectPath = Path.Combine(buildDirectory, "content.contentproj");
            string outputPath = Path.Combine(buildDirectory, "bin");

            // Create the build project.
            projectRootElement = ProjectRootElement.Create(projectPath);

            // Include the standard targets file that defines how to build XNA Framework content.
            projectRootElement.AddImport(Application.StartupPath + "\\Exporters\\FBX\\XNA\\XNA Game Studio\\" +
                                         "v4.0\\Microsoft.Xna.GameStudio.ContentPipeline.targets");

            buildProject = new Project(projectRootElement);

            buildProject.SetProperty("XnaPlatform", "Windows");
            buildProject.SetProperty("XnaProfile", "Reach");
            buildProject.SetProperty("XnaFrameworkVersion", "v4.0");
            buildProject.SetProperty("Configuration", "Release");
            buildProject.SetProperty("OutputPath", outputPath);
            buildProject.SetProperty("ContentRootDirectory", ".");
            buildProject.SetProperty("ReferencePath", Application.StartupPath);

            // Register any custom importers or processors.
            foreach (string pipelineAssembly in pipelineAssemblies)
            {
                buildProject.AddItem("Reference", pipelineAssembly);
            }

            // Hook up our custom error logger.
            errorLogger = new ErrorLogger();

            buildParameters = new BuildParameters(ProjectCollection.GlobalProjectCollection)
                                  {Loggers = new ILogger[] {errorLogger}};
        }
 private async Task <MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildParameters parameters, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
 {
     // only allow one build to use the default build manager at a time
     using (await s_buildManagerLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
     {
         return(await BuildAsync(MSB.Execution.BuildManager.DefaultBuildManager, parameters, requestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false));
     }
 }
Beispiel #21
0
		private static bool _BuildSolutionFile(string solutionFile, string configuration)
		{
			var buildProperties = new Dictionary<string,string>();
			buildProperties["Configuration"] = configuration;
			var buildRequest = new BuildRequestData(solutionFile, buildProperties, null, new string[] { "Build" }, null);
			var buildParameters = new BuildParameters();
			var buildResult = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest);
			return buildResult.OverallResult == BuildResultCode.Success;
		}
Beispiel #22
0
 public void EmptyBuildWithNoLoggers()
 {
     BuildManager buildManager = BuildManager.DefaultBuildManager;
     MuxLogger muxLogger = new MuxLogger();
     BuildParameters parameters = new BuildParameters();
     parameters.Loggers = new ILogger[] { muxLogger };
     buildManager.BeginBuild(parameters);
     buildManager.EndBuild();
 }
 public BuildResult BuildProject(string directoryPath, IBenchmarkLogger logger)
 {
     string projectFileName = Path.Combine(directoryPath, MainClassName + ".csproj");
     var consoleLogger = new MSBuildConsoleLogger(logger);
     var globalProperties = new Dictionary<string, string>();
     var buildRequest = new BuildRequestData(projectFileName, globalProperties, null, new[] { "Build" }, null);
     var buildParameters = new BuildParameters(new ProjectCollection()) { DetailedSummary = false, Loggers = new ILogger[] { consoleLogger } };
     var buildResult = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest);
     return buildResult;
 }
 public BenchmarkBuildResult Build(BenchmarkGenerateResult generateResult)
 {
     var projectFileName = Path.Combine(generateResult.DirectoryPath, BenchmarkClassicGenerator.MainClassName + ".csproj");
     var consoleLogger = new MSBuildConsoleLogger(logger);
     var globalProperties = new Dictionary<string, string>();
     var buildRequest = new BuildRequestData(projectFileName, globalProperties, null, new[] { "Build" }, null);
     var buildParameters = new BuildParameters(new ProjectCollection()) { DetailedSummary = false, Loggers = new ILogger[] { consoleLogger } };
     var buildResult = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest);
     return new BenchmarkBuildResult(generateResult, buildResult.OverallResult == BuildResultCode.Success, buildResult.Exception);
 }
        ContentProject(ILogger logger)
        {
            Logger = logger;

            buildParameters = new BuildParameters();

            if (Logger != null)
            {
                buildParameters.Loggers = new ILogger[] { Logger };
            }
        }
Beispiel #26
0
        public bool DoBuild(BuildJob job, ILogger logger)
        {
            BuildParameters parameters = new BuildParameters();
            parameters.MaxNodeCount = 1;
            parameters.Loggers = new ILogger[] { logger };

            Program.Log("Building target '" + job.Target + "' in " + job.ProjectFileName);
            string[] targets = job.Target.Split(';');
            BuildRequestData request = new BuildRequestData(job.ProjectFileName, job.Properties, null, targets, null);

            BuildResult result = BuildManager.DefaultBuildManager.Build(parameters, request);
            return result.OverallResult == BuildResultCode.Success;
        }
        private Microsoft.Build.Execution.BuildResult BuildWithManagedApi(ILogger logger, string projectFilePath)
        {
            var consoleLogger = new MsBuildConsoleLogger(logger);
            var globalProperties = new Dictionary<string, string>();
            var buildRequest = new BuildRequestData(projectFilePath, globalProperties, null, new[] { "Build" }, null);
            var buildParameters = new BuildParameters(new ProjectCollection())
            {
                DetailedSummary = false,
                Loggers = new Microsoft.Build.Framework.ILogger[] { consoleLogger }
            };

            return BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest);
        }
        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 void GetToolset ()
		{
			var bp = new BuildParameters (ProjectCollection.GlobalProjectCollection);
			Assert.IsNull (bp.GetToolset ("0.1"), "#1");
			var ts = bp.GetToolset ("2.0");
			// They are equal
			Assert.AreEqual (ProjectCollection.GlobalProjectCollection.Toolsets.First (t => t.ToolsVersion == "2.0"), ts, "#2");

			bp = new BuildParameters ();
			Assert.IsNull (bp.GetToolset ("0.1"), "#1");
			ts = bp.GetToolset ("2.0");
			// They are NOT equal, because ProjectCollection seems to be different.
			Assert.AreNotEqual (ProjectCollection.GlobalProjectCollection.Toolsets.First (t => t.ToolsVersion == "2.0"), ts, "#2");			
		}
        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");
        }
Beispiel #31
0
        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();
            }
        }
Beispiel #32
0
        public bool BuildProject(string projectFile, string outputDir, 
            Dictionary<string, string> extraParams)
        {
            extraParams.Add("OutputPath", outputDir);

            var coll = new ProjectCollection();
            var parameters = new BuildParameters(coll)
                {
                    Loggers = new[] {Logger}
                };
            var request = new BuildRequestData(projectFile, extraParams,
                "4.0", new[] {"Build"}, null);

            var result = BuildManager.DefaultBuildManager.Build(parameters, request);
            return result.OverallResult == BuildResultCode.Success;
        }
Beispiel #33
0
        public static string[] Build(string solutionFile, string buildConfiguration = null, string buildPlatform = null)
        {
            string configString = String.Format("{0}|{1}", buildConfiguration ?? "<default>", buildPlatform ?? "<default>");

            if ((buildConfiguration ?? buildPlatform) != null)
                Console.Error.Write("// Building '{0}' ({1}) ...", Program.ShortenPath(solutionFile), configString);
            else
                Console.Error.Write("// Building '{0}' ...", Program.ShortenPath(solutionFile));

            var pc = new ProjectCollection();
            var parms = new BuildParameters(pc);
            var globalProperties = new Dictionary<string, string>();

            if (buildConfiguration != null)
                globalProperties["Configuration"] = buildConfiguration;
            if (buildPlatform != null)
                globalProperties["Platform"] = buildPlatform;

            var request = new BuildRequestData(
                solutionFile, globalProperties,
                null, new string[] { "Build" }, null,
                BuildRequestDataFlags.ReplaceExistingProjectInstance
            );

            parms.Loggers = new[] {
                new ConsoleLogger(LoggerVerbosity.Quiet)
            };

            var manager = BuildManager.DefaultBuildManager;
            var result = manager.Build(parms, request);
            var resultFiles = new HashSet<string>();

            Console.Error.WriteLine(" done.");

            foreach (var kvp in result.ResultsByTarget) {
                var targetResult = kvp.Value;

                if (targetResult.Exception != null)
                    Console.Error.WriteLine("// Compilation failed for target '{0}':\r\n{1}", kvp.Key, targetResult.Exception.Message);
                else {
                    foreach (var filename in targetResult.Items)
                        resultFiles.Add(filename.ItemSpec);
                }
            }

            return resultFiles.ToArray();
        }
Beispiel #34
0
        public static Response Compile(CompileRequest request)
        {
            var logger = new CompilerLogger();
            logger.Verbosity = LoggerVerbosity.Detailed;

            var pc = new ProjectCollection();
            var globalProperty = new Dictionary<string, string>();
            globalProperty.Add("Configuration", request.Configuration ?? "Release");
            //globalProperty.Add("Platform", "AnyCPU");
            globalProperty.Add("VisualStudioVersion", "14.0");
            if (!string.IsNullOrEmpty(request.OutputDirectory))
            {
                globalProperty.Add("OutputDirectory", request.OutputDirectory);
            }
            if (!string.IsNullOrEmpty(request.SigningKey))
            {
                globalProperty.Add("SignAssembly", "true");
                globalProperty.Add("AssemblyOriginatorKeyFile", request.SigningKey);
            }
            if (!request.SkipCodeAnalysis)
            {
                globalProperty.Add("RunCodeAnalysis", "true");
                globalProperty.Add("CodeAnalysisRuleSet", Path.Combine(BuilderAssemblyDirectory, "AllRules.ruleset"));
                globalProperty.Add("MBSBuilderPath", BuilderAssemblyDirectory);
                globalProperty.Add("CustomBeforeMicrosoftCSharpTargets", Path.Combine(BuilderAssemblyDirectory, "ImportStyleCop.targets"));
            }
            else
            {
                globalProperty.Add("RunCodeAnalysis", "false");
                globalProperty.Add("CodeAnalysisRuleSet", string.Empty);
            }

            var buildRequest = new BuildRequestData(request.SolutionPath, globalProperty, "14.0", new [] { request.Target }, null);

            var parameters = new BuildParameters(pc);
            parameters.Loggers = new ILogger[] { logger };
            parameters.DetailedSummary = true;

            var buildResult = BuildManager.DefaultBuildManager.Build(parameters, buildRequest);
            if (buildResult.OverallResult == BuildResultCode.Failure)
            {
                logger.Messages.Add(Message.CreateError("BuildResult is false"));
            }

            return new Response(logger.Messages);
        }
Beispiel #35
0
        private static MSBE.BuildResult BuildAsync(MSBE.BuildParameters parameters, MSBE.BuildRequestData requestData)
        {
            var buildManager = MSBE.BuildManager.DefaultBuildManager;

            var taskSource = new TaskCompletionSource <MSB.Execution.BuildResult>();

            buildManager.BeginBuild(parameters);

            // enable cancellation of build
            CancellationTokenRegistration registration = default(CancellationTokenRegistration);

            // 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.Result);
        }
Beispiel #36
0
        protected async Task <ProjectInstance> BuildAsync(string taskName, MSB.Framework.ITaskHost taskHost, CancellationToken cancellationToken)
        {
            // prepare for building
            var buildTargets = new BuildTargets(_loadedProject, "Compile");

            // don't execute anything after CoreCompile target, since we've
            // already done everything we need to compute compiler inputs by then.
            buildTargets.RemoveAfter("CoreCompile", includeTargetInRemoval: false);

            // create a project instance to be executed by build engine.
            // The executed project will hold the final model of the project after execution via msbuild.
            var executedProject = _loadedProject.CreateProjectInstance();

            if (!executedProject.Targets.ContainsKey("Compile"))
            {
                return(executedProject);
            }

            var hostServices = new Microsoft.Build.Execution.HostServices();

            // connect the host "callback" object with the host services, so we get called back with the exact inputs to the compiler task.
            hostServices.RegisterHostObject(_loadedProject.FullPath, "CoreCompile", taskName, taskHost);

            var buildParameters = new MSB.Execution.BuildParameters(_loadedProject.ProjectCollection);

            var buildRequestData = new MSB.Execution.BuildRequestData(executedProject, buildTargets.Targets, hostServices);

            var result = await this.BuildAsync(buildParameters, buildRequestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);

            if (result.Exception != null)
            {
                throw result.Exception;
            }

            return(executedProject);
        }
Beispiel #37
0
        public static ProjectDetails LoadProjectDetails(string projectFile, string configuration)
        {
            var            key = Tuple.Create(projectFile, configuration);
            ProjectDetails details;

            if (_allProjects.TryGetValue(key, out details))
            {
                if (!details.HasChanged())
                {
                    if (_log.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                    {
                        _log.Debug($"Using cached project file details for [{projectFile}]");
                    }

                    return(details);
                }
                else
                {
                    if (_log.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                    {
                        _log.Debug($"Reloading project file details [{projectFile}] as one of its imports has been modified.");
                    }
                }
            }

            if (_log.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
            {
                _log.Debug($"Loading project file [{projectFile}]");
            }

            details = new ProjectDetails();

            var properties = new Dictionary <string, string>(ImmutableDictionary <string, string> .Empty);

            properties["DesignTimeBuild"]                  = "true"; // this will tell msbuild to not build the dependent projects
            properties["BuildingInsideVisualStudio"]       = "true"; // this will force CoreCompile task to execute even if all inputs and outputs are up to date
            properties["BuildingInsideUnoSourceGenerator"] = "true"; // this will force prevent the task to run recursively
            properties["Configuration"] = configuration;
            properties["UseHostCompilerIfAvailable"] = "true";
            properties["UseSharedCompilation"]       = "true";

            // Platform is intentionally kept as not defined, to avoid having
            // dependent projects being loaded with a platform they don't support.
            // properties["Platform"] = _platform;

            var xmlReader  = XmlReader.Create(projectFile);
            var collection = new Microsoft.Build.Evaluation.ProjectCollection();

            collection.RegisterLogger(new Microsoft.Build.Logging.ConsoleLogger()
            {
                Verbosity = LoggerVerbosity.Normal
            });

            collection.OnlyLogCriticalEvents = false;
            var xml = Microsoft.Build.Construction.ProjectRootElement.Create(xmlReader, collection);

            // When constructing a project from an XmlReader, MSBuild cannot determine the project file path.  Setting the
            // path explicitly is necessary so that the reserved properties like $(MSBuildProjectDirectory) will work.
            xml.FullPath = Path.GetFullPath(projectFile);

            var loadedProject = new Microsoft.Build.Evaluation.Project(
                xml,
                properties,
                toolsVersion: null,
                projectCollection: collection
                );

            var buildTargets = new BuildTargets(loadedProject, "Compile");

            // don't execute anything after CoreCompile target, since we've
            // already done everything we need to compute compiler inputs by then.
            buildTargets.RemoveAfter("CoreCompile", includeTargetInRemoval: false);

            details.Configuration = configuration;
            details.LoadedProject = loadedProject;

            // create a project instance to be executed by build engine.
            // The executed project will hold the final model of the project after execution via msbuild.
            details.ExecutedProject = loadedProject.CreateProjectInstance();

            var hostServices = new Microsoft.Build.Execution.HostServices();

            // connect the host "callback" object with the host services, so we get called back with the exact inputs to the compiler task.
            hostServices.RegisterHostObject(loadedProject.FullPath, "CoreCompile", "Csc", null);

            var buildParameters = new Microsoft.Build.Execution.BuildParameters(loadedProject.ProjectCollection);

            // This allows for the loggers to
            buildParameters.Loggers = collection.Loggers;

            var buildRequestData = new Microsoft.Build.Execution.BuildRequestData(details.ExecutedProject, buildTargets.Targets, hostServices);

            var result = BuildAsync(buildParameters, buildRequestData);

            if (result.Exception == null)
            {
                ValidateOutputPath(details.ExecutedProject);

                var projectFilePath = Path.GetFullPath(Path.GetDirectoryName(projectFile));

                details.References = details.ExecutedProject.GetItems("ReferencePath").Select(r => r.EvaluatedInclude).ToArray();

                if (details.References.None())
                {
                    LogFailedTargets(projectFile, result);
                    return(details);
                }
            }
            else
            {
                LogFailedTargets(projectFile, result);
            }

            _allProjects.TryAdd(key, details);

            details.BuildImportsMap();

            return(details);
        }
Beispiel #38
0
        private void HandleNodeConfiguration(NodeConfiguration configuration)
        {
            // Grab the system parameters.
            _buildParameters = configuration.BuildParameters;

            _buildParameters.ProjectRootElementCache = s_projectRootElementCacheBase;

            // Snapshot the current environment
            _savedEnvironment = CommunicationsUtilities.GetEnvironmentVariables();

            // Change to the startup directory
            try
            {
                NativeMethodsShared.SetCurrentDirectory(BuildParameters.StartupDirectory);
            }
            catch (DirectoryNotFoundException)
            {
                // Somehow the startup directory vanished. This can happen if build was started from a USB Key and it was removed.
                NativeMethodsShared.SetCurrentDirectory(BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory);
            }

            // Replicate the environment.  First, unset any environment variables set by the previous configuration.
            if (_currentConfiguration != null)
            {
                foreach (string key in _currentConfiguration.BuildParameters.BuildProcessEnvironment.Keys)
                {
                    Environment.SetEnvironmentVariable(key, null);
                }
            }

            // Now set the new environment
            foreach (KeyValuePair <string, string> environmentPair in _buildParameters.BuildProcessEnvironment)
            {
                Environment.SetEnvironmentVariable(environmentPair.Key, environmentPair.Value);
            }

            // We want to make sure the global project collection has the toolsets which were defined on the parent
            // so that any custom toolsets defined can be picked up by tasks who may use the global project collection but are
            // executed on the child node.
            ICollection <Toolset> parentToolSets = _buildParameters.ToolsetProvider.Toolsets;

            if (parentToolSets != null)
            {
                ProjectCollection.GlobalProjectCollection.RemoveAllToolsets();

                foreach (Toolset toolSet in parentToolSets)
                {
                    ProjectCollection.GlobalProjectCollection.AddToolset(toolSet);
                }
            }

            // Set the culture.
            CultureInfo.CurrentCulture   = _buildParameters.Culture;
            CultureInfo.CurrentUICulture = _buildParameters.UICulture;

            // Get the node ID.
            _buildParameters.NodeId      = configuration.NodeId;
            _buildParameters.IsOutOfProc = true;

#if FEATURE_APPDOMAIN
            // And the AppDomainSetup
            _buildParameters.AppDomainSetup = configuration.AppDomainSetup;
#endif

            // Set up the logging service.
            LoggingServiceFactory loggingServiceFactory = new LoggingServiceFactory(LoggerMode.Asynchronous, configuration.NodeId);
            _componentFactories.ReplaceFactory(BuildComponentType.LoggingService, loggingServiceFactory.CreateInstance);

            _loggingService = _componentFactories.GetComponent(BuildComponentType.LoggingService) as ILoggingService;

            BuildEventArgTransportSink sink = new BuildEventArgTransportSink(SendPacket);

            _shutdownException = null;

            if (configuration.LoggingNodeConfiguration.IncludeEvaluationMetaprojects)
            {
                _loggingService.IncludeEvaluationMetaprojects = true;
            }

            if (configuration.LoggingNodeConfiguration.IncludeEvaluationProfiles)
            {
                _loggingService.IncludeEvaluationProfile = true;
            }

            if (configuration.LoggingNodeConfiguration.IncludeTaskInputs)
            {
                _loggingService.IncludeTaskInputs = true;
            }

            if (configuration.LoggingNodeConfiguration.IncludeEvaluationPropertiesAndItems)
            {
                _loggingService.IncludeEvaluationPropertiesAndItems = true;
            }

            try
            {
                // If there are no node loggers to initialize dont do anything
                if (configuration.LoggerDescriptions?.Length > 0)
                {
                    _loggingService.InitializeNodeLoggers(configuration.LoggerDescriptions, sink, configuration.NodeId);
                }
            }
            catch (Exception ex) when(!ExceptionHandling.IsCriticalException(ex))
            {
                OnEngineException(ex);
            }

            _loggingService.OnLoggingThreadException += OnLoggingThreadException;

            string   forwardPropertiesFromChild = Environment.GetEnvironmentVariable("MSBUILDFORWARDPROPERTIESFROMCHILD");
            string[] propertyListToSerialize    = null;

            // Get a list of properties which should be serialized
            if (!String.IsNullOrEmpty(forwardPropertiesFromChild))
            {
                propertyListToSerialize = forwardPropertiesFromChild.Split(MSBuildConstants.SemicolonChar, StringSplitOptions.RemoveEmptyEntries);
            }

            _loggingService.PropertiesToSerialize = propertyListToSerialize;
            _loggingService.RunningOnRemoteNode   = true;

            string forwardAllProperties = Environment.GetEnvironmentVariable("MSBUILDFORWARDALLPROPERTIESFROMCHILD");
            if (String.Equals(forwardAllProperties, "1", StringComparison.OrdinalIgnoreCase) || _buildParameters.LogInitialPropertiesAndItems)
            {
                _loggingService.SerializeAllProperties = true;
            }
            else
            {
                _loggingService.SerializeAllProperties = false;
            }

            // Now prep the buildRequestEngine for the build.
            _loggingContext = new NodeLoggingContext(_loggingService, configuration.NodeId, false /* inProcNode */);

            if (_shutdownException != null)
            {
                HandleShutdown(out Exception exception);
                throw exception;
            }

            _buildRequestEngine.InitializeForBuild(_loggingContext);

            // Finally store off this configuration packet.
            _currentConfiguration = configuration;
        }
        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);
        }
Beispiel #40
0
 public BuildResult Build(BuildParameters parameters, BuildRequestData requestData)
 {
     throw new NotImplementedException();
 }
Beispiel #41
0
 public void BeginBuild(BuildParameters parameters)
 {
     throw new NotImplementedException();
 }
Beispiel #42
0
        public static ProjectDetails LoadProjectDetails(BuildEnvironment environment)
        {
            var            key = Tuple.Create(environment.ProjectFile, environment.Configuration);
            ProjectDetails details;

            if (_allProjects.TryGetValue(key, out details))
            {
                if (!details.HasChanged())
                {
                    if (_log.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                    {
                        _log.LogDebug($"Using cached project file details for [{environment.ProjectFile}]");
                    }

                    return(details);
                }
                else
                {
                    if (_log.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                    {
                        _log.LogDebug($"Reloading project file details [{environment.ProjectFile}] as one of its imports has been modified.");
                    }
                }
            }

            if (_log.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
            {
                _log.LogDebug($"Loading project file [{environment.ProjectFile}]");
            }

            details = new ProjectDetails();

            var properties = new Dictionary <string, string>(ImmutableDictionary <string, string> .Empty)
            {
                ["DesignTimeBuild"]                  = "true", // this will tell msbuild to not build the dependent projects
                ["BuildingInsideVisualStudio"]       = "true", // this will force CoreCompile task to execute even if all inputs and outputs are up to date
                ["BuildingInsideUnoSourceGenerator"] = "true", // this will force prevent the task to run recursively
                ["Configuration"] = environment.Configuration,
                ["UseHostCompilerIfAvailable"] = "true",
                ["UseSharedCompilation"]       = "true",
                ["VisualStudioVersion"]        = environment.VisualStudioVersion,

                // Force the intermediate path to be different from the VS default path
                // so that the generated files don't mess up the file count for incremental builds.
                ["IntermediateOutputPath"] = Path.Combine(environment.OutputPath, "obj") + Path.DirectorySeparatorChar
            };

            // Target framework is required for the MSBuild 15.0 Cross Compilation.
            // Loading a project without the target framework results in an empty project, which interatively
            // sets the TargetFramework property.
            if (environment.TargetFramework.HasValue())
            {
                properties["TargetFramework"] = environment.TargetFramework;
            }

            // TargetFrameworkRootPath is used by VS4Mac to determine the
            // location of frameworks like Xamarin.iOS.
            if (environment.TargetFrameworkRootPath.HasValue())
            {
                properties["TargetFrameworkRootPath"] = environment.TargetFrameworkRootPath;
            }

            // Platform is intentionally kept as not defined, to avoid having
            // dependent projects being loaded with a platform they don't support.
            // properties["Platform"] = _platform;

            var xmlReader  = XmlReader.Create(environment.ProjectFile);
            var collection = new Microsoft.Build.Evaluation.ProjectCollection();

            // Change this logger details to troubleshoot project loading details.
            collection.RegisterLogger(new Microsoft.Build.Logging.ConsoleLogger()
            {
                Verbosity = LoggerVerbosity.Minimal
            });

            // Uncomment this to enable file logging for debugging purposes.
            // collection.RegisterLogger(new Microsoft.Build.BuildEngine.FileLogger() { Verbosity = LoggerVerbosity.Diagnostic, Parameters = $@"logfile=c:\temp\build\MSBuild.{Guid.NewGuid()}.log" });

            collection.OnlyLogCriticalEvents = false;
            var xml = Microsoft.Build.Construction.ProjectRootElement.Create(xmlReader, collection);

            // When constructing a project from an XmlReader, MSBuild cannot determine the project file path.  Setting the
            // path explicitly is necessary so that the reserved properties like $(MSBuildProjectDirectory) will work.
            xml.FullPath = Path.GetFullPath(environment.ProjectFile);

            var loadedProject = new Microsoft.Build.Evaluation.Project(
                xml,
                properties,
                toolsVersion: null,
                projectCollection: collection
                );

            var buildTargets = new BuildTargets(loadedProject, "Compile");

            // don't execute anything after CoreCompile target, since we've
            // already done everything we need to compute compiler inputs by then.
            buildTargets.RemoveAfter("CoreCompile", includeTargetInRemoval: true);

            details.Configuration = environment.Configuration;
            details.LoadedProject = loadedProject;

            // create a project instance to be executed by build engine.
            // The executed project will hold the final model of the project after execution via msbuild.
            details.ExecutedProject = loadedProject.CreateProjectInstance();

            var hostServices = new Microsoft.Build.Execution.HostServices();

            // connect the host "callback" object with the host services, so we get called back with the exact inputs to the compiler task.
            hostServices.RegisterHostObject(loadedProject.FullPath, "CoreCompile", "Csc", null);

            var buildParameters = new Microsoft.Build.Execution.BuildParameters(loadedProject.ProjectCollection);

            // This allows for the loggers to
            buildParameters.Loggers = collection.Loggers;

            var buildRequestData = new Microsoft.Build.Execution.BuildRequestData(details.ExecutedProject, buildTargets.Targets, hostServices);

            var result = BuildAsync(buildParameters, buildRequestData);

            if (result.Exception == null)
            {
                ValidateOutputPath(details.ExecutedProject);

                var projectFilePath = Path.GetFullPath(Path.GetDirectoryName(environment.ProjectFile));

                details.References = details.ExecutedProject.GetItems("ReferencePath").Select(r => r.EvaluatedInclude).ToArray();

                if (!details.References.Any())
                {
                    if (_log.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Error))
                    {
                        _log.LogError($"Project has no references.");
                    }

                    LogFailedTargets(environment.ProjectFile, result);
                    details.Generators = new (Type, Func <SourceGenerator>)[0];