Wiremock on Windows Azure

Wiremock is a great tool which lets you mock responses back to an endpoint. If you setup your app to proxy through it, you can set your own responses to matching requests – great for testing.

I’m going to try this out next week. It should be simple enough to invoke the app using the scripts in the links above, which essentially starts a web app which routes all web requests through to the jar.

Posted in Blog Posts | Leave a comment

Powershell Prettify XML

Got some XML you need to prettify in powershell? No problem!

Example xml:

<first><second><third>hello world</third><second><first>

Load the XML and preview it in the console prettified:

PS> [xml]$xml = Get-Content C:\temp\input.xml
PS> $xml.Save([System.Console]::Out)

<first>
  <second>
    <third>hello world</third>
  <second>
</first>

Load a file, prettify it, and save it as another file:

PS> [xml]$xml = Get-Content C:\temp\input.xml
PS> $xml.Save(c:\temp\output.xml)

Further reading:

Posted in Powershell | Leave a comment

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.

> DBCC CHECKIDENT ('TableName', NORESEED)
Checking identity information: current identity value '12345', current column value '56789'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.

> SELECT IDENT_CURRENT('TableName')
12345

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);
Posted in Blog Posts, MSSQL | Leave a comment

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
	db.name AS DBName,
	mf.name 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 db.name 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]
ON
( NAME = 'ExampleDatabase_rows', FILENAME = 'F:\Snapshots\201607041516_ExampleDatabase_Snapshot\ExampleDatabase_rows.ss' ),
( NAME = 'ExampleDatabase_files', FILENAME = 'F:\Snapshot\201607041516_ExampleDatabase_Snapshot\ExampleDatabase_files.ss' )
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
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
GO

RESTORE DATABASE ExampleDatabase from 
DATABASE_SNAPSHOT = '201607041516_ExampleDatabase_Snapshot';
GO

ALTER DATABASE ExampleDatabase
SET MULTI_USER;
GO
Posted in Blog Posts, MSSQL | Leave a comment

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

Posted in Blog Posts | Leave a comment

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:

  • URLWithBody:REGEX:example.com 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).

 

Posted in Blog Posts | Leave a comment

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.

<system.net>
   <defaultProxy>
     <proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
   </defaultProxy>
</system.net>

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.

Posted in Blog Posts | Leave a comment

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:

     [Test]
        public void SimpleStepAreDeserializedIntoCorrectTypes()
        {
            var knownTypesBinder = new KnownTypesBinder();
            knownTypesBinder.AddAssembly(Assembly.GetAssembly(typeof(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
            });

            Assert.IsInstanceOf(deserialized);
            Assert.IsInstanceOf(deserialized.Steps[0]);
            Assert.IsInstanceOf(deserialized.Steps[0].PostValidationRules[0]);
            Assert.IsInstanceOf(deserialized.Steps[1]);
            Assert.IsInstanceOf(((StoreNewItemStep)deserialized.Steps[1]).WhatToDo[0]);
        }

Here’s the implementation. Inspiration taken from the [Type Converting thread|http://json.codeplex.com/discussions/56031] and the [Custom Serialization Binder|http://www.newtonsoft.com/json/help/html/SerializeSerializationBinder.htm] 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())
            {
                _knownTypes.Add(type);
            }
        }

        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": "step1@example.com",
      "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": "step2@example.com",
      "Tags": null,
      "PreValidationRules": [],
      "PostValidationRules": []
    }
  ],
  "Links": [],
  "Groups": []
}
Posted in Blog Posts | Leave a comment

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,
Alex

Posted in Blog Posts | Leave a comment

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 (id_rsa.pub). Never disclose your private key. Share your .pub key instead.
  • Upload the id_rsa.pub github.com ssh keys
  • Save the private id_rsa file in your ~\.ssh folder
  • Restart your terminal if it doesn’t work
Posted in Blog Posts | Leave a comment