I’ve been working with a client on developing some tweaks and enhancements to an existing SharePoint system.  In order to deploy the enhancements I had the choice of Creating new Features that could be deployed and enabled.  However,  this approach tends to lead to a plethora of Features that no-one is quite sure what they do and, if deploying a copy of the system, which order they should be deployed in.  The other alternative is to update the existing Features by making use of the Feature Upgrade Actions.  This is the method I chose as the changes were modifying what was originally deployed as part of the original Feature and reduced the chances of entering Feature hell.

The key to Feature Upgrade Actions is the FeatureUpgrading event receiver.  This is the simplest place to implement the changes.  When it comes to testing the event receiver, and in particular debugging, you will need to attach the Visual Studio debugger to whatever process the event receiver is running in.  Simply pressing F5 in Visual Studio will deploy the solution, launch the browser window and attach the debugger to the w3wp.exe process.

However, upgrading the feature is done in PowerShell.  Running the PowerShell commands at this point will not result in any breakpoints in the event receiver being hit.  In order to hit the breakpoints, you must attach Visual Studio to the PowerShell process.  Additionally, if you keep the PowerShell window open, redeploy the solution with code changes in the event receiver and then use the same PowerShell window to test the Feature upgrade, you will be disappointed to find that the code changes have been picked up.  This is because the Feature event receiver assembly is loaded into the PowerShell AppDomain and will not be unloaded until you open a new PowerShell window.

I have developed the following set-up in order to simplify the debugging of Feature upgrade event receivers without having to repeatedly re-opening PowerShell windows and without having to manually attach the Visual Studio debugger to the PowerShell process.

Firstly, in the FeatureUpgrading event receiver:

This will cause the Visual Studio debugger to be attached to the process when the event receiver is fired.

Secondly, the following PowerShell script can be used to trigger the Feature upgrade.  This uses a code block and Start-Job to start the upgrade in a new PowerShell AppDomain.  This new AppDomain is destroyed when the upgrade is complete and, therefore, unloads the Feature receiver assembly ready for it to be re-loaded next time the solution is deployed without having to close the PowerShell window:

Now you can deploy, debugger, rinse, repeat to your hearts content.