Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an AfterBuild event to a project when installing my NuGet package?

I have a nuget package which adds an executable that I need to run after a project builds each time.

I can manually add this by adding a section to each project file like so:

<Target Name="AfterBuild">
    <PropertyGroup>
      <PathToOutputExe>..\bin\Executable.exe</PathToOutputExe>
      <PathToOutputJs>"$(MSBuildProjectDirectory)\Scripts\Output.js"</PathToOutputJs>
      <DirectoryOfAssemblies>"$(MSBuildProjectDirectory)\bin\"</DirectoryOfAssemblies>
    </PropertyGroup>
    <AspNetCompiler Condition="'$(MvcBuildViews)'=='true'" VirtualPath="temp" PhysicalPath="$(ProjectDir)" />
    <Exec Command="$(PathToOutputExe) $(PathToOutputJs) $(DirectoryOfAssemblies)" />
  </Target>

How can I add this to a project when I install the nuget package? (i.e. using the DTE $project object in the Install.ps1 file)

I would greatly appreciate any help on this.

Thanks

Richard

like image 334
Richard Avatar asked Nov 11 '11 15:11

Richard


2 Answers

As of NuGet 2.5, by convention, if you add a targets file at build\{packageid}.targets (note 'build' is at the same level as content and tools), NuGet will automatically add an Import to the .targets file in the project. Then you don't need handle anything in install.ps1. The Import will be automatically removed on uninstall.

Also, I think the recommended way to do what you want would to create a separate target that is configured to run after the standard "Build" target:

<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <Target Name="NuGetCustomTarget" AfterTargets="Build">
        <PropertyGroup>
            <PathToOutputExe>..\bin\Executable.exe</PathToOutputExe>
            <PathToOutputJs>"$(MSBuildProjectDirectory)\Scripts\Output.js"</PathToOutputJs>
            <DirectoryOfAssemblies>"$(MSBuildProjectDirectory)\bin\"</DirectoryOfAssemblies>
        </PropertyGroup>
        <AspNetCompiler Condition="'$(MvcBuildViews)'=='true'" VirtualPath="temp" PhysicalPath="$(ProjectDir)" />
        <Exec Command="$(PathToOutputExe) $(PathToOutputJs) $(DirectoryOfAssemblies)" />
    </Target>
</Project>
like image 152
Mike Zboray Avatar answered Nov 15 '22 03:11

Mike Zboray


Here's a script that adds a afterbuild target. It also user the NugetPowerTools mentioned above.

$project = Get-Project
$buildProject = Get-MSBuildProject

$target = $buildProject.Xml.AddTarget("MyCustomTarget")
$target.AfterTargets = "AfterBuild"
$task = $target.AddTask("Exec")
$task.SetParameter("Command", "`"PathToYourEXe`" $(TargetFileName)")

The hard part was getting the quotes right. This is what it looks like in my powertools script.

like image 42
Gluip Avatar answered Nov 15 '22 05:11

Gluip