- | rssFeed | My book on MSBuild and Team Build | Archives and Categories 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)  #     | 
Thursday, May 22, 2008

MSBuild Output Inferral and CreateProperty.ValueSetByTask

Ok there is this hidden feature of MSBuild its called output inferral. This is used when a target is skipped due its Inputs & Outputs (incremental building) but the target creates properties and items. Eventhough the inputs and outputs are up to date the side effects (properties & items) may change the rest of the build process. Because of this output inferral is required. When a target is skipped MSBuild will inspect the target for properties & items that were created and create those. This will ensure that other targets down the chain will not be affected by the target being skipped. In MSBuild 3.5 there is a new property on the CreateProperty task, this property is ValueSetByTask. The whole purpose of this is to only be used when you do not want its value to be inferred. By using this property instead of Value you would be guaranteed that the target was actually executed. Let's clear this up with an example take a look at the project file shown below.

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

<!--
This target will always be skipped .
Neither property One or Two exists but One will be inferred
by MSBuild.
-->
<Target Name="SetupValues"
Inputs="$(MSBuildProjectFullPath)"
Outputs="$(MSBuildProjectFullPath)">

<Message Text="SetuptValues Executed!" Importance="high"/>

<CreateProperty Value="1111">
<Output PropertyName="One" TaskParameter="Value"/>
<!-- Property One is actually inferred by this statement. -->
</CreateProperty>
<CreateProperty Value="2222">
<Output PropertyName="Two" TaskParameter="ValueSetByTask"/>
<!-- Using ValueSetByTask we can ensure bypassing any inferring here -->
</CreateProperty>

<PropertyGroup>
<!-- 3.5 syntax: Property Three is also inferred -->
<Three>3333</Three>
</PropertyGroup>

<!-- Items are inferred too! -->
<ItemGroup>
<File Include="app.config"/>
</ItemGroup>
</Target>

<Target Name="PrintValues" DependsOnTargets="SetupValues">
<Message Text="One: $(One)" />
<Message Text="Two: $(Two)" />
<Message Text="Three: $(Three)"/>
<Message Text="File: @(File)"/>
</Target>

</Project>

In this file (you can download from link at end) there are two targets, SetupValues and PrintValues. PrintValues depends on SetupValues. Because the Inputs and Outputs on SetupValues point to the same file the target will always be skipped. But we declare properties and items so they have to be inferred by the MSBuidl engine so that the remainder of the build will not be hosed because of it. If you execute the PrintValues target the result would be what you see in the image below.

As you can see the values for the properties One & Three were provided by inference but the value for Two was passed over because it uses the ValueSetByTask instead of Value. I would suggest that you continue to use the Value property and not the ValueSetByTask unless you are trying to detect this exact scenario, which most of the time shouldn't matter anywayz.

OutputInferral.proj


Sayed Ibrahim Hashimi

msbuild Thursday, May 22, 2008 6:09:41 AM (GMT Daylight Time, UTC+01:00)  #     | 
Thursday, May 08, 2008

MSBuild: Building the same project multiple times

After some discussion at the MSBuild MSDN Forum I started investigating building the same project with different Compiler constants defined. I was actually pretty surprised by what I found. I created a simple Windows Form Application with a lone button one it. The image below show the simple app.

Here is the entire code behind file.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

namespace WindowsFormsApplication1

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

 

private void buttonExample_Click(object sender, EventArgs e)

{

string message = "default message";

#if CONSTANT_ONE

message = "CONSTANT_ONE";

#endif

#if CONSTANT_TWO

message = "CONSTANT_TWO";

#endif

 

MessageBox.Show(message);

}

}

}

Ddd

The parts to take note are the regions highlighted in yellow. So if the constant CONSTANT_ONE is defined the message results to CONSTANT_ONE and if CONSTANT_TWO is defined it will show the message CONSTANT_TWO.

I then created the simple build file.

<?xml version="1.0" encoding="utf-8"?>

<Project DefaultTargets="BuildAll" ToolsVersion="3.5"

xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

 

<PropertyGroup>

<ConstOne>CONSTANT_ONE</ConstOne>

<ConstTwo>CONSTANT_TWO</ConstTwo>

</PropertyGroup>

 

<ItemGroup>

<Projects Include="$(MSBuildProjectDirectory)\..\WindowsFormsApplication1\WindowsFormsApplication1.csproj">

</Projects>

</ItemGroup>

 

<!--

Cleans the project before we start the build process.

The only reason I am calling this is to remove artifacts of

previous builds, to clearly demonstrate what's going on.

-->

<Target Name="CleanAll">

<MSBuild Projects="@(Projects)" Targets="Clean" />

</Target>

 

<Target Name="BuildAll" DependsOnTargets="CleanAll;BuildConstOne;BuildConstTwo" />

 

<Target Name="BuildConstOne">

<MSBuild Projects="@(Projects)"

Properties="DefineConstants=$(ConstOne);OutputPath=binOne\;"/>

</Target>

<Target Name="BuildConstTwo">

<MSBuild Projects="@(Projects)"

Properties="DefineConstants=$(ConstTwo);OutputPath=binTwo\;"

 

/>

</Target>

 

<!-- ===========================================================================

This region rebuilds the projects, so after it is built once it is then cleaned

before building it again.

This produces the assemblies with the desired behavior

================================================================================-->

 

<Target Name="ReBuildAll" DependsOnTargets="CleanAll;ReBuildConstOne;ReBuildConstTwo" />

<Target Name="ReBuildConstOne">

<MSBuild Projects="@(Projects)" Targets="Rebuild"

Properties="DefineConstants=$(ConstOne);OutputPath=binOne\;"/>

</Target>

<Target Name="ReBuildConstTwo">

<MSBuild Projects="@(Projects)" Targets="Rebuild"

Properties="DefineConstants=$(ConstTwo);OutputPath=binTwo\;"/>

</Target>

 

<!--==========================================================================

This region calls the default target (Build) but also specifies the

BaseIntermediateOutputPath so it works as well because the projects

are building to different locations on disk.

==============================================================================-->

<Target Name="BuildAllBetter" DependsOnTargets="CleanAll;BuildConstOneBetter;BuildConstTwoBetter" />

<Target Name="BuildConstOneBetter">

<MSBuild Projects="@(Projects)"

Properties="DefineConstants=$(ConstOne);OutputPath=binOne\BaseIntermediateOutputPath=objOne\"/>

</Target>

<Target Name="BuildConstTwoBetter">

<MSBuild Projects="@(Projects)"

Properties="DefineConstants=$(ConstTwo);OutputPath=binTwo\;BaseIntermediateOutputPath=objTwo\;"

 

/>

</Target>

 

</Project>

Ddddd

Let's take a look at what's going on here. The BuildConstOne target passes the CONSTANT_ONE value as a property when invoking the MSBuild task, and builds to the binOne folder. The BuildConstTwo target passes the CONSTANT_TWO value and builds to binTwo. If you execute the target BuildAll, you would expect that the exe in binOne would show the message CONSTANT_ONE and the exe in the binTwo folder has CONSTANT_TWO message showing. What you actually get is that both actually show CONSTANT_ONE. This is because MSBuild doesn't entirely rebuild the project when building it for the second time in BuildConstTwo. The real reason behind this would be because both projects are building to the same BaseIntermediateOutputPath, obj\. There are two ways to of getting around this, one is to call Rebuild instead of Build, and the other is to specify the BaseIntermediateOutputPath as well. In the above I have demonstrated both approaches. The ReBuildAll calls Rebuild, and the BuildAllBetter specifies the BaseIntermediateOutputPath as well as OutputPath.

Questions?!

You can download all the files at:

DefineConst.zip

Sayed Ibrahim Hashimi

msbuild | Visual Studio Thursday, May 08, 2008 12:52:14 AM (GMT Daylight Time, UTC+01:00)  #     | 
Tuesday, April 29, 2008

How to debug MSBuild tasks

A question that comes up pretty frequently is "How can I debug an MSBuild task"? It's actually pretty simple. In this post I will describe how to easily an effectively debug MSBuild tasks that you are creating. In this example I will be demonstrating a task from my open source tasks at www.codeplex.com/Sedodream. The task is one that was contributed by Grant Holliday.

First in the project where your tasks are contained create a folder that will be used to contain sample MSBuid files that can be used to debug the tasks. This is also a good idea, because it will show people how to use your tasks. If you are don't want to mix samples & code in the same project then just make sure in your build you copy the files to the correct locations. In the sample project, which you can download at the bottom, the folder is named Samples. When you add MSBuild files to the folder make sure you set the file to be copied to the output folder as well. See the image below.

By setting this, the file will be copied to the output folder when the project is built. Since it will be in the output folder we can use a relative path to get to the assembly that contains the task. Take a look at the sample MSBuild file for this task.

<?xml version="1.0" encoding="utf-8"?>

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

   <PropertyGroup>

    <TaskLocation Condition="$(TaskLocation)==''">$(MSBuildProjectDirectory)\..\DebugTask.dll</TaskLocation>

  </PropertyGroup>

   <UsingTask TaskName="CreateGuid" AssemblyFile="$(TaskLocation)"/>

 

  <Target Name="Example">

    <Message Text="Starting example" />

    <CreateGuid>

        <Output PropertyName="Guid" TaskParameter="Output"/>

      </CreateGuid>

    <Message Text="Guid: $(Guid)" />

   </Target>

</Project>

 

The line highlighted contains the path to the assembly that contains the task. This path is relative to the location in the output folder, not the source folder. Also another thing to take note, is that we only write to the TaskLocation property if it is empty. This is useful because you can overwrite the location through command line parameters if necessary. But this shouldn't be needed for what we are trying to accomplish here.

After you create the sample, build the solution. And open a command prompt to verify that it works. Here is a sample of the result of this project file.

Once you've verified that that MSBuild file works then you can right click on the project that contains your task, and select properties. From there go to the debug tab. What we want to do is start the msbuild.exe executable on that sample project file. To do this fill in the full path to it in the Start External program text box, i.e. 'C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe'. In the command line arguments you should pass the name of the project file followed by any msbuild parameters. Typically I will attach a file logger to the process. Finally you should set the working directory to the folder containing the sample. The result should look something like the image shown below.

Following this set a break point in your task, set the project as the startup project and hit F5! Another thing to take note of is that these properties are stored in the .user file so it shouldn't affect any other developers on your team.

Below is the link containing a simple solution that was used here.

 

DebugTask.zip

Sayed Ibrahim Hashimi

msbuild | Visual Studio Tuesday, April 29, 2008 6:10:03 AM (GMT Daylight Time, UTC+01:00)  #     | 
Tuesday, April 15, 2008

MSBuild + JSLint = Good Javascript

Recently I was introduced to a tool that was to a tool that would analyze Javascript for syntactical errors as well as usage of bad practices. This tool is JSLint. Douglas Crockford from Yahoo! created, and maintains, JSLint. If you haven't heard of him, he is a well known Javascript expert.

Now how can we verify our Javascript with JSLint & MSBuild? In my open source project Sedodream MSBuild I have created a new JSLint task. You can get the installer by going to http://www.codeplex.com/Release/ProjectReleases.aspx?ProjectName=Sedodream&ReleaseId=12530. After you install the msi you can follow these steps to invoke the JSLint on your projects.

Edit your web project file and include the following snippet before the </Project> tag.

<Import Project="$(MSBuildExtensionsPath)\Sedodream\Sedodream.tasks"/>

<Import Project="$(MSBuildExtensionsPath)\Sedodream\JSLint.targets"/>

 

<PropertyGroup>

<BuildDependsOn>

$(BuildDependsOn);

RunJSLint;

</BuildDependsOn>

</PropertyGroup>

 

The first line includes makes the tasks from my project available, and the second line includes the file that knows how to execute the JSLint tool. Following that I extend the build process to execute the RunJSLint target. If you are not familiar with this take a look at my article Inside MSBuild.

After you do this you may be prompted with a security warning from Visual Studio, you should pick 'Load Project Normally'. You can read more about how to disable it at http://msdn2.microsoft.com/en-us/library/ms228217.aspx. I chose to not have my installer set that registry flag. For the time being I think that users should make that decision themselves, although I would like to think I'm trustworthy J

After you do this and allow Visual Studio to load the project normally, if your create Javascript files that have errors, or JSLint doesn't like you will be warned in the error list as shown below.

 

With that being said keep in mind this is a V1 deal, so this may not work perfect. I am working to make sure that it works well, but it was kinda tricky to get this to work period!

As always I welcome your feedback and I will post more info about this later. Oh yeah by default from JSLint the GoodParts are enforced keep an eye on this blog, or send me a message, to see how to change that.

Sayed Ibrahim Hashimi

msbuild | Visual Studio | Javascript Tuesday, April 15, 2008 6:25:01 AM (GMT Daylight Time, UTC+01:00)  #     | 
Friday, March 28, 2008

MSBuild Batching Part 3

This post is to supplement the two previous posts that I have focused on batching those are located at:

Batching continues to be confusing and I hope that that post will help to further clarify it a little bit. In the two previous posts I think that I was "hiding" what was really happening by using built in metadata. This time I will expose what's happening by a simple example that only uses custom metadata. The first thing to know about batching, it always occurs over metadata, either Well Known or custom. Take a look at the project file shown below, Batching03.proj.

<!—

© Copyright 2008, Sayed Ibrahim Hashimi (sayed.hashimi@gmail.com)

-->

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

<ItemGroup>

<Server Include="Server1">

<Type>2008</Type>

<Name>SVR01</Name>

</Server>

<Server Include="Server2">

<Type>2003</Type>

<Name>SVR02</Name>

</Server>

<Server Include="Server3">

<Type>2008</Type>

<Name>SVR03</Name>

</Server>

<Server Include="Server4">

<Type>2003</Type>

<Name>SVR04</Name>

</Server>

</ItemGroup>

 

<Target Name="TaskBatching">

<Message Text="%40(Server->'%(Name)'): @(Server->'%(Name)')" />

<Message Text="===========================================" />

<!--

Task Batching Here over the Name metadata.

Notice that Message task is invoked once per unique batch

-->

<Message Text="%25(Server.Name): %(Server.Name)" />

<Message Text="===========================================" />

<Message Text="%25(Server.Type): %(Server.Type)" />

<Message Text="===========================================" />

</Target>

 

<Target Name="TargetBatching01" Outputs="%(Server.Name)">

<Message Text="===== TargetBatching01 ============" />

<Message Text="%25(Server.Name): %(Server.Name)" />

<Message Text="%25(Server.Type): %(Server.Type)" />

<Message Text="Server: @(Server)" />

<Message Text="==================================="/>

</Target>

<Target Name="TargetBatching02" Outputs="%(Server.Type)">

<Message Text="===== TargetBatching01 ============" />

<Message Text="%25(Server.Name): %(Server.Name)" />

<Message Text="%25(Server.Type): %(Server.Type)" />

<Message Text="Server: @(Server)" />

<Message Text="==================================="/>

</Target>

 

 

<Target Name="All" DependsOnTargets="TaskBatching;TargetBatching01;TargetBatching02"/>

</Project>

There are three targets that are important TaskBatching, which demonstrates how you can invoke individual tasks once per batch and then two targets; TargetBatching01 & TargetBatching02, which demonstrate batching an entire target once per batch. When you want to proform batching you will always use the %(…) notation somewhere. In Task batching this will be notated only inside of the tasks' parameters. In target batching this notation will be declared in the targets Outputs attribute.

Zooming in on TaskBatching target here are the results and we will discuss

The comments on the image pretty much describe what's happening. In the first execution there we are not batching. So the item is transformed into a string and passed into the Message task. The transformation is described by what is contained in the ->(). So the Metadata Name for each element in Server is evaluated and a string is created from that by concatenating each of these values. If there were duplicate values then the duplicates would show up in the resulting string.

Moving on to the next one, we batch on the Name Metadata. Since there were 4 Name metadata values the Message task is invoked 4 distinct times. The same applies for the Next invocation of the Message task.

Now let's take a look at the Target Batching. I simply invoked these targets, nothing special. The TargetBatching01 target is batching on the Name Metadata, and the TargetBatching02 on the Type Metadata. The output is shown below.

Because there are 4 distinct Name values TargetBatching is invoked 4 times, and similarily TargetBatching twice because of the distinct Type values. So if you just need to perform a single task over a set of parameters, the use Task batching. But If you need to perform a set of actions on a set of parameters then use Target Batching. More to come later on this topic I'm sure.

As a note I have decided to resume work on the MSBuild book I referenced in earlier posts. You'll be happy to know that I will cover batching in great detail there.

 

Sayed Ibrahim Hashimi

 

 

 

 

 

 

ddd

Friday, March 28, 2008 8:04:53 PM (GMT Standard Time, UTC+00:00)  #     | 
Monday, February 25, 2008

MSBuild Property & Item evaluation

The other day I was talking to a friend of mine and he was experiencing some difficulties understanding some behavior in his build file. To summarize what was confusing him, Properties are evaluated on the fly and as files are imported. Items are gathered as files are imported then evaluated at the end of the project parsing but before any target is executed. To demonstrate this in a simple MSBuild example take a look at the simple build file example below.

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

 

<PropertyGroup>

<PropBefore>[$(Configuration)]</PropBefore>

</PropertyGroup>

<ItemGroup>

<ItemBefore Include="[$(Configuration)]" />

</ItemGroup>

 

 

<PropertyGroup>

<Configuration>Debug</Configuration>

</PropertyGroup>

 

<PropertyGroup>

<PropAfter>[$(Configuration)]</PropAfter>

</PropertyGroup>

<ItemGroup>

<ItemAfter Include="[$(Configuration)]" />

</ItemGroup>

 

<Target Name="PrintInfo">

<Message Text="PropBefore: $(PropBefore)"/>

<Message Text="ItemBefore: @(ItemBefore)"/>

 

<Message Text="==============================================="/>

 

<Message Text="PropAfter: $(PropAfter)"/>

<Message Text="ItemAfter: @(ItemAfter)"/>

 

</Target>

 

</Project>

 

So here the property Configuration is defined in the middle, before and after that I have declared both a Property & an Item that contains its value. Take a look at the output below.

The noticeable difference here is that the ItemBefore actually has the correctly resolved value for the Configuration property where as the PropBefore property does not. If you think about this it makes sense because properties depend on other properties and you can change/extend the value for a property as the project is loaded. Items don't behave in this manner. Anywayz this is something that you should be careful not to trip on.

 

Sayed Ibrahim Hashimi

msbuild Monday, February 25, 2008 7:26:48 AM (GMT Standard Time, UTC+00:00)  #     |