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 ]

Comments (53)

  1. Gauthier Segay says:

    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; }

    }

  2. msbuild says:

    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

  3. Shadi Mari says:

    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?

  4. Introduction

    Ok you have written your custom build task (if not visit MSDN for a starting point or here…

  5. Karine Bosch says:

    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

  6. 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.

  7. Rathinavelan says:

    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

  8. Sometimes a user might want to add vcbuild commandline optins (such as /useenv (/u)/wrnfile:&amp;lt;file…

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

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

  11. bankruptcy says:

    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

  12. gifts says:

    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

  13. truck new says:

    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

  14. christmas1 says:

    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

  15. gift4 says:

    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

  16. 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

  17. mortgage1 says:

    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

  18. 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

  19. cadillac says:

    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

  20. 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

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

  22. 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

  23. pizdavsem says:

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

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

  24. pizdavsem says:

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

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

  25. degree mya says:

    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

  26. prokuror says:

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

  27. gerpescom says:

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

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

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

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

  30. David Savage says:

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

  31. Ryan McLean says:

    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

  32. Ryan McLean says:

    Actually never mind, turns out it was the IDE I was using that was timing out and killing MSBuild

  33. Anthony Harrison says:

    Thanks Mike, this is still relevant in 2015. 9 years later, great post!