Pre- and Post- Build Differences in MSBuild

Again with the large codebases. Along with many other problems, it can be difficult to see what physical binaries have been created or copied when a build takes place, particularly if pre- and post- build events are used as a sort of batch file within the .csproj. Migrating away from that undesirable kind of build process can be difficult if you can’t tell what is supposed to be happening.

If we use the BeforeTargets and AfterTargets hooks in the msbuild pipeline we can take a snapshot of the output folder immediately before the build and immediately after it and store both snapshots in correspondingly named files. Then we can use a diff tool to look at, well, the differences.


<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<Target Name="SnapshotBeforeBuild" BeforeTargets="BeforeBuild">

	<PropertyGroup>
		<PreBinariesDir>$(TargetDir)\</PreBinariesDir>
		<SnapshotOutput>$(SolutionDir)\$(ProjectName).Pre.Snapshot.txt</SnapshotOutput>
	</PropertyGroup>	

	<ItemGroup>
		<PreBinaries Include="$(PreBinariesDir)**\*.*" />
	</ItemGroup>
	
	<WriteLinesToFile 
		Lines="@(PreBinaries)" 
		File="$(SnapshotOutput)" 
		Encoding="Unicode" 
		Overwrite="true"
		/>
</Target>

<Target Name="SnapshotAfterBuild" AfterTargets="AfterBuild">

	<PropertyGroup>
		<PostBinariesDir>$(TargetDir)\</PostBinariesDir>
		<SnapshotOutput>$(SolutionDir)\$(ProjectName).Post.Snapshot.txt</SnapshotOutput>
	</PropertyGroup>	

	<ItemGroup>
		<PostBinaries Include="$(PostBinariesDir)**\*.*" />
	</ItemGroup>
	
	<WriteLinesToFile 
		Lines="@(PostBinaries)" 
		File="$(SnapshotOutput)" 
		Encoding="Unicode" 
		Overwrite="true"
		/>
</Target>

</Project>