PowerShell: Take care with null arguments and SilentlyContinue…

I just had an excellent gotcha at work that took down one of our test servers.

I’m using PowerShell scripts as part of an msdeploy process to stop a service in the presync command so that the files can be updated, followed by yet more PowerShell starting the service back up again in the postsync command.

My script looked like this:

Get-Service $serviceName -ErrorAction SilentlyContinue | Stop-Service

I made two mistakes here and learned two valuable lessons.

Lesson 1 – Don’t misuse SilentlyContinue

For reasons I won’t bore you with, $serviceName wasn’t defined. Normally the interpreter would’ve halted proceedings and prevented anything from happening, but since I was eating all the errors it just went along and passed $null into Stop-Service. Which of course stopped all the services.

Yes, all of them.

Even Parental Controls. PARENTAL CONTROLS! THINK OF THE CHILDREN!

Since I wanted one specific service, I’ve now chosen to do something more like this:

$service = Get-Service | ?{ $_.ServiceName -eq $serviceName } | select -First 1

if ($service) {
$service.Stop()
}

This isn’t very “functional” and PowerShell experts will have more elegant and PowerShell-like ways to resolve this, but at least I’m not eating exceptions any more.

Lesson 2 – Be careful with null arguments

In that first example, what if $serviceName was defined, but was currently null? Run this for yourself and see:

Get-Service $null

That’s right, no error, and it returns ALL your services. Which in my case would’ve been piped into Stop-Service…

This is obvious when you think about it. “Get-Service $null” is exactly the same as “Get-Service”. The default behaviour for which being to return all services.

So beware when using variables as arguments – think about what the default behaviour is if those values are null.

Lesson 3 – Scripts are software too

I said there were 2 lessons, but I just thought of this one so I threw it in. I should have known better than to eat all the exceptions. I’d never do this in C#, for example:

try
{
// Do stuff
}
catch
{
// Om nom nom
}

So why did I allow myself to do it here? I think subconsciously I was thinking “It’s only a script” but of course that was a mistake. In future I will try and make sure I treat scripts with the same respect as any other software I write. Even a simple batch file could do untold damage if badly written, let alone the more intricate things that are possible with PowerShell.

My first F# program

I love C# and have some experience in other languages. I have a hobby project and have contributed to another open source project as part of GiveCampUK. I love Pluralsight and although I’m still learning, am quite passionate about DDD, CQRS and Event Sourcing. However I still like to find alternative ways to exercise the “little grey cells” and so, despite having no use for it whatsoever, I’m going to make a concerted effort to learn F#. Here’s my first attempt of something marginally useful:

let pi = 3.141592654
let area r = pi * (r * r)
let x = area 2.0

I’ve been using tryfsharp.org, which seems to be quite a neat way to get into it. I’ll probably checkout Tekpub and Pluralsight, too. I just wish I knew what it was for

Apple Store Lockout

I’m in the market for a new laptop. I’ve spent a fair amount of time looking around and, despite being a 100% Windows user for my entire career, am seriously considering a 15" MacBook Pro Retina for my next upgrade. It’s a massive extravagance but I’m hoping it’ll last me even longer than my tired old Dell 6400.

Now since these things don’t come cheap, I want to have a good opportunity to play with them before I take the plunge. So I went to the Birmingham UK Bullring Apple store on Sunday to have another go with one.

As I arrived at the store, I saw the queue of die-hards outside the shop waiting patiently in line for the new iPad Mini, and decided there was no need for me to join that queue. I asked the chap at the door if I could come in to look at a MacBook.

"Oh we’re queuing just for entrance at the moment."

So I walked away. I still intend to get one of these machines at some point, but it’s safe to say it won’t be going on the monthly sales figures for that store.

I can understand making people queue to get one of the first handful of a new thing (putting aside the artificially-strangled stock availability), but I can’t understand why the store would make me queue behind them to look at something totally different?

DDD: Refactoring toward deeper insight

A good question came up on the DDD/CQRS group earlier today, and I thought I’d publish my response here.

The questioneer was asking how they should model deletions in their domain, where they might have a “Delete[Entity]Command”.

If you read Eric Evans’ DDD book, you’ll find it often talks about “refactoring toward deeper insight“. This basically means when you’re not sure which way to go when modelling the domain that you should go back and talk to your domain experts. Keep talking as the information soaks in and you’ll find yourself picking up on little seemingly throwaway phrases and bits of information here and there. They don’t think are particularly special because they’re so used to them, but to you these little facts are incredibly important. It’s like panning for gold.

In this case, “delete” might not be a use-case your domain experts need. In fact, unless your domain experts are in the domain of computers and file systems, I’d go as far as to say it’s highly unlikely. A Domain Model is just that – a model of the domain. Since most domains are in the real world, “delete” doesn’t really exist. You can’t “delete” a stock item, or a financial transaction. You can perhaps mark a stock item as “lost” or create a reciprocating financial transaction though.

Take an example of sales orders (modelled by a SalesOrder AR). If you ask your domain experts “what happens when you delete an order?” they’ll likely respond “Oh no – you can’t delete orders!”. You explain that’s not quite what you meant, and discover that orders can be “cancelled” or “completed”, in which case you can’t add any more line items.

In this example “completed” and “cancelled ” are the key words, and you’d implement the appropriate invariants in your SalesOrder aggregate root (AR). Of course that implementation may end up as a state machine, but then it’s often the case that an AR works like a state machine (i.e. favour a variable “state” rather than a heap of boolean flags).

In fact in general you should be wary of terms like “create”, “update” and “delete” when modelling your domain. If these are the only verbs in your ubiquitous language you should probably not be using DDD for that system.

Remember that DDD is allowing the Domain to Drive your Design. The Domain Experts know it best so they’re your best tool. Your domain model should reflect behaviours and rules required and defined by the domain experts and only those behaviours and rules.

Session Submission Nerves

People who know me will know that I talk a lot. They would not be surprised to hear that my school reports often included comments from teachers about being talkative to the point of distracting my classmates. I think I’m fairly personable, and enjoy being in company.

Yet I’m still nervous about the fact that last week I submitted a session for DDD10.

Don’t get me wrong; I’m very excited and will be gutted if I don’t get picked to speak (although that’s what voting is all about), but now it’s real. Now I really might have to go through with it.

I’ve got my fingers crossed that I’ll get the gig (and won’t die on my arse). Hopefully everything will go to plan and it’ll all be worth it if I’ve enthused at least a few people about my chosen subject. I’ll be putting a fair amount of preparation in, and I’m fortunate enough to be able to perform live testing on humans at the ShropshireNET user group later this month, but still it’s a new beginning for me and I just hope I’m worthy.

If you fancy finding out a bit more about the practical side of actually doing things with CQRS and Event Sourcing, please feel free to come to the user group session and/or vote for me at DDD10.

Here’s to trying new things and getting out of your comfort zone!

Permutations

Disclaimer: I know those of you who’ve done computer science or software engineering at university will already know how to do this, and know the name for the pattern, but in case we don’t use it I wanted to show it off somewhere. Smile

A colleague and I just had a code-off without realising it; we were both thinking about the same problem at the same time. That problem being a way to take a list of things, and get a list of the permutations of them.

So { “P1”, “P2”, “P3” } should result in:

{
    { “P1” },
    { “P2” },
    { “P3” },
    { “P1”, “P2” },
    { “P1”, “P3” },
    { “P2”, “P3” },
    { “P1”, “P2”, “P3” }
}

I remembered an trick an old boss of mine taught me for finding combinations of items in a series, using bits. If you think of iterating a series of bytes you see the usual pattern:

  • 1 = 00000001
  • 2 = 00000010
  • 3 = 00000011
  • 4 = 00000100

So this means that iterating a numeric value (i.e. 1 to 256) and converting the loop variable to a sequence of bits on each iteration is basically going to generate all the combinations of true and false for a series of 8 boolean flags. That’s the behaviour we’re looking for. Of course, 8 is quite a limitation, but if we use Integer rather than byte we get 32, which is more than enough (in fact I get OutOfMemoryExceptions with a series of 23 items on my 8gig Quad-Xeon machine).

Here’s my implementation. Notice I’m using the trick, but I’m not iterating all the “powers of 2”, I’m iterating the items in a list, and only taking the ones where the bit representing their position in the list is set:

using System;
using System.Collections.Generic;

namespace ConsoleApplication13
{
    public class Combinator
    {
        public IList<List<T>> AllCombinationsOf<T>(IList<T> items)
        {
            if (items == null) throw new ArgumentNullException("items");
            if (items.Count > 32) throw new ArgumentException("Only 32 values are supported.", "items");

            int top = GetTop(items.Count);

            var permutations = new List<List<T>>();
            for (int combinationId = 1; combinationId <= top; combinationId++)
            {
                AddPermutations(permutations, combinationId, items);
            }

            return permutations;
        }

        private static void AddPermutations<T>(List<List<T>> permutations, int filter, IEnumerable<T> items)
        {
            var permutation = new List<T>();

            int i = 1;
            int bitIndex = 1;
            foreach (var item in items)
            {
                if ((filter & bitIndex) == bitIndex)
                {
                    permutation.Add(item);
                }

                i++;
                bitIndex = (int)Math.Pow(2, i - 1);
            }

            permutations.Add(permutation);
        }

        private static int GetTop(int count)
        {
            int result = 0;
            for (int i = 0; i < count; i++)
            {
                result = (result << 1) + 1;
            }
            return result;
        }
    }
}

Simplify string and path operations in FinalBuilder with PowerShell

At work we use FinalBuilder as our continuous integration server. Essentially it works like CruiseControl etc, but has software you use to build the project files rather than eating your XML raw. The basis of FinalBuilder is assembling “actions” into a build script that is executed either in the FinalBuilder software, or on a build server running FinalBuilder Server.

Now typically, performing path and string manipulation is tricky, because you need to use FinalBuilder actions like “String Trimming”, “String Replace” and “String Pos”. All of which work on the basis that they take the value of a global variable defined in the project, and set the result to another global variable defined in the project. If you have a lot of string work to do, this can quickly become unwieldy.

So instead, I propose ignoring the built-in string and path manipulation actions, and swopping them all for one or two “Run Script” actions with PowerShell scripts. In my case, I have a URL to a Mercurial repository hosted on a Kiln server passed-in to my project, and I want to apply a convention to work out what the local repository path for me to clone to and build from should be. I do this by:

  1. Adding a single “Run Script” action at the top of my project
  2. Selecting it
  3. In the “Script Editor” window (View->Script Editor), select “PowerShell” as the scripting language
  4. In the script editor window, add the following:

$RepositoriesLocation      = $FBVariables.GetVariable("_RepositoriesLocation") # Global variable configured on FB Server
$RepositoryUrl             = $FBVariables.GetVariable("RepositoryUrl") # Passed-in at runtime
$uri                       = New-Object -type System.Uri -argumentlist $RepositoryUrl

$repositoryName            = $uri.Segments[$uri.Segments.Length - 1].Trim(‘/’) # Parse the repo name
$projectName               = $uri.Segments[$uri.Segments.Length - 3].Trim(‘/’) # Parse the Kiln project name

$WorkingCopyRoot = [System.IO.Path]::Combine($WorkingCopiesLocation, $projectName)
$WorkingCopyRoot = [System.IO.Path]::Combine($workingCopyRoot, $repositoryName)

$FBVariables.SetVariable("WorkingCopyRoot", $workingCopyRoot) # The the global variable for subsequent actions to use

As you can see, this obtains the value passed-in to the project from the HgUrl variable, breaks it up and re-arranges it to produce a local path for the URL. There’s some other stuff about the location of the working copies being in a common location but that’s all there is to it.

I’ve recently gone a bit mad for this approach. How about this method of establishing the solution file to build in any given Hg repository, for example?:

$workingCopyRoot = $FBVariables.GetVariable("WorkingCopyRoot")
$solutionFileFullName = Get-ChildItem $workingCopyRoot -filter *.sln | select-object FullName -first 1
$FBVariables.SetVariable("SolutionFileFullName", $solutionFileFullName)

Happy, erm, “PowerShelling”… :)