Setting up dev environment in Ubuntu

sudo apt-get install -y git-core


wget -qO- | sh


heroku login
ssh-keygen -t rsa
heroku keys:add

Create your dev environment: git init, git clone
cd into directory

heroku create
git push heroku master

Configure node and npm:

sudo apt-get update
sudo apt-get install -y python-software-properties python g++ make
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install -y nodejs

Find groups in a list that a user is a member of

Excel can be useful for creating quick and dirty “loops” where you’ve already got a data set list. For example, to find groups from a list that a given user is a member of stick the groups in column A and this formula in column B and drag down:

=CONCATENATE("@dsquery group -name ", A1, " | dsget group -members |
  findstr /i /p /c:<username>")

Does the job.

Shuffle a List

Given a list, how can one randomly shuffle it? Like so:

private static IEnumerable<T> ShuffleList<T>(IList<T> list) {
  var length = list.Count;

  var random = new RNGCryptoServiceProvider();
  var data = new byte[length];

  var numbers = Enumerable.Range(0, length).ToList();
  var shuffledIndices = numbers.OrderBy(x => data[x]).ToArray();

  foreach (var index in shuffledIndices) {
    yield return list[index];

Note the use of RNGCryptoServiceProvider rather than using the Random class, which makes this code much more complicated due to the lack of a Next() method. However, it is cryptographically more sound.
Also, note the Range method of Enumerable to generate a sequence of numbers, which is a function I’m often needing and always forgetting exists (like std::iota in C++).

Strong signing of compiled assemblies

I decided I’d finally start finishing my projects properly by signing them before deployment. Everything I make (to date) has been for internal use only, so my lack of signing thus far has been of no consequence. Still, I thought I’d try to learn something – how hard could it be? You just enable code signing in your project and compile, right? Possibly.

My issues came two-fold: firstly, I made use of a referenced to three other DLLs, internally developed, but not by me. These were not strongly signed and so I could not sign my own project. Lowest common denominator. Browsing the web, I found this article. The basic premise is: decompile the DLL (which everybody knows is super simple in .NET) and then recompile, but with a strong name (i.e. signed).

I couldn’t get the key created by Visual Studio to work with this process so, as mentioned in the article, I created a new one with a different format:

sn.exe -k SigningKey.snk

Decompile your DLL into intermediate language (this also creates a resource file):

ilDasm.exe Some.dll /

Recompile, with a strong name:

ilAsm.exe /dll /resource=Some.res /key=SigningKey.snk

ZOMG – This works! At least, it did until I tried to run my application, at which point it crashed trying to load one of the DLLs.

The second problem I had was that one of my references also referenced another, so I had to also update the internal reference of the DLL to use the strongly-signed version of the other. I poked around in the generated IL and looked at that of other libraries referencing strongly named assemblies. And I copied that.

One needs to add a .publickeytoken attribute to the relevant .assembly section, like so (with the correct Public Key Token):

.assembly extern mscorlib
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
  .ver 2:0:0:0

Et voilà. Everything runs nicely.

As a final note, and much simpler to resolve, in order for a test project to access internal methods of a strongly-named assembly, you need to sign the test assembly and then specify its Public Key in the InternalsVisibleTo attribute. You can grab this as follows:

sn.exe -p SigningKey.snk SigningKey.PublicKey
sn.exe -tp SigningKey.PublicKey

The attribute becomes:

[assembly: InternalsVisibleTo(
  "Project.Test, PublicKey=<really_long_hex_string>")]

via Brenton House’s Blog @

Restore Domain Trust – No Reboot

Sometimes computers fall off the domain. Either you deleted a computer object (oops!) or you restored a VM snapshot in which you forgot to disable computer object password updates. Most domain rejoin methods require a machine reboot, but not this command:

netdom resetpwd /server:<domain_server> /userD:<user> /passwordD:*

Simply log off and then you can log on again with your domain account.


Additionally, you can test the status of domain trust with this PowerShell commandlet:


via MCTExpert Blog

WSUS: Get Superceded Status of Updates

I create Windows Server images and like to ensure they are patched up to date, but in the most efficient way possible. One approach would be to install every patch ever released, but that might take forever. Instead, I only want to install the latest patches for anything, i.e. ones that have not been superseded. To that end, I put together the following PowerShell snippet to run through the list of patches I currently install (exported to a text file) and show me the ones that are superseded. This snippet targets Server 2008 R2 patches only at the moment, but can easily be tweaked for other platforms.

The interesting parts are connecting to and searching the WSUS server.

                       "Microsoft.UpdateServices.Administration") | Out-Null
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer(
                       "", $false)

Get-Content .\patches.txt | % {
        $wsus.SearchUpdates($_) |
        Where {$_.legacyname -like '*2008R2*SP1-X64*'} |
        Select KnowledgebaseArticles, IsSuperseded

via Hey, Scripting Guys! Blog

Getting Last User Logons for a Host

Where I work, we have a lab full of servers, both virtual and physical. There used to be a “booking system”, but it fell into disrepair and the information is very out-of-date. Rather than a free-for-all, I like to check who’s recently logged onto a box before using it myself. If I get a name back, I can ask them for permission. Alternatively, if I can see that it hasn’t been touched for three months, then I’m more confident that it isn’t in use.

Here’s some PowerShell I put together for scanning the security event log for logon events and displaying them. Server 2008 R2 has the very useful Get-WinEvent commandlet lacking in earlier versions. This supports native filtering; on earlier systems we have to pull all events back and then filter them (hence the much larger default maxEvents).

Windows Server 2008 R2

function Get-LastLogons([int]$maxEvents=100) {
  # We need to flip the culture thanks to a bug introduced in PowerShell 3
  # that fails to populate localisable fields in certain locales, e.g. en-GB.
  $orgCulture = Get-Culture
  [System.Threading.Thread]::CurrentThread.CurrentCulture =
    New-Object "System.Globalization.CultureInfo" "en-US"

  $events = Get-WinEvent -MaxEvents $maxEvents
                         -FilterHashtable @{logname='security'; id=4624}

  [System.Threading.Thread]::CurrentThread.CurrentCulture = $orgCulture

  $logons = @()
  foreach ($e in $events) {
    $accNamePos = $e.Message.IndexOf("Account Name:")
    $accNamePos = $e.Message.IndexOf("Account Name:", $accNamePos + 1)
    $accDomPos = $e.Message.IndexOf("Account Domain:", $accNamePos)
    $logonIdPos = $e.Message.IndexOf("Logon ID:", $accDomPos)
    $accName = $e.Message.Substring($accNamePos + 13,
                                    $accDomPos - $accNamePos - 13).Trim()
    $accDom = $e.Message.Substring($accDomPos + 15,
                                   $logonIdPos - $accDomPos - 15).Trim()
    $logon = New-Object PsObject
    $logon | Add-Member -MemberType NoteProperty
                        -Name Name -Value $accName -PassThru |
             Add-Member -MemberType NoteProperty
                        -Name Domain -Value $accDom -PassThru |
             Add-Member -MemberType NoteProperty
                        -Name Time -Value $e.TimeCreated
    $logons = $logons + $logon


Windows Server 2003 and Server 2008

function Get-LastLogons([int]$maxEvents=10000) {
  $events = Get-EventLog -LogName Security -Newest $maxEvents |
              Where {$_.InstanceID -eq 540 -or $_.InstanceID -eq 4624}

  $logons = @()
  foreach ($e in $events) {
    $accNamePos = $e.Message.IndexOf("Account Name:")
    $accNamePos = $e.Message.IndexOf("Account Name:", $accNamePos + 1)
    $accDomPos = $e.Message.IndexOf("Account Domain:", $accNamePos)
    $logonIdPos = $e.Message.IndexOf("Logon ID:", $accDomPos)
    $accName = $e.Message.Substring($accNamePos + 13,
                                    $accDomPos - $accNamePos - 13).Trim()
    $accDom = $e.Message.Substring($accDomPos + 15,
                                   $logonIdPos - $accDomPos - 15).Trim()
    $logon = New-Object PsObject
    $logon | Add-Member -MemberType NoteProperty
                        -Name Name -Value $accName -PassThru |
             Add-Member -MemberType NoteProperty
                        -Name Domain -Value $accDom -PassThru |
             Add-Member -MemberType NoteProperty
                        -Name Time -Value $e.TimeGenerated
    $logons = $logons + $logon



You can just call the relevant Get-LastLogons commandlet on your system, but this call will remove local and SYSTEM logons. For my use case, this is what I needed.

Get-LastLogons |
  where { $_.Name -ne "$($env:computername)`$" -and
          $_.Name -ne "SYSTEM" }

Download Script 


Filling the Disk

I’m trying to test one my applications that installs various things onto the system. As such, there is a minimum required disk space for it to work correctly. In order to determine this threshold, I wished to simulate various low disk-space scenarios. I used the below command to create a large sparse file (i.e. not suitable as an actual data source) to fill the disk.

fsutil file createnew c:\temp\bigfile.dat <size_in_bytes>


Finding a Host in AD by GUID

Windows Server 2003 Users and Computers allowed the specification of managed GUIDs when creating new computer objects. Any clashes in the domain would be displayed and this was my quick go-to method of tracking down duplicate GUIDs (a sometimes painful issue causing PXE boot problems).

This was removed from the default installation of this MMC snap-in on Server 2008. I believe you get it back if you install the WDS role, but I can’t do that on my Windows 7 machine. Instead, we can resort to hand-crafting LDAP queries to find any existing computer objects with our target GUID:


Be careful to get the ordering correct of the GUID correct. The presence of hyphens often means the bytes need to be reordered .

WCF Impersonation Pass-through

I wanted to call another WCF service from within my WCF service (in fact, I was calling the same service but hosted on a different machine). The function itself uses the callers identity to determine its behaviour, but the second call was arriving as the computer account on the remote machine (this is expected when the caller is running as Local System).

I used the advice from this page in order to reuse the caller’s identity.

In particular, I went with the declarative model (mostly since it was easier).

[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public bool PassThroughMethod(string input)
  // Do things with the client's credentials,
  // e.g. call another service.
  return true;

Don’t forget both server code and the client need to be configure to enable impersonation.

using System.Security.Principal;
using System.ServiceModel;

// namespace and class and method setup, etc.

var channel = new ChannelFactory<IService>(
  new WSHttpBinding(),
  new EndpointAddress("http://localhost:8000/Service/service"));
channel.Credentials.Windows.AllowedImpersonationLevel =
return channel.CreateChannel();