Showing posts with label team build. Show all posts
Showing posts with label team build. Show all posts

25 November 2008

How To: Skip Actions When Queuing a Build

One of the tasks we commonly build into our Team Build scripts is the ability to run FitNesse tests along with other tests (such as unit tests).  If any of the tests fail, we do not deploy the product for user acceptance testing.

The advantage to this approach is that we find out relatively quickly if we have "broke" the build if we have failing tests.  The down side to this is two-fold: 1) the build takes longer to run (not that big of an issue in our case) and 2) Sometimes we refactor code that should break the FitNesse tests.

In the latter case, it may take somebody several hours (or even sometimes, days) to review the failing tests and get them corrected.  In the meantime, none of our updates get deployed for further testing.

Properties to the Rescue

Some time ago, I wrote a short post explaining how to access the various properties, items, and meta data that you can define and/or make use of in your Team Build scripts.  By making use of a simple property declared within the build script we can allow the developers to queue a new build and override the execution of the FitNesse tests so the build can proceed.  Configuring the build script to achieve this requires three steps:

1. Create a custom property that will be used as a flag to determine whether the desired functionality should be executed or overridden (i.e. skipped).  In my example below, I named the property SkipFitNesse.

<PropertyGroup> 
  <SkipFitNesse>false</SkipFitNesse>
</PropertyGroup>

2. Place the task(s) to be executed into a custom target specifying a condition.  For example:

<Target Name="RunFitNesseTests" Condition="'$(SkipFitNesse)' == 'false'">
  < tasks go here... />
</Target>

Notice that the property name, SkipFitNesse, is used in the condition.  As long as it remains set to its default value (in this case, false) the target will execute.

3.  Call the target at the desired point from within the build script.  In the example below, I am calling the target to run the FitNesse tests in the <AfterCompile> target.

<Target Name="AfterCompile" Condition="'$(IsDesktopBuild)'!='true'"> 
   <!-- Run FitNesse tests for Risk Rating -->
  <CallTarget Targets="RunFitNesseTests"/>
</Target>

Now that the build script is setup, you can manually override the execution of the FitNesse tests when you queue a new build by entering the following text into the command-line arguments field:

    /p:SkipFitNesse=true

For example:

queue

With this approach, the developers on our team now have a quick and simple method for skipping the execution of FitNesse tests if they are known to be in a "non-passing" condition and we want the build to continue.  This is only one example of how you might override the value of a property on the queue build dialog.  There are undoubtedly countless uses for this technique.

Also, if you're interested in seeing how we execute FitNesse tests as part of our builds, check out this post.

14 October 2008

Team Foundation Build 2010

I just finished watching a great video from Jim Lamb on Channel 9 covering some of the new features for Team Foundation Build 2010.  The video is about 35 minutes long and is well worth the watch.  Here's a quick synopsis of what's covered in the video:

  • Team Foundation Build 2010 will support Windows Workflow 4.0.  This feature alone would make a worthy upgrade to Team Foundation Build.  The new Workflow UI being designed for the .NET Framework 4.0 will be included in the build type editor within VS 2010 providing a fantastic user experience for modifying build types (can you say "XML - not for me, thank you" :-).  There will be several Team Foundation Build-related Workflow Activities included out of the box with VS 2010 and I would imagine several 3rd party/open source activities will appear on the scene shortly after its release.
  • "Gated" check-ins will be supported.  This feature, when turned on, will ensure that a given build type successfully runs before any artifacts are checked into version control.  This will be a great enhancement for teams making use of continuous integration within Team Foundation Server.
  • "Private/Buddy" check-ins will be supported.  This feature is very much like "Gated" check-ins except that the check-in, and resulting build, are treated as a separate, private build associated only with the user who initiated the build.  You can even set distinct retention policies for "Private" builds.
  • Support for Symbol Server Integration.  With the integration of Symbol Server into Team Foundation Build, the debugger within Visual Studio will know how to navigate to the correct source code within TFS Version Control.
  • Build Controllers.  You will have the ability to configure "pools" of build agents which can then be associated with a build type.  The build server can then utilize the least active build agent when starting a new build.
  • Build Agent Tags.  You will be able to associate tags with build agents.  For example, you may tag a build server as "SQL Server 2008", meaning that SQL Server 2008 has been installed on that server.  Another build agent may be tagged with "MOSS 2007", etc.
  • "All Inclusive" Build Agent.  There is a desire to have the build services include support for MSTest and DBPro without having to install the Test or DBPro SKUs.  This will be a great convenience and something that I believe that should have been included from the first version.
  • Log Enhancements.  The Build Log has been improved tremendously and is much easier to read and navigate.  You can now, for example, click a link on an error in the build log and be taken to the exact location within source code where the error occurred.
  • Build Deletion Control.  When deleting build types, you will now have the ability to be more specific as to what gets deleted.  For example, you can choose one or more of the following (all are selected by default): Details, Drop, Test Results, Label, Symbols, or Build.  This can be done manually and/or specified within the retention policy settings.

The video goes into a little more detail about each of the above items as well as a few others that I haven't mentioned.  It is really nice to see that Team Foundation Build is getting some attention.  I think the current product is good but there is a lot of room for improvement and it appears that is the direction it's heading.

28 July 2008

VSLive! Las Vegas

Several weeks ago I was informed that I had been selected to present at this year’s VSLive! in Las Vegas.  Although I have presented at other conferences in the past (e.g. Heartland Developers Conference and Tulsa TechFest) this will be the largest conference I’ve presented at to date.  I have to admit, I’m pretty excited about it all.

I will be presenting on Using Team Build in the “Real” World on Thursday, October 16th at 08:30.

VSLive! Schedule Snippet

I’m looking forward to meeting new people and learning new things.  So, if you’re planning on attending VSLive! in Las Vegas this year and have an interest in Team Build (or Team Foundation Server in general) be sure to look me up.

23 July 2008

DelayedBuildTask

A few days ago a fellow co-worker asked me if I could create a simple build task that would allow anyone on their team the opportunity to cancel a build, once it has been queued, before the build actually did anything.  The idea was simple:

  1. A new build gets queued.
  2. The build sends out an e-mail notification (via a custom task) informing the recipients that a new build has been queued.  The e-mail message also has a link that, when clicked, will cancel the build.
  3. The build waits a pre-determined amount of time (e.g. 5 minutes) giving the e-mail recipients a chance to cancel the build before it continues.
  4. If the build is not canceled, the build will proceed as usual once the delay has expired.

The driving reason behind this request was to allow any active testing to continue without being interrupted by a new build – i.e. the testers have the ability to cancel a build.

Building the custom task was pretty simple – it basically just sends out an e-mail message (based on a customizable HTML template) and then waits for the specified number of seconds (the default is 300 seconds).

The more interesting piece of the puzzle was creating a simple, one-page web site that, when called, will cancel a build.  The web page takes the build URI as its only parameter and utilizes the Team Foundation Server web services API to cancel the build.

All in all it worked out nicely.  If this sounds like something that may benefit your team, you can check it out on the MSDN Code Gallery here.  The source code as well as the binaries are available for download.

The next challenge (that was presented to me today) is to also include a link in the e-mail notification message that, when clicked, will instruct the build to continue immediately.  This one will take a little more thought…

Click here for more information on the DelayedBuildTask.

30 June 2008

Creating Team Build Types

I was answering a question related to programmatically creating team build types today and realized there weren’t too many examples on the web.  I didn’t see any examples that included all the details I was looking for – for example:

  • Adding the solution to be built to the new build type
  • Turning on/off test execution
  • Turning on/off code analysis

An example containing these details may exist, I just didn’t come across it during my initial search.

So, with that said, I decided to post the main part of the example application I put together to test out some concepts.  The items listed above are included in the example code below.

The example code includes two methods:

  • CreateBuildType – this method accepts six arguments that can be used to programmatically create a new build type.
  • VersionControlItemExists – this is a helper method that determines whether an item already exists in version control.

Although the example below can be used to create a new build type “as is”, there is always room for improvement.  For example:

  • Add a parameter to specify the default build agent.  Currently, the first build agent returned is used as the default when creating the build type.
  • Add a parameter to control the exact placement of the build type in version control (a common pattern is used in the example below).
  • Throw exceptions instead of displaying message boxes when exceptional conditions arise.  The message boxes were used for example purposes only.

With that said, here is the source code…

using System;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Build.Common;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.VersionControl.Common;



private static bool CreateBuildType(string serverName, string teamProject, string buildName, string solutionPath, string dropFolder, bool runTests)
{
// Get a connection to Team Foundation Server
TeamFoundationServer tfServer = TeamFoundationServerFactory.GetServer(serverName, new UICredentialsProvider());

// Get a reference to a build service
IBuildServer buildServer = (IBuildServer)tfServer.GetService(typeof(IBuildServer));

// Get a list of build agents associated with the specified team project
IBuildAgent[] buildAgents = buildServer.QueryBuildAgents(teamProject);

if (buildAgents.Length == 0)
{
MessageBox.Show(
@"The specified Team Project does not have any build agents associated with it. Please create at least one build agent.",
"No Default Build Agent Found",
MessageBoxButtons.OK, MessageBoxIcon.Warning);

return false;
}

// Create the new build type definition
IBuildDefinition buildType = buildServer.CreateBuildDefinition(teamProject);

// Specify the name of the new build type
buildType.Name = buildName;

// Specify where the new build type should be stored in version control
buildType.ConfigurationFolderPath = string.Format(@"$/{0}/TeamBuildTypes/{1}", teamProject, buildName);

// Set the default build agent
buildType.DefaultBuildAgent = buildAgents[0];

// Set the default drop location
buildType.DefaultDropLocation = dropFolder;

if (!VersionControlItemExists(tfServer, buildType.ConfigurationFolderPath))
{
IProjectFile projectFile = buildType.CreateProjectFile();

// Add a new solution to be built to the project
ISolutionToBuild solution = projectFile.AddSolutionToBuild();

// Set the path of the solution to build
solution.SolutionPath = solutionPath;

// Specify whether tests should be ran or not
projectFile.RunTest = runTests;

// Run code analysis if the project is setup to do so
projectFile.RunCodeAnalysis =
CodeAnalysisRunType.Default;

// Save the project file
projectFile.Save(buildType.ConfigurationFolderPath);

// Save the new build type
buildType.Save();
}
else
{
// The specified build type already exists
MessageBox.Show(
"The specified Build Type already exists. Please specify a different Build Type name.",
"Build Type Already Exists",
MessageBoxButtons.OK, MessageBoxIcon.Warning);

return false;
}

return true;
}


private static bool VersionControlItemExists(TeamFoundationServer tfServer, string itemPath)
{
string projectFilePath = VersionControlPath.Combine(itemPath, BuildConstants.ProjectFileName);

return ((VersionControlServer)tfServer.GetService(typeof(VersionControlServer))).ServerItemExists(
projectFilePath, VersionSpec.Latest, DeletedState.NonDeleted, ItemType.File);
}

28 May 2008

Omaha Team System User Group

Well, the 2nd Omaha Team System User Group meeting is, as they say, in the books!  We had a great turnout with about 25 attendees that showed up to listen to Mike Douglas speak about TFS build automation and the coolness factor of incorporating (authentic) stoplights into the build process.

Mike also demonstrated his latest CodePlex contribution - Team Deploy.  Team Deploy is a set of custom MSBuild tasks that provide functionality for deploying MSI files as well as controlling X10 devices (e.g. stoplights, lava lamps, etc.).  Some of the tasks included are:

  • Install Task - installs an MSI on a remote machine.
  • Uninstall Task - uninstall an MSI from a remote machine.
  • Kill Process Tasks - kills a process on a remote machine.
  • Deploy Task - utilizes a deployment script to automate the installation of MSIs on a set of remote machines.  This is the most common task to be used in the collection.
  • Start Service Task - starts a Windows Service on a remote machine.
  • Stop Service Task - stops a Windows Service on a remote machine.
  • Device Controller Task - allows you to control X10-enabled devices from your builds.

Once again, our meeting was sponsored by Farm Credit Services of America which provided pizza, pop, a great place to mingle prior to the presentation, and an excellent meeting room for the presentation.

You can download the PowerPoint slides here.

18 February 2008

So, what's the deal with $, @, and % anyway?

So, you've decided that the default build script that's built by the "New Build Type" wizard doesn't quite do everything that you need it to do. So, you click on over to the Version Control Explorer, check out the TFSBuild.proj file, and dive in!

At first glance, everything looks simple enough, you have various combinations of Targets, Tasks, and Properties. Things start to get a little interesting as you explore the concept of Item Groups. However, you start to notice a subtle difference with how various properties (or at least what look like properties) are accessed - e.g. some begin with '$', some with '@', and yet others with '%'. What's going on here? What's the difference? Before we can answer this question, we need to take a look at Properties and Items.

Properties
You can think of properties as MSBuild's version of a variable (as you might use it in some programming language such as C#). Once you declare a property, you can use it throughout your build script to reference whatever value it may hold. You create a property by defining an element within a PropertyGroup element. For example:

<PropertyGroup>
<WebBinSource>Binaries</WebBinSource>
</PropertyGroup>

In the above example, the property is named "WebBinSource" and can be referenced in your build script as $(WebBinSource). You can create as many properties within the PropertyGroup element as you like. You can also create as many PropertyGroup elements as you like.

Aside from the obvious advantages of using properties within your build script (i.e. so you don't have to hard-code values in multiple places) another nice feature is that you can pass in custom property values on the MSBuild command line. For example:

MSBuild.exe MyProject.proj /p:WebBinSource=Bin

These properties can also be specified in the Team Explorer "Queue Build" dialog:

Queue Build Dialog

You can also reference environment variables using the same syntax. For example, you can reference the environment variable PATH using the syntax $(Path). If you declare a custom property with the same name as an existing environment variable, the custom property will override the environment variable and its value will be used when referenced.

MSBuild defines several reserved properties that you can utilize in your build scripts. There are also several customizable properties available within Team Foundation Build for use within your TFS build scripts.

Items
Items allow you to create user-defined collections which can then be used an input arguments for MSBuild tasks. The task can then act on the individual items within the collection as needed. You create an item collection by defining elements within an ItemGroup element. For example:

<ItemGroup>
<SourceFiles Include = "default.aspx"/>
<SourceFiles Include = "register.aspx"/>
</ItemGroup>

NOTE: You can also include multiple items within a single element by separating each item with a semicolon. For example:

<ItemGroup>
<SourceFiles Include = "default.aspx;register.aspx"/>
</ItemGroup>

In this example, the item list is named "SourceFiles" and can be referenced in the build script as @(SourceFiles). For example, you may have a custom task that deploys a collection of files to a web server:

<Target Name="AfterBuild">
<DeployWeb Sources="@(SourceFiles)" />
</Target>

Depending upon the task using the item collection, it may support the use of wildcards in the item definition. You can also change the item delimiter to be something other than the default semicolon for custom processing.

Although items are a useful feature, they're even more useful if you can associate metadata with them.

Metadata
Each individual item contained within an item collection may also contain metadata information. For example, a collection of files to be copied may contain the attributes of each file (e.g. read only, archive bit, etc.) or possibly the creation and last updated date/time.

You can associate metadata with individual items by adding child elements to the individual item elements. For example:

<ItemGroup>
<SourceFiles Include = "default.aspx">
<Copy>true</Copy>
</SourceFiles>

<SourceFiles Include = "Web.config">
<Copy>false</Copy>
</SourceFiles>

</ItemGroup>

Using this example, the following task will copy all web files that have a metadata item of Copy with a value of true:

<Target Name="AfterBuild">
<DeployWeb Sources="@(SourceFiles)" Condition=" '%(Copy)' == 'true' />
</Target>

Also, any time a new item is created, there is a set of "well-known" metadata created and assigned to each item.

Putting it All Together
So, now when you see items prefixed with a '$', you'll know that it's referencing a property whereas items prefixed with a '@' are referencing a collection of items to be processed. If a task (or condition) needs access to the metadata for an individual item (or collection of items) then you will see the metadata items being prefixed with the '%'.

Hopefully this has cleared up the differences between the different types of "variables" in MSBuild and your Team Foundation Build scripts.

References

06 February 2008

Working with the BuildStep Task

One of the new convenience tasks added to Team Foundation Build 2008 is the BuildStep task.  This task allows you to add custom messages to the build reports created when you run a team build.  For example, you may want to display the message "Publishing web site" while your build script is updating some files on a web site.  Having the ability to "see" what your build script is currently executing is not only useful but can also be a great debugging tool (the messages are also logged as well as being displayed).

The BuildStep task accepts the following parameters:

  • TeamFoundationServerUrl - specifies the Team Foundation Server URL.  For example: $(TeamFoundationServerUrl).
  • BuildUri - specifies the build URI - for example: $(BuildUri).
  • Name - specifies the name of the build step added by this task.  NOTE: this parameter appears to be optional - i.e. it works just fine with or without a Name being specified.
  • Message - specifies the text of the message to be displayed within the build report.
  • Id - specifies the optional input/output parameter. If specified, this is the ID of the build step that is updated. If not specified, a new build step is created.
  • Status - specifies the status for the build step.  For example, Succeeded, Failed, or Stopped.

There are several variations in how you can implement the BuildStep task.  I've listed two of the more common scenarios below:

Simplest Scenario - Add a Message
The simplest scenario involves just adding a build step message to the build report with a status of "Succeeded".  To do this, use the following pattern (note: the target "PackageBinaries" is used for illustration purposes only - the task can be utilized from within any target you wish):

<Target Name="PackageBinaries">
  <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
             BuildUri="$(BuildUri)"
             Message="Publishing web site"
             Status="Succeeded" />
</Target>

This will display the text "Publishing web site" in the build report:

buildStep_1

You can leave off the Status parameter, however, the icon displayed next to the build step will not indicate a completed task.  If you leave the Status parameter in, then the status icon will indicate a completed task as soon as the build step is displayed, even if the task has not yet completed.  To present a more accurate indication of what's currently executing, use the next template.

Complete Scenario - Display Actual Status
Ideally, you would want to display the icon that indicates a build step is executing until the step has completed and then change the icon (and optionally the message) to a "completed" status.  To do this, use the following pattern:

<Target Name="PackageBinaries">
  <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
             BuildUri="$(BuildUri)"
             Message="Publishing web site...">
    <Output TaskParameter="Id" PropertyName="MyBuildStepId" />
  </BuildStep>

  <!-- Long running task goes here... -->
  <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
             BuildUri="$(BuildUri)"
             Id="$(MyBuildStepId)"
             Message="Web site published"
             Status="Succeeded" />
</Target>

In this example, we're tracking the ID of the newly created build step (in the property MyBuildStepId) so we can use it in a subsequent BuildStep task to set the status icon to "Succeeded" and update the build report text.

buildStep_2

NOTE: You can leave the Message parameter off in the second BuildStep task in the above example if you want to leave the original message text unchanged.

Although this is a new addition to the TFS 2008 release, you can get similar functionality for TFS 2005 by using a custom build task.  One example of such a custom build task is available here.