Create a subset of Unit Tests with a Playlist

Visual Studio Unit Test Tools comes with another excellent feature to manage unit test as a group /subset, called as “Playlist”. A Playlist is a subset of unit test methods grouped under some category. The Playlist could be a logical subset based on modules, features, layers etc. A Playlist is useful when we want to test a particular set of test cases among all the test methods. In that case, we just create a group of those test cases which may get impacted by our current changes in the actual code, and execute them only to ensure nothing breaks.

You can create a playlist either from the Test Explorer or the main menu by navigating to Test –> Playlist. Let’s have a look how we can do that.

  • Step 1 : Select Unit Test methods together for which you want to create a playlist.
  • Step 2 : Navigate to Add to Playlist –> New Playlist

The rest I’m sure you can work out for yourself, if you want more information on this check out Daily .NET Tips

Timeout Process

When you are dealing with large amounts of data or processes that are very time hungry you sometimes need the ability to timeout that task and continue.

Here is a snippet of code that loops around that takes 1 second, and you can set a timeout to any time you like, but if it is less than 1 second, it will cancel the task and free up resources.

class Program
 public static void Main()
 int timeOutInMilliseconds = 450;
 var startTime = DateTime.Now;

var cTokenSource = new CancellationTokenSource();

// Create a cancellation token from CancellationTokenSource
 var cToken = cTokenSource.Token;
 // Create a task and pass the cancellation token
 var t1 = Task<int>.Factory.StartNew(() => GenerateNumbers(cToken), cToken);

// to register a delegate for a callback when a cancellation request is made
 cToken.Register(() => cancelNotification(cTokenSource));

 while (true)
 Console.WriteLine("Finished Processing");

if (DateTime.Now > startTime.AddMilliseconds(timeOutInMilliseconds))
 Console.WriteLine("Timed out");


private static Task HandleTimer(CancellationTokenSource cancellationTokenSource)
 Console.WriteLine("\nHandler not implemented...");
 return Task.Run(() => { var a = 0; });

static int GenerateNumbers(CancellationToken cancellationTokenSource)
 int i;
 for (i = 0; i < 10; i++)
 Console.WriteLine("Method1 - Number: {0}", i);

// poll the IsCancellationRequested property
 // to check if cancellation was requested
 if (cancellationTokenSource.IsCancellationRequested)
 return i;

// Notify when task is cancelled
 static void cancelNotification(CancellationTokenSource cancellationTokenSource)

Source: Parallel

Search every column in a SQL Server Database

Following on from the Search every table and field in a SQL Server Database article I posted last week, I thought it would be useful also to be able to search every column for some text and return where it was found.

Here is the script that I have produced which does the job and is quick in its response.

CREATE PROC [SearchAllColumns]
 @SearchStr nvarchar(100)
 TABLE_NAME AS 'TableName'
 WHERE COLUMN_NAME LIKE '%' + @SearchStr + '%'
 ORDER BY TableName,




In the article we are going to look at the importance of a good version control system, and why it is crucial when it comes to API versioning.

It is essential that we deploy a Web API version control from an early stage in our project. Versioning will ensure that the project is built on a solid base and that a standard is maintained. A good version control system will enable us to collaborate and scale in a managed way, and as such will provide our customers with a more straightforward progression through our upgrades.

The first point to note we should always version our Web API, while at the same time keeping as much of the same URI as possible, with the possibility of newer versions having a different URI and a clear upgrade path.

What is versioning?

Versioning is a thoughtful application of changes to a system that is already in production.

There are two types of versioning, they are:

  • Versioning Data – changing the way we lay out our data structures, name things and so on
  • Version SOAP Endpoints – adding or removing functionality, such as functions that can be called or changing parameters that can be called on those endpoints

Plan Versioning

How do we handle versioning?  We are producing a plan for the first release, and we need to do the following:

  • At the start
    • Pick a version-able identifier
    • pick a versioning pattern
  • Version-able identifiers
    • XML Data: XML Namespace
    • Things that listen at URL’s: URL Path
  • Numbering Pattern
    •[service name]/major.[minor].[build[
    • Each number increases monotonically: 1,2,3,4, …., 9, 10, 11
  • Date Pattern
    •[service name]/[yyyy]/[mm]/[dd]
    •[service name]/[yyyy].[mm].[dd]

The only time we ever need to version is when we change the contract with the client, we can change the contract in one of three ways:

  • Data
    • Add a new type
    • Removing a type
    • Change fields
    • Required fields
  • SOAP
    • Add/remove methods
    • Change parameter names
    • In session: change the set of initiating/termination actions
  • REST
    • Change URI structure
    • Add methods

Versioning Data

There are times when you need to version the data:

  • Reasons to version data
    • Name chooser picked terrible names (aka renames)
    • Adding/removing fields
  • Things to handle upon versioning data
    • Co-existing old/new clients
  • Reason not to version data
    • Re-ordering for aesthetic reasons

New Members

  • If a new member is required, define sensible default
    • Caveat: if no sensible default exists, you have a severe bug in a previous version
    • If you think you have no reasonable default and customers won’t change, you will suddenly find a sensible default
  • Place at the end
    • Some clients may be ordinal dependent, not name
    • Use DataMember.Order property
  • Or inherit Data Transformation Object if new item breaks old clients

Versioning SOAP Endpoints

  • Reasons to version endpoints
    • Name chooser picked terrible names (aka renames)
    • Adding methods
    • Removing methods
    • Updating method parameters (new version of old type)
    • Adding terminating functions (might already exist)
  • Things to handle upon versioning endpoints
    • Update old to call out to controller properly
  • Reasons not to version endpoint
    • Re-ordering for esthetic reasons (don’t do this!)

Handle Versioning

  • Keep services light
  • Keep details in separate class
  • Use MVC type pattern
    • DTO is Model
    • Service is View
    • “Separate class” is Controller
  • Benefits
    • Minimize code churn in services
    • Keep logic mapping DTO to Business in one place

Key Points

  • Keep service code clean, simple.
  • Think of service as a machine UI to the real object model.
  • Let internal logic worry about mapping DTO to the business objects.
  • Handle upgrade in one place, away from service.

Versioning REST Endpoints

  • Reasons to version REST endpoints
    • Name chooser picked terrible names
    • Paths don’t make sense
    • Updating data types, parameters (new version of old model)
  • Things to handle upon versioning endpoints
    • Update old to call out to controller properly
  • Reasons not to version endpoint
    • Supporting more of Uniform Interface (GET | HEAD, PUT, POST, DELETE)

Where to version?

  • New set of services in new directory
    • Pros: clean separation, small files, easy to read, allows for more natural deletion later
    • Cons: not necessary, moves logic to new file
  • Keep everything in one file, add new UriTemplates
    • Pros: All URLs in one place, easy to see what uses code, can see evolution in one place
    • Cons: Likely to clutter code, increase maintenance burden over time

Support Plans for Versioning

  • Need an SLA between service and consumers
  • Need to define
    • How long a consumer can depend on a version
    • What constitutes end of life for a version
  • Need to prepare for
    • Extensions to end of life
    • Presence of older clients
    • Work with client to update to latest

Assets to Create to Assist/Reduce Burden

  • Documentation on wire-level formats
    • XSD, HTML documents, sample code
  • SDKs in client languages
    • Java, Ruby, PHP, Python, .NET
    • Can ease migration.
      • Client uses new library, works till clean compile
      • Versioning issue becomes deployment issue
  • Support staff
    • Dedicate staff to help support clients who are migrating code.


  • Versioning: The retrospective application of changes to a system.
  • Plan ahead
    • URL structure, version names, use MVC pattern
  • Changes hit in three, related areas: Data, SOAP Methods, REST
  • Manage changes
  • Create new endpoints for new data types
  • Use Data Transformation Objects
  • Keep logic to translate between Data Transformation Objects and business in one place


Versioning Strategies by Microsoft

Best Practices: Data Contract Versioning

ASP.NET Core RESTful Web API versioning made easy by Scott Hanselman


Search every table and field in a SQL Server Database

One thing I do like about MySQL is when using phpMyAdmin is the ability to search the whole database for any string, this should only be available for developers who are searching for data in an extensive database.  It does take some time to run, but remember it has a lot to do.

Here is the script that Narayana Vyas Kondreddi has produced which does the trick and works very well.

CREATE PROC SearchAllTables
 @SearchStr nvarchar(100)
 -- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
 -- Purpose: To search all columns of all tables for a given search string
 -- Written by: Narayana Vyas Kondreddi
 -- Site:
 -- Updated and tested by Tim Gaunt
 -- Tested on: SQL Server 7.0, SQL Server 2000, SQL Server 2005 and SQL Server 2010
 -- Date modified: 03rd March 2011 19:00 GMT
 CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
 DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
 SET @TableName = ''
 SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
 SET @ColumnName = ''
 SET @TableName = 
 ), 'IsMSShipped'
 ) = 0
 WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
 SET @ColumnName =
 AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
 IF @ColumnName IS NOT NULL
 'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
 ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
 SELECT ColumnName, ColumnValue FROM #Results
 DROP TABLE #Results

Original post

DataSets with Entity framework

Why, why, why I hear you say would you want to use Datasets with the Entity Framework?

I’m not here to debate the whys and wherefores for doing this, just finding a simple solution to the problem.

99.9% of the time I would say don’t, but if you have a legacy system and all the code is driven by DataSet’s you have many choices.

  1. Rewrite all the business logic code to support EF
  2. Use an old style connection to the database
  3. Use DataSet’s via EF connection

Each has their issues, the first could take some time, and would need full testing to ensure nothing had changed.

Using an old style database connection, you might as well just use the old legacy code.

What I’m going to be covering here is being able to call a Stored Procedure using the Entity Framework and return a dataset, this way the legacy code remains the same but allow you to utilise the Entity Framework for your connection.

Let’s get to work; first, we will create a Database Manager that will receive the Entity Framework DbContext

public class DatabaseManager
 private readonly DbContext _context;

public DatabaseManager(DbContext context)
 _context = context;

Then we need to call a Stored Procedure using the Entity Framework DbContext connection:

new SqlConnection(_context.Database.Connection.ConnectionString)

I won’t go over creating the command with its parameters, as this is assumed you know how this works already.  What I will mention is the SqlDataAdapter that calls the Stored Procedure and returns the DataSet

using (var adapter = new SqlDataAdapter(command))

All you have to do now is return the dataSet and you are done.  It is that easy, here is the full code base:  DataSetEF

Choosing the Boring Solution

When solving a complex problem, it’s sometimes very tempting to choose an excellent solution. Not only will this solve the problem – but it will also impress your teammates and bring you everlasting glory.

An even better solution, however, would probably be a boring one. One that is easy to understand, even for your junior colleagues. One that is well-known for your platform and language. One that is entirely not extraordinary.

Using such a tedious solution means that you’re using simple vocabulary, which significantly increases the chances of everybody understanding you. This will make it a lot easier for everybody to follow along – including new team members (and yourself, a couple of weeks after you’ve written that code).

Aiming for Simplicity

Acronyms FTW! Car enthusiasts might now think of BMW, but software developers should think of KISS and YAGNI.

“Keep it simple, stupid” should remind us that the simple solution will always beat the overengineered solution. The reasons why this is true are almost endless. And they might be easier to understand when looking at the opposite: complex code.

  • Complex code is a perfect hiding place for mistakes.
  • Complex code is hard to understand, for your coworkers and yourself.
  • Complex code cannot easily be extended.
  • Complex code cannot be reused. And, last but certainly not least, writing complex code will cause your teammates to brand you as an outlaw.When a more straightforward solution seems sufficient right now, you should always aim for it.

“Writing complex code will cause your teammates to brand you as an outlaw.”

When you realise that your solution isn’t essential at all, you should drop it. This is what YAGNI is about – “You ain’t gonna need it” reminds us to stay modest when planning the volume and scope of our implementations. Will users need this feature? Will they need this option within a feature? These questions, of course, will translate to our code: will we need that class/ module/routine?

Stack-Overflow-Driven Development

Thank God for I seriously can’t imagine my (programming) life without it. And with it being one of the most visited sites on the web, I guess I’m not alone.

There’s a long friendship between Stack Overflow and me. It helped me countless times when I was stuck on a problem. It gave me an idea of how other people had approached the same problem. Sometimes these other people helped me solve my problem. Sometimes they gave me a hint for a possible solution. And sometimes reading their issues at least let me know that I wasn’t alone with a miserable bug…

After hours or even days of searching and trying different things, your shields are down. You are crawling through your code on all fours like a man who’s lost in the desert. But all of a sudden your search is fruitful! Eureka! Searching Stack Overflow has finally yielded a piece of code that works!

That’s when you have to watch out and resist the temptation to take code that works for the system that’s good. What you’ve found on Stack Overflow is – in all but the rarest cases – not a solution but rather a clue. It can certainly make for a great pointer, but it was not written with your exact problem/ requirements/ constraints/codebase/application in mind. And sometimes, it might just be a dirty hack.

Embrace Stack Overflow as a good source of guidance for specific problems. But also take the time to thoroughly and honestly evaluate if you’ve found a real, reliable solution.

Design Patterns

Sometimes, a solution is so beautiful, and you wish you had the right problem to apply it to. But unfortunately, issues come first. As impressive as your new screwdriver may be (imagine a handle made of gold, with your initials engraved, of course, if the problem at hand is to knock in a nail, it makes for only a less than perfect solution.

Now, after teaching you all I know about manual craft, let’s return to software development – and consider “design patterns” as your toolbox. Every design pattern you know (and understand) is an instrument in your toolbox. It’s certainly great to have many of them!

The problems start, however, as soon as you let the patterns dictate your coding. They should be there to support you, to propose a proven solution – for the right problem! Programming paradigms should be used where they fit and not be enforced. Your components should be designed with your application’s requirements in mind – not with a beautiful design pattern.

In cases where you’ve indeed found a helpful pattern for your current problem, there’s only one more thing: be sure to understand the pattern and its consequences on your coding.