Welcome to MSDN Blogs Sign in | Join | Help

How To: Implementing Custom Tasks - Part I

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="http://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 ]

Published Saturday, January 21, 2006 11:01 PM by msbuild
Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

Saturday, January 21, 2006 7:52 PM by Gauthier Segay

# re: How To: Implementing Custom Tasks - Part I

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; }
}
Sunday, January 22, 2006 6:35 PM by msbuild

# re: How To: Implementing Custom Tasks - Part I

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
Saturday, February 04, 2006 10:30 AM by Antoine Driard

# Team Build : comment cr

Monday, February 20, 2006 12:49 PM by Shadi Mari

# re: How To: Implementing Custom Tasks - Part I

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?
Tuesday, February 28, 2006 2:22 AM by Grant Archibald

# MSI deployment of custom team build task

Introduction
Ok you have written your custom build task (if not visit MSDN for a starting point or here...
Tuesday, February 28, 2006 7:13 AM by Karine Bosch

# re: How To: Implementing Custom Tasks - Part I

Hi,

I'm developing a nightly build process. Two of the tasks I need to execute, is uninstalling a windows service before the compilation of the sources starts; and installing and registering a windows service when the sources are compiled and before unit testing starts. I've created my custom tasks. But how can I define in my build file when these tasks need to execute?

Kind regards,

Karine
Wednesday, March 01, 2006 6:59 PM by Tod Birdsall, MCSD for .NET

# re: How To: Implementing Custom Tasks - Part I

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.
Sunday, April 16, 2006 1:15 PM by Rathinavelan

# re: How To: Implementing Custom Tasks - Part I

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
Friday, June 16, 2006 7:43 AM by Chaitanya's Blog

# TeamBuild and VC++ - adding additional vcbuild options

Sometimes a user might want to add vcbuild commandline optins (such as /useenv (/u)/wrnfile:&amp;lt;file...
Friday, December 22, 2006 2:22 PM by Visual Studio Team System en français

# Team Build : comment créer vos propres tâches

Team Build, pour ceux qui n'auraient pas suivi, est le module d'intégration/build de Team System. Il

# re: How To: Implementing Custom Tasks - Part I

Cool design, great info! Would you please also visit my homepage?

Tuesday, July 24, 2007 12:58 AM by ctl00$_$ctl00$_$ctl01$_$form$_$tbname

# re: How To: Implementing Custom Tasks - Part I

ultram weight <a href= http://dimko11111.kostenloses-forum.com >ultram mg</a> [url=http://dimko11111.kostenloses-forum.com]ultram mg[/url]

Tuesday, July 24, 2007 8:23 PM by ctl00$_$ctl00$_$ctl01$_$form$_$tbname

# re: How To: Implementing Custom Tasks - Part I

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]

Wednesday, July 25, 2007 2:56 AM by ctl00$_$ctl00$_$ctl01$_$form$_$tbname

# re: How To: Implementing Custom Tasks - Part I

estate ultram <a href= http://ultra.blogtopia.com >ultram 3ctd</a> [url=http://ultra.blogtopia.com]ultram 3ctd[/url]

Saturday, December 01, 2007 1:38 AM by bankruptcy

# re: How To: Implementing Custom Tasks - Part I

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

Wednesday, December 12, 2007 6:56 AM by gifts

# re: How To: Implementing Custom Tasks - Part I

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

Sunday, December 16, 2007 12:20 PM by truck new

# re: How To: Implementing Custom Tasks - Part I

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

Wednesday, December 19, 2007 8:06 PM by christmas1

# re: How To: Implementing Custom Tasks - Part I

Funny sites <a href="http://christmasforu1.info/104.html ">counted cross stitch christmas ornament</a> <a href="http://christmasforu1.info/553.html ">hosta night before christmas</a> <a href="http://christmasforu1.info/294.html ">advent calendar christmas lampoons national vacation</a> <a href="http://christmasforu1.info/315.html ">felt christmas tree advent calendar</a> [URL=http://christmasforu1.info/22.html]1996 christmas crystal ornament swarovski[/URL] [URL=http://christmasforu1.info/43.html]a christmas carol madison square garden[/URL] more

Thursday, December 20, 2007 1:40 PM by gift4

# re: How To: Implementing Custom Tasks - Part I

All about site <a href="http://giftforyou2.info/712.html ">chilis gift certificate</a> <a href="http://giftforyou2.info/33.html ">balloon and gift delivery boise idaho</a> <a href="http://giftforyou2.info/662.html ">cellophane gift wrap</a> <a href="http://giftforyou2.info/795.html ">cleveland fruit and gift basket</a> [URL=http://giftforyou2.info/360.html]zadie gifts jewish[/URL] [URL=http://giftforyou2.info/765.html]christmas gift for chef christmas cards hotgiftideasnet[/URL] online

Tuesday, January 08, 2008 8:32 PM by volkswagen cars

# re: How To: Implementing Custom Tasks - Part I

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

Tuesday, February 05, 2008 3:02 AM by mortgage1

# mortgage1

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

Saturday, February 09, 2008 11:52 PM by my_credit_card

# my_credit_card

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

Wednesday, March 05, 2008 4:22 AM by cadillac

# cadillac

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

Thursday, March 06, 2008 5:41 PM by real estate c blog

# real estate c blog

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

# Installing Windows Services Remotely Using C# - Part 3 | Jared Boelen's Soapbox

Thursday, May 08, 2008 2:44 PM by ctl00$_$ctl00$_$ctl01$_$form$_$tbname

# антимаулнетизм надежно

антимаулнетизм оперативно <a href= http://antiprivichka.ru >антимаулнетизм надежно</a> [url=http://antiprivichka.ru]антимаулнетизм надежно[/url]

Monday, June 09, 2008 4:26 PM by furniture store

# furniture store

Looking <a href="http://fenasik.info/200.html ">painted furniture in the dc metro</a> <a href="http://fenasik.info/157.html ">office furniture malaysia sdn bhd</a> <a href="http://fenasik.info/274.html ">hendredon furniture</a> <a href="http://fenasik.info/339.html ">royce furniture website</a> [URL=http://fenasik.info/512.html]bar furniture georgia[/URL] [URL=http://fenasik.info/399.html]exterior wood furniture[/URL] groove

Sunday, July 13, 2008 9:56 AM by pizdavsem

# re: How To: Implementing Custom Tasks - Part I

Great site! You can find related info on the following sites:

<a href= http://www.google.com/pizda >vsem pizda, ya skazal!</a>

Sunday, July 13, 2008 9:56 AM by pizdavsem

# re: How To: Implementing Custom Tasks - Part I

Great site! You can find related info on the following sites:

<a href= http://www.google.com/pizda >vsem pizda, ya skazal!</a>

Wednesday, July 16, 2008 2:17 AM by degree mya

# degree mya

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

Wednesday, August 13, 2008 5:46 AM by prokuror

# Заявление - исковое заявление, как верно составить форму заявления

<a href = "http://zayvka.ru">  Заявление</a> - заявление в суд, на данном сайте рассказанно как  правильно составить образец и бланк искового заявления. Публикации и статьи практикующих юристов, большое количество различных образцов и форм составления заявлений.

Tuesday, September 02, 2008 6:16 AM by <a href = "http://ndflnalog.ru">форма 2 ндфл </a>

# <a href = "http://ndflnalog.ru">ндфл </a>

<a href = "http://ndflnalog.ru">3 ндфл </a>

Sunday, November 16, 2008 8:57 AM by gerpescom

# Герпес - познавательный сайт повествующий про половой герпес.

Герпес - лечить болезнь при помощи антибиотиков. Ресурс будет полезен всем болеющим половым герпесом, а также врачам и аспирантам, и любому кому интересны проблемы герпеса.

Tuesday, November 18, 2008 11:46 AM by http://il1.ru/

# Лечить геморрой - лечить заболевание при помощи народных средств.

Геморрой - лечить болезнь при помощи антибиотиков. Сайт будет полезен всем страдающим анальными трещинами, а также врачам и аспирантам, и любому кому интересны проблемы геморроя. Отдельный раздел ресурса посвящен методам излечения от геморроя при помощи народной медицины.

Sunday, January 18, 2009 11:31 AM by Customising Setup Projects | keyongtech

# Customising Setup Projects | keyongtech

Friday, February 06, 2009 9:34 PM by http://hemorrhoid.ru/

# Климакс симптомы - все самое важное и необходимое про менопаузу.

Климакс - все самое важное и необходимое про климакс. На ваши вопросы про состояние климакса ответят на страницах нашего ресурса практикующие врачи геронтологи высшей квалификации. Наш сайт подробно расскажет вам о том, что такое предклимакс и почему климакс еще называют менопаузой, мы рассматриваем как изменяется  форма и функциональность груди, какие проблемы могут возникнуть со зрением. Новый раздел нашего сайта представляет информацию о подготовке к  наступлению климакса, также есть информация про правильное питание во время климакса.

Главное знать - ничего страшного в климаксе нет, климакса не нужно бояться. Климакс или Менопауза это все лишь новое состояние вашего организма.

Monday, March 09, 2009 5:01 PM by David Savage

# 6 Things Every ASP.NET Developer Should Know by 2010

A look at the top 6 things that I think all developers should know by 2010.

# MSBuild Team Blog How To Implementing Custom Tasks Part I | Paid Surveys

# MSBuild Team Blog How To Implementing Custom Tasks Part I | My Site

# MSBuild Team Blog How To Implementing Custom Tasks Part I | Hammock Stand

# MSBuild Team Blog How To Implementing Custom Tasks Part I | Green Tea Fat Burner

# MSBuild Team Blog How To Implementing Custom Tasks Part I | outdoor rugs

# MSBuild Team Blog How To Implementing Custom Tasks Part I | debt settlement program

# MSBuild Team Blog How To Implementing Custom Tasks Part I | fix my credit

# MSBuild Team Blog How To Implementing Custom Tasks Part I | patio set

# MSBuild Team Blog How To Implementing Custom Tasks Part I | bar stools

# MSBuild Team Blog How To Implementing Custom Tasks Part I | porch swing

# MSBuild Team Blog How To Implementing Custom Tasks Part I | garden statues

# MSBuild Team Blog How To Implementing Custom Tasks Part I | adirondack chairs

# MSBuild Team Blog How To Implementing Custom Tasks Part I | debt consolidator

# MSBuild Team Blog How To Implementing Custom Tasks Part I | debt solutions

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker