Category Archives: Blog Posts

Adding Specflow to a Visual Studio project

I’m using Visual Studio Community 2015 and want to write some acceptance tests – here are the quick steps to get started. Most of these can be found on the SpecFlow getting started page.

High level steps

  1. Install a Visual Studio Plugin so you don’t have to write too much SpecFlow glue code
  2. Write your features and steps
  3. Run your tests in your favourite test runner

Detailed steps:

  1. Install SpecFlow for Visual Studio
    This is a .vsix extension for Visual Studio 2015. There should be a version for your Visual Studio. This adds shortcuts such as feature files and custom tools, which means when you change your feature files, your feature.cs files are automatically generated upon each build. If you don’t have this, you’re probably going to have a long process of manually creating those files instead.
  2. Restart Visual Studio after the install so you get all the tools from the SpecFlow extension
  3. Create a test project and install the SpecFlow nuget
    Install-Package SpecFlow.NUnit

  4. Add a new .feature file to describe your feature in Cucumber language syntax. Right click and choose Add Item. Choose “SpecFlow Feature”. These templates were added by the .vsix Visual Studio Extension.When you add the item, you’ll see the feature file has been added, along with it’s glue – the .feature.cs file. This file is generated automatically by SpecFlow and joins the feature file to the any separate files. This file is generated at each build (or when you click Run custom tool on the .feature file), so don’t put your code for your steps in here, instead create another file.Here’s my example .feature file:
    Feature: InstancesFromTemplates
    	In order run new flows
    	As a user
    	I can create a new flow instance from a flow template
    Scenario: Do something example
    	Given I setup something
    	And I setup something else
    	When I do an action
    	Then I check the result
  5. Create a file for your steps. This is going to be a blank C# file with a [Binding] attribute on top so SpecFlow can discover it.
    using TechTalk.SpecFlow;
    namespace Flow.WebApi.Tests
        public class Steps
            // steps will go here
  6. Write a few steps in your feature file and generate the steps by right clicking the feature lines in the .feature file and clicking Generate Steps.
  7. Copy the generated steps into the clipboard and paste them into the Steps.cs file.
  8. Your steps file will look like this:
    using TechTalk.SpecFlow;
    namespace Flow.WebApi.Tests
        public class Steps
            [Given(@"I setup something")]
            public void GivenISetupSomething()
                // setup
            [Given(@"I setup something else")]
            public void GivenISetupSomethingElse()
                // setup something else
            [When(@"I do an action")]
            public void WhenIDoAnAction()
                // act
            [Then(@"I check the result")]
            public void ThenICheckTheResult()
                // assert
  9. Now when you rebuild, because you’ve got a Specflow [Binding] attribute on that class which makes it discoverable, your steps will be hit and your tests will be run in your runner.
    Rebuild your project, and run your tests:


Running Powershell as an Administrator

From Powershell:

Start a new Powershell process as an Administrator from an existing Powershell command:

Start-Process powershell -Verb runAs

Or with arguments:

Start-Process powershell -Verb runAs -ArgumentList <Arguments>

From the command line:

Run the following from a non-powershell command line:

powershell -Command "Start-Process PowerShell –Verb RunAs"


Performance Counters with NLog

I spotted that NLog have a performance counter target and decided to give it a whirl.

I’m currently working heavily with windows performance counters using a framework called PerfIt! and wanted to see if there was an easier (to configure) way.

Grab the source code here:

Install-Package NLog
Install-Package NLog.Config
Install-Package Topshelf

Using the topshelf getting started guide I created a quick example app which would write an INFO level log every second.

public class Program
  public static void Main()
    HostFactory.Run(x =>
      x.Service<Service>(s =>
        s.ConstructUsing(name => new Service());
        s.WhenStarted(tc => tc.Start());
        s.WhenStopped(tc => tc.Stop());

      x.SetDescription("Ex Topshelf Host");

public class Service
  readonly Timer _timer;
  private readonly ILogger _logger = LogManager.GetCurrentClassLogger();
  public Service()
    _timer = new Timer(1000) { AutoReset = true };
    _timer.Elapsed += (sender, eventArgs) => _logger.Info("This is an info log message");
  public void Start() { _timer.Start(); }
  public void Stop() { _timer.Stop(); }

The real magic happens in the target file. This is where the counters are created using the
autoCreate flag.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="" xmlns:xsi="" xsi:schemaLocation=" NLog.xsd" autoReload="true" throwExceptions="true" internalLogLevel="Info" internalLogFile=".\nlog-internal.log">

     counterHelp="This was created by NLog"
     incrementValue="1" />

   <target xsi:type="Console" name="console" detectConsoleAvailable="true" />

   <logger name="*" minlevel="Debug" writeTo="perf" />
   <logger name="*" minlevel="Debug" writeTo="console" />

When you put this all together, you get automatically created Performance Counters (available after you’ve restarted your console of course).

PS> Get-Counter -ListSet *example*

CounterSetName     : ExampleCategoryName
MachineName        : .
CounterSetType     : SingleInstance
Description        : Category created by NLog
Paths              : {\ExampleCategoryName(*)\Alexw.Example}
PathsWithInstances : {\ExampleCategoryName(logwritten)\Alexw.Example}
Counter            : {\ExampleCategoryName(*)\Alexw.Example}

Change Visual Studio 2015 TFS Associate or Resolve work item settings


VS showing item resolution in checkin screen with arrow pointing to item resolution

The default action for VS 2015 is to resolve the work item(s) you’re currently working on. In teams that check-in frequently this causes pain because they might be adding several check-ins before the story is complete.

Visual Studio 2015

You can change the default action in Visual Studio settings:

  • Navigate to Options > Source Control > Visual Studio Team Foundation Server
    • Or search for “Resolve associated work items” in the find box at the top right of Visual Studio 2015
  • Change the “Resolve associated work items on check-in”
    • Check this box to set the default action to resolve
    • Uncheck this box to set the default action to associate

Visual Studio 2015 VSTS options with arrow pointing at resolve option checkbox

Other Visual Studio Versions

That’ll be a registry edit I’m afraid. See this Stack Overflow for more information:

Finding and Deleting Windows Performance Counters

Golden Rule #1: Restart your command process and any existing apps when you modify performance counters. Performance counters are installed into the registry, so are not refreshed – only loaded in once to the current process. This causes much frustration.

Golden Rule #2: Don’t mess about with the registry, it can cause performance counters to vanish but still exist so you can’t create them again.

Listing performance counters

Remember: After modifying counters, close your console session. Performance counters are only loaded when a process is started.

To see all the performance counters installed on a Windows machine and save them in the counters.txt text file, run the following in either cmd or powershell:

typeperf.exe -q > counters.txt

To find a performance counter by name using wildcards using Powershell:

Get-Counter -ListSet "My.Counter.Name(*)"

Deleting Performance Counters

To delete an existing performance counter using Powershell – this has to be exact!

[Diagnostics.PerformanceCounterCategory]::Delete( "My.Counter.Name" )

Further reading

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.

Edit: I still need to come back to this, the last time I tried this it didn’t work and then I got distracted by work!

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!)