Examples of tasks include Copy, which copies one or more files, MakeDir, which creates a directory, and Csc, which compiles Visual C# source code files. Each task is implemented as a .NET class that implements the ITask interface, which is defined in the Microsoft.Build.Framework.dll assembly.
There are two approaches you can use when implementing a task:
Implement the ITask interface directly.
Derive your class from the helper class, Task, which is defined in the Microsoft.Build.Utilities.dll assembly. Task implements ITask and provides default implementations of some ITask members. Additionally, logging is easier.
In both cases, you must add to your class a method named Execute, which is the method that is called when the task runs. This method takes no parameters and returns a Boolean value: true if the task succeeded or false if it failed. The following example shows a task that performs no action and returns true.
|
using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace MyTasks
{
public class SimpleTask : Task
{
public override bool Execute()
{
return true;
}
}
}
|
The following project file runs this task:
|
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="MyTarget">
<SimpleTask />
</Target>
</Project>
|
When tasks run, they can also receive inputs from the project file if you create .NET properties on the task class. MSBuild sets these properties immediately before calling the task's Execute method. To create a string property, use task code such as:
|
using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace MyTasks
{
public class SimpleTask : Task
{
public override bool Execute()
{
return true;
}
private string myProperty;
public string MyProperty
{
get { return myProperty; }
set { myProperty = value; }
}
}
}
|
The following project file runs this task and sets MyProperty to the given value:
|
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="MyTarget">
<SimpleTask MyProperty="Value for MyProperty" />
</Target>
</Project>
|