1

环境:

C# 项目、Visual Studio 2008、C#、.Net 3.5、MSBuild

客观的:

为我的 C# 项目运行我自己的自定义构建任务,并基于平台(Soln 配置平台),在构建之前对 Project 对象本身进行一些操作。比如将 BuildAction 设置为 EmbeddedResource 等。

完成后,我打电话给Project.Build(). 我不想在 GlobalEngine 上使用 Project 对象,因为无论如何修改 Project 对象后,它都会将文件标记为脏文件(并从 TFS 签出)。

问题:

因为我使用的是我自己的引擎实例和项目,所以我无法将构建输出、错误定向到 VS。我只得到一个布尔值Project.Build()。我没有发现任何我可以连接的事件可以允许访问BuildErrorEventArgs和类似的东西。我知道我可以用来Log.LogErrorEvent()将消息记录到 VS 错误列表中。但我需要先获得构建输出本身才能做到这一点。

代码:

// Execute method in my custom build task class, derives from a BaseTask class
public override bool Execute()
{
Engine engine = new Engine();
Project project = new Project(engine);
project.Load(ProjectName);
Log.LogMessage(Microsoft.Build.Framework.MessageImportance.High, "Got the Project");
// Set the project's DefaultTargets to "Build" to be able to build with CSharp targets
project.DefaultTargets = "Build";
IsBuilt = project.Build(); // Isbuilt bool is a property in my BaseTask class
// Here's where I want to get Build output and direct it to VS output window and errorlist window

engine.Shutdown();
return base.Execute();
}
4

1 回答 1

4

我想通了,只需实现一个自定义记录器并在事件处理程序中使用 Log.LogMessage 或 LogError

public class MyCustomBuildLogger : ILogger
{
    private IEventSource source;

 public void Initialize(IEventSource eventSource)
        {
            this.source = eventSource;
            //Events.ProjectStarted += new ProjectStartedEventHandler(Events_ProjectStarted);
            //Events.ProjectFinished += new ProjectFinishedEventHandler(Events_ProjectFinished);
            Events.WarningRaised += new BuildWarningEventHandler(Events_WarningRaised);
            Events.ErrorRaised += new BuildErrorEventHandler(Events_ErrorRaised);
            Events.BuildFinished += new BuildFinishedEventHandler(Events_BuildFinished);
            //Events.BuildStarted += new BuildStartedEventHandler(Events_BuildStarted);
            Events.MessageRaised += new BuildMessageEventHandler(Events_MessageRaised);
            //Events.CustomEventRaised += new CustomBuildEventHandler(Events_CustomEventRaised);

            Events.MessageRaised += new BuildMessageEventHandler(Events_MessageRaised);
        }

 void Events_ErrorRaised(object sender, BuildErrorEventArgs e)
        {
            // This logs the error to VS Error List tool window
            Log.LogError(String.Empty, 


             String.Empty,
                    String.Empty, 
                    e.File, 
                    e.LineNumber, 
                    e.ColumnNumber,
                    e.LineNumber, 
                    e.ColumnNumber, 
                    e.Message);
           }
}

在 MyCustomBuildTask 类中,您可以在其中设置和加载引擎和项目,

_logger = new MyCustomBuildLogger();
_logger.Log = Log;
_engine.RegisterLogger(_logger);
于 2008-12-02T22:33:30.960 回答