Copy Build Definition From Project "A" to Project b” Using TFS API

This article will help when you want to copy an existing Build definition from Project A to Project B.

As shown in the following figure:

TFSAPI1.jpg

The following is the piece of code to perform the task to copy a Build Definition from one project to another project.

  1. Add the following references to your project:

    You can get these references from your system at the location: <C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0>.

    TFSAPI2.jpg
     
  2. The piece of code to perform the copy of the builds definition:
     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    //Add this NameSpace to work on TFS api
    using Microsoft.TeamFoundation.Client;
    using Microsoft.TeamFoundation.Build.Client;
    //Author: Md. Jawed
    //Dated: 01.05.2010
    //Discription:Programmaticaly copy Build Definition from one project to another project using TFS API.
    namespace TFSAPI
    {
        class Program
        {
            /// <summary>
            /// This Main would copy the Build definition from project "A" to Project "B" with in the same TFS.
            ///</summary>
            ///<param name="args"></param>
            staticvoid Main(string[] args)
            {
                try
                {
                    //Connect to your TFS
                    var server =TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new
    Uri("http://tfs:8080/tfs/defaultcollection"));
                    IBuildServer buildServer = server.GetService<IBuildServer>();
                    //Get all Build from ALM project
                    var buildDetails = buildServer.QueryBuildDefinitions("Project1");
                    foreach (var build in buildDetails)
                    {
                        if (build.Name=="DemoBuildDefinition")
                        {
                            var buildDefinition = buildServer.CreateBuildDefinition("Project2");
                            buildDefinition.Name = "Copy of " + build.Name;
                            buildDefinition.BuildController = build.BuildController;
                            // This finds the template to use
                            buildDefinition.Process = buildServer.QueryProcessTemplates("Project2")[0];
                            buildDefinition.ProcessParameters = build.ProcessParameters;
                            buildDefinition.Save();
                        }//end of if block
                    }//end of for each loop
                }//end of try
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);

                }//end of catch
            }//end of main
        }//end of class
    }
    //end of name space


Similar Articles