示例#1
0
        /// <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
        }
示例#2
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;
            }
        }
示例#3
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));
            }
        }
示例#4
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));
                }
            }
        }
    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;
    }
示例#6
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();
        }
示例#7
0
        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);
            }
        }
示例#8
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));
        }
        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.");
            }
        }
示例#10
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.");
        }
示例#11
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());
            }
        }
示例#12
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);
        }
    }
示例#13
0
        public static string Start(DotnetBuildParams objBuildParams)
        {
            try
            {
                ProjectCollection pc = new ProjectCollection();

                pc.DefaultToolsVersion = "4.0";
                Dictionary<string, string> GlobalProperty = new Dictionary<string, string>();

                GlobalProperty.Add("Configuration", objBuildParams.Configuration);

                GlobalProperty.Add("Platform", objBuildParams.Platform);

                //Here, we set the property

                GlobalProperty.Add("OutputPath", objBuildParams.OutputPath);

                BuildRequestData BuidlRequest = new BuildRequestData(objBuildParams.projectFileName, GlobalProperty, null, objBuildParams.TargetsToBuild, null);

                BuildResult buildResult = BuildManager.DefaultBuildManager.Build(new BuildParameters(pc), BuidlRequest);

                return  ((BuildResultCode)buildResult.OverallResult).ToString();

            }
            catch (Exception ex)
            {
                return BuildResultCode.Failure.ToString() ;
            }
            finally
            {

            }
        }
示例#14
0
        /// <summary>
        /// 
        /// </summary>
        public static bool ReloadScripts()
        {
            if (SceneManager.GameProject == null) return false;

            string projectFileName = SceneManager.GameProject.ProjectPath + @"\Scripts.csproj";
            string tmpProjectFileName = SceneManager.GameProject.ProjectPath + @"\_Scripts.csproj";
            string hash = string.Empty;

            hash = GibboHelper.EncryptMD5(DateTime.Now.ToString());

            try
            {
                /* Change the assembly Name */
                XmlDocument doc = new XmlDocument();
                doc.Load(projectFileName);
                doc.GetElementsByTagName("Project").Item(0).ChildNodes[0]["AssemblyName"].InnerText = hash;
                doc.Save(tmpProjectFileName);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            /* Compile project */
            ProjectCollection projectCollection = new ProjectCollection();
            Dictionary<string, string> GlobalProperty = new Dictionary<string, string>();
            GlobalProperty.Add("Configuration", SceneManager.GameProject.Debug ? "Debug" : "Release");
            GlobalProperty.Add("Platform", "x86");

            BuildRequestData buildRequest = new BuildRequestData(tmpProjectFileName, GlobalProperty, null, new string[] { "Build" }, null);
            BuildResult buildResult = BuildManager.DefaultBuildManager.Build(new BuildParameters(projectCollection), buildRequest);

            Console.WriteLine(buildResult.OverallResult);

            string cPath = SceneManager.GameProject.ProjectPath + @"\bin\" + (SceneManager.GameProject.Debug ? "Debug" : "Release") + "\\" + hash + ".dll";

            if (File.Exists(cPath))
            {
                /* read assembly to memory without locking the file */
                byte[] readAllBytes = File.ReadAllBytes(cPath);
                SceneManager.ScriptsAssembly = Assembly.Load(readAllBytes);

                if (SceneManager.ActiveScene != null)
                {
                    SceneManager.ActiveScene.SaveComponentValues();
                    SceneManager.ActiveScene.Initialize();
                }

                Console.WriteLine("Path: " + SceneManager.ScriptsAssembly.GetName().Name);
            }
            else
            {
                File.Delete(tmpProjectFileName);
                return false;
            }

            File.Delete(tmpProjectFileName);

            return true;
        }
示例#15
0
文件: MSBuild.cs 项目: NN---/nuproj
        /// <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);
        }
示例#16
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;
 }
示例#17
0
		public BuildResult Build (BuildParameters parameters, BuildRequestData requestData)
		{
			BeginBuild (parameters);
			var ret = BuildRequest (requestData);
			EndBuild ();
			return ret;
		}
 public void TestConstructor2NullFile()
 {
     Assert.Throws<ArgumentNullException>(() =>
     {
         BuildRequestData config1 = new BuildRequestData(null, new Dictionary<string, string>(), "toolsVersion", new string[0], null);
     }
    );
 }
 public void TestValidConfiguration()
 {
     BuildRequestData data = new BuildRequestData("file", new Dictionary<string, string>(), "toolsVersion", new string[0], null);
     BuildRequestConfiguration config = new BuildRequestConfiguration(1, data, "2.0");
     ConfigurationMetadata metadata = new ConfigurationMetadata(config);
     Assert.AreEqual(data.ProjectFullPath, metadata.ProjectFullPath);
     Assert.AreEqual(data.ExplicitlySpecifiedToolsVersion, metadata.ToolsVersion);
 }
 public void TestConstructorNullProps()
 {
     Assert.Throws<ArgumentNullException>(() =>
     {
         BuildRequestData config1 = new BuildRequestData("file", null, "toolsVersion", new string[0], null);
     }
    );
 }
示例#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;
		}
 public BuildResult BuildProject(string directoryPath)
 {
     string projectFileName = Path.Combine(directoryPath, MainClassName + ".csproj");
     var projectCollection = new ProjectCollection();
     var globalProperties = new Dictionary<string, string>();
     var buidlRequest = new BuildRequestData(projectFileName, globalProperties, null, new[] { "Build" }, null);
     var buildResult = BuildManager.DefaultBuildManager.Build(new BuildParameters(projectCollection), buidlRequest);
     return buildResult;
 }
        public void TestConstructorGood()
        {
            BuildRequestData data1 = new BuildRequestData("foo", new Dictionary<string, string>(), "tools", new string[0], null);
            FullyQualifiedBuildRequest request = new FullyQualifiedBuildRequest(new BuildRequestConfiguration(data1, "2.0"), new string[1] { "foo" }, true);

            request = new FullyQualifiedBuildRequest(new BuildRequestConfiguration(data1, "2.0"), new string[0] { }, true);

            BuildRequestData data3 = new BuildRequestData("foo", new Dictionary<string, string>(), "tools", new string[0], null);
            request = new FullyQualifiedBuildRequest(new BuildRequestConfiguration(data1, "2.0"), new string[0] { }, false);
        }
 public void TestConstructorInvalidConfigId()
 {
     Assert.Throws<InternalErrorException>(() =>
     {
         BuildRequestData data = new BuildRequestData("file", new Dictionary<string, string>(), "toolsVersion", new string[0], null);
         BuildRequestConfiguration config1 = new BuildRequestConfiguration(1, data, "2.0");
         BuildRequestConfiguration config2 = config1.ShallowCloneWithNewId(0);
     }
    );
 }
 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);
 }
    internal static Task<BuildResult> BuildAsync(this BuildManager buildManager, BuildRequestData buildRequestData)
    {
        Requires.NotNull(buildManager, nameof(buildManager));
        Requires.NotNull(buildRequestData, nameof(buildRequestData));

        var tcs = new TaskCompletionSource<BuildResult>();
        var submission = buildManager.PendBuildRequest(buildRequestData);
        submission.ExecuteAsync(s => tcs.SetResult(s.BuildResult), null);
        return tcs.Task;
    }
        public void TestConstructorGood()
        {
            BuildRequest request = CreateNewBuildRequest(1, new string[0] { });
            BuildRequestData data = new BuildRequestData("foo", new Dictionary<string, string>(), "foo", new string[0], null);
            BuildRequestConfiguration config = new BuildRequestConfiguration(1, data, "2.0");
            BuildRequestEntry entry = new BuildRequestEntry(request, config);

            Assert.AreEqual(entry.State, BuildRequestEntryState.Ready);
            Assert.AreEqual(entry.Request, request);
        }
 public void TestProperties()
 {
     BuildRequestData data = new BuildRequestData("foo", new Dictionary<string, string>(), "tools", new string[0], null);
     BuildRequestConfiguration config = new BuildRequestConfiguration(data, "2.0");
     FullyQualifiedBuildRequest request = new FullyQualifiedBuildRequest(config, new string[1] { "foo" }, true);
     Assert.AreEqual(request.Config, config);
     Assert.AreEqual(request.Targets.Length, 1);
     Assert.AreEqual(request.Targets[0], "foo");
     Assert.AreEqual(request.ResultsNeeded, true);
 }
 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 bool Build()
        {
            BuildManager.DefaultBuildManager.BeginBuild(buildParams);

            BuildRequestData request = new BuildRequestData(buildProject.CreateProjectInstance(), new string[0]);
            BuildSubmission submission = BuildManager.DefaultBuildManager.PendBuildRequest(request);
            var result = submission.Execute();

            BuildManager.DefaultBuildManager.EndBuild();

            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);
        }
示例#32
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;
        }
示例#33
0
        public Option <string> BuildSolution(FilePath SolutionPath)
        {
            var manager = MSEX.BuildManager.DefaultBuildManager;
            var project = new MSEX.ProjectInstance(SolutionPath);

            var logPath      = SolutionPath.ChangeExtension("binlog");
            var buildRequest = new MSEX.BuildRequestData(project, array("Build"));
            var result       = manager.Build
                               (
                new MSEX.BuildParameters
            {
                Loggers = metacore.roitems <ILogger>(new MSL.ConsoleLogger())
            },
                buildRequest
                               );

            var targetResults = result.ResultsByTarget["Build"];

            return(targetResults.ResultCode.ToString());
        }
示例#34
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);
        }
示例#35
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);
        }
示例#36
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];
示例#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);
        }
示例#38
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();
                }
            }
        }
示例#39
0
        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);
        }
示例#40
0
 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));
     }
 }