This section contains some exercises advanced over trivial examples.
Example 1: Cross Product
The following code realizes the cross product of two item groups. Please contribute
more elegant ways and examples to do it.
Recipe
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
[<ItemGroup>]
<fruit Include="apple"/>
<fruit Include="rhubarb"/>
<fruit Include="apricot"/>
<form Include="cake"/>
<form Include="pie"/>
<form Include="sorbet"/>
<form Include="mousse"/>
[</ItemGroup>]
<Target Name="Baking" Inputs="@(fruit)" Outputs="%(identity)">
<Message Text="@(fruit) %(form.identity)"/>
</Target>
</Project>
The fruits are enumerated by target batching, the forms by task batching. Appearantly, while baking, each individual fruit can be refered to using the
at notation.
Enjoy your meal!
Baking Target:
apple cake
apple pie
apple sorbet
apple mousse
Baking Target:
rhubarb cake
rhubarb pie
rhubarb sorbet
rhubarb mousse
Baking Target:
apricot cake
apricot pie
apricot sorbet
apricot mousse
Example 2: Intersection
This code was discussed as
Brainteaser at http://blogs.msdn.com/msbuild/archive/2006/05/18/601146.aspx.
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
[<ItemGroup>]
<GroupA Include="file1.txt"/>
<GroupA Include="file2.txt"/>
<GroupA Include="file3.txt"/>
<GroupA Include="file4.txt"/>
[</ItemGroup>]
[<ItemGroup>]
<GroupB Include="file1.txt"/>
<GroupB Include="file3.txt"/>
<GroupB Include="file5.txt"/>
[</ItemGroup>]
<Target Name="Build">
[<CreateItem] Include="@(GroupA)" Condition="'%(Identity)' != _ and '@(GroupA)' != _ and '@(GroupB)' != ''">
<Output TaskParameter="Include" ItemName="GroupC"/>
[</CreateItem>]
<Message Text="@(GroupC)"/>
</Target>
</Project>
Example 3: Filtering
A demonstration how item groups can be filtered by their metadata.
Advice
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
[<ItemGroup>]
<fruit Include="apple">
<consistency>firm</consistency>
</fruit>
<fruit Include="orange">
<consistency>pulpy</consistency>
</fruit>
<fruit Include="banana">
<consistency>softish</consistency>
</fruit>
<fruit Include="pear">
<consistency>unsound</consistency>
</fruit>
<fruit Include="apricot">
<consistency>unsound</consistency>
</fruit>
[</ItemGroup>]
<Target Name="Compost">
<Message Text="%(fruit.identity)" Condition="%(consistency) == 'pulpy' or %(consistency) == 'unsound' "/>
</Target>
</Project>
Execution
Compost Target:
orange
pear
apricot
Variation
Choose as message text :
@(fruit)
What is the output?