Reseeding MSSQL tables

Getting the current primary key seed value for a table

To get the next value from the primary key column of the database, either use the verbose descriptive CHECKIDENT method, or if you want to select it into a variable, use the IDENT_CURRENT function.

Checking identity information: current identity value '12345', current column value '56789'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.


Updating the primary key seed for a table

You can use either CHECKIDENT again to set the value.

DBCC CHECKIDENT ('TableName', RESEED, 12345)

Updating the primary key seed automatically

DECLARE @tableName VARCHAR(255); SET @tableName = 'TableName';
DECLARE @currentIdentity INT; SET @currentIdentity = (SELECT IDENT_CURRENT(@tableName))
DBCC CHECKIDENT (@tablename, RESEED, @currentIdentity);

Creating database snapshots using Microsoft SQL Server

Finding data files

Before you create a snapshot you need to know the files used by the database. Here’s a query to get the current list of files associated with a mounted database:

SELECT AS DBName, as [Filename],
	type_desc AS FileType,
	Physical_Name AS Location
FROM sys.master_files mf
INNER JOIN sys.databases db ON db.database_id = mf.database_id
WHERE LIKE 'ExampleDatabase'

Example output:

DBname   Filename     FileType  Location
Contoso	 Contoso      ROWS      C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\Contoso.mdf
Contoso	 Contoso_log  LOG       C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\Contoso_log.ldf

Make a note of all the ROWS and FILESTREAM entries. You cannot create a snapshot of LOG entries.

If you want to use the SQL Server Management Studio GUI, right click on the database and click on the Files section.

Creating a snapshot

Make sure the folder exists and your credentials can write to it otherwise you’ll get an error. Remember this is all happening on the server the command is running on, and this might not be your local machine.

You can only have one snapshot for a database, and snapshots cannot chain be chained together. You cannot create a snapshot of a snapshot.

Creating a snapshot via T-SQL:

CREATE DATABASE [201607041516_ExampleDatabase_Snapshot]
( NAME = 'ExampleDatabase_rows', FILENAME = 'F:\Snapshots\201607041516_ExampleDatabase_Snapshot\' ),
( NAME = 'ExampleDatabase_files', FILENAME = 'F:\Snapshot\201607041516_ExampleDatabase_Snapshot\' )
AS SNAPSHOT OF ExampleDatabase

Make sure to add an entry for each data file.

Restoring a snapshot

When you’ve got a snapshot and need to restore a database to it, use the below SQL.

The “WITH ROLLBACK IMMEDIATE” statement rolls back any currently open transactions. The database must be in single user mode to be restored. After it’s been restored, it’s set to multi-user mode.

USE master; 

ALTER DATABASE ExampleDatabase

RESTORE DATABASE ExampleDatabase from 
DATABASE_SNAPSHOT = '201607041516_ExampleDatabase_Snapshot';

ALTER DATABASE ExampleDatabase

Running an android emulator on Windows

Today I wanted to use an Android emulator and use the Charles Web Application Proxy to debug headers being sent over the wire. Here’s how to get an Android emulator running on your Windows machine.

Useful links

Edit: There are more useful things out there now Microsoft and Android play together a bit more nicely. Check out the Xamarin suite – especially the Xamarin Live Player. (Cheers Chris!)

Match Fiddler AutoResponder on body content

It’s possible to get Fiddler to manipulate your responses before they are returned to your application when Fiddler is acting as a proxy to your application.

Interestingly I couldn’t get the Chrome Advanced REST Client to go through Fiddler, but Chrome PostMan worked without any issues.

After you’ve setup your app to use your local Fiddler port, open up the AutoResponse tab.

  • Tick the enable rules checkbox to use the AutoResponse feature
  • Tick the Unmatched Requests Passthrough to enable other responses that don’t match a rule to continue to their destination
  • Items at the top of the list will get matched first
  • The first item that is matched will return the configured response
  • You can drag items from the traffic history into the responses dropdown, and edit the response. Really cool!

Here are some useful matches:

  • REGEX:example
    This lets you match the url and body with regular expressions
  • Header:MyHeader=exactmatch
    Match a particular header

Struggling matching? It might be an encoding thing or you might want to see more rules (tip: click the dropdowns in the Rules Editor to see some built in examples).


Force .NET application proxy

Forcing a .NET application proxy via web.config or app.config

This lets you force a proxy for a .NET application including web sites, running under any user or service account. Very useful for proxying via Fiddler.

     <proxy autoDetect="false" bypassonlocal="false" proxyaddress="" usesystemdefault="false" />

Mocking and testing live responses

Instead of doing this, I highly recommend using a mockable proxy such as MockServer or running it in memory using an OWIN based hosted mocking server like JustFakeIt and running tests in memory.

Deserializing different types using Newtonsoft JSON.NET

I want to be able to serialize and deserialize different types in my datastore json. This is how you can do it in .NET using a custom SerializationBinder. Json.NET uses the .NET SerializationBinder to work out custom types.

This relies upon a $type field being added to objects in your JSON, but this is probably going to be OK since we don’t need types for arrays or simple types (like string or int).

Lets start off with a test to explain what I’m doing:

        public void SimpleStepAreDeserializedIntoCorrectTypes()
            var knownTypesBinder = new KnownTypesBinder();

            var json = JsonConvert.SerializeObject(_template, Formatting.Indented, new JsonSerializerSettings
                TypeNameHandling = TypeNameHandling.Objects,
                Binder = knownTypesBinder

            var deserialized = JsonConvert.DeserializeObject(json, new JsonSerializerSettings
                TypeNameHandling = TypeNameHandling.Objects,
                Binder = knownTypesBinder


Here’s the implementation. Inspiration taken from the [Type Converting thread|] and the [Custom Serialization Binder|] page which this is based on.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;

namespace Flow.Library
    public class KnownTypesAssemblyBinder: SerializationBinder
        private readonly IList _knownTypes = new List();

        public void AddAssembly(Assembly assembly)
            foreach (var type in assembly.GetTypes())

        public override Type BindToType(string assemblyName, string typeName)
            var result = _knownTypes.SingleOrDefault(t => t.Name == typeName);
            return result;

        public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
            assemblyName = null;
            typeName = serializedType.Name;

This absolutely passes with no issues. Note the $type attribute in the example output below:

  "$type": "FlowTemplate",
  "Id": null,
  "Name": "Example Flow Template",
  "Version": 0,
  "Modified": "0001-01-01T00:00:00",
  "Author": null,
  "Tags": null,
  "Steps": [
      "$type": "FormCollectionStepTemplate",
      "Form": "Step 1 Form",
      "Id": "Step 1 Id",
      "Version": 111,
      "Name": "Step 1 Name",
      "Author": "",
      "Tags": null,
      "PreValidationRules": [],
      "PostValidationRules": [
          "$type": "RegexValidationRule",
          "IsValid": false
      "$type": "StoreNewItemStep",
      "WhatToDo": [
          "$type": "StoreWhatWhere",
          "SourceKey": "name",
          "Collection": "customer",
          "Key": "name"
          "$type": "StoreWhatWhere",
          "SourceKey": "email",
          "Collection": "customer",
          "Key": "email"
      "Id": "Step 2 Id",
      "Version": 222,
      "Name": "Store Customer Information",
      "Author": "",
      "Tags": null,
      "PreValidationRules": [],
      "PostValidationRules": []
  "Links": [],
  "Groups": []

I’m Leaving JustEat (true story)

Today I sent my leaving letter around work. It’s a shame I couldn’t send it to the whole department but it feels nicer to hand select the people I wanted to send it to.

Dear Friends and Colleagues,

After two very happy and successful years at Just Eat I have decided to hand in my notice and try something new.

It’s been fantastic working with you and this has been the best company I’ve ever worked for. I’m so very thankful to have met you and to have delivered real change together on the platform.

My leaving drinks are on Friday in the Wine Cellar, a hidden gem underneath Holborn Viaduct. I hope you’ll be able to come and say goodbye!

Many thanks,

Configuring SSH keys for Github using Windows 10

You’ll need to install:

Create an ssh key and set it as your default:

  • Run ssh-keygen
  • Create a key. Name it id_rsa. You’ll get a private key (id_rsa) and a public key ( Never disclose your private key. Share your .pub key instead.
  • Upload the ssh keys
  • Save the private id_rsa file in your ~\.ssh folder
  • Restart your terminal if it doesn’t work

Fixing Powershell Params “The input to an assignment operator must be an object that is able to accept assignments”

Problem: The input to an assignment operator must be an object that is able to accept assignments

Write-Host "Ahoy hoy!"
    [Parameter(Mandatory=$true)][string]$environment="example" # error here

Solution: You’ve got a problem with your params. In my case I had a statement before declaring the params section. Params should be at the start of the file, or at the start of a function.

    [Parameter(Mandatory=$true)][string]$environment="example" # error here
Write-Host "Ahoy hoy!"

More information:

Wrapping using statement with dispose in powershell

Today I’m working with zip archives for lambda functions. I needed to take the zip file and add deployment configuration. Lambdas are currently packaged up with their configuration so I need to inject in a file into the zip.

It’s relatively trivial to work with compressed zip files in Powershell, however you need to dispose the handle when you’ve finished with it.

$disposeMe = [System.IO.Compression.ZipFile]::Open($path, "Update");
# ...

A using statement is really just a try catch that calls dispose if the object isn’t null. Dave Wyatt’s Using-Object: PowerShell version of C#’s “using” statement post has a good example function of where this is all taken care of and uses a $ScriptBlock to execute it.

So instead of manually calling dispose, we can now write a using lookalike, and the handle will be disposed for us. Lovely!

Using-Object ($zip = [System.IO.Compression.ZipFile]::Open($path, "Update")) {
    # ... 

If you don’t want to add the function, you can always just wrap a try catch around it.

try { $disposeMe = [System.IO.Compression.ZipFile]::Open($path, "Update"); }
  if ($null -ne $disposeMe -and $disposeMe -is [System.IDisposable]) { $disposeMe.Dispose() }