Ask Learn
Preview
Please sign in to use this experience.
Sign inThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
While MSBuild is all about build customization,we never really blogged about what is involved in implementing custom tasks. Partly, I suppose that's because implementing a custom task is as easy as falling off a log most of the time: 1) Subclass Microsoft.Build.Utilities.Task abstract class 2) Implement the Execute method
But there's a lot more to tasks than just that. In this series of posts, I hope to cover all there is to know about MSBuild tasks - both at a conceptual level as well as on variations such as ToolTask, AppDomainIsolatedTask, etc. In this post I'd like to set the context for discussing some of those topics.
A task, in principle is nothing more than an implementation of the GoF Command Object Pattern i.e. an object that knows how to perform an action encapsulated via an Execute method. While it is possible to utilize tasks programmatically via code, the primary motivation was to provide a way of performing self standing units of work within build targets.
In the crudest form, a task is a type that implements the Microsoft.Build.Framework.ITask interface from the Microsoft.Build.Framework assembly. Here's a simple implementation of a task that can set environment variables.
using Microsoft.Build.Framework;
namespace SimpleTask
{
public class SetEnvironmentVariable : ITask
{
private IBuildEngine engine;
public IBuildEngine BuildEngine
{
get { return engine; }
set { engine = value; }
}
private ITaskHost host;
public ITaskHost HostObject
{
get { return host; }
set { host = value; }
}
private string name;
[Required]
public string Name
{
get { return name; }
set { name = value; }
}
private string varValue;
[Required]
public string Value
{
get { return varValue; }
set { varValue = value; }
}
public bool Execute()
{
System.Environment.SetEnvironmentVariable(name, varValue);
string message = string.Format("Environment Variable {0} set to {1}", name, varValue);
BuildMessageEventArgs args = new BuildMessageEventArgs(
message, string.Empty, "SetEnvironmentVariable", MessageImportance.Normal);
engine.LogMessageEvent(args);
return true;
}
}
}
In addition to the Execute method that performs the actual work, at the minimum all tasks must expose two properties - BuildEngine of type IBuildEngine, and HostObject of type ITaskHost. For the purposes of most tasks, the implementation I have shown here will suffice.
IBuildEngine itself is used by the task to report messages, warnings and errors to the MSBuild engine. ITaskHost is an interface that is used to represent host objects that can form a basis for richer communication between tasks and an environment that hosts MSBuild (such as Visual Studio). ITaskHost is extremely useful in cases where you are hosting the build engine yourself. I will cover the details of this beast in a later post.
.NET properties on a task type allow you define parameters on the task in order to communicate with the task via the project file. So, in the case of the SetEnvironmentVariable task, I have defined Name and Value properties as inputs into the task. My use of the Required attribute on these two properties ensures that the invocation of the tasks will not be possible without specifying those two parameters. In this context, it makes sense because the task cannot perform its function without having those to values specified to it.
Finally, returning true from the Execute method indicates success to the MSBuild engine. I have ignored the possibility of the task failing in this case to keep it simple - look for more details on this subject alone in a subsequent post.
Here's how the task is invoked from a project file:
<Project xmlns="https://schemas.microsoft.com/developer/msbuild/2003">
<UsingTask AssemblyFile="SimpleTasks.dll" TaskName="SimpleTask.SetEnvironmentVariable" />
<PropertyGroup>
<OutputPath>c:\temp</OutputPath>
</PropertyGroup>
<Target Name="MyTarget">
<SetEnvironmentVariable Name="OutputPath" value="$(OutputPath)" />
</Target>
</Project>
That's all there is to defining and using custom tasks. Of course, it is way simpler to derive from the abstract class Microsoft.Build.Utilities.Task that is included in the Microsoft.Build.Utilities assembly, and that's what you should be using most of the time unless you require a richer interaction with the MSBuild engine.
In the next post, I will dig into more details on interacting with tasks via the project file. We will examine the types of objects that can be passed in and out of tasks, caveats to watch out for, etc.
[ Author: Faisal Mohamood ]
Anonymous
January 21, 2006
Hi I don't have digged much on msbuild, it's great to have a MS supported build tool and find it very similar to the Ant approach.
By the way, I think your exemple is not working:
[Required]
public string Value
{
get { return Value; }
set { varValue = value; }
}
it should be:
[Required]
public string Value
{
get { return varValue; }
set { varValue = value; }
}
Anonymous
January 22, 2006
Yes - thanks for pointing out the mistake. I had tried the task out before I posted it - but obviously the get property was not getting used becasue I had not used it as an Output property, and that's why I didn't spot the mistake.
Good catch!
Faisal Mohamood
Anonymous
February 20, 2006
How can i define two task matually exclusive properties where either one of them is required in case the other is not specified.
e.g. In a database operation task, either [usename & password] or Trusted_Connection=Yes can be specified.
I wonder if this is possible in MsBuild?
Anonymous
February 27, 2006
Introduction
Ok you have written your custom build task (if not visit MSDN for a starting point or here...
Anonymous
February 27, 2006
The comment has been removed
Anonymous
March 01, 2006
Thank you for the nice tutorial. I used it as a reference for creating a custom MSBuild Task to label projects in Visual SourceSafe. I then created a tutorial and published it on my site and at The Code Project. Here is the link:
http://www.tod1d.net/articles/MSBuild_Tutorial_SourceSafe_Label_Task.asp
I hope others find it useful.
Anonymous
April 16, 2006
Hi all, I have the same issue/request for information as Karine Bosch , I need to be able to stop an installed windows service, and start it, upon successfull deployment in the app server, FYI, I am able to successfully build the application ( web application) in the Build server, and copy it to the app server, and there by deploying the fresh web build.
Only issue now is this windows server, any help will be appreciated
Anonymous
June 15, 2006
Sometimes a user might want to add vcbuild commandline optins (such as /useenv (/u)/wrnfile:&lt;file...
Anonymous
December 22, 2006
Team Build, pour ceux qui n'auraient pas suivi, est le module d'intégration/build de Team System. Il
Anonymous
June 16, 2007
Cool design, great info! Would you please also visit my homepage?
Anonymous
July 23, 2007
ultram weight <a href= http://dimko11111.kostenloses-forum.com >ultram mg</a> [url=http://dimko11111.kostenloses-forum.com]ultram mg[/url]
Anonymous
July 24, 2007
tab ultram <a href= http://cutalink.com/rug-prescription.org/s5.php > tab ultram</a> [url=http://cutalink.com/rug-prescription.org/s5.php] tab ultram[/url]
Anonymous
July 24, 2007
estate ultram <a href= http://ultra.blogtopia.com >ultram 3ctd</a> [url=http://ultra.blogtopia.com]ultram 3ctd[/url]
Anonymous
November 30, 2007
All about <a href="http://dikiw.info/152.html ">amicable bankruptcy scottish</a> <a href="http://dikiw.info/509.html ">bankruptcy injury kmart lawsuit personal</a> <a href="http://dikiw.info/274.html ">bankruptcy thermoplastics</a> <a href="http://dikiw.info/59.html ">cornelius pools bankruptcy</a> [URL=http://dikiw.info/304.html]mikal gilmore bankruptcy[/URL] [URL=http://dikiw.info/49.html]bankruptcy metaldyne[/URL] nice
Anonymous
December 11, 2007
Greetings <a href="http://dotora.info/628.html ">gift in ireland mcsweeneys today</a> <a href="http://dotora.info/661.html ">giftware independent</a> <a href="http://dotora.info/326.html ">black masked lovebird gifts</a> <a href="http://dotora.info/367.html ">biotherm gift</a> [URL=http://dotora.info/632.html]pampering gifts for women[/URL] [URL=http://dotora.info/709.html]ceramic premium gift malaysia[/URL] too
Anonymous
December 16, 2007
In bookmarks <a href="http://ecilika.info/616.html ">tonka monster trucks serial</a> <a href="http://ecilika.info/197.html ">toyota trucks hompepage</a> <a href="http://ecilika.info/738.html ">dodge big horn truck</a> <a href="http://ecilika.info/691.html ">jack rabbit truck topper</a> [URL=http://ecilika.info/492.html]moveing trucks[/URL] [URL=http://ecilika.info/195.html]used pickup trucks in akron ohio[/URL] loves
Anonymous
December 19, 2007
The comment has been removed
Anonymous
December 20, 2007
The comment has been removed
Anonymous
January 08, 2008
Budu v tope <a href="http://hikcax.info/60.html ">volkswagen group milton keynes</a> <a href="http://hikcax.info/485.html ">1999 volkswagen jetta wolfsburg edition</a> <a href="http://hikcax.info/770.html ">2000 volkswagen jetta gls</a> <a href="http://hikcax.info/755.html ">volkswagen touareg w12 for sale</a> [URL=http://hikcax.info/196.html]volkswagen diesel 2007[/URL] [URL=http://hikcax.info/523.html]2001 volkswagen golf gls specifications[/URL] and other
Anonymous
February 04, 2008
Nice world <a href="http://aroundall3.info/836.html ">vendee mortgage trust</a> <a href="http://aroundall3.info/157.html ">mortgage calculator td</a> <a href="http://aroundall3.info/802.html ">baloon mortgage</a> <a href="http://aroundall3.info/703.html ">sps mortgage</a> [URL=http://aroundall3.info/574.html]assumable mortgages alberta[/URL] [URL=http://aroundall3.info/11.html]manhatten mortgage[/URL] portals
Anonymous
February 09, 2008
Hello, people <a href="http://bank-cards-inf.info/144.html ">hsbc credit card login</a> <a href="http://bank-cards-inf.info/33.html ">bmi baby credit card</a> <a href="http://bank-cards-inf.info/150.html ">instant credit card</a> <a href="http://bank-cards-inf.info/43.html ">canadian tire mastercard</a> [URL=http://bank-cards-inf.info/64.html]citibank citicards[/URL] [URL=http://bank-cards-inf.info/165.html]low intrest credit cards[/URL] best
Anonymous
March 04, 2008
Access <a href="http://gikasde.info/396.html ">cadillac seville diesel</a> <a href="http://gikasde.info/781.html ">cadillac seville sts</a> <a href="http://gikasde.info/446.html ">history of the fleetwood cadillac</a> <a href="http://gikasde.info/39.html ">1957 cadillac biarritz convertible</a> [URL=http://gikasde.info/694.html]cadillac broughman[/URL] [URL=http://gikasde.info/421.html]feature programming mode cadillac seville 2002[/URL] work
Anonymous
March 06, 2008
Welcome to <a href="http://real-estate-cblog.info/644.html ">pavones real estate</a> <a href="http://real-estate-cblog.info/605.html ">pagosa springs colorado real estate</a> <a href="http://real-estate-cblog.info/434.html ">nayarit real estate</a> <a href="http://real-estate-cblog.info/907.html ">real estate appraiser license sc</a> [URL=http://real-estate-cblog.info/330.html]montelongo real estate[/URL] [URL=http://real-estate-cblog.info/691.html]peterborough nh real estate[/URL] more
Anonymous
April 28, 2008
PingBack from http://blog.jrboelens.com/?p=8
Anonymous
May 08, 2008
антимаулнетизм оперативно <a href= http://antiprivichka.ru >антимаулнетизм надежно</a> [url=http://antiprivichka.ru]антимаулнетизм надежно[/url]
Anonymous
June 09, 2008
The comment has been removed
Anonymous
July 13, 2008
The comment has been removed
Anonymous
July 13, 2008
The comment has been removed
Anonymous
July 15, 2008
Funny sites <a href="http://xcsabj.info/160.html ">school locker organizer</a> <a href="http://xcsabj.info/225.html ">radiologist school jobs lincoln nebraska</a> <a href="http://xcsabj.info/14.html ">ventura college pirates</a> <a href="http://xcsabj.info/15.html ">veggietales preschool curriculum kit</a> [URL=http://xcsabj.info/50.html]thelearningchannel[/URL] [URL=http://xcsabj.info/381.html]online school for paranormal investigator[/URL] likes
Anonymous
August 12, 2008
<a href = "http://zayvka.ru"> Заявление</a> - заявление в суд, на данном сайте рассказанно как правильно составить образец и бланк искового заявления. Публикации и статьи практикующих юристов, большое количество различных образцов и форм составления заявлений.
Anonymous
September 01, 2008
<a href = "http://ndflnalog.ru">3 ндфл </a>
Anonymous
November 16, 2008
Герпес - лечить болезнь при помощи антибиотиков. Ресурс будет полезен всем болеющим половым герпесом, а также врачам и аспирантам, и любому кому интересны проблемы герпеса.
Anonymous
November 18, 2008
Геморрой - лечить болезнь при помощи антибиотиков. Сайт будет полезен всем страдающим анальными трещинами, а также врачам и аспирантам, и любому кому интересны проблемы геморроя. Отдельный раздел ресурса посвящен методам излечения от геморроя при помощи народной медицины.
Anonymous
January 18, 2009
PingBack from http://www.keyongtech.com/1189333-customising-setup-projects
Anonymous
February 06, 2009
The comment has been removed
Anonymous
March 09, 2009
A look at the top 6 things that I think all developers should know by 2010.
Anonymous
May 29, 2009
PingBack from http://paidsurveyshub.info/story.php?title=msbuild-team-blog-how-to-implementing-custom-tasks-part-i
Anonymous
May 31, 2009
PingBack from http://patiochairsite.info/story.php?id=1114
Anonymous
May 31, 2009
PingBack from http://hammockstandsite.info/story.php?id=515
Anonymous
June 07, 2009
PingBack from http://greenteafatburner.info/story.php?id=1192
Anonymous
June 13, 2009
PingBack from http://onlyoutdoorrugs.info/story.php?id=797
Anonymous
June 15, 2009
PingBack from http://edebtsettlementprogram.info/story.php?id=22225
Anonymous
June 16, 2009
PingBack from http://fixmycrediteasily.info/story.php?id=2357
Anonymous
June 17, 2009
PingBack from http://patiosetsite.info/story.php?id=424
Anonymous
June 18, 2009
PingBack from http://barstoolsite.info/story.php?id=1179
Anonymous
June 18, 2009
PingBack from http://fancyporchswing.info/story.php?id=1599
Anonymous
June 18, 2009
PingBack from http://gardenstatuesgalore.info/story.php?id=1277
Anonymous
June 18, 2009
PingBack from http://adirondackchairshub.info/story.php?id=2393
Anonymous
June 19, 2009
PingBack from http://mydebtconsolidator.info/story.php?id=15460
Anonymous
June 19, 2009
PingBack from http://debtsolutionsnow.info/story.php?id=1098
Anonymous
January 28, 2013
Is there a default timeout impletemented y MSBuild for a custom task and if so can it be overridden?
I have a custom task that calls uses weblcient.downloadfile to download a 900Mb file, the code works fie if run from a c# console program but if I call it from an MSBuild script as a Custom Task then it fails after 30seconds.
Regards,
Ryan
Anonymous
February 04, 2013
Actually never mind, turns out it was the IDE I was using that was timing out and killing MSBuild
Anonymous
August 27, 2015
Thanks Mike, this is still relevant in 2015. 9 years later, great post!
Please sign in to use this experience.
Sign in