SnoopShell: The marriage of Snoop WPF and PowerShell
2012-07-01

I was given the opportunity to review a couple chapters of the excellent book PowerShell for Developers, written by my colleague Doug Finke.  One of the concepts in the book was embedding a PowerShell console into your application.  This idea is ingenious and we added this feature to our client’s software, and so far it has increased our productivity and opened the doors to many possibilities.

So what’s so cool about embedding a shell into your application?  Well, for starters, one of the immediate advantages is that it gives you the opportunity to test your application at run time.  If you are implementing the MVVM pattern then basically anything you can see in the UI is bound to some property in your view model.  What if you could expose an instance of your view model to the PowerShell console?  Yes, you would be able to interact with it directly, change values, and property change notification will kick in and update the UI.

The possibilities start to open up from there.  You can start scripting out common tasks – write once, run many times.  Or you can write a full fledge test suite as a script, give it to a QA tester, and have them run through it as a special kind of integration testing, one that happens with live, real data.  Or how about being able to modify code, at runtime, to try out an implementation without need to recompile or restart the application?  Sounds pretty awesome to me!

With this, I started thinking why don’t I try and add this to Snoop?  It’s a staple tool for any WPF developer, and adding scripting capabilities to Snoop will make it even more useful.

So, I sat down for a weekend and took a shot at it.  And with that, SnoopShell was born!

My fork of Snoop can be found here: https://github.com/bling/snoopwpf

It’s still in super-duper alpha, so features/ideas are still getting formulated, but here’s a glimpse of what it can do now.

The $root variable points to the root of the tree.  As you can see, Snoop represents this as a ApplicationTreeItem, which has a bunch of properties, the important ones being IsSelected and IsExpanded.

image

Let’s try interacting with the object by setting the IsExpanded to true.

image

So far so good.  Now let’s find my username using Ctrl+Shift.  The $selected variable is automatically synchronized with the selected item in the tree.

image

Let’s do some black magic and change my name.

image

Finally, let’s find every ListBox in the application.  Find-Item is used to recursively find everything in the visual tree which is a ListBox.

image

And from here, it’s as simple as grabbing the DataContext of any control to get access to the view model.

By the way, this is targeting PowerShell V3, so you will need to have the RC installed.

Try it out and let me know what you think!

comments powered by Disqus