Aug 242016
 

This post is one of those brief ones I put out here as a reminder to myself and as a potential help to anyone else experiencing similar grief.

Recently, out of nowhere, I started getting the error “No valid combination of account information found” when executing a parse on a connection string for an Azure Storage Account.  Specifically, the failure occurred on

CloudStorageAccount.Parse(storageSetting);

Come to find out, in the midst of a huge merge of code, someone had inadvertently changed the connection string in the Web.config file of my ASP.NET site.  The string changed from

“DefaultEndpointsProtocol=https;AccountName=**************;AccountKey=*********

to

“DefaultEndpointsProtocol=https;Accountname=**************;AccountKey=*********

With this library, case matters and “AccountName” was changed to “Accountname”, which caused the error.

So beware, Microsoft.WindowsAzure.Storage is picky when it comes to casing.

Jan 052016
 

CODE KeyboardAs I type this, the sweet, sweet clicky sound of my new CODE Keyboard fills the air and my fingers, typing speed, and general demeanor couldn’t be happier. I have been debating purchasing a mechanical keyboard for a while now and decided to treat myself to a nice keyboard for Christmas.

 

My prior keyboard was a Logitech KB350, which is a wireless, rubber-dome keyboard. I used it for at least five years and it served me well. However, I had been hearing all of the hype about mechanical keyboards for quite some time. A couple friends had gotten them for gaming, but swore by them for general typing for coding as well. After some research, I discovered that rubber-dome keyboards require the key to travel the full distance to the PCB (printed circuit board) to make contact with the circuit on the board. Supposedly, this causes more fatigue and causes more typing errors due to the longer key travel.

Logitech KB350 and CODE Keyboard

Logitech KB350 and CODE Keyboard

I have been using this keyboard for a day, so I can’t speak to it’s magical powers of productivity increases, but I can say that it is very solidly built. Here are my first impressions:

  1. WASD Keyboard takes pride in their devices.  You need to go check out WASD Keyboards.  They make custom mechanical keyboards that are solid.  This keyboard is heavy.  The possibilities of the keyboards that they can make are endless.  You can go off-script and make any custom mechanical keyboard you want, with different key colors for every key if you want.  You can even have them print images across your keys.  Further, you can specify which MX switch key color that you want on your keyboard.
  2. Cherry MX mechanical keys are cool.  The most important customization that you can make with a mechanical keyboard is the type of switch that is used for each key.  After a lot of consideration, I went with the Cherry MX blue keys.  I thought that I would like the travel and satisfying click of the keys and so far my assumption was correct.  Some folks like the harder-to-push green, or the no-click browns.  To me, these blues are perfect, but you can choose from blue, green, brown, or clear to suit your particular typing style.
  3. I really like the LED backlighting.  You can choose between 6 different levels of brightness.  It’s just a cool, clean look that is nice in a dark office.  You should know that (at the time of typing this) WASD doesn’t have a backlighting option for their other keyboards (other than the CODE).  So if you want, you can print your cat’s picture across your keys.  You just can’t have the keys backlit.
  4. The CODE Keyboard is a collaboration between WASD Keyboards and Jeff Attwood of the popular Coding Horror blog.  This keyboard looks and feels like a clean, professional keyboard. There aren’t any crazy colors to distract.  Just a solid keyboard to get code done.
  5. The multimedia controls on the keys are understated, but very convenient.  On my old KB350, the multimedia controls are on top of the keyboard.  They stand out very prominently and add about 2 inches to the top of the keyboard.  On the CODE, the multimedia controls are in the Home cluster as function keys.  You can control them with one hand very easily.  The nice thing about having the keys as function keys is that you don’t have a lot of other clutter making the keyboard larger.  This isn’t a big deal to me, but I nice the nice, sleek form factor of the CODE.
  6. CODE is configurable for a Windows or Mac and you can tweak the function of the Caps Lock and OS keys via the dip switch on the back.

Back of CODE Keyboard

Will the CODE Keyboard make my C# code more efficient?  Will it make my Azure Powershell scripts more readable?  Will it make my writing more interesting?  Probably not.  However, in the journey from my head to the screen, my fingers and ears will experience a miniscule bit of tactile and audible happiness, which, when multiplied by each click will make me happier, so I think the CODE was a good purchase.

Dec 132015
 

I recently set up a project on Visual Studio Online.  After pushing the source code to a VSO-hosted Git repository, I went to set up the VSO-hosted CI builder.  Setting it up was a breeze.  Microsoft has really made this a great product.

The only problem that I found was that when the build ran, the project build failed because MSBuild couldn’t find a dll that I had referenced.

This all led to a StackOverflow Q&A post – one of those where you post a question and answer it at the same time.  Check it out here.

Jul 172015
 

The Problem

I recently created a new ASP.NET Web Application project in Visual Studio. Upon launching it for debug in the Google Chrome browser, I was greeted with an SSL Connection Error screen from Chrome. I also noticed that the url was changed from “http:” to “https:” (https://localhost:49500/).

I looked at my project settings in Visual Studio under the Web tab and found that my Project Url was set to http://localhost:49500/, which indicated to me that the project should have been launched in as http, not https.

Project Settings with Http

There was no launching as http, and the fact that my browser was demanding that the site be secured was causing me to not be able to load and debug my project.

The Cause

I didn’t want my project launched as https and couldn’t understand why this was happening.  After consulting with an associate (thanks Tim!) I discovered that this problem was caused by a custom header setting in the Web.config file of an old project that I had debugged, coupled with the HTTP Strict Transport Security cache in my Chrome browser.

I had debugged another, existing ASP.NET project in the recent past that had this customHeader line in its Web.config file:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Strict-Transport-Security" value="max-age=16070400; includeSubDomains" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

The “Strict-Transport-Security” customHeader line causes the server (in this case http://localhost) to add a line in the response header that a HSTS-capable browser (e.g. Google Chrome) reads.  The browser takes this as a sign that any further communication (within the given time) with this server should be done via HTTPS only.  Per the Chromium.org HSTS page:

When the browser sees this, it will remember, for the given number of seconds, that the current domain should only be contacted over HTTPS. In the future, if the user types http:// or omits the scheme, HTTPS is the default.

Since the project that I debugged had this header in its Web.config, I had told all HSTS-compatible browsers that I had used in debugging to always require http://localhost to default to https.  This was borne out by looking at the HSTS cache in chrome by going to this url in the Google Chrome browser:  chrome://net-internals/#hsts and querying for localhost:

hsts cache in Chrome

The query shows “localhost” as being in the list of domains in the HSTS set.

The Solution

After finding that I had cached the domain “localhost” as requiring HTTPS, the solution was as simple as deleting the domain from my cache.  In the Google Chrome browser, I navigated to chrome://net-internals/#hsts, typed “localhost” into the Delete domain text field, and hit Delete.  After doing so, I queried for “localhost” again and received a “Not found”

Localhost not found

Then, I re-launched my project from Visual Studio into Chrome and found that my ability to launch as HTTP had returned.

http load

Jul 132015
 
Knoxville, Tennessee

Knoxville, Tennessee

I just got back from a great tech conference in Knoxville, Tennessee called “CodeStock”.  It was a 2 day event where software developers, technologists, and entrepreneurs gathered to listen, discuss, and share information about the latest in software development and software related technologies.

The first day was a treat as I got to hear Scott Hanselman speak for a second time.  For those of you who might not know, Scott is a developer/technologist/speaker/evangelist for Microsoft.  His main focus is on the web.  His talk was hilarious (as usual) as it was full of humor that only a room of 900 software nerds would understand.  He discussed how the web has grown, how javascript is the assembly language of the web, and distributed computing.  I read his blog over at hanselman.com, his podcasts at hanselminutes.com, and some of his Azure Friday talks.  Suffice it to say, I’m a fanboy and I would recommend his work to any of you, especially those of you who work in the .NET/ASP.NET stack.

Scott Hanselman at CodeStock 2015

Scott Hanselman at CodeStock 2015

There were many great talks, but the hottest topics this year were DDD, functional programming, and AngularJS.  The amount of interest that was shown in the DDD and AngularJS sessions was as I would have expected, but the functional programming talks were surprisingly well attended.  The ones that I went to were filled to capacity+.  As for me, I went into the functional talks a bit skeptical.  I thought, functional is interesting, but is F# really production worthy?  Is it worth the OOP to FP paradigm shift?  Is F# syntactically rich enough to provide the functionality that I need to make products work and work well?  Aaron Erickson provided some very compelling arguments in favor of a shift or, at minimum, consideration of F#.  When Aaron asked, “How much code do you write that does a cool algorithm compared to code you wrote to make the framework work?”, he had me.  If there is a less verbose way to get things done, it is worth a look.  If it isn’t worth investigation, perhaps we should just give up and revert to COBOL (as I shudder at the very thought).

“How much code do you write that does a cool algorithm compared to code you wrote to make the framework work?”- Aaron Erickson

F# is interesting and I hope to post more on it later.  The amount of attendees in the functional programming sessions seemed to indicate that functional is on its way back in some form or fashion.

Along with the sessions on functional programming, I was able to go to some really great talks on C# 6, vNext, and JWT Authentication.  There was also a talk by David Mohundro entitled “A Brief History of .NET Threading”.   This was by far my favorite talk as it provided background on the evolution of threading in the .NET Framework.  By explaining where we came from, it helped me to appreciate the simple beauty of async/await and how to better apply this pattern.  If you have any interest in threading in .NET, I would recommend checking out his post on the topic here.

I would definitely recommend going to CodeStock in the future, particularly if you live in the region.  There were 900 attendees this year, which gives it some credibility on volume alone.  The organizers did a good job in selecting the venue and it was definitely smoothly run.  One word to the wise, though.  When you go, make sure to check out the presenters online before making your choice on sessions.  Some presenters will obviously be more well-versed in their topics based on their blogs, tweets, etc.  Make sure to make this part of your session-choosing criteria.

Thanks to the organizers!  I hope to attend again.

May 112015
 

hacktn7

A couple weekends ago, I had a great time at Hack Tennessee 7.  For the uninitiated, a hackathon is an event where developers from all over the area gather to work on projects for fun for a weekend.  It was a great time of meeting colleagues, checking out some cool tech, and (as an added bonus) introducing my 14 year-old son to the world of software development.  Since he is an avid gamer, he has been curious as to what it would take to build a game. Hack Tennessee seemed like the perfect venue to show him what the industry is like and what it takes to build a (exceedingly) simple game.

breakintocodeI searched for a game project that we could do quickly and to which he could add his own touches.  I found the Microsoft Imagine Cup’s “Break Into Code” contest and it seemed to fit the bill nicely.  For the challenge, students use a simple block language to build up a brick breaker game.  After getting the initial game together, students are free to extend the game as much as they want.

blockbreaker

The first version of the game looked like Microsoft’s sample image on the left

The first step was for my son to start with the stock project and build the block breaker game.  It was really simple and very spartan in terms of “splash”.

After he got the first version finished, we began working on what he wanted to make his game look like.  We discussed the basic gameplay, the mechanics of how characters in the game would work, and dreamed up some new levels.

IMG_4118

To make the experience more true to the whole agile development experience, we drew up what our game “MVP” (minimal viable product) would be, just as if we were a game development company trying to get out a first version of a game.  All of the cool ideas of multiple levels, flying dragons, and power-ups had to be jettisoned so that we could focus solely on getting out that first version.

wizardhero

The finished version of “Wizard Hero”

We had a great time finding image assets and tweaking what was a block breaker game to a game where a goblin is firing arrows down at a wizard while the wizard shoots fireballs to break through the wall to finally defeat the goblin.  He learned about coding and even that things get frustrating when your framework doesn’t provide some of the things you need (we had to get a little creative and count frames instead of milliseconds for timing).  In the end, he wound up with a playable game that met his MVP requirements.  It was a great project and I think he came away with a greater understanding of the culture and what it takes to create a game.

IMG_4095

As for me, it was my first time to Hack Tennessee.  Having just moved to the area, it was a great opportunity to meet other developers in the community and to see just how much talent is here.  Nashville is an awesome town for tech and I would highly recommend attending a Hack Tennessee event to anyone interested in software or electronics tinkering.

Jan 262015
 

Reticle with ComponentModelCache Folder

Several times in the past few months, I have experienced an error loading a solution in Visual Studio 2013 that goes something like:

“The ‘<packagename>’ package did not load correctly.”

Every time that I have had this error, the solution has been to go to the “C:\Users\<user>\AppData\Local\Microsoft\VisualStudio\12.0 folder and delete the ComponentModelCache folder.

I suspect that the contents of the cache folder get corrupted and/or out of sync when the OS shuts down unexpectedly while Visual Studio 2013 is up.  It’s annoying, but deleting the ComponentModelCache forces Visual Studio to load without the cache and fixes the problem every time.

Jan 112015
 
The Void - That's where your test results have gone

The Void – That’s where your test results have gone

Recently, I have been writing integration tests that cover async functions. During this work, I have encountered a quirky pain (of my own making) that I wanted to document. The purpose of the documentation is two-fold. First, the shame and self-deprecation of calling myself out will help to reinforce this point in my mind, and second, you might be able to avoid this goof up yourself.

The spoiler and 5 second take-away: When writing any function that uses async in C#, you must NEVER return void. The async keyword means that you intend to return something upon which the caller will await. That’s it. Lesson over.

If you want to know how weird things can get if you do this wrong in integration testing, read on…

So, I wrote a function that asynchronously returns a Task of string. Something like this:

public class Foo
{
    public async Task GetAStringFromIO()
    {
        // This is, presumably, a task that will take some time, so
        // we're going to await it.
        return await GetTheString();
    }

    private static Task GetTheString()
    {
        return Task.Run(() =>
        {
            // Simulate some really slow IO
            Thread.Sleep(1000);
            return "A String";
        });
    }
}

…and to test that, I wrote something along these lines:

[TestClass]
public class MyTests
{
    [TestMethod]
    public async void CanGetTheStringFromIO()
    {
        var foo = new Foo();
        string myString = null;
        myString = await foo.GetAStringFromIO();
        Assert.IsNotNull(myString);
    }
}

To my annoyance and great dismay, the test didn’t seem to run and my breakpoint wasn’t hit. The test wasn’t shown in the TestExplorer window. No bueno.
TestExplorer When Running Function returning void
The problem here, quite obviously, is that the async test function is returning void. The test runner expects something back on which it can await, but I am giving it nothing. This causes the test runner to exit. I wish it were more obvious, but there is no success, error, or inconclusive result – just a Test Explorer window without my test function.

After correcting the test by simply changing the return type to Task, life is good again. The Test Explorer shows my test and I can set breakpoints which actually pause execution of the test:
TestExplorerWithTask

Again, when writing any function that uses async in C#, you must NEVER return void. The async keyword means that you intend to return something upon which the caller will await. It’s just that easy.

If you are interested in a deep dive on this topic, I would recommend that you check out this article by Stephen Cleary: http://msdn.microsoft.com/en-us/magazine/dn818493.aspx. He has published books, articles, and blog posts surrounding all things C# asynchronous programming.

Dec 082014
 

In my last post, I showed a way to generate unit tests for existing code where a pattern exists using .NET’s System.Reflection library. The post showed an executable that would take the paths to a dll and an output file as input parameters where this executable would then tear through the assembly, looking for string properties for which I wanted tests. The exe would generate stub code to ensure that I wouldn’t miss any of the string properties.

I was discussing this with a colleague who suggested that I consider generating a T4 text template within Visual Studio to do this same work.  I had never used the templates before, but have found them to be amazingly simple, yet very useful tools to have in the arsenal.  I was able to take the code from the exe that I described in the last post, incorporate it into a template, and have it generate the same test code in about 5 minutes.

The benefit to using T4 text templates is that they are meta-code that reside within your Visual Studio project.  The cool thing is that the meta code regenerates the output file from the template during builds and after edits to the template.  Because of this close relationship with code in their project, these templates can be used to auto-generate output files that respond to changes in the code.  This can be particularly handy if you are creating schema files, config files, tests, or other forms of output that need to be kept fresh as your code changes.

I took the project that I used in the last post and added the T4 text template.  To do this, I simply added a new Text Template:

AddNewTextTemplate

After adding the template, you can see the template in the Solution Explorer window.  You can also see the generated code file as a child of the text template, as shown here:

TemplateInSolutionExplorer

When you first generate a text template, it puts header information in the .tt file for you that you have to edit.  You’ll notice that code that is to be evaluated is placed inside of <# #> bracketing.  The text within these delimiters will not be shown in the output file, but will contain the code needed to output something useful to the file.

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".txt" #>

You can see that the default output extension is .txt. I changed that to .cs. You can also see that the template is generated with assembly and import directives. Assembly is like adding a reference to a project and import is analogous to a using directive in a C# file. Since I already knew my dependencies from my prior project, I modified this information to look like this:

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System"#>
<#@ assembly name="System.Xml"#>
<#@ assembly name="System.Xml.Linq"#>
<#@ import namespace="System" #>
<#@ import namespace="System.Xml.Linq"#>
<#@ import namespace="System.Reflection" #>

This block is code that the template will use when run. It is the list of references (assembly tag) and usings (import tag) that the code I will add later will use.

Next I will add the using statement block that I want my output file to have. This text will not be inside the <# #> delimiters because I actually want to see this code in my output file. Note that this text is not the usings that the template will need to run. Since it is outside of the delimiters, it is seen as simple text to be output:

using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

Next, since I was writing a unit test file generator, the namespace and class declaration needed to be added. These were in funky functions in executable in my prior post. These functions added “header” and “footer” information, for lack of better terminology. This was awkward, but here it is quite elegant because I am actually writing this one-time-output text as it will be seen in the output.

namespace MyProject.Tests
{
    [TestClass]
    public class MyTests
    {
    }
}

After this, I extracted the code from the executable I built in the prior post and put it into the template. You’ll notice the <#= stuff #> where I wanted to emit text generated from code into the output file. This is the final text template file:

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System"#>
<#@ assembly name="System.Xml"#>
<#@ assembly name="System.Xml.Linq"#>
<#@ import namespace="System" #>
<#@ import namespace="System.Xml.Linq"#>
<#@ import namespace="System.Reflection" #>
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MyProject.Tests
{
	[TestClass]
	public class MyTests
	{
		<#
		var a = Assembly.LoadFrom(@"c:\temp\ProjectToTest\ProjectToTest.dll");
        foreach (var type in a.GetTypes())
        {
            // get all public static properties of MyClass type
            var propertyInfos = type.GetProperties();

            // sort properties by name
            Array.Sort(propertyInfos,
                delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
                {
                    return propertyInfo1.Name.CompareTo(propertyInfo2.Name);
                });

            // write property names
            foreach (var propertyInfo in propertyInfos)
            {
                if (propertyInfo.PropertyType == typeof(string))
				{

		#>
[TestMethod]
		public void MyTests_<#=  type.Name.Replace("`", "") #>_<#= propertyInfo.Name #>()
		{
			// Put in code here for your test
		}
		<#
				}
            }
        } 
		#>
	}
}

If you’ll notice, the “[TestMethod]” indention looks a little nutty in the text template file. I found that I had to play a little to get the indention right. Also, you can see that I have hard-coded the path to the dll that I wanted to reflect. This could be made better via a project variable somehow.

After the final updates to the template file, Visual Studio automatically generated this output when I saved the template:

using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MyProject.Tests
{
	[TestClass]
	public class MyTests
	{
		[TestMethod]
		public void MyTests_Class1_String1()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class1_String2()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class1_String3()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class1_String4()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class1_String5()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class1_String6()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class2_String1()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class2_String2()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class2_String3()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class2_String4()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class2_String5()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class2_String6()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class3_String1()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class3_String2()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class3_String3()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class3_String4()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class3_String5()
		{
			// Put in code here for your test
		}
		[TestMethod]
		public void MyTests_Class3_String6()
		{
			// Put in code here for your test
		}
			}
}

If I had some severely repetitious checks to make, I could make this file regenerate and change with every change to my code. This is interesting for unit testing, but really has cool applications in other areas, like schema generation, documentation, etc.

Much thanks to my colleague for pointing T4 text templates out to me! This is another cool tool to keep handy.

Nov 202014
 

There are times when you need to write unit tests and it is important to ensure that you get full code coverage.  That first sentence alone will tip you off to the fact that this is not a TDD scenario, but rather a situation where you need to create test cases for pre-existing code.  It is easy to overlook methods or properties when backfilling tests, so it would be nice to have a tool to help in these situations.  Thankfully, you can use .NET reflection to trawl through your assemblies, writing stub code, looking for the properties and/or methods that you have interest in and making sure that you don’t overlook important items.

I have written a quick example to illustrate how useful reflection can be in auto-generating tests and test stubs. The point here is not that I have written the be-all-end-all test generator, but to show that you can quickly cover some ground in brownfield testing with the proper application of the System.Reflection library.

In this quick example, I have 3 classes that each have some string properties:

namespace AssemblyToTest
{
    public class Class1
    {

        public string String1 { get; set; }
        public string String2 { get; set; }
        public string String3 { get; set; }
        public string String4 { get; set; }
        public string String5 { get; set; }
        public string String6 { get; set; }

    }
    
    public class Class2
    {
        public string String1 { get; set; }
        public string String2 { get; set; }
        public string String3 { get; set; }
        public string String4 { get; set; }
        public string String5 { get; set; }
        public string String6 { get; set; }
    }

    public class Class3
    {
        public string String1 { get; set; }
        public string String2 { get; set; }
        public string String3 { get; set; }
        public string String4 { get; set; }
        public string String5 { get; set; }
        public string String6 { get; set; }
    }
}

Let’s say that you’re interested in looking for all public string properties in classes in your assembly to ensure that you have proper string validation.  In TDD, you would have already written the tests before writing the code, so problem solved!  However, in many cases, you may find yourself retrofitting old code with new tests.  In this example, you can use reflection to load the assembly in which you are interested, loop through all of the types in the assembly, and then loop through the properties of each type.  Armed with this information, you can then use a writer to generate a unit test code file, complete with stubs.  You could even generate some of the test code, if you have enough domain information.

Check out this simple program for generating stub tests:

using System;
using System.IO;
using System.Linq;
using System.Reflection;  // reflection namespace

namespace UnitTestGenerator
{
    /// <summary>
    /// This program returns/generates a list of all properties for all classes in the given assembly that are of type string.  
    /// This program borrows from code found at the following sites:
    /// http://www.csharp-examples.net/reflection-property-names/
    /// http://stackoverflow.com/questions/1315665/c-list-all-classes-in-assembly
    /// http://msdn.microsoft.com/en-us/library/system.reflection.assemblyname(v=vs.110).aspx
    /// http://msdn.microsoft.com/en-us/library/1009fa28(v=vs.110).aspx
    /// http://stackoverflow.com/questions/3723934/using-propertyinfo-to-find-out-the-property-type
    /// </summary>
    /// 
    /// This program generates unit test stubs for all of the string properties of all of the types in an assembly.  It will need to 
    /// be modified to specifically generate the test stubs desired.  
    /// Argument 0 = Path to the assembly
    /// Argument 1 = Path and file name for output file
    class Program
    {
        static void Main(string[] args)
        {
            if (!ValidateArguments(args)){return;}

            using (var sw = File.CreateText(args[1]))
            {
                WriteUsingBlock(sw);
                WriteClassHeader(sw);
              
                var a = Assembly.LoadFrom(args[0]);
                foreach (var type in a.GetTypes())
                {
                    // get all public static properties of MyClass type
                    var propertyInfos = type.GetProperties();

                    // sort properties by name
                    Array.Sort(propertyInfos,
                        delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
                        {
                            return propertyInfo1.Name.CompareTo(propertyInfo2.Name);
                        });

                    // write property names
                    foreach (var propertyInfo in propertyInfos)
                    {
                        if (propertyInfo.PropertyType == typeof(string))
                            WriteTestForProperty(sw, type.Name.Replace("`", ""), propertyInfo.Name);
                    }
                }

                WriteClassFooter(sw);
            }
        }

        private static void WriteUsingBlock(TextWriter sw)
        {
            sw.WriteLine("using System;");
            sw.WriteLine("using System.Linq;");
            sw.WriteLine("using Microsoft.VisualStudio.TestTools.UnitTesting;");
            sw.WriteLine("");
        }

        private static void WriteClassHeader(TextWriter sw)
        {
            sw.WriteLine("namespace MyProject.Tests");
            sw.WriteLine("{");
            sw.WriteLine("    [TestClass]");
            sw.WriteLine("    public class MyTests");
            sw.WriteLine("    {");    
        }

        private static void WriteClassFooter(TextWriter sw)
        {
            sw.WriteLine("    }");
            sw.WriteLine("}");
        }

        private static void WriteTestForProperty(TextWriter sw, string typeName, string propertyName)
        {
            sw.WriteLine("      [TestMethod]");
            sw.WriteLine("      public void MyTests_{0}_{1}()", typeName, propertyName);
            sw.WriteLine("      {");
            sw.WriteLine("          // Put in code here for your test");
            sw.WriteLine("      }");
            sw.WriteLine("");
        }

        private static bool ValidateArguments(string[] args)
        {
            if (!args.Any() || args[0] == "/?" || args[0] == "/h" || args[0] == "/help" || args.Count() != 2)
            {
                Console.WriteLine("GenerateUnitTests takes 2 arguments.  The first is the dll for which tests will be created and the second is the output file.");
                Console.WriteLine("Usage: GenerateUnitTests <dll file path> <output file>");
                return false;
            }

            return true;
        }

    }
}

After running the generator code, you will get stub code that looks like this:

using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MyProject.Tests
{
    [TestClass]
    public class MyTests
    {
      [TestMethod]
      public void MyTests_Class1_String1()
      {
          // Put in code here for your test
      }

      [TestMethod]
      public void MyTests_Class1_String2()
      {
          // Put in code here for your test
      }

      [TestMethod]
      public void MyTests_Class1_String3()
      {
          // Put in code here for your test
      }

      [TestMethod]
      public void MyTests_Class1_String4()
      {
          // Put in code here for your test
      }

      // The generator created many more tests, but I have 
      // omitted them for the sake of brevity.

This is just stub code from the example, but you could expand the generator to fit your testing needs.

TDD is definitely the desired way to generate greenfield code.  The benefits of focus alone prove that out.  However, when you have to retrofit tests for when refactoring or generating tests on existing code, using .NET’s reflection capability will save an enormous amount of “pattern pounding” and it will make sure you are thorough!