2011年6月16日 星期四

自訂Visual Studio專案建置項目 - Target

在Visual Stduio中專案進行建置時會透過MSBuild進行編譯,它的定義檔會是以XML方式呈現,試著打開由Visual Studio所建立的專案檔(*.csproj)可以看到類似以下的內容:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
  <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
  <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
  <ProductVersion>8.0.30703</ProductVersion>
  <SchemaVersion>2.0</SchemaVersion>
  <ProjectGuid>{B6B8C599-6FA9-4E30-8985-5D50B048FB6B}</ProjectGuid>
  <OutputType>Library</OutputType>
  <AppDesignerFolder>Properties</AppDesignerFolder>
  <RootNamespace>MyBuild</RootNamespace>
  <AssemblyName>MyBuild</AssemblyName>
  <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  <FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
  <DebugSymbols>true</DebugSymbols>
  <DebugType>full</DebugType>
  <Optimize>false</Optimize>
  <OutputPath>bin\Debug\</OutputPath>
  <DefineConstants>DEBUG;TRACE</DefineConstants>
  <ErrorReport>prompt</ErrorReport>
  <WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
  <DebugType>pdbonly</DebugType>
  <Optimize>true</Optimize>
  <OutputPath>bin\Release\</OutputPath>
  <DefineConstants>TRACE</DefineConstants>
  <ErrorReport>prompt</ErrorReport>
  <WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
  <Reference Include="System" />
  <Reference Include="System.Core" />
  <Reference Include="System.Xml.Linq" />
  <Reference Include="System.Data.DataSetExtensions" />
  <Reference Include="Microsoft.CSharp" />
  <Reference Include="System.Data" />
  <Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
  <Compile Include="Class1.cs" />
  <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
     Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

在最後可以看到Visual Studio本身就提供了兩個Target(BeforeBuild,AfterBuild)給使用者進行自定,但是如果不用這兩個該如何處理?

1. 複寫BuildDependsOn屬性(位於C:\Windows\Microsoft.NET\Framework\'vVersion'\Microsoft.Common.targets)
<PropertyGroup>
<BuildDependsOn>
  MyCustomTarget1;
  $(BuildDependsOn);
  MyCustomTarget2
</BuildDependsOn>


2. 新增上述加入的新Target
<Target Name="MyCustomTarget1">
<Message Importance="High" Text="Running MyCustomTarget1..."/>
</Target>
<Target Name="MyCustomTarget2">
<Message Importance="High" Text="Running MyCustomTarget2..."/>
</Target>
</PropertyGroup>


完成後,就可以在Visual Stduio進行編譯,並可以在Output的視窗看到以下結果:

沒有留言:

張貼留言