Introduction
Recently I had to run a custom exe when publishing a SharePoint App from Visual Stuid 2012. I had to pull information from a couple of sources, and including it as a Tip so it can save time for some one trying to do something similar.
Note: I've only tested it on Visual Studio 2012 and for a SharePoint App project. I think it should work for Visual Studio 2013 and probably for other project types that can be published.
Background
It is possible to extend the Visual Studio Build process. By default VS allows us to define pre/post build events through the designer but we can get access to more by directly editing the csproj file.
https://msdn.microsoft.com/en-us/library/ms366724.aspx
Publish
Unfortunately I could not find any information on how to hook into the Publish event for a SharePoint 2013 app. The BeforePublish and AfterPublish targets did not fire for a SharePoint 2013 App.
I turned on detailed MSBuild project verbosity and found that different target (events) were raised during the publish process. One of the interesting one was the PackageSharePointApp. During this process, the package is pushed out into the publish directory. The MSBuild logs the following before completion of this target.
Successfully created package at: c:\somedir\app.publish\1.0.0.0\MyApp.app
So I could hook after this event and run my task. But the second piece of the puzzle was to figure out the path where the package was published.
I could not find any macro available in MSBuild that would give me the publish directory
https://msdn.microsoft.com/en-us/library/c02as0cs.aspx
However, after some more googling (or binging) I found that MSBuild has a parameter PublishDir that can be used to specify the publish directory. We can retrieve it in MSBuild, but it gives us the relative path. To get the complete path we can combine it with the ProjectDir. That is
$(ProjectDir)$(PublishDir)
The final bit of code to run an executable on the directory where the SharePoint App is published looks like the following. This code should be added near the end of the SharePoint App csproj file, just before the </Project> tag.
<Import Project="$(MSBuildToolsPath)\Microsoft.Common.targets" />
<Target Name="CallSomeExe" AfterTargets="PackageSharePointApp">
<Exec Command=""$(ProjectDir)\Some.exe" "$(ProjectDir)$(PublishDir) "">
<Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
</Exec>
</Target>
History
22-July-2015: First version