다음을 통해 공유


연습: 사용자 지정 작업을 통해 Team Foundation Build 사용자 지정

업데이트: 2007년 11월

고유의 사용자 지정 작업을 만든 다음 빌드하는 동안 실행하여 Team Foundation Build를 확장할 수 있습니다. 이 항목에서는 사용자 지정 작업으로 빌드 정의를 확장하는 데 필요한 단계를 설명합니다.

필수 권한

이 연습을 완료하려면 빌드 관리 권한이 허용으로 설정되어 있어야 합니다. 자세한 내용은 Team Foundation Server 권한을 참조하십시오.

빌드 정의 만들기

빌드 정의 대화 상자를 사용하여 새 빌드 정의를 만들 수 있습니다. 기존 TFSBuild.proj 파일을 공유하거나 MSBuild 프로젝트 파일 만들기 마법사를 사용하여 새 TFSBuild.proj 파일을 만들 수 있습니다. TFSBuild.proj 파일을 편집하여 이 파일과 연결된 각 빌드 정의를 사용자 지정합니다. 빌드 정의 만들기에 대한 자세한 내용은 방법: 빌드 정의 만들기를 참조하십시오.

사용자 지정 작업 만들기

작업은 빌드 프로세스를 진행하는 동안 실행되는 코드를 제공합니다. 이러한 작업은 MSBuild 프로젝트 파일의 Target 요소에 포함됩니다. MSBuild는 Team Foundation Build의 기반이 되는 엔진입니다. 사용자 지정 작업은 MSBuild에서 이해할 수 있는 형식이어야 합니다. 각 작업은 Microsoft.Build.Framework.dll 어셈블리에 정의되어 있는 ITask 인터페이스를 구현하는 .NET 클래스로 구현되어야 합니다.

다음 두 가지 방법을 사용하여 작업을 구현할 수 있습니다.

  • ITask 인터페이스를 직접 구현합니다.

  • Microsoft.Build.Utilities.dll 어셈블리에 정의되어 있는 Task 도우미 클래스에서 사용자 클래스를 파생시킵니다. TaskITask를 구현하고 일부 ITask 멤버의 기본 구현을 제공합니다.

두 경우 모두 작업이 실행될 때 호출되는 메서드인 Execute 메서드를 클래스에 추가해야 합니다. 이 메서드는 매개 변수를 사용하지 않으며 Boolean 값을 반환합니다. 즉, 작업이 성공하면 true를 반환하고, 실패하면 false를 반환합니다. 다음 예제에서는 작업을 수행하지 않고 true를 반환하는 작업을 보여 줍니다.

using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace MyTasks
{
    public class SimpleTask : Task
    {
        public override bool Execute()
        {
            return true;
        }
    }
}

작업 또한 매개 변수를 허용하거나, 이벤트를 발생시키거나, 출력을 로깅할 수 있습니다. 자세한 내용은 MSBuild 작업MSBuild 개요를 참조하십시오.

TFSBuild.proj 체크 아웃

작업을 작성한 후에는 빌드 프로세스의 원하는 지점에서 작업 코드가 실행될 수 있도록 작업을 등록하고 대상 중 하나에서 호출해야 합니다. MSBuild 프로젝트 파일 만들기 마법사를 사용하여 MSBuild 프로젝트 파일을 만들고 소스 제어의 기본 위치를 적용한 경우 TFSBuild.proj 파일은 Visual Studio Team System 소스 제어의 $/MyTeamProject/TeamBuildTypes/MyBuildName 폴더에 있습니다. 이 시나리오에서 MyTeamProject는 팀 프로젝트의 이름인 동시에 모든 팀 프로젝트 소스의 루트 노드이며 MyBuildName은 TFSBuild.proj 파일을 처음 만들 때 빌드 정의에 지정한 이름입니다.

TFSBuild.proj 파일의 소스 제어 위치를 확인하려면 팀 탐색기의 빌드 폴더에서 빌드 정의를 선택하고 마우스 오른쪽 단추를 클릭한 다음 편집을 클릭합니다. TFSBuild.proj 파일의 소스 제어 위치가 빌드 정의 대화 상자의 프로젝트 파일 창에 표시됩니다.

참고:

Microsoft.TeamFoundation.Build.targets 파일을 사용자 지정하면 변경한 내용이 해당 컴퓨터의 모든 빌드에 적용되므로 이 파일을 편집하지 마십시오.

파일 체크 아웃에 대한 자세한 내용은 Team Foundation 버전 제어 사용을 참조하십시오.

작업 등록

작업을 만든 후에는 TFSBuild.proj 파일의 UsingTask 요소에 작업을 지정하여 등록해야 합니다. UsingTask 요소는 작업을 작업의 구현이 포함된 어셈블리에 매핑합니다. 자세한 내용은 UsingTask 요소(MSBuild)를 참조하십시오.

사용자 지정 작업을 등록하려면

  1. TFSBuild.proj 파일을 엽니다.

  2. 파일에 UsingTask 요소를 추가하고 작업 세부 정보를 지정합니다.

    예를 들면 다음과 같습니다.

    <UsingTask 
        TaskName="MyTasks.SimpleTask" 
        AssemblyName="MyAssembly.Build.Tasks"/>
    

    -또는-

    <UsingTask 
        TaskName="MyTasks.SimpleTask" 
        AssemblyFile="MyAssembly.Build.Tasks.dll"/>
    

    -또는-

    <UsingTask
        TaskName="MyTasks.SimpleTask"
        AssemblyFile="c:\somediskpath\MyAssembly.Build.Tasks.dll"/>
    
  3. 파일을 저장합니다.

사용자 지정 작업 실행

작업을 만들고 등록했으면 빌드 프로세스에서 작업을 실행할 지점을 지정해야 합니다.

작업을 실행하려면

  1. 빌드 프로세스에서 사용자 지정 작업을 실행할 지점을 결정합니다.

    빌드 프로세스를 확장할 수 있는 지점에 대한 자세한 내용은 Team Foundation Build 구성 파일 이해를 참조하십시오.

  2. TFSBuild.proj를 열고 위에서 선택한 Target 요소를 추가합니다.

  3. 작업을 실행할 작업 요소를 Target 요소 내에 추가합니다.

    예를 들어, TFSBuild.proj의 다음 XML은 Get 대상 바로 앞에서 실행되는 BeforeGet 대상에서 SimpleTask 작업을 실행합니다.

    <Target Name="BeforeGet">
        <SimpleTask />
    </Target>
    
  4. 파일을 저장합니다.

파일 체크 인

변경 내용을 적용하려면 TFSBuild.proj 파일을 체크 인해야 합니다. Team Foundation Build에서는 이 파일을 소스 제어에서 빌드 컴퓨터로 복사하여 컴퓨터의 로컬 복사본 변경 내용이 빌드에 영향을 주지 않도록 합니다. 소스 제어로 파일을 체크 인하는 것에 대한 자세한 내용은 방법: 보류 중인 변경 내용 체크 인을 참조하십시오.

Team Foundation Build에서 작업 DLL을 빌드 컴퓨터로 복사하도록 만들려면 작업 DLL을 팀 프로젝트 노드 아래의 소스 제어에 추가해야 합니다.

예제 작업

다음 예제에서는 빌드를 통해 생성된 파일의 크기를 로깅하여 TFSBuild.proj 파일과 연결된 빌드 정의를 확장하는 사용자 지정 작업을 만듭니다. 이 예제는 다음과 같은 두 부분으로 구성됩니다.

  • 작업 코드

  • TFSBuild.proj 파일

이 작업에서 로깅된 정보는 빌드 저장 폴더에 있는 빌드 로그 파일인 Buildlog.txt에서 볼 수 있습니다. 빌드 로그에는 다음과 같은 정보가 포함됩니다.

전체 크기는 d:\BuildDir\MyTeamProj\MyBuildType\sources\..\Binaries\Release 디렉터리에서 9216바이트입니다.

C# 작업 코드

아래 예제에는 이진 폴더에 있는 파일의 크기를 더해서 총 이진 크기를 계산하는 코드가 포함되어 있습니다.

참고:

빌드하는 동안 생성된 모든 이진 파일은 빌드 에이전트의 빌드 디렉터리 폴더에 있는 Binaries 폴더에 보관됩니다.

이 작업을 빌드에 포함하려면 컴파일된 DLL을 팀 프로젝트 폴더의 소스 제어로 체크 인해야 합니다. 이렇게 하면 빌드하는 동안 파일이 빌드 에이전트로 복사됩니다.

다음 코드는 빌드 디렉터리의 Binaries 폴더에 있는 이진 파일의 크기를 계산합니다. 솔루션 루트 속성은 Team Foundation Build 스크립트에 의해 이 작업으로 전달됩니다.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Build.Framework; 
using Microsoft.Build.Utilities;
using System.Diagnostics;
using System.IO;

namespace BuildTask
{
    public class BinSize : Task
    {
        private string sourceDir;

        [Required]
        public string SourceDir
        {
            get { return sourceDir; }
            set { sourceDir = value; }
        }
        public override bool Execute()
        {
            string szDir = sourceDir + "\\..\\Binaries";
            ProcessDirectory(szDir);
            return true;
        }
        private void ProcessDirectory(string targetDirectory)
        {
            // Process the list of files found in the directory.
            string[] fileEntries = Directory.GetFiles(targetDirectory, "*.*");
            if (fileEntries.Length > 0)
            {
                dwSize = 0;
                szCurrDir = targetDirectory;
                foreach (string fileName in fileEntries)
                    ProcessFile(fileName);
                ////////////////////////////////////////////////////////////////////////
                // This log message would just print out a line in the build log file. 
                // You need to add code to do what you need to do with this data. e.g. 
                // publishing it into the warehouse for reporting. 
                ///////////////////////////////////////////////////////////////////////
                Log.LogMessage("The total size of is {0} bytes in {1} dir",
                    dwSize, targetDirectory);
            }
            // Recurse into subdirectories of this directory.
            string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
            foreach (string subdirectory in subdirectoryEntries)
                ProcessDirectory(subdirectory);
        }
        private void ProcessFile(string path)
        {
            FileInfo fi = new FileInfo(path);
            dwSize = dwSize + fi.Length;
        }
        private long dwSize;
        private string szCurrDir;
    }
}

TFSBuild.proj 파일

작업이 컴파일되어 소스 제어로 체크 인된 다음에는 TFSBuild.proj 파일에서 호출되어야 합니다. 다음 예제에서는 파일이 컴파일되고 모든 이진 파일이 Binaries 디렉터리로 복사된 후 작업이 호출됩니다. 따라서 작업이 BeforeDropBuild 대상에서 실행됩니다. TFSBuild.proj의 확장 가능 대상에 대한 자세한 내용은 Team Foundation Build 구성 파일 이해를 참조하십시오.

아래 예제에는 수정된 TFSBuild.proj 파일의 코드가 포함되어 있습니다. 예제 XML 파일은 파일의 끝에 있는 UsingTask 요소와 Target 요소를 제외하고는 거의 모든 부분이 MSBuild 프로젝트 파일 만들기 마법사를 통해 생성되었습니다.

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="DesktopBuild" xmlns="https://schemas.microsoft.com/developer/msbuild/2003">
  <!-- TO EDIT BUILD TYPE DEFINITION

   TODO: Update all of the comments in this file!

   To edit the build type, you will need to edit this file which was generated
   by the Create New Build Type wizard.  This file is under source control and
   needs to be checked out before making any changes.

   The file is available at:
   
       $/{TeamProjectName}/TeamBuildTypes/{BuildTypeName}
       
   where you will need to replace TeamProjectName and BuildTypeName with your
   Team Project and Build Type name that you created

   Checkout the file
     1. Open Source Control Explorer by selecting View -> Other Windows -> Source Control Explorer
     2. Ensure that your current workspace has a mapping for the $/{TeamProjectName}/TeamBuildTypes folder and 
        that you have done a "Get Latest Version" on that folder
     3. Browse through the folders to {TeamProjectName}->TeamBuildTypes->{BuildTypeName} folder
     4. From the list of files available in this folder, right click on TfsBuild.Proj. Select 'Check Out For Edit...'


   Make the required changes to the file and save

   Checkin the file
     1. Right click on the TfsBuild.Proj file selected in Step 3 above and select 'Checkin Pending Changes'
     2. Use the pending checkin dialog to save your changes to the source control

   Once the file is checked in with the modifications, all future builds using
   this build type will use the modified settings
  -->

  <!-- Do not edit this -->
  <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\TeamBuild\Microsoft.TeamFoundation.Build.targets" />

  <ProjectExtensions>

    <!-- Team Foundation Build Version - DO NOT CHANGE -->
    <ProjectFileVersion>2</ProjectFileVersion>

    <!--  DESCRIPTION
     TODO: Obsolete.
    -->
    <Description>this one automatically  builds on check in</Description>

    <!--  BUILD MACHINE
     TODO: Obsolete.
    -->
    <BuildMachine>ahetod-test2</BuildMachine>

  </ProjectExtensions>

  <PropertyGroup>

    <!-- Properties set by the build type creation wizard -->
    
    <!--  TEAM PROJECT
     TODO: Obsolete.
    -->
    <TeamProject>TeamProjectName</TeamProject>

    <!--  BUILD DIRECTORY
     TODO: Obsolete.
    -->
    <BuildDirectoryPath>C:\Documents and Settings\user\Local Settings\Temp\1\TeamProjectName\BuildDefinitionName</BuildDirectoryPath>

    <!--  DROP LOCATION
     TODO: Obsolete.
    -->
    <DropLocation>\\UNKNOWN\drops</DropLocation>

    <!--  TESTING
     Set this flag to enable/disable running tests as a post build step.
    -->
    <RunTest>false</RunTest>

    <!--  CODE ANALYSIS
     To change CodeAnalysis behavior edit this value. Valid values for this
     can be Default,Always or Never.

         Default - To perform code analysis as per the individual project settings
         Always  - To always perform code analysis irrespective of project settings
         Never   - To never perform code analysis irrespective of project settings
     -->
    <RunCodeAnalysis>Never</RunCodeAnalysis>

    <!-- Additional Properties -->

    <!--  WorkItemType
     The type of the work item created on a build break - if empty, "Bug" will be used 
     -->
    <WorkItemType Condition=" '$(WorkItemType)'=='' "></WorkItemType>

    <!--  WorkItemFieldValues
     Add/edit key value pairs to set values for fields in the work item created
     during the build process. Please make sure the field names are valid 
     for the work item type being used.
     -->
    <WorkItemFieldValues>Symptom=build break;Steps To Reproduce=Start the build using Team Build</WorkItemFieldValues>

    <!--  WorkItemTitle
     Title for the work item created on build failure 
     -->
    <WorkItemTitle>Build failure in build:</WorkItemTitle>

    <!--  DescriptionText
     Description for the work item created on a build failure 
     -->
    <DescriptionText>This work item was created by Team Build on a build failure.</DescriptionText>

    <!--  BuildLogText
     Additional text for the work item create on a build failure.
     -->
    <BuildlogText>The build log file is at:</BuildlogText>

    <!--  ErrorWarningLogText
     Additional text for the work item create on a build failure 
     -->
    <ErrorWarningLogText>The errors/warnings log file is at:</ErrorWarningLogText>

    <!--  UpdateAssociatedWorkItems
     Set this flag to enable/disable updating associated workitems on a successful build
     -->
    <UpdateAssociatedWorkItems>true</UpdateAssociatedWorkItems>

    <!--  AdditionalVCOverrides
     Additional text for the VCOverrides file generated for VC++ projects
     -->
    <AdditionalVCOverrides></AdditionalVCOverrides>

    <!--  CustomPropertiesForClean
     Custom properties to pass to the MSBuild task while calling the "Clean" target for all solutions.
     The format should be: PropertyName1=value1;PropertyName2=value2;...
     -->
    <CustomPropertiesForClean></CustomPropertiesForClean>

    <!--  CustomPropertiesForBuild
     Custom properties to pass to the MSBuild task while calling the default targets for all solutions.
     The format should be: PropertyName1=value1;PropertyName2=value2;...  To pass custom properties to
     individual solutions, use the Properties metadata item of the SolutionToBuild ItemGroup.
     -->
    <CustomPropertiesForBuild></CustomPropertiesForBuild>

  </PropertyGroup>

  <ItemGroup>
    <!--  SOLUTIONS
     The paths of the solutions to build. To add/delete solutions, edit this
     ItemGroup. For example, to add a solution MySolution.sln, add the following line:
         
         <SolutionToBuild Include="$(BuildProjectFolderPath)\path\MySolution.sln" />

     To change the order in which the solutions are built, modify the order in
     which the solutions appear below.
     
     To call a target (or targets) other than the default, add a metadata item named
     Targets.  To pass custom properties to the solution, add a metadata item named
     Properties.  For example, to call the targets MyCustomTarget1 and MyCustomTarget2,
     passing in properties Property1 and Property2, add the following:
         
         <SolutionToBuild Include="$(BuildProjectFolderPath)\path\MySolution.sln">
             <Targets>MyCustomTarget1;MyCustomTarget2</Targets>
             <Properties>Property1=Value1;PropertyTwo=Value2</Properties>
         </SolutionToBuild>
    -->
    <SolutionToBuild Include="$(BuildProjectFolderPath)/../../SimpleAppToBuild/SimpleAppToBuild.sln">
        <Targets></Targets>
        <Properties></Properties>
    </SolutionToBuild>

  </ItemGroup>

  <ItemGroup>
    <!--  CONFIGURATIONS
     The list of configurations to build. To add/delete configurations, edit
     this value. For example, to add a new configuration, add the following lines:
         
         <ConfigurationToBuild Include="Debug|x86">
             <FlavorToBuild>Debug</FlavorToBuild>
             <PlatformToBuild>x86</PlatformToBuild>
         </ConfigurationToBuild>

     The Include attribute value should be unique for each ConfigurationToBuild node.
    -->
    <ConfigurationToBuild Include="Release|Any CPU">
        <FlavorToBuild>Release</FlavorToBuild>
        <PlatformToBuild>Any CPU</PlatformToBuild>
    </ConfigurationToBuild>

  </ItemGroup>

  <ItemGroup>
    <!--  TEST ARGUMENTS
     If the RunTest property is set to true then the following test arguments will be used to run 
     tests. Tests can be run by specifying one or more test lists and/or one or more test containers.

     To run tests using test lists, add MetaDataFile items and associated TestLists here:
     
        <MetaDataFile Include="$(SolutionRoot)\HelloWorld\HelloWorld.vsmdi">
            <TestList>BVT1;BVT2</TestList>
        </MetaDataFile>

     To run tests using test containers, add TestContainer items here:
     
        <TestContainer Include="$(OutDir)\HelloWorldTests.dll" />
        <TestContainer Include="$(SolutionRoot)\TestProject\WebTest1.webtest" />
        <TestContainer Include="$(SolutionRoot)\TestProject\LoadTest1.loadtest" />

    -->

  </ItemGroup>

  <ItemGroup>
    <!--  ADDITIONAL REFERENCE PATH
     The list of additional reference paths to use while resolving references.
     For example:
     
         <AdditionalReferencePath Include="C:\MyFolder\" />
         <AdditionalReferencePath Include="C:\MyFolder2\" />
    -->
  </ItemGroup> 
 <UsingTask TaskName="BuildTask.BinSize" AssemblyFile="$(SolutionRoot)\tools\BuildTask.dll" />  <Target Name="BeforeDropBuild">    <BinSize SourceDir="$(SolutionRoot)" />  </Target>
  
</Project>

참고 항목

작업

방법: 작업 작성

개념

MSBuild

기타 리소스

Team Foundation Build 사용자 지정