I was speaking with some co-workers earlier this week, and someone mentioned you own all variations of your Gmail email address that contain different period placements. This means that if you register joe.blow@gmail.com, you also own joeblow@gmail.com, j.o.e.blow@gmail.com, and joe.bl.ow@gmail.com. You can verify this two ways. First, you can log in to Gmail using any of these variations; it will still take you to the same inbox you’re used to seeing. Second, you can send an email to any of these variations, and you’ll receive it just like you’d expect.

The usefulness of this is questionable, but I still thought it was fun and interesting to know. And maybe you wished you could make your gmail more specific (for example, nycanal@gmail.com could use ny.canal@gmail just so there’s no confusion).

## Unit Testing: Hello, World!

The “Hello, World!” of unit tests typically involves a function that accepts inputs and provides an expected output. Consider the following Calculator class:

```public class Calculator
{
public static int Add(int x, int y)
{
return x + y;
}
public static int Divide(int dividend, int divisor)
{
return dividend / divisor;
}
}
```

Writing unit tests for the Add method is simple and straightforward. We can declare our inputs, come up with the expected output, execute the function and verify the result.

```[TestMethod]
{
int x = 1;
int y = 2;
int expected = 3;
int actual = Calculator.Add(x, y);
Assert.AreEqual(expected, actual);
}
```

The Add method is so simple that there isn’t much more you can do with it, so let’s take a look a the Divide method. Similarly to the Add method, we can write a simple unit test to verify our core behavior.

```[TestMethod]
public void DivideTest()
{
int dividend = 10;
int divisor = 2;
int expected = 5;
int actual = Calculator.Divide(dividend, divisor);
Assert.AreEqual(expected, actual);
}
```

Now that we have that out of the way, let’s deal with an exception case: division by zero. Before we can test or code, we must decide what we want our application to do in this scenario. I have decided that application should simply throw the default divide-by-zero exception, so let’s write a test for it to help ensure that this functionality isn’t lost with future changes.

```[TestMethod]
[ExpectedException(typeof(System.DivideByZeroException))]
public void DivideTest_DivisionByZero()
{
int dividend = 10;
int divisor = 0;
int actual = Calculator.Divide(dividend, divisor);
}
```

By decorating the test method with the ExpectedException attribute, the test will fail if the exception is not thrown.

You can see that writing unit tests for these something-in-something-out functions can be very easy. Try to test as many different scenarios as you can come up with. Some common situations to consider are minimums, maximums, default values, and nulls. Write skeleton tests up-front to help you remember relevant scenarios to be handled by your code.

## Unit Testing Guidelines

There always seems to be a lot of discussion regarding the whens and hows of unit testing. These can be challening topics when you’re getting started with unit testing, and I wanted to document some of the rules, guidelines, and lessons-learned that I apply when writing my own tests.

### Keep it simple.

If it seems like testing a piece of functionality is really hard, there’s probably an easier way. One of the keys to writing good unit tests is having testable code. (Duh, right?) Well, one of the best skills that you can have is the ability to take a block of untestable code and transform it into a well-tested masterpiece. Doing this isn’t as hard as it may seem. The secret is identifying the natural seams in the code and extracting them into testable and/or mockable objects and functions. Divide and conquer!

### It’s not all or nothing.

Sometimes when you’re working with legacy code that doesn’t have unit tests, it’s easy to follow suit and not write tests yourself. Just because tests don’t exist for existing code doesn’t mean that you can’t write tests for your changes, though. If you write a test to confirm a change that you make, you’re future-proofing your change. If somebody comes along later and messes up your change, your test will fail even if it’s the only test in the whole world.

It’s been said before, but it’s true: one test is better than no tests. It’s also unlikely that you’ll ever go back and unit test everything in a project hat wasn’t tested previously, so just start already!

### Test what makes sense.

Code coverage is great, and 100% is a great goal to strive for, but I don’t think it’s realistic in most situations. If you’re writing a test where you’re replicating the entire contents of the function you’re testing to create expectations and asserts of the test, it may be a bad test for two reasons. First, you don’t feel good about the test you’ve written. Second, you’ve made your code more rigid because changing the actual function will require you to make the same change again in the unit test. Blech!

Instead, strive to write tests that you believe are meaningful and useful. A good example of this would be translating a person object. It may not be useful to test that ObjectA.LastName equals ObjectB.LastName and ObjectA.FirstName equals ObjectB.FirstName, but it may be worthwhile to write a test that verifies that ObjectA.SsnAsInteger populates correctly into ObjectB.SsnFormattedString. It’s hard to come up with a good, brief example of this, but what I’m trying to get at is that you shouldn’t spend hours and hours working on tests that you yourself see no value in. Grab a peer and look at it together. Maybe they can help you see the value or come up with a better way to test. Or maybe you’ll both agree that the code in question simply doesn’t need to be tested.

### Don’t write random value generators and object populators.

I’ve gone through this phase, and I’ve seen others go through it. I want to save you, though. Don’t do this. I know that it seems like a good idea. This should work for any string of any length, so I’ll just write a function to populate my object with a random string of random length! The problem is that when this test fails randomly 1 out of 50 test runs, you may not be able to re-create the situation. I believe it’s better to write a specific test for your specific situation. If you need to test multiple scenarios, write multiples tests.

One of my least favorite unit testing experiences comes from working with a project whose unit tests were written by a code generator that randomly populated complex source business objects, manipulated them, and then used comparison-via-reflection to verify correctness. The problem is that these tests were nearly impossible to maintain and troubleshoot when they failed.

## Regular expressions with ASCII values

I was writing some unit tests today to test a format out. The format that I was testing used ASCII characters for FS, GS, RS, and US.

A sample format might look like this:

```1.03:1[us]00[rs]2[us]01[rs]10[us]01[gs]
```

So, in my test, I wanted to verify that my string started with “1.03:” and ended with “[rs]10[us]someValue[gs]” However, I didn’t know how to check for those pesky ASCII characters, though! After a bit of Googling, I found the answer, and it’s actually pretty simple. You can use an escaped u in a regular expression to specify a four-digit Unicode character. After a quick ASCII-to-Unicode lookup (here) I came up with the perfect regular expression:

```Regex.IsMatch(contents, @"1.03:.*?\u001E10\u001F0*" + expected + @"\u001D")
```

Thanks for being so awesome, regular expressions!

## WPF Combo Box validation

I’ve been working on a small WPF project that requires some business rule validation. I thought this would be relatively simple but proved to be slightly more complicated than expected. At the end of the day, I found two relatively simple ways to perform the validation.

The first is to simply bind ComboBox.Selected item to a property and do the validation in the set block.

```    private MyDataObject _someData;
public MyDataObject SomeData
{
get
{
return _ someData;
}
set
{
_ someData = value;
if (value == null || string.IsNullOrEmpty(value.MyProperty))
throw new ApplicationException("SomeData is required");
}
}
```

Then, in the XAML, you just need to hook it up to treat exceptions as validation errors.

```    <ComboBox.SelectedItem>
<Binding Path="SomeData" ElementName="Window">
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
</ComboBox.SelectedItem>
```

The second method gives more flexibility but requires the creation of a custom ValidationRule class.

```    public class MyCustomValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value is MyDataObject)
{
var myDataObj = (MyDataObject)value;
return new ValidationResult(true, null);
}

return new ValidationResult(false, "Invalid selection!");
}
}
```

And then you hook up the validation rules to use the new custom class.

```    <ComboBox.SelectedItem>
<Binding Path="SomeData" ElementName="Window">
<Binding.ValidationRules>
<local:PersonValidation />
</Binding.ValidationRules>
</Binding>
</ComboBox.SelectedItem>
```

(Note that the “local” prefix requires an additional namespace at the top of your XAML file, xmlns:local=”clr-namespace:MyNamespace”)

One last tip that threw me off for a bit is that I was missing x:Name=”Window” in my Window tag at the top of my XAML; this caused the ComboBox’s SelectedItem to not bind properly and the validation rules consequently didn’t work.

## Mass find & replace in TFS using Powershell

One of the problems that seems to come up semi-frequently is, “We need to update all x files to have y!” The old solution to this was manually going through all x files and updating them to have y. However, this can be accomplished quickly and easily using Powershell.
Here’s an example. We had a number of VB6 project files whose BCO paths were set to use a mapped “O:” drive that no longer existed. Instead, these projects should be using a relative path. There were 100 or so of these projects that needed to be updated, and I was able to check them out from TFS and make the change to all of them in a matter of seconds by using the following script (sorry for the formatting!):

```Get-ChildItem "C:\Code" -recurse |
Where-Object {\$_.Extension -eq ".vbp"} |
ForEach-Object {Write-Host "  "\$_.FullName; &amp; "C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\TF.exe" checkout "\$(\$_.FullName)" | Out-Null; (Get-Content \$_.FullName) |
ForEach-Object {\$_ -replace "O:\\.*?\\BCO\\", "..\..\BCO\"} |
Set-Content \$_.FullName -Force}
```

And another example. I needed to update the revision numbers of all projects in a sub-directory to be automatic. Here’s the same script modified to accomplish that. I’ve made this more re-usable by accepting parameter values from the command line.

```# example usage: .\UpdateVersion.ps1 -path "C:\Code" -build "1.0.0.*"

# get param values
param(
[int] \$build,
[string] \$path,
[string] \$root)

if (\$build -eq \$null)
{
\$build = Read-Host "Build number:"
}
if (\$path -eq \$null)
{
\$path = ".\"
}

# \$root will be trimmed from start of directory string
# when checking for exceptions
if (\$root -eq \$null)
{
\$root = "c:\"
}

# \$exceptionDirs will not have their versions updated
\$exceptionDirs = "test"

Write-Host "Updated the following files:"

# recursively search \$path for AssemblyInfo.cs
# if found, update version number &amp; save
Get-ChildItem \$path -recurse |
Where-Object {\$_.Name -eq "AssemblyInfo.cs"} |
Where-Object {\$exceptionDirs -notcontains \$_.Directory.ToString().ToUpper().TrimStart(\$root.ToUpper())} |
ForEach-Object {Write-Host "  "\$_.FullName; &amp; "C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\TF.exe" checkout "\$(\$_.FullName)"; (Get-Content \$_.FullName) |
ForEach-Object {\$_ -replace "(?(\d+\.){3})\d+", "`\${ver}\$build"} |
Set-Content \$_.FullName -Force}
```

❤ Powershell!

## Supported Project References in WiX

This was really helpful to me, and something that I never really knew about today… A complete list of preprocessor variables that can be used with Wix!

http://blogs.msdn.com/b/jrock/archive/2008/01/29/complete-list-of-candle-preprocessor-variables.aspx

## VS2010 Extensions

I just upgraded to VS2010 at work this week, and I feel like a kid in a candy store with all of the extensions available online. (http://visualstudiogallery.msdn.microsoft.com/en-us) Here are some of the ones that I’ve already fallen in love with…

Team Foundation Server Power Tools April 2010:
TFPT.exe; PowerShell Cmdlets for VSTS; Windows Shell Extensions
http://visualstudiogallery.msdn.microsoft.com/en-us/3e8c9b68-6e39-4577-b9b7-78489b5cb1da

PowerCommands for Visual Studio 2010:
Copy/paste classes & references; email code snippets; open containing folder from Solution Explorer

Collapse Selection in Solution Explorer:
Recursively collapse the selected node in Solution Explorer
http://visualstudiogallery.msdn.microsoft.com/en-us/cb0ec47d-05a4-40a7-ba39-9a2da6492f1c

Search Work Items for TFS 2010:
Search TFS work items from a menu bar textbox
http://visualstudiogallery.msdn.microsoft.com/en-us/3f31bfff-5ecb-4e05-8356-04815851b8e7

## SFTP Access with SharpSSH

A project that I was working on required the use of SFTP to transfer some files. I was surprised to find that there seemed to be no support for this anywhere in the .net Framework. After Googling around for a bit, I found a nice open source project called SharpSSH.

SharpSSH was surprisingly easy to use and worked great! I was able to SFTP a file in 4 lines of code:

```SshTransferProtocolBase sshCp = new Sftp("127.0.0.1", "ftp", "ftp123");
sshCp.Connect();
sshCp.Put("c:\\testdoc.txt", "test123.txt");
sshCp.Close();
```

This was exactly what I was looking for: a simple, lightweight SFTP library. I added some exception handling and logging, removed my hard-coded values with user-defined settings, and called it a day!

Resources:
SharpSSH
http://sourceforge.net/projects/sharpssh/

freeSSHd (a free SFTP server)
http://www.freesshd.com/