- | rssFeed | My book on MSBuild and Team Build | Archives and Categories Friday, June 27, 2008

MSBuild Conditions on Targets

This post is related to my  previous post MSBuild RE: Enforcing the Build Agent in a Team Build which is a response on the post by Michael Ruminer at http://manicprogrammer.com/cs/blogs/michaelruminer/archive/2008/06/19/enforcing-the-build-agent-in-a-team-build.aspx.

Basically every MSBuild element can contain a Condtions attribute. You can read more at MSBuild Conditions. So even targets can have conditions attached to them! Despite the fact that you can do this, you should not. I recommend that you do not use conditions on targets. Conditions on targets seem straight forward but after you take a closer look they are more complicated. We can take a look at some of the items that come to mind here.

Conditions on targets and DependsOnTargets don’t play well

Take a look at this simple project file

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="2.0"
         xmlns="
http://schemas.microsoft.com/developer/msbuild/2003"
         DefaultTargets="Demo">

  <PropertyGroup>
    <AllowTarget>true</AllowTarget>
  </PropertyGroup>

  <Target Name="SupressTarget">
    <CreateProperty Value="false">
      <Output PropertyName="AllowTarget" TaskParameter="Value"/>
    </CreateProperty>
    <Message Text=" ==== SupressTarget ==== " Importance="high"/>
    <Message Text="AllowTarget: $(AllowTarget)"/>
  </Target>
 
 
  <Target Name="Demo" Condition="'$(AllowTarget)'=='true'"
          DependsOnTargets="SupressTarget">
    <Message Text=" ===== Demo ===== " Importance="high" />

    <Message Text="AllowTarget: $(AllowTarget)"/>
  </Target>
 
</Project>

In this project the main target is Demo and it depends on a target SupressTarget which actually disables the Demo target based on its condition. If you execute the command msbuild /t:Demo you get the results shown below.

Most users would expect that the target SupressTarget target would execute which sets the AllowTarget value to false, and then the Demo target is skipped. But what is happening here is that by the time DependsOnTargets is evaluated the condition has already been evaluated and has passed! The even more interesting thing here is if you execute msbuild /t:SupressTarget;Demo the results are shown below.

 

So this time it was skipped, because SupressTarget was called before the Demo target was invoked so the condition evaluated to false.

 

Conditions and target batching doesn’t work well either

If you are batching a target and you want to execute the target for some batches but not others, this cannot be achieved with target conditions, for a few reasons but the simplest is: Either a target is or is not defined. When the target is going to be executed for the first time the condition is evaluated. If the condition is true it will exist, otherwise it will not.

I thought of some other issues but they are not coming to me at this time, but I think this is enough to deter you from using target dependencies. Instead of target dependencies you should take a look at other way of achieving the same results.

 

Sayed Ibrahim Hashimi

msbuild | Team Build | TFS Friday, June 27, 2008 7:28:35 AM (GMT Daylight Time, UTC+01:00)  #     | 
Friday, June 20, 2008

MSBuild RE: Enforcing the Build Agent in a Team Build

This is a post that responds to a post by Michael Ruminer at Enforcing the Build Agent in a Team Build. I hope I correctly understand his situation. Here is my summary of it.

My solution to this problem is to create a property, AllowedBuildAgents, which will contain a semi-colon separated list of the allowed build agent names. Then this is converted into an item, AllowedBuildAgentsItem, so batching can be preformed over it. If you are not familiar with MSBuild batching you can see my previous postings at:

The main objective here is to create an item that contains all the allowed names, AllowedBuildAgentsItem, and batch over them. If the value for BuildAgentName is equal to any value in that item then we want to allow the build. I create a property BuildAgentAllowed which defaults to false, and if that condition is true then I set BuildAgentAllowed to true. So I created a target DetermineIfAuthorizedBuildAgent that depends will throw an error if BuildAgentAllowed is false. Also this target depends on the target that will actually populate that value, which is the GetBuildAgentAllowed target. The build script is placed below. I added a few elements that were for demo only. Those are; value for BuildAgentName and BeforeEndToEndIteration target. See comments in the file (which can be downloaded at the end of this post).

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="2.0"
         xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
         DefaultTargets="BeforeEndToEndIteration">

  <!--
  Assume that this value has been set already.
  I'm declaring it here for this demonstration.
  -->
  <PropertyGroup>
    <BuildAgentName>Sayed_001</BuildAgentName>
  </PropertyGroup>

 
 
  <PropertyGroup>
    <BeforeEndToEndIterationDependsOn>
      $(BeforeEndToEndIterationDependsOn);
      DetermineIfAuthorizedBuildAgent;
    </BeforeEndToEndIterationDependsOn>
  </PropertyGroup>

  <!--
  Define this here as a property so it can be passed
  via Properties from various callers.
  -->
  <PropertyGroup>
    <AllowedBuildAgents>Sayed_001;Sayed_003;Sayed_005</AllowedBuildAgents>
  </PropertyGroup>

  <!--
  Convert the property into an item so we can batch over it.
  -->
  <ItemGroup>
    <AllowedBuildAgentsItem Include="$(AllowedBuildAgents)"/>
  </ItemGroup>
  <!--
  Specify this value to false. If allowed it will be set to true.
  -->
  <PropertyGroup>
    <BuildAgentAllowed>false</BuildAgentAllowed>
  </PropertyGroup>
 
 

  <Target Name="PrintInfo">
    <Message Text="AllowedBuildAgentsItem: @(AllowedBuildAgentsItem,'%0a%0d')"/>
  </Target>

  <!-- Executing this target will make the GetBuildAgentAllowed target execute first -->
  <Target Name="DetermineIfAuthorizedBuildAgent"
          DependsOnTargets="GetBuildAgentAllowed">
    <Message Text="BuildAgentAllowed: $(BuildAgentAllowed)"/>
    <Error Text="This build can only be run on one of the following build agents: @(AllowedBuildAgentsItem)" 
           Condition="'$(BuildAgentAllowed)'=='false'" />
  </Target>
 
  <!--
  This target will be executed for each value in the AllowedBuildAgentsItem.
  If the BuildAgentName is equal to any value in AllowedBuildAgentsItem then the
  property BuildAgentAllowed will be set to true.
  -->
  <Target Name="GetBuildAgentAllowed" Outputs="%(AllowedBuildAgentsItem.Identity)">
    <Message Text="GetBuildAgentAllowed %25(AllowedBuildAgentsItem.Identity): %(AllowedBuildAgentsItem.Identity)"/>
   
    <CreateProperty Value="true" Condition="'$(BuildAgentName)'=='%(AllowedBuildAgentsItem.Identity)'">
      <Output PropertyName="BuildAgentAllowed" TaskParameter="Value"/>
    </CreateProperty>
   
  </Target>


 
  <!--
  This target is really executed by TeamBuild but I will
  put it here for demonstration. If this target executes then the build
  was allowed otherwise an error will be shown.
  -->
  <Target Name="BeforeEndToEndIteration" DependsOnTargets="$(BeforeEndToEndIterationDependsOn)">
    <Message Text="EndToEndIteration starting"/>
  </Target>
 
</Project>

The only reason that I have defined the allowed build agents in a property (AllowedBuildAgents) is because I want to allow external sources to specify it. You can specify properties through the command line or when using the MSBuild Task. Then the script converts this to an item. If I execute this project I would expect it to succeed because the defined value for BuildAgentName is contained in the list of AllowedBuildAgents. The results of executing this project are shown below.

Now we can change the value for BuildAgentName, by using the command msbuild.exe BuildAgent01.proj /p:BuildAgentName=Sayed_010. We would expect the build to fail. The results of this are below.

   

So the build failed as expected so we are good. Any questions?

   

BuildAgent01.proj

Sayed Ibrahim Hashimi

Friday, June 20, 2008 5:22:57 AM (GMT Daylight Time, UTC+01:00)  #     | 
Monday, June 16, 2008

Changing Build Verbosity in Visual Studio

If you are customizing your build process you may need to increase the verbosity that Visual Studio uses when building your projects. It is pretty easy to change this value, you just go to Tools->Options then find the Project and Solutions->Build and Run node. The dialog is shown here

The area where the verbosity setting lies is highlighted. I've got mine set to Detailed, which produces a lot of output. If you set it to Diagnostic, then you should be ready for a lot of output. Most like much more then you need!


Sayed Ibrahim Hashimi

msbuild | Visual Studio Monday, June 16, 2008 6:50:26 AM (GMT Daylight Time, UTC+01:00)  #     | 
Monday, June 09, 2008

MSBuild Reserved Properties

If you take a look the MSDN documentation for the reserved MSBuild Reserved Properties you will see many properties listed. For one reason or another there are actually several reserved properties that are missing from that list. Here is the list of all the reserved properties, the ones missing from that page are presented here in bold. For those that are listed on that page the description is taken from the MSDN. Also this is the list for MSBuild 3.5.

 

 

Take a look at this project file that prints out these values.

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
DefaultTargets="PrintProperties"
ToolsVersion="3.5">

<Target Name="PrintProperties">
<Message Text="MSBuildNodeCount: $(MSBuildNodeCount)"/>
<Message Text="MSBuildExtensionsPath32: $(MSBuildExtensionsPath32)"/>
<Message Text="MSBuildProjectDirectoryNoRoot: $(MSBuildProjectDirectoryNoRoot)"/>
<Message Text="MSBuildToolsPath: $(MSBuildToolsPath)"/>
<Message Text="MSBuildToolsVersion: $(MSBuildToolsVersion)"/>
<Message Text="MSBuildBinPath: $(MSBuildBinPath)"/>
<Message Text="MSBuildExtensionsPath: $(MSBuildExtensionsPath)"/>
<Message Text="MSBuildProjectDefaultTargets: $(MSBuildProjectDefaultTargets)"/>
<Message Text="MSBuildProjectDirectory: $(MSBuildProjectDirectory)"/>
<Message Text="MSBuildProjectExtension: $(MSBuildProjectExtension)"/>
<Message Text="MSBuildProjectFile: $(MSBuildProjectFile)"/>
<Message Text="MSBuildProjectFullPath: $(MSBuildProjectFullPath)"/>
<Message Text="MSBuildProjectName: $(MSBuildProjectName)"/>
<Message Text="MSBuildStartupDirectory: $(MSBuildStartupDirectory)"/>

</Target>
</Project>

If you execute this you will get something like what's shown here.

 

I'm not sure how important this, but you may need to know one day.

ReservedProperties.proj

Sayed Ibrahim Hashimi

msbuild Monday, June 09, 2008 6:52:31 AM (GMT Daylight Time, UTC+01:00)  #     | 
Wednesday, June 04, 2008

DataContract XML Helper

Lately I've been doing some work with WCF and I have had a need to easily convert from object->XML and from XML->object. These XML strings were created using the DataContractSerializer. So I threw together this util class [yeah I know I probably shouldn't have these, but you know you do too J ]. There are really 2 methods GetDataContractXml and BuildFromDataContractXml. The GetDataContractXml returns the XML for the object provided and the BuildFromDataContractXml method will create the object from the XML string. These methods have both a generic and non-generic method. The non-generic versions are particularly useful if you are using this with reflection. Anywayz, the class itself is shown below, and you can download the file at the bottom of this post.

///
/// © Copyright Sayed Ibrahim Hashimi
/// www.sedodream.com
///
using System;
using System.IO;
using System.Xml;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Xml.Serialization;
namespace Sedodream.Sample.Serialization01.Util
{
    public static class XmlUtils
    {
        /// 
        /// Builds an object of the specified type from the given
        /// XML representation that can be passed to the DataContractSerializer
        /// 
        public static object BuildFromDataContractXml(string xml, Type type)
        {
            if (string.IsNullOrEmpty(xml)) {throw new ArgumentNullException("xml"); }
            if (type == null) { throw new ArgumentNullException("type"); }

            object result = null;
            DataContractSerializer dcs = new DataContractSerializer(type);
            using (StringReader reader = new StringReader(xml))
            using (XmlReader xmlReader = new XmlTextReader(reader))
            {
                result = dcs.ReadObject(xmlReader);
            }

            return result;
        }
        /// 
        /// Builds an object from its XML 
        /// representation that can be passed to the DataContractSerializer.
        /// 
        public static T BuildFromDataContractXml(string xml)
        {
            if (string.IsNullOrEmpty(xml)) { throw new ArgumentNullException("xml"); }

            T result = default(T);

            object objResult = BuildFromDataContractXml(xml, typeof(T));
            if (objResult != null)
            {
                result = (T)objResult;
            }
            return result;
        }
        /// 
        /// Gets the XML representation of the given object
        /// by using the DataContracSerializer.
        /// 
        public static string GetDataContractXml(T obj)
        {
            if (obj == null) { throw new ArgumentNullException("obj"); }

            return GetDataContractXml(obj.GetType(), obj);
        }
        /// 
        /// Gets the XML representation of the given object
        /// of specfiied type by using the DataContracSerializer.
        /// 
        public static string GetDataContractXml(Type type, object val)
        {
            if (type == null) { throw new ArgumentNullException("type"); }
            if (val == null) { throw new ArgumentNullException("val"); }

            MemoryStream ms = new MemoryStream();
            string xml = null;
            try
            {
                DataContractSerializer dcs = new DataContractSerializer(type);

                using (XmlTextWriter xmlTextWriter = new XmlTextWriter(ms, System.Text.Encoding.Default))
                {
                    xmlTextWriter.Formatting = System.Xml.Formatting.Indented;
                    dcs.WriteObject(xmlTextWriter, val);
                    xmlTextWriter.Flush();
                    ms = (MemoryStream)xmlTextWriter.BaseStream;
                    ms.Flush();
                    xml = UTF8ByteArrayToString(ms.ToArray());
                }
            }
            finally
            {
                if (ms != null)
                {
                    ms.Close();
                    ms = null;
                }
            }
            return xml;

        }
        /// 
        /// Writes the XML representation from the DataContractSerializer
        /// into the specified filename. If a file at filename
        /// already exists then an Exception will be thrown.
        /// 
        public static void WriteDateContractToFile(string filename, T obj)
        {
            WriteDateContractToFile(filename, obj.GetType(), obj);
        }
        /// 
        /// Writes the XML representation from the DataContractSerializer
        /// into the specified filename. If a file at filename
        /// already exists then an Exception will be thrown.
        /// 
        public static void WriteDateContractToFile(string filename, Type type, object val)
        {
            if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("filename"); }
            if (val == null) { throw new ArgumentNullException("val"); }

            if (File.Exists(filename)) { throw new ArgumentException("filname"); }

            //TODO: Stream this into the file instead of this!!!
            File.WriteAllText(filename, GetDataContractXml(type, val));
        }
        private static String UTF8ByteArrayToString(Byte[] characters)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            string constructedString = encoding.GetString(characters);
            return (constructedString);
        }
        private static Byte[] StringToUTF8ByteArray(String pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }
    }
}

To show how this can be used here is a quick sample unit test shown below, this will be a part of a later post on a related topic.

using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using Sedodream.Sample.Serialization01;
using Sedodream.Sample.Serialization01.Util;

namespace unittest.Sedodream.Sample.Serialization01
{
    [TestFixture]
    public class TestXmlUtils
    {
        [Test]
        public void TestCreateXml()
        {
            string name = "Sayed Ibrahim Hashimi";
            string email = "sayed.hashimi@gmail.com";


            Person person = new Person();
            person.Name = name;
            person.Email = email;

            string xml = XmlUtils.GetDataContractXml(person);
            Assert.IsTrue(!string.IsNullOrEmpty(xml));
            Assert.IsTrue(xml.Contains(name));
            Assert.IsTrue(xml.Contains(email));
        }
        [Test]
        public void TestCreateFromXml()
        {
            const string xml =
@"
  sayed.hashimi@gmail.com
  9891668d-8107-4f3e-85a4-79e941453be2
  Sayed Ibrahim Hashimi
";

            string name = "Sayed Ibrahim Hashimi";
            string email = "sayed.hashimi@gmail.com";
            Guid id = new Guid("9891668d-8107-4f3e-85a4-79e941453be2");

            Person person = XmlUtils.BuildFromDataContractXml(xml);
            Assert.IsNotNull(person);
            Assert.AreEqual(name, person.Name);
            Assert.AreEqual(email, person.Email);
            Assert.AreEqual(id, person.Id);
        }
    }
}

Where the simple Person class is shown here

[DataContract(Namespace="http://schemas.sedodream.com/Serialization/2008/04")]
public class Person
{
    #region Constructors
    public Person()
    {
        Id = Guid.NewGuid();
    }
    #endregion

    [DataMember]
    public string Name
    {
        get;
        set;
    }
    [DataMember]
    public string Email
    {
        get;
        set;
    }
    [DataMember]
    public Guid Id
    {
        get;
        set;
    }
}

From the two simply test you can see how to create the object from the XML string and vice versa. As far as I know these work pretty good, if you find any issues please let me know and I can update them. At some point I will post some more information that is related to this keep an eye for it.

 

XmlUtils.cs

Sayed Ibrahim Hashimi

DataContractSerializer | WCF Wednesday, June 04, 2008 6:54:58 AM (GMT Daylight Time, UTC+01:00)  #     |