Thursday, May 23, 2013

Manipulating Projects with NuGet Powershell scripts

I’ve been playing with hosting NuGet packages on our internal NuGet server a fair bit recently and encountered some interesting feedback from a colleague: none of our packages are signed with a strong-name. Gasp! Strong naming is definitely something that falls under the you really should bucket but gets quickly put in the not today simply because it’s a pain. If you’re familiar with the concept, the challenge with strong-naming is that if you give one assembly a strong-name then all dependent assemblies must also have one. This quickly cascades into a lot of repetitive tasks.

The pain of repetitive tasks is something that NuGet handles really well, so why not put my signing-key in a nuget package to automate this process? The concept of this package is extremely straight forward:

  1. Add my snk file to the project as content
  2. Manipulate the project properties in the install.ps1 script

I’ve really been wanting to write some PowerShell scripts for NuGet packages for a while now, but haven’t had the opportunity. My initial thought was to manipulate the project as an Xml document, but abandoned that approach as some research showed that Visual Studio would prompt the user to reload the project.

After some Googling, I came across a HaaHa (Haack/Hanselman) presentation at MIX11, where Scott’s AddMVC3ToWebForms package had some dirty hacks to manipulate the project. There’s a really good discussion in the NuGet forums that suggests using MSBuild API is a good approach to manipulate the Project properties only if what you want isn’t directly available from the Visual Studio API

Fortunately for me, manipulating the properties I wanted was dead easy so my script couldn’t be simpler:

param($installPath, $toolsPath, $package, $project)

$project.Properties.Item("AssemblyOriginatorKeyFile").Value = "mykey.snk";
$project.Properties.Item("SignAssembly").Value = "true";


Few handy tips I discovered while writing this…

You can get access to the $project variable using the Package Manager Console:

$project = Get-Project

You can list the details of your objects using the get-member cmdlet:

$project | get-member

And you can get a dump of the current values, and list of properties easily:

$project.Properties | select Name

Well, that’s all for now. Let’s hope this is the start of some awesome PowerShell NuGet badassness for you.

Happy Coding'.