Convert a Class Library to a Test Project in Visual Studio

Occasionally, you may run into a Visual Studio Class Library project that contains unit tests. This can be a frustrating scenario because creating a unit test using Visual Studio’s right-click context menus will not allow you to add a test to the project.

This can be remedied quite easily, though, by adding the correct project type guid to the Class Library’s project file. Here are the steps to do this from within Visual Studio:

  1. Right-click the project in Solution Explorer and choose Edit Project File
  2. Add a new child in the <PropertyGroup> node:
    <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
  3. Save your changes and close the file
  4. Right-click the project in Solution Explorer and choose Reload Project

After following those steps, your project will show in the list of output projects in the Create Unit Tests dialog box.

For a list of known project type Guids, check out this site: http://www.mztools.com/articles/2008/mz2008017.aspx

Advertisements

The Magic of Doing One Thing at a Time

Full post here: http://blogs.hbr.org/schwartz/2012/03/the-magic-of-doing-one-thing-a.html

In the past, the focus has always been on doing more at the same time. Multitasking equals increased productivity, right? This article states the opposite, and I agree. I know from personal experience that trying to do 3, 4, 5, or more things at the same results in thrashing that absolutely destroys my productivity. So much time is spent switching between tasks that nothing is ultimately accomplished.

One of the methods that you can use to help keep focused is called The Pomodoro Technique. The idea here is simple: get yourself a 25 minute timer, pick a task, and work on that task uninterrupted for 25 minutes. After each interval, you get a short break to collect yourself and rest, and then you start again. After 4 intervals, take a longer break. Keep a list of your tasks on a blank piece of paper. When interruptions that need your attention occur, add them to your list but do not let them distract you. Getting behind on email? Make it a task! This is a great way to improve your time management. As a bonus, you get a documented log of all that you’ve accomplished in a day!

However you do it, try to focus on a single task at-hand, and I bet your productivity will skyrocket!

Ordered Tests with Rhino Mocks AAA Syntax

Before the AAA syntax was introduced, you would create ordered unit tests by wrapping Expect calls in a using block like so:

var mocks = new MockRepository();
using (mocks.Ordered())
{
    // ...
}

However, AAA syntax does not require you to instantiate a MockRepository, so how can we do ordered tests? This can be accomplished by accessing the implied MockRepository via the GetMockRepository method.

var myMock = MockRepository.GenerateMock<IMyInterface>();
using (myMock.GetMockRepository().Ordered())
{
    // ...
}

Here’s a complete example.

[TestMethod]
public void RunTest()
{
    // Arrange
    var target = new Program();
    var mockModel = MockRepository.GeneratePartialMock<MyModel>();
    target.Model = mockModel;

    using (mockModel.GetMockRepository().Ordered())
    {
        mockModel.Expect(x => x.Populate());
        mockModel.Expect(x => x.Save());
    }

    // Act
    target.Run();

    // Assert
    mockModel.VerifyAllExpectations();
}
// This fails
public void Run()
{
    Model.Save();
    Model.Populate();
}

// This passes
public void Run()
{
    Model.Populate();
    Model.Save();
}

The Almighty Console Application

When I was learning C++ in college, I couldn’t wait to start developing applications that were more than just a console app. It was the twenty-first century, and “real” applications had forms with stuff you could click with a mouse. Nobody wants an app that you can only interact with by typing. And no graphics? No thanks.

It’s funny how time can change you.

I still believe that, generally, people don’t want a console application. And if I’m writing an application intended to be used by others, I’m probably going to go with Windows Forms, ASP.net, or WPF. I do a significant amount of development that isn’t aimed at end users, though, and that’s where I’ve learned to appreciate the value of the console application.

Your first try will likely be your worst

The first time you try something new, it’s likely to be your worst attempt. So, if you’re experimenting with a new technology or implementing logic that you aren’t familiar with, why would you try in production code? Further, once you’ve got it implemented and functional in your production code, there’s a chance that some unnecessary figuring-it-out code will sneak into the product.

This is where the oft overlooked console application comes into play. For my money, the console app is the fastest way to an isolated, bare-bones sandbox for learning and optimizing a solution. A valid argument can be made that a Windows Forms application is just as fast(er), but you can waste time manipulating controls on a form that really don’t provide any value at the end of the day. Hard-code your input or prompt the user and use Console.ReadLine()–it’s as fast as declaring a variable, and your project doesn’t get any of the extra “fluff” that comes with forms and designers. (It’s also great for blogging since you don’t have to explain what each control is or provide screenshots!)

A personal library

You know how you did that one cool thing for some project a few years ago? Can you send me that code?

A great side-effect of doing your learning and experimenting outside of the application it’s ultimately targeted for is that you build a personal snippet and reference library. If you browse through my Visual Studio projects folder, you’ll see a LOT of folders: EncryptionConsole, ZipConsole, FtpConsole, TfsSdkConsole, SerializationConsole, etc. It’s easy to find a functional, self-contained code sample that you can share with others. Or, if you need to expand on a previous topic with a more advanced technique, you’ve got a foundation already built.

Regular Expression Capture Groups in C#

We all know regular expressions are great for matching patterns and parsing strings, but if you really want to take your Regex game to the next level, spend some time looking at capture groups. Using capture groups–more specifically, named capture groups–makes it easier to manipulate results and replacements, and it also has a fortunate side-effect of improving readability.

To create a named capture group in a .net regular expression, use the syntax “(?<Name>pattern).” The name acts like an inline comment and allows you to reference the group using that name by using “${Name}” in Result and Replace statements.

Let’s look at an example that uses Replace. Social Security numbers are a sensitive piece of information that is often masked when displaying details. Let’s use a regular expression to hide part of the number.

var ssn = "123-45-6789";
var re = new Regex(@"\d{3}-\d{2}-(?<lastFour>\d{4})");
var masked = re.Replace(ssn, "xxx-xx-${lastFour}");
Console.WriteLine("{0} -> {1}", ssn, masked);
123-45-6789 -> xxx-xx-6789

Another common scenario is to extract a piece of data from a string. Here’s another quick example that extracts the month and year from a date string (great for grouping items in a reporting scenario!).

var date = "01/15/2012";
var re = new Regex(@"(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{4})");
var monthYear = re.Match(date).Result("${year}-${month}");
Console.WriteLine("{0} -> {1}", date, monthYear);
01/15/2012 -> 2012-01

Parse US Street Addresses with Regular Expression in VB6

I have a confession to make: this article was actually implemented in VB6 originally. The meat of it is the same, but here’s the VB6 edition in case it’s of interest to anybody.

Enjoy!

Private Sub Form_Load()
    
    Call ClearControls
    
End Sub

Private Sub ClearControls()
    uxHouseNumber = ""
    uxStreetPrefix = ""
    uxStreetName = ""
    uxStreetType = ""
    uxStreetSuffix = ""
    uxApt = ""
    uxAdditionalInfo = ""
End Sub

'---------------------------------------------------------------------------------------
' Procedure : ConstructRegex
' Purpose   : Returns a regular expression pattern for parsing US street addresses
'---------------------------------------------------------------------------------------
'
Private Function ConstructRegex() As String
    
'    ConstructRegex = "^" & _                           -> begin string
'        "(\d+)" & _                                    -> 1 or more digits
'        "(\s+(?:" & GetStreetPrefixes() & "))?" & _    -> whitespace + valid prefix (optional)
'        "(\s+.*?)" & _                                 -> whitespace + one or characters
'        "(?:" & _                                      -> group (optional) {
'            "(\s+(?:" & GetStreetTypes() & "))" & _    ->   whitespace + valid street type
'            "(\s+(?:" & GetStreetSuffixes() & "))?" & _->   whitespace + valid street suffix (optional)
'            "(\s+.*)?" & _                             ->   whitespace + anything else (optional)
'        ")?" & _                                       -> }
'        "$"                                            -> end string

    ConstructRegex = "^" & _
        "(\d+)" & _
        "(\s+(?:" & GetStreetPrefixes() & "))?" & _
        "(\s+.*?)" & _
        "(?:" & _
            "(\s+(?:" & GetStreetTypes() & "))" & _
            "(\s+(?:" & GetStreetSuffixes() & "))?" & _
            "(\s+.*)?" & _
        ")?" & _
        "$"


End Function

'---------------------------------------------------------------------------------------
' Procedure : GetStreetPrefixes
' Purpose   : Returns a pipe-delimited list of valid street prefixes
'---------------------------------------------------------------------------------------
'
Private Function GetStreetPrefixes() As String
    
    GetStreetPrefixes = "TE|NW|HW|RD|E|MA|EI|NO|AU|SE|GR|OL|W|MM|OM|SW|ME|HA|JO|OV|S|OH|NE|K|N"
    
End Function

'---------------------------------------------------------------------------------------
' Procedure : GetStreetTypes
' Purpose   : Returns a pipe-delimited list of valid street types
'---------------------------------------------------------------------------------------
'
Private Function GetStreetTypes() As String
    
    GetStreetTypes = "TE|STCT|DR|SPGS|PARK|GRV|CRK|XING|BR|PINE|CTS|TRL|VI|RD|PIKE|MA|LO|TER|UN|CIR|WALK|CO|RUN|FRD|LDG|ML|AVE|NO|PA|SQ|BLVD|VLGS|VLY|GR|LN|HOUSE|VLG|OL|STA|CH|ROW|EXT|JC|BLDG|FLD|CT|HTS|MOTEL|PKWY|COOP|ACRES|ESTS|SCH|HL|CORD|ST|CLB|FLDS|PT|STPL|MDWS|APTS|ME|LOOP|SMT|RDG|UNIV|PLZ|MDW|EXPY|WALL|TR|FLS|HBR|TRFY|BCH|CRST|CI|PKY|OV|RNCH|CV|DIV|WA|S|WAY|I|CTR|VIS|PL|ANX|BL|ST TER|DM|STHY|RR|MNR"
    
End Function

'---------------------------------------------------------------------------------------
' Procedure : GetStreetSuffixes
' Purpose   : Returns a pipe-delimited list of valid street suffixes
'---------------------------------------------------------------------------------------
'
Private Function GetStreetSuffixes() As String
    
    GetStreetSuffixes = "NW|E|SE|W|SW|S|NE|N"
    
End Function

'---------------------------------------------------------------------------------------
' Procedure : uxAddress_Change
' Purpose   : Parses user input and displays components to user
'---------------------------------------------------------------------------------------
'
Private Sub uxAddress_Change()
    
    Dim strInput As String
    Dim re As RegExp
    Dim mc As MatchCollection
    Dim ma As Match
    
    Call ClearControls
    
    strInput = UCase$(uxAddress.Text)
    
    Set re = New RegExp
    re.Pattern = ConstructRegex()
    re.Global = True
    
    If re.Test(strInput) Then
        Set mc = re.Execute(strInput)
        Set ma = mc(0)
        
        uxHouseNumber = Trim$(ma.SubMatches(0))
        uxStreetPrefix = Trim$(ma.SubMatches(1))
        uxStreetName = Trim$(ma.SubMatches(2))
        uxStreetType = Trim$(ma.SubMatches(3))
        uxStreetSuffix = Trim$(ma.SubMatches(4))
        uxApt = Trim$(ma.SubMatches(5))
        
        Set ma = Nothing
        Set mc = Nothing
    Else
        uxStreetName = strInput
    End If
    
    Set re = Nothing
    
End Sub

Unit Testing Stored Procedure Calls with Rhino Mocks

Database stored procedure calls are one of the trickiest things to unit test, and there are many different approaches that can be taken. My team has run the gamut: test DBs that rollback with each run, no testing for direct data access functions (!), virtual functions w/ partial mocks (see here).

The latest approach that I’ve been using is much more straightforward and feels like a more natural use of Rhino Mocks. Let’s look at some examples of how to test some common database stored procedure tasks. (Note that these examples assume use of the Microsoft Enterprise Library.)

Create a mockable Database

The primary challenge that I’ve found with testing database code is that Microsoft.Practices.EnterpriseLibrary.Data.Database isn’t mock-friendly. However, the other “pieces” such as DbCommand and DbCommandParameterCollection are very easy to work with. So, we can solve the Database problem by creating a simple wrapper (Important! Note that the methods have the virtual keyword, which will allow them to be overridden.):

public class DatabaseWrapper
{
    private Database _database;
    private Database Database
    {
        get { return _database = _database ?? DatabaseFactory.CreateDatabase(); }
        set { _database = value; }
    }

    public virtual DbCommand GetStoredProcCommand(string storedProcedureName)
    {
        return Database.GetStoredProcCommand(storedProcedureName);
    }

    public virtual void DiscoverParameters(DbCommand command)
    {
        Database.DiscoverParameters(command);
    }
}

Executing a stored procedure

Now that we are able to mock the database object, we can write some useful tests. Let’s say you want to execute a stored procedure named “MyStoredProcedure,” and you want to write a test to verify that your code handles an exception thrown when it’s executed. That’s very easy!

Here’s my class with the function I want to test:

public class MyDataAccess
{
    public DatabaseWrapper Database { get; set; }
    public Thingy GetThingy()
    {
        Thingy thingy = null;
        try
        {
            var dbCommand = Database.GetStoredProcCommand("MyStoredProcedure");
            Database.DiscoverParameters(dbCommand);
            var result = dbCommand.ExecuteNonQuery();
            // populate thingy
        }
        catch (Exception ex)
        {
            // handle exception
        }
        return thingy;
    }
}

And here’s my test that will throw an exception when the stored procedure is executed. I create my DatabaseWrapper as a PartialMock, allowing me to override its methods.

[TestMethod]
public void GetThingyHandlesException()
{
    // Arrange
    var target = new MyDataAccess();
    var mockDatabase = MockRepository.GeneratePartialMock<DatabaseWrapper>();
    target.Database = mockDatabase;

    // mock Database
    const string storedProc = "MyStoredProcedure";
    var mockDbCommand = MockRepository.GenerateMock<DbCommand>();
    mockDatabase.Expect(x => x.GetStoredProcCommand(storedProc))
        .Return(mockDbCommand);
    mockDatabase.Expect(x => x.DiscoverParameters(mockDbCommand));
    
    // mock DbCommand
    var ex = new Exception("Oh noes!");
    mockDbCommand.Expect(x => x.ExecuteNonQuery())
        .Throw(ex);

    // Act
    var actual = target.GetThingy();

    // Assert
    mockDatabase.VerifyAllExpectations();
    mockDbCommand.VerifyAllExpectations();
    Assert.IsNull(actual);
}

Setting input parameters

Need to set some input parameters? No problem!

dbCommand.Parameters["@id"].Value = id;

And, in your test, you add this:

var mockParams = MockRepository.GenerateMock<DbParameterCollection>();
var mockParam = MockRepository.GenerateMock<DbParameter>();

mockDbCommand.Expect(x => x.Parameters).Return(mockParams);

mockParams.Expect(x => x["@id"]).Return(mockParam);

const int id = 123;
mockParam.Expect(x => x.Value = id);

mockParams.VerifyAllExpectations();
mockParam.VerifyAllExpectations();

Reading output parameters

How about output parameters?

thingy.Value = dbCommand.Parameters["@Value"].Value as string;

Add the additional mocks and assertions:

var mockOutParam = MockRepository.GenerateMock<DbParameter>();

mockParams.Expect(x => x["@Value"]).Return(mockOutParam);

const string value = "MyValue";
mockOutParam.Expect(x => x.Value).Return(value);

mockParams.VerifyAllExpectations();
mockOutParam.VerifyAllExpectations();
Assert.AreEqual(value, actual.Value);

Working with sets of parameters

When you have more than a few parameters to work with, the unit test code can get quite lengthy. I like to keep it clean by extracting the duplicated logic into a separate function, like so:

var paramsToVerify = new List<DbParameter>();
mockParams.Expect(x => x["@whammyparammy"])
    .Return(MockParameter<int>(paramsToVerify));

My function allows you to specify and verify the type of each parameter, but you could easily modify it to expect a specific value.

private static DbParameter MockParameter<T>(List<DbParameter> paramsCollection)
{
    // set Expect with Arg<T>.Is.TypeOf to force the specific type
    var mockParam = MockRepository.GenerateMock<DbParameter>();
    mockParam.Expect(x => x.Value = Arg<T>.Is.TypeOf);

    if (paramsCollection != null)
        paramsCollection.Add(mockParam);

    return mockParam;
}

I keep the parameters in a list so I can verify them during my assertions.

paramsToVerify.ForEach(x => x.VerifyAllExpectations());

Custom Shaped Windows Forms From Images

One of the neat things you can do to make an application unique is give it a custom shape, and it’s surprisingly easy to do with windows forms. This article is going to show you how to make a ninja-shaped form in four ridiculously easy steps.

1. Find your image

This step is so simple, it’s almost not worth mentioning. You just need to find or create an image with the shape that you want. For the purposes of this article, I’m going to use this awesome ninja picture.

2. Edit the image

The next step is to edit your image by making undesired sections transparent. You can use Photoshop, Gimp, or any number of other editors to accomplish this. Here’s my transparent ninja image.

I added this image to my project and set its Copy to Output Directory property to Always so that it will be available in step 4. You could definitely compile it as a resource or handle this in a number of different ways if you didn’t want to deploy the image, though.

3. Create a region from your image

The third step is where you’ll actually have to do a little coding. The function below will scan through a provided bitmap pixel by pixel to create a region. (The original function comes from here. I made a slight adjustment to look for transparent pixels instead of a color provided as a parameter.)

private Region GetRegion(Bitmap _img)
{
    var rgn = new Region();
    rgn.MakeEmpty();
    var rc = new Rectangle(0, 0, 0, 0);
    bool inimage = false;
    for (int y = 0; y < _img.Height; y++)
    {
        for (int x = 0; x < _img.Width; x++)
        {
            if (!inimage)
            {
                // if pixel is not transparent
                if (_img.GetPixel(x, y).A != 0)
                {
                    inimage = true;
                    rc.X = x;
                    rc.Y = y;
                    rc.Height = 1;
                }
            }
            else
            {
                // if pixel is transparent
                if (_img.GetPixel(x, y).A == 0)
                {
                    inimage = false;
                    rc.Width = x - rc.X;
                    rgn.Union(rc);
                }
            }
        }
        if (inimage)
        {
            inimage = false;
            rc.Width = _img.Width - rc.X;
            rgn.Union(rc);
        }
    }
    return rgn;
}

4. Change the form’s region

That wasn’t so bad, was it? Now you’re basically done. The final step is simply to assign your newly created region to your form’s Region property.

private void Form1_Load(object sender, EventArgs e)
{
    var bitmap = new Bitmap("ninja.png");
    Region = GetRegion(bitmap);
}

Voila! You’re done, and now you have a sweet ninja form! (For added authenticity, modify the form’s opacity.)

Bonus material!

One of the problems with a custom shaped form is that you lose the title bar, so you can’t easily move it around. This can be remedied by adding some handlers to a few mouse events on the form, like so:

private bool _mouseDown;
private Point _startPoint;

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    _mouseDown = true;
    _startPoint = new Point(e.X, e.Y);
}

private void Form1_MouseUp(object sender, MouseEventArgs e)
{
    _mouseDown = false;
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (_mouseDown)
    {
        var p1 = new Point(e.X, e.Y);
        var p2 = PointToScreen(p1);
        var p3 = new Point(p2.X - _startPoint.X,
                             p2.Y - _startPoint.Y);
        Location = p3;
    }
}

With this code in place, you can click anywhere in the form to move it around.