Пример #1
0
        public void StartBatchBuild(IDictionary <string, string> globalProperties = null)
        {
            if (_batchBuildStarted)
            {
                throw new InvalidOperationException();
            }

            globalProperties = globalProperties ?? ImmutableDictionary <string, string> .Empty;
            var allProperties = s_defaultGlobalProperties.AddRange(globalProperties);

            _batchBuildProjectCollection = new MSB.Evaluation.ProjectCollection(allProperties);

            _batchBuildLogger = new MSBuildDiagnosticLogger()
            {
                Verbosity = MSB.Framework.LoggerVerbosity.Normal
            };

            var buildParameters = new MSB.Execution.BuildParameters(_batchBuildProjectCollection)
            {
                Loggers = new MSB.Framework.ILogger[] { _batchBuildLogger }
            };

            MSB.Execution.BuildManager.DefaultBuildManager.BeginBuild(buildParameters);

            _batchBuildStarted = true;
        }
Пример #2
0
        public async Task BuildSolution(string target)
        {
            State = AppState.Building;
            BuildStarted?.Invoke(this, EventArgs.Empty);

            var results = new List <Microsoft.Build.Execution.BuildResult>();

            await Task.Factory.StartNew(() =>
            {
                ClearOutput();

                var msbuild = Microsoft.Build.Execution.BuildManager.DefaultBuildManager;
                var projs   = Microsoft.Build.Evaluation.ProjectCollection.GlobalProjectCollection;

                projs.AddToolset(new Microsoft.Build.Evaluation.Toolset("Current", Path.Combine(DotNetInfo.SdkPath, DotNetInfo.SdkVersion), projs, Path.Combine(DotNetInfo.SdkPath, DotNetInfo.SdkVersion)));

                var globalProperties = new Dictionary <string, string>()
                {
                    { "Configuration", SelectedConfiguration },
                    { "PlatformTarget", SelectedPlatform }
                };

                foreach (var proj in this.Workspace.CurrentSolution.Projects)
                {
                    projs.LoadProject(proj.FilePath);
                }

                var parameters = new Microsoft.Build.Execution.BuildParameters(projs);

                var loggers = new List <Microsoft.Build.Framework.ILogger>();
                var cl      = new Microsoft.Build.Logging.ConsoleLogger(Microsoft.Build.Framework.LoggerVerbosity.Normal, new Microsoft.Build.Logging.WriteHandler((s) => MSBuildLog(s)), new Microsoft.Build.Logging.ColorSetter((c) => MSBuildLogSetColor(c)), new Microsoft.Build.Logging.ColorResetter(() => MSBuildLogResetColor()));

                loggers.Add(cl);

                parameters.Loggers = loggers;

                msbuild.BeginBuild(parameters);

                var targets = new[] { target };

                if (!target.Equals("restore", StringComparison.OrdinalIgnoreCase) && !target.Equals("clean", StringComparison.OrdinalIgnoreCase))
                {
                    targets = new[] { "restore", target };
                }

                foreach (var p in Workspace.ProjectInstances)
                {
                    var pinstance   = new Microsoft.Build.Execution.ProjectInstance(p.FullPath, globalProperties, projs.DefaultToolsVersion, projs);
                    var requestData = new Microsoft.Build.Execution.BuildRequestData(pinstance, targets);

                    results.Add(msbuild.BuildRequest(requestData));
                }

                msbuild.EndBuild();
            });

            State = AppState.SolutionReady;
            BuildFinished?.Invoke(this, EventArgs.Empty);
            OnBuildFinished(results);
        }
Пример #3
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));
     }
 }
Пример #4
0
        public async Task <bool> BuildProject(BuildMode mode)
        {
            var referencePath = this.GetReferencePath();

            if (!Directory.Exists(referencePath))
            {
                Directory.CreateDirectory(referencePath);
            }

            foreach (var file in this._referenceFiles)
            {
                File.Copy(file, Path.Combine(referencePath, file), true);
            }

            foreach (var configuration in this.CurrentProject.BuildConfigurations)
            {
                configuration.CopyMonoGameFrameworkDLL(referencePath);
            }

            var result = await this.BuildContent(mode);

            var tempDirectoryPath = this.GetTempDirectoryPath();

            if (result)
            {
                await Task.Run(async() => {
                    this.CurrentProject.GameSettings.StartupScenePath = Path.ChangeExtension(this.CurrentProject.StartUpSceneAsset?.GetContentPath(), null);

                    var properties = new Dictionary <string, string> {
                        { "Configuration", mode.ToString() }
                    };

                    var solutionPath    = this.GetSolutionPath();
                    var buildParameters = new Microsoft.Build.Execution.BuildParameters();
                    var buildRequest    = new Microsoft.Build.Execution.BuildRequestData(solutionPath, properties, null, new string[] { "Build" }, null);
                    var buildResult     = Microsoft.Build.Execution.BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest);
                    result &= buildResult.OverallResult == Microsoft.Build.Execution.BuildResultCode.Success;

                    if (result)
                    {
                        await FileHelper.DeleteDirectory(tempDirectoryPath, SecondsToAttemptDelete, true);
                        FileHelper.CopyDirectory(this.GetBinPath(true), tempDirectoryPath);
                    }
                    else if (!Directory.Exists(tempDirectoryPath))
                    {
                        Directory.CreateDirectory(tempDirectoryPath);
                        foreach (var file in this._referenceFiles)
                        {
                            File.Copy(file, Path.Combine(tempDirectoryPath, file), true);
                        }
                    }
                });
            }

            await this._assemblyService.LoadAssemblies(tempDirectoryPath);

            return(result);
        }
Пример #5
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="nodeId">The node id.</param>
 /// <param name="buildParameters">The build parameters</param>
 /// <param name="forwardingLoggers">The forwarding loggers.</param>
 /// <param name="appDomainSetup">The AppDomain setup information.</param>
 public NodeConfiguration
 (
     int nodeId,
     BuildParameters buildParameters,
     LoggerDescription[] forwardingLoggers,
     AppDomainSetup appDomainSetup
 )
 {
     _nodeId            = nodeId;
     _buildParameters   = buildParameters;
     _forwardingLoggers = forwardingLoggers;
     _appDomainSetup    = appDomainSetup;
 }
Пример #6
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="nodeId">The node id.</param>
 /// <param name="buildParameters">The build parameters</param>
 /// <param name="forwardingLoggers">The forwarding loggers.</param>
 /// <param name="appDomainSetup">The AppDomain setup information.</param>
 public NodeConfiguration
     (
     int nodeId,
     BuildParameters buildParameters,
     LoggerDescription[] forwardingLoggers,
     AppDomainSetup appDomainSetup
     )
 {
     _nodeId = nodeId;
     _buildParameters = buildParameters;
     _forwardingLoggers = forwardingLoggers;
     _appDomainSetup = appDomainSetup;
 }
Пример #7
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 MSB.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);

            // capture errors that are output in the build log
            var errorBuilder = new StringWriter();
            var errorLogger  = new ErrorLogger(errorBuilder)
            {
                Verbosity = MSB.Framework.LoggerVerbosity.Normal
            };

            buildParameters.Loggers = new MSB.Framework.ILogger[] { errorLogger };

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

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

            if (result.OverallResult == MSB.Execution.BuildResultCode.Failure)
            {
                if (result.Exception != null)
                {
                    return(new BuildInfo(executedProject, result.Exception.Message));
                }
                else
                {
                    return(new BuildInfo(executedProject, errorBuilder.ToString()));
                }
            }
            else
            {
                return(new BuildInfo(executedProject, null));
            }
        }
Пример #8
0
        private void RunBuild(String projectPath, String target, Dictionary <String, String> properties, Action <BuildLogger> handler)
        {
            BuildLogger         logger          = new BuildLogger();
            IVsOutputWindow     outWindow       = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow;
            Guid                generalPaneGuid = VSConstants.GUID_OutWindowDebugPane;
            IVsOutputWindowPane debugPane;

            outWindow.GetPane(ref generalPaneGuid, out debugPane);
            logger.OutputWindow = debugPane;

            logger.Verbosity = LoggerVerbosity.Detailed;
            MsBuild.Execution.BuildRequestData buildRequest = new MsBuild.Execution.BuildRequestData(projectPath, properties, null, new string[] { target }, null);
            MsBuild.Execution.BuildParameters  buildParams  = new MsBuild.Execution.BuildParameters()
            {
                DetailedSummary = false,
                Loggers         = new List <ILogger>()
                {
                    logger
                }
            };

            ThreadPool.QueueUserWorkItem((Object) =>
            {
                String selectedFiles = properties["SelectedFiles"];
                logger.Write(String.Format("Alcantarea info: compile started \"{0}\"\n", selectedFiles));
                try
                {
                    MsBuild.Execution.BuildResult result = MsBuild.Execution.BuildManager.DefaultBuildManager.Build(buildParams, buildRequest);
                    if (result.OverallResult == MsBuild.Execution.BuildResultCode.Success)
                    {
                        logger.Write(String.Format("Alcantarea info: compile succeeded \"{0}\"\n", selectedFiles));
                        handler(logger);
                    }
                    else
                    {
                        logger.Write(String.Format("Alcantarea info: compile failed \"{0}\"\n", selectedFiles));
                    }
                }
                catch (Exception er)
                {
                }
            });
        }
Пример #9
0
        public void Execute(IInstallerBuildContext buildContext)
        {
            var csprojFiles = buildContext.FileSystemAdapter.FindFiles(buildContext.BuildConfiguration.InstallerProjectPath, "*.csproj");

            if (csprojFiles.Length == 0)
            {
                throw new ApplicationException($"Can't find a project file in {buildContext.BuildConfiguration.InstallerProjectPath.AsString()}");
            }

            if (csprojFiles.Length > 1)
            {
                throw new ApplicationException($"Too many project files detected in {buildContext.BuildConfiguration.InstallerProjectPath.AsString()}");
            }


            var csProjFile = csprojFiles.First().AsString();

            buildContext.Logger.Info($"Compiling {csProjFile}");

            var buildRequestData = new Microsoft.Build.Execution.BuildRequestData(csProjFile,
                                                                                  buildContext.BuildConfiguration.GlobalProperties,
                                                                                  null,
                                                                                  new string[] { "Build" },
                                                                                  null);

            var buildParameters = new Microsoft.Build.Execution.BuildParameters()
            {
                Loggers = new Microsoft.Build.Framework.ILogger[] { new CompileActionLogger(buildContext.Logger) }
            };

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

            if (buildResult.Exception != null)
            {
                buildContext.Logger.Exception("MSBuild exception: ", buildResult.Exception);
            }

            if (buildResult.OverallResult == Microsoft.Build.Execution.BuildResultCode.Failure)
            {
                throw new ApplicationException("Compile action failed! See previous errors for more details!");
            }
        }
Пример #10
0
        private static bool RunMsBuild(Project project, IVsOutputWindowPane outputPane)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var parameters = new Microsoft.Build.Execution.BuildParameters(new Microsoft.Build.Evaluation.ProjectCollection())
            {
                //Loggers = new Microsoft.Build.Framework.ILogger[] { new Microsoft.Build.Logging.ConsoleLogger() }
                Loggers = new Microsoft.Build.Framework.ILogger[] { new OutputPaneLogger(outputPane) }
            };
            var globalProperty = new Dictionary <string, string>()
            {
                { "Configuration", project.ConfigurationManager.ActiveConfiguration.ConfigurationName },
                //{"Platform", project.ConfigurationManager.ActiveConfiguration.PlatformName },
            };

            var result = Microsoft.Build.Execution.BuildManager.DefaultBuildManager.Build(
                parameters,
                new Microsoft.Build.Execution.BuildRequestData(project.FullName, globalProperty, null, new [] { "Build" }, null));

            return(result.OverallResult == Microsoft.Build.Execution.BuildResultCode.Success);
        }
Пример #11
0
        public void Start()
        {
            if (_started)
            {
                throw new InvalidOperationException();
            }

            _projectCollection = new MSB.Evaluation.ProjectCollection(s_defaultGlobalProperties);

            _logger = new MSBuildDiagnosticLogger()
            {
                Verbosity = MSB.Framework.LoggerVerbosity.Normal
            };

            var buildParameters = new MSB.Execution.BuildParameters(_projectCollection)
            {
                Loggers = new MSB.Framework.ILogger[] { _logger }
            };

            MSB.Execution.BuildManager.DefaultBuildManager.BeginBuild(buildParameters);

            _started = true;
        }
Пример #12
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;

            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);
        }
Пример #13
0
        private void RunBuild(String projectPath, String target, Dictionary<String, String> properties, Action<BuildLogger> handler)
        {
            BuildLogger logger = new BuildLogger();
            IVsOutputWindow outWindow = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow;
            Guid generalPaneGuid = VSConstants.GUID_OutWindowDebugPane;
            IVsOutputWindowPane debugPane;
            outWindow.GetPane(ref generalPaneGuid, out debugPane);
            logger.OutputWindow = debugPane;

            logger.Verbosity = LoggerVerbosity.Detailed;
            MsBuild.Execution.BuildRequestData buildRequest = new MsBuild.Execution.BuildRequestData(projectPath, properties, null, new string[] { target }, null);
            MsBuild.Execution.BuildParameters buildParams = new MsBuild.Execution.BuildParameters()
            {
                DetailedSummary = false,
                Loggers = new List<ILogger>() { logger }
            };

            ThreadPool.QueueUserWorkItem((Object) =>
            {
                String selectedFiles = properties["SelectedFiles"];
                logger.Write(String.Format("Alcantarea info: compile started \"{0}\"\n", selectedFiles));
                try
                {
                    MsBuild.Execution.BuildResult result = MsBuild.Execution.BuildManager.DefaultBuildManager.Build(buildParams, buildRequest);
                    if (result.OverallResult == MsBuild.Execution.BuildResultCode.Success)
                    {
                        logger.Write(String.Format("Alcantarea info: compile succeeded \"{0}\"\n", selectedFiles));
                        handler(logger);
                    }
                    else
                    {
                        logger.Write(String.Format("Alcantarea info: compile failed \"{0}\"\n", selectedFiles));
                    }
                }
                catch(Exception er)
                {

                }
            });
        }