Share via


Team System

Team Build 2008

Brian A. Randell

Code download available at:MSDN Code Gallery(165 KB)

Contents

About Team Build
Creating a Team Build
Creating a Build Agent
Running a Team Build
Programming Team Build

Team Foundation Server (TFS) is about teams. Sure, a team of one can use it, but TFS is really all about collaboration with other humans on your development projects.

Build automation is not F5. Build automation is about collecting, assembling, validating, and auditing. The idea is that you will collect all of the artifacts that comprise your solution and assemble said artifacts based upon a well-defined integration plan. Compilation is a typical task defined in the assembling phase. You use various types of automated tests, often know as build verification tests (BVTs) or smoke tests, to then validate your team's collective work.

Finally, you'll perform some type of audit to assess the overall quality of the build. The audit helps provide data to help you answer the tough questions. For example, do the bits as of this build create a product? Is your product of high quality? Do you have any regressions? Are you on schedule? The value of build auditing is making it trivial to take the pulse of your team.

In this column I will introduce you to Visual Studio 2008 Team Foundation Server Build (Team Build) and walk you through the process of creating and running a team build. I'll also demonstrate the managed API now available that lets you program against Team Build 2008.

About Team Build

Team Build is a core feature of TFS 2008. Microsoft designed it to be an industrial-strength build automation tool. You could say it provides the F5 experience for your team. In a typical environment, you'll install Team Build on its own dedicated server (although if you have a very small team or a tight budget, you can install Team Build on your TFS box).

Unlike other portions of TFS, the 2008 release of Team Build was a major update. In the 2005 release, Microsoft created a good build automation product. Using MS-Build as its engine, Team Build 2005 supported many of the core automation features you'd expect: version control, compilation, multiple build types, unit tests, static analysis, and code coverage.

In addition, it provided excellent reporting features including build reports and data updates to the TFS data warehouse to support historical trend analysis. The 2005 release of Team Build also supported multiple-build machines, build notifications, and the ability to start a build from the command line or through the Team Explorer user interface.

For Team Build 2008, Microsoft did more than just spit and polish. Major enhancements include continuous integration support, build queuing, scheduled builds through Team Explorer, and a managed object model. In addition, Microsoft separated build agent definition from build definition, created a build definition editing user interface, and added better build management tools.

Combined with the solid Team Build 2005 feature set, Team Build 2008 presents a compelling build automation solution. In addition, because Microsoft continues to support backward compatibility, you can upgrade your TFS installation and your Team Build servers even if your development team is still using Visual Studio 2005.

Creating a Team Build

To use Team Build you naturally need a TFS installation, either a single server or dual server configuration. You'll need to have installed Team Build and properly configured your build server. The details are covered in the recently updated Team Foundation Installation Guide . Finally, you'll need a team project with some code checked into the version control repository.

In Visual Studio 2008 with a Team Foundation Server client installed, open the Team Explorer window with your team project loaded. In this example, let's assume you've created a team project called MSDNMag using the MSF-Agile template. (If you want to follow along, download the code from this column as well as the Team System 2008 TFS and Team Suite Virtual PC image .) This example uses a custom workspace called MSDNMag with the trunk mapped to C:\Work in the Virtual PC image.

With all of that out of the way, you can expand the MSDNMag Team Project node in the Team Explorer window and locate the Builds folder. If you right-click on the Builds folder, you'll be presented with a number of options. Of concern to you at this point is the New Build Definition command. Once selected, the Build Definition dialog appears (see Figure 1 ).

fig01.gif

Figure 1 A Blank Build Definition Dialog (Click the image for a larger view)

Unlike the wizard in Team Build 2005, you can return to this dialog when you need to edit a build definition. First you provide a build name such as SimpleBuildExplorer-OnDemand. In addition, you can keep the build offline by checking the Disable this build definition option.

When you create a new build, it's mandatory that you provide a build definition name, a Team Build project file, and that you specify the build agent and drop location. That said, the second option, Workspace, is critical in my opinion.

In Team Build 2005, the Workspace option was something you just had to know about. The implementation details have changed, but the purpose is the same: to limit what artifacts Team Build downloads during the get sources step of the build process. In Team Build 2005, you had to modify a file called WorkspaceMapping.xml. In Team Build 2008, you use a GUI similar to that found in the Workspace mapping dialog for version control (see Figure 2 ).

fig02.gif

Figure 2 The Build Definition Dialog’s Workspace Page (Click the image for a larger view)

Workspace lets you define what sections of your source code repository you want used as part of the build. By default, Team Build maps the trunk of your Team Project to the source download location used by the build (something that you can control when associating the build agent that runs the build with the build definition). To be clear, if you don't adjust this setting, every time you execute a build, Team Build will do a get on the trunk, pulling down the latest of everything. Not a big deal when you're doing demos or testing, but once you've got six months of work in your team project and multiple branches, it's not the best way to run a build.

Even though the demo scenario here only has one Visual Studio solution, you should still adjust the mapping. When you click the first item under the Source Control Folder column, you'll have the option of either typing in a restricted path or using the Browse for Folder dialog. For this example, I set the Source Control Folder to $/MSDNMag/Main/src/TeamSystem/C08.

Just as in the dialog used for version control workspace mapping, you can define more than one folder mapping. The variable $(SourceDir) is an environment variable that Team Build expands to the build directory specified for the build agent in the build agent properties dialog. In general, you will want use $(SourceDir) so that paths are relative. However, Team Build does not force you to use it. For this example, I leave it as is.

Finally, if you have an existing workspace that has all of the mappings configured how you want, you can use the Copy Existing Workspace option to copy the version control folder part of the mapping, saving you time.

Once you've defined your workspace settings, you need to define a build project file. When you click on the Project File option, you have the option of providing the path to an existing TFSBuild.proj file that is already under version control. TFSBuild.proj is an XML file that in the 2005 release contained all the build configuration data and was the file you customized to enhance the actual build process. Team Build 2008 continues to use this file for build customization, but most of the data related to the build definition is stored in the TFS databases. If you don't have a file already, you click the Create button and build one using a simple wizard.

One big change in Team Build 2008 is that you can now specify where you'd like to store your TFSBuild.proj file. In Team Build 2005, Microsoft hardcoded the path to a specific location in the version control repository. By default, the Team Build 2008 dialog specifies a Team Build 2005-compatible path in the form of %TeamProjectName%/TeamBuildTypes/%BuildDefinitionName%.

For this current example, you will see $/MSDNMag/TeamBuildTypes/SimpleBuildExplorer-OnDemand for the proposed version control folder. The major benefit of being able to change the path is that you can now branch your TFSBuild.proj file with other artifacts. For this example, accept the default path and click the Create button.

When you click the Create button, Team Build presents you with a wizard. The wizard is one of the few UI remnants from the Team Build 2005 release. The first page asks you to select the Visual Studio solutions you'd like to build. The wizard filters the list presented to only those solutions available relative to your workspace mapping. If you don't change the default workspace mapping, you'd see all the solutions in your Team Project. Select the single solution provided and click Next.

The second page of the wizard allows you to choose what type of Visual Studio configurations you'd like built. While the wizard only exposes Debug and Release for configuration, you can type in custom configurations. The same rule applies to Platform. Accept the defaults and click Next.

The final page of the wizard lets you control test and static analysis execution. VSTS needs to be installed on the build agent computer in order for test execution and static analysis to work. As was possible with the Team Build 2005 release, you can choose a test metadata file and from this select any test lists that support unattended execution. However, you can alternately choose to have Team Build automatically scan your output assemblies for MSTest compatible tests and run them without the need for a test list. You can choose to have Team Build execute static analysis if you've enabled it in one or more of your Visual Studio projects. The sample solution for this column doesn't have any tests or static analysis, so click Finish to complete the wizard and create the TFSBuild.proj file.

At this point, you only have to complete the build defaults. First, let's look at the retention policy and trigger settings. A huge improvement over the Team Build 2005 release, Team Build 2008 now lets you configure per build definition retention policies (see Figure 3 ). Based upon a particular build's outcome, you can control how many build results Team Build keeps.

fig03.gif

Figure 3 Controlling a Build Definition Retention Policy (Click the image for a larger view)

Once a build completes, you can mark a build result so that Team Build keeps it regardless of the retention policy. For this example, note that you should leave the retention policy set to the defaults.

If you click the Trigger option in Team Build 2008, it works just like Team Build 2005—it only runs builds when you ask. However, you'll note that now Team Build also supports continuous integration (CI). (For more information on CI, see the March 2008 article " Redefine Your Build Process with Continuous Integration ".) This means a build is queued whenever someone checks in a change to a file that is mapped by a build definition's workspace mappings. The dialog exposes this with the Build each check-in (more builds) option.

A second option, Accumulate check-ins until the prior build finishes (fewer builds), provides a delayed form of CI. Finally, the last option lets you configure a scheduled build (see Figure 4 ).

fig04.gif

Figure 4 Configuring Team Build to Execute Builds on a Schedule
(Click the image for a larger view)

You should leave the trigger set to the default of Check-ins do not trigger a new build, and select the Build Defaults option. Use the build defaults to specify the build agent to use and the drop location for the build output. You specify the drop location using a UNC path. If you're using the Microsoft provided Virtual PC image, you can enter \\localhost\Drops\MSDNMag\SimpleBuildExplorer-OnDemand. Only the share needs to exist. Team Build will create additional subfolders as necessary. Team Build will create a folder under this path using the build number.

When creating the share, you need to ensure you assign proper permissions. At a minimum, the Team Build and TFS Service accounts need Full Control rights to the share. In addition, you need to give Write permissions to anyone who is going to publish test results related to the build. You should give Read permissions to those people who need to pull down completed builds.

Assuming you've got the share configured, you need to specify a build agent. If you've already defined a build agent, you can choose it from the combobox. If not, you can click the New button, which opens the standard Build Agent Properties dialog. You'll need to define a new agent for this example, so click New.

Creating a Build Agent

Unlike in the Team Build 2005 release, Team Build 2008 build agents are independent of build definitions. Once you've defined an agent, you can easily use it again. The Build Agent Properties dialog lets you define all of the critical properties related to the agent. You first provide a display name and optional description. You then provide the computer name in the form of a NETBIOS or DNS name. The display name and computer name can be completely different. If you're using SSL, you can specify that option.

A critical setting is the working directory. By default, it uses a path in the form of $(Temp)\$(BuildDefinitionPath). While this works for many builds, it can cause problems due to the dreaded MAX_PATH issue. $Temp on a Windows Server 2003 machine will be %SystemDrive%\Documents and Settings\<build agent service account>\Local Settings\Temp. That's too many characters to be giving up. I generally recommend people change this to something shorter, especially if building Database Professional builds. For this example, change the working directory to C:\Builds\$(BuildDefinitionPath).

Finally, you can control the agent's status. This is particularly useful for servicing. In addition, TFS will change an agent's status to unreachable if it can't contact a build agent, thus preventing use of the agent until an administrator changes the setting. Leave the setting set to enabled and click OK to close the completed Build Agent Properties dialog (see Figure 5 ). Back in the Build Definition dialog, all of the warning triangles will now be gone and you can click OK to complete defining the build.

fig05_L.gif

Figure 5 Completed Build Agent Properties Dialog

In the Team Explorer window, under the Builds folder, you'll now see your build definition. If you right-click on it, you can see there is now an Edit Build Definition option that returns you to the same Build Definition dialog you just used. In addition, you can queue a new build using the Queue New Build option.

Unlike Team Build 2005, Team Build 2008 now supports queuing of builds—a necessary feature if Microsoft was going to properly support continuous integration. When you select this option, the Queue Build dialog opens (see Figure 6 ) and you can adjust a few options. First, you can easily change the default build agent to an alternative if you would like. Second, you can adjust the drop location. In addition, you can have a particular build "jump the queue" by adjusting the Priority in queue option. Finally, you can pass MSBuild command-line arguments if the user has the Administer Builds permission.

fig06.gif

Figure 6 Queue Build Dialog

Running a Team Build

Click Queue to start the build. When you do, the updated Build Explorer window will open. It has two main tabs. The queued tab by default shows you all builds that are queued regardless of agent or status. You'll find combo­boxes that you can use to adjust which builds the Build Explorer shows based upon build definition, the build's status, or the build agent.

The completed tab displays the completed builds and supports the same type of filtering. When you start your build, you can double-click on the build to view the live build report. Team Build updates this report in real time as it progress through the build process.

When you run a team build, a number of actions occur. Once TFS starts the build from the queue, the build agent is prepared to run the build. TFS creates a build number and the build agent synchronizes sources with the location specified in the build definition. The agent then compiles the code and runs code analysis if required. The build agent then runs tests. Then the agent runs a task that updates any associated work items with the build number.

For example, the default Task work item from the MSF-Agile template has an Integration Build field that Team Build updates. The agent calculates code coverage (if tests are configured to run as part of the build and code coverage is enabled) and determines all of the changesets between the last good build (compilation was successful) and the current build. It copies the files up to the drop share, publishes the build results to TFS, and TFS fires a build completion event. See my May 2008 column for details about TFS events.

There are two important changes that Microsoft made in Team Build 2008 related to tests and work items. The first change is that a build that has one or more failing tests does not fail the build. Instead, a build with one or more failed tests will show as Partially Completed, not Failed, as in Team Build 2005. Second, in Team Build 2005, the first time you ran a build, Team Build would list all of the work items and change­sets related to the items built on the first build report since the beginning of the team project. Team Build 2008 only starts showing and updating work items after a build's first successful run. In my next column, I'll cover how to adjust these behaviors through build customization.

Programming Team Build

One of the great enhancements made in Team Build 2008 is the addition of a managed API. The Microsoft.TeamFoundation.Build.Client.dll is the primary assembly you will use. The sample application for this column references this assembly as well as the Microsoft.TeamFoundation.Client.dll and the Microsoft.TeamFoundation.VersionControl.Client.dll assemblies.

The sample application is a simple Windows Forms application that exercises some of the new API. The application connects to TFS and enumerates the list of all team projects, loading them into a tree view control. Under each team project, it adds Build Agents and Build Definitions nodes (see Figure 7 ).

fig07.gif

Figure 7 Sample Application (Click the image for a larger view)

When you expand a node, code in the TreeNode's Before­Expand event runs and enumerates the available build agents, build definitions, or completed builds depending upon the node you've expanded. In addition, the main form hosts a Property Grid control. When you select a node that has a non-null tag value, the application loads the reference object into the Property Grid's SelectedObject property. Figure 7 displays the application with the MSDNMag team project expanded and the Main Build Agent selected.

Most of the application is simple enumeration code. However, it has one feature that Microsoft did not surface in Team Explorer. When you define a build agent, TFS scopes the build agent to that particular team project. I've found, however, that many organizations only have one or two build agents. That means they end up having to recreate the build agent multiple times. Using the sample application, if you right-click on a build agent instance, you'll be presented with a context menu and a Copy Agent To command (see Figure 8 ).

fig08_L.gif

Figure 8 Copy Agent To Command

Choosing this option opens a dialog that allows you to chose the Team Project to which you wish to copy the build agent definition. All of the interesting code is in the CopyAgentToToolStripMenuItem_Click event handler shown in Figure 9 .

Figure 9 CopyAgentToToolStripMenuItem_Click Method

Private Sub CopyAgentToToolStripMenuItem_Click( _
  ByVal sender As System.Object, _
  ByVal e As System.EventArgs) _
  Handles CopyAgentToToolStripMenuItem.Click

  Dim current As TreeNode = tv.SelectedNode
  Dim ba As IBuildAgent = _
    TryCast(current.Tag, IBuildAgent)

  If ba Is Nothing Then Exit Sub

  Dim parentProject As String = ba.TeamProject

  Using frm As New frmPickProject
    frm.cboProjects.DataSource = _
      (From item In teamProjectNames _
       Where item <> parentProject _
       Select item).ToArray()

    If frm.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
      Dim teamProjectName As String = _
        frm.cboProjects.SelectedItem.ToString()

      Dim existingAgent = _
        (From item As IBuildAgent In _
         m_bs.QueryBuildAgents(teamProjectName) _
         Where item.Name = ba.Name).SingleOrDefault

      If existingAgent Is Nothing Then
        Dim newBuildAgent As IBuildAgent = _
        ba.CopyTo(teamProjectName)
        newBuildAgent.Save()

        MessageBox.Show(newBuildAgent.Name & " copied.")
      Else
        MessageBox.Show(existingAgent.Name & " already exists.")
      End If
    End If
  End Using
End Sub

Assuming the selected node has a tag set to an IBuildAgent reference, the code shows the frmPickProject form. This form contains a combobox that displays all of the available team projects except the current build agent's team project.

The code populates the data source of the combobox by executing a LINQ query against the string array of all team project names gathered when you expand the root of the tree view for the first time. Assuming you select a team project and click OK on the project selection form, the code runs a LINQ query to verify that the target team project does not already have a build agent with the same name. If it finds one, it displays a message. However, if it doesn't find one, it copies the build agent definition.

Of particular interest is that Microsoft provides a CopyTo method. When I first worked out this code, I had planned to do a per-property copy against a new IBuildAgent instance. It looks like Microsoft got the API in but not added to the user interface.

I hope you see that Team Build 2008 is an industrial-strength build product. If you're using Team Build 2005, there's a ton of value in upgrading to Team Build 2008. In my next column, I'll dig into build customization and how you can have your builds not only compile a solution but deploy to test environments and more.

I would like to thank Ken Getz and Martin Woodward for their help with this column.

Send your questions and comments for Brian to mmvsts@microsoft.com .

Brian A. Randell is a Senior Consultant with MCW Technologies LLC. He spends his time speaking, teaching, and writing about Microsoft technologies. Brian is the author of Pluralsight's Applied Team System course and is a Microsoft MVP. Contact Brian via his blog at mcwtech.com/cs/blogs/brianr .