Author: Pete

Code Tips

NUnit

NUnit. Chances are that you know what NUnit and Test Driven Development are, but if you don’t I’ll give you a quick primer. Test Driven Development means that you drive your development from tests. I know I just reversed the order of the words, but lets take a look at what that means 😉 Test Driven Development has a little motto that goes, “Red. Green. Refactor”.
Red. Green. Refactor.

The red refers to writing the tests for what you want your code to do before you write the code to do it. When a test fails in NUnit (and other Testing Frameworks), they show up as red. Next, you write the actual functional code to make the test pass (green), and then you refactor the code so it is as clean, extendable, testable, and maintainable as possible. Then you run the tests again to make sure that none fail. If they do, you fix your code so that the tests can pass again. You repeat this process as much as is prudent for the project that you are on.

The extra added benefit is that you can feel safe in making changes to your code later. If you have written sufficient test coverage, you can run your tests and if they all pass, then your changes will cause no problems when you deploy.

Now, on to NUnit. NUnit is the first unit testing framework that I ever heard of or used, so I have a soft spot for it. You can get started by downloading NUnit from their download page here. The easiest way to get going quickly is to pick the download named NUnit-2.4.8-net-2.0.msi and then just run the install wizard.

Once you have everything installed, let’s get started. For a sample, let’s just make a new C# class library project called NUnitExample. Add a reference to nunit.framework.dll that can be found at (if you accepted the defaults on install) at C:\Program Files\NUnit 2.4.8\bin\nunit.framework.dll.

Now, enter the following code into the default Class1.cs file and build the project:

using System;
using NUnit.Framework;

namespace NUnitExample
{
    /// <summary>
    /// [TestFixture] is an attribute that you 
    /// add above any class that you want to 
    /// contain tests.
    /// </summary>
    [TestFixture]
    public class MathTests
    {
        protected int a;
        protected int b;
        protected int c;

        /// <summary>
        /// Any variable setting or state 
        /// setup you need to do can be done
        /// in a method marked with the 
        /// [TestFixtureSetUp] attribute.
        /// </summary>
        [TestFixtureSetUp]
        protected void Setup()
        {
            a = 9;
            b = 2;
            c = 0;
        }

        /// <summary>
        /// You can create tests by applying 
        /// the [Test] attribute to any method 
        /// that is public, takes no params, 
        /// and returns void. If the method 
        /// does not meet these requirements, it 
        /// will be ignored.
        /// </summary>
        [Test]
        public void Adding()
        {
            Assert.AreEqual(11, a + b);
        }

        /// <summary>
        /// This Test will fail. Normally, you test for purposeful failure 
        /// (like a validation error) and that is a "passed test", that 
        /// isn't what I'm doing here.  I'm just showing what a failed test 
        /// looks like in the Test Runner.
        /// </summary>
        [Test]
        public void Dividing()
        {
            Assert.AreEqual(4.5M, a / b);
        }

        [Test]
        public void DivideByZeroException()
        {
            try
            {
                int x = a / c;

                // If we get to this line, throw an 
                // exception because the above division 
                // shouldn't work.
                throw new Exception("Division Worked");
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(typeof(DivideByZeroException), ex);
            }
        }

        [Test]
        public void Comparison()
        {
            Assert.That(a > b);
        }

        /// <summary>
        /// These next 3 tests will be ignored 
        /// because their signatures aren't 
        /// correct.
        /// </summary>
        [Test]
        private void Ignored1()
        {
            Assert.AreEqual(1, 2);
        }

        [Test]
        public string Ignored2()
        {
            Assert.AreEqual(1, 2);
            return string.Empty;
        }

        [Test]
        public void Ignored3(int a, int b)
        {
            Assert.AreEqual(1, 2);
        }
    }
}

Now, fire up the NUnit Test Runner GUI. It is located at C:\Program Files\NUnit 2.4.8\bin\nunit.exe. When it opens, click File –> Open Project and then navigate to the .dll that was created from the project that you built and click “Open”.

The NUnit GUI should now look like this:
NUnit Ready to Run Tests

Make sure you have the top level highlighted and click Run. It will look like this:
NUnit After Initial Tests

What you see is that the entire test fixture of NUnitExample has failed (the red circle with the X). Parent levels are always shown as having the same success level as the lowest success level below it. You see that Adding, Comparison, and DivideByZeroException passed. No surprise here. Additionally, the three tests named ignored have been ignored because their signatures were incorrect. If you click the “Tests Not Run” tab at the bottom of the runner, you can see why.
Reasons for ignored tests

If you click the “Errors and Failures” tab, you will see why the Dividing Test failed.

NUnitExample.MathTests.Dividing:
  Expected: 4.5m
  But was:  4m

Oh, yeah. Integers only hold whole numbers. Lets go back and change the code. (Normally, you’d change your code, but here the “active” code is embedded in the tests because of this simple sample.) Change the Dividing test to the following:

public void Dividing()
{
    Assert.AreEqual(4.5M, Convert.ToDecimal(a) / b);
}

When you switch back to the NUnit Test Runner, it will have automatically refreshed because the test project has changed. Run it again and the Dividing test will pass and the overall status will be yellow because the lowest level of success in the child tests was also yellow.

If you instead would like to use the command line for NUnit (perhaps for continuous integration or just as part of your build task on your program) you can do that as well. Open a command window and enter the following command: (If you changed anything on NUnit install, change “c:\Program Files\NUnit 2.4.8\bin” to match your install path. The argument passed in is the path to the .dll of the project that you created.)

"c:\Program Files\NUnit 2.4.8\bin\nunit-console" c:\code\blog\NUnitExample\NUnitExample\bin\Debug\NUnitExample.dll

When you run it, you get the following results:

c:\Program Files>"C:\Program Files\NUnit 2.4.8\bin\nunit-console" C:\Code\Blog\NUnitExample\NUnitExample\bin\Debug\NUnitExample.dll
NUnit version 2.4.8
Copyright (C) 2002-2007 Charlie Poole.
Copyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov.
Copyright (C) 2000-2002 Philip Craig.
All Rights Reserved.

Runtime Environment -
   OS Version: Microsoft Windows NT 6.0.6001 Service Pack 1
  CLR Version: 2.0.50727.1434 ( Net 2.0.50727.1434 )

.....N.N.N
Tests run: 4, Failures: 0, Not run: 3, Time: 0.031 seconds

Tests not run:
1) NUnitExample.MathTests.Ignored1 : Method Ignored1's signature is not correct:
 it must be a public method.
2) NUnitExample.MathTests.Ignored2 : Method Ignored2's signature is not correct:
 it must return void.
3) NUnitExample.MathTests.Ignored3 : Method Ignored3's signature is not correct:
 it must not have parameters.

In a later post, I will look at doing Test First development with a true “Red. Green. Refactor.” feel.

Code Tips

NLog

Every application needs logging. It is, of course, especially helpful if you need to provide a user with just an apology message, but you need to store all kinds of data about the exception so that you can reproduce and debug it. Many people write their own because at its core, what you are doing it writing a string to a text file or saving a string to a database. However, to make that operation very robust, you need to do a lot of defensive coding around the operation.

This causes many people to turn to logging libraries like NLog. Quoting from their website, they indicate that NLog is able to do the following:

  • the ability to control the level of detail of our trace messages (such as displaying only warnings and errors or very detailed program trace)
  • the possibility of turning the tracing on and off for components of our proram separately, without turning the application off and recompiling it
  • writing trace messages to the file, system log, message queue or other output
  • being able to send particularly important messages by email or store them in a database
  • and others…

You can target your logs to go to a file, a console, email, a database, a message queue, event logs, pretty much anywhere that it would make sense for them to go. In addition, if you aren’t happy with the targets that NLog provides, you can write your own.

To get started with NLog, you can download it from here.

After you get it downloaded and extracted, you can either put the appropriate .dll (in my case I’m going to use NLog.dll v. 1.0.0.505, labeled as NLog for .Net 2.0) in the GAC or store it somewhere that you put your shared .dlls so that you know where to go and reference it later. For this example, I’m just going to copy it right into my bin folder.

Create a new C# console application, named whatever you like. Add a reference to the NLog .dll and then add an application configuration file to your application (Right click on project–>Add–>New Item–>Application Configuration File). Put the following code into your application config file (app.config). All of the ${} stuff are just variables that NLog understands. They are all pretty straightforward and for a complete list, go see their website.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>    
  </configSections>
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
      <target name="console" xsi:type="Console" layout="${shortdate}|${level}|${message}" />
      <target name="file" xsi:type="File" layout="${longdate}|${stacktrace}|${message}" fileName="c:\Logs\${logger}.txt" />
    </targets>
    <rules>
      <logger name="*" minlevel="Debug" writeTo="console" />
      <logger name="*" minlevel="Error" writeTo="file" />
    </rules>
  </nlog>
</configuration>

A small bit of explanation of the XML file. The targets section allows you to specify what kind of messages go to what kind of logging endpoint. The rules tell NLog where to go with certain types of messages, for instance, you can log Error to the file system, but just show debugging messages in the console.

Now, for the C# code. In your Program.cs, you can put the following code:

using NLog;

namespace NLogSample
{
    class Program
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();

        static void Main(string[] args)
        {
            logger.Debug("I won't go to the file, but I'll go to the screen");
            logger.Error("I'll do both.");
        }
    }
}

When you run this sample, you see this:

Output from our simple NLog Example

When I look in the log file, which I specified as c:\Logs\{name of logger, which is by default Namespace.Class}.txt, I find the following:

2008-07-29 10:43:45.8617|Program.Main|I'll do both.

That’s all there is to using NLog. As you can see, setting it up and using it is a snap and exposes much more functionality than common “roll your own” implementations. If you are doing web applications, the code from our app.config can go in the web.config and then you are all set to go.

We use NLog with my current employer and I couldn’t be happier with the results. If you don’t have a good logging framework in place, give NLog a try. Also, look around their site and give some of the other logging options a try.

Fluff

How I Got Started in Programming

Lots of people around the web have done this one and who am I to break the trend? 😉

How old were you when you started programming?
I wrote a little about my journey to becoming a coder here. Basically, I was very very young. I used to program BASIC by copying the programs out of GAMES magazine and getting them to work. I also used to write programs to simulate computer systems like what you’d see in Wargames, for instance.

What was your first language?
I Speak Basic to my Commodore 64Kind of mentioned it above, but BASIC on my Commodore 64. In fact, my first book on programming was called “I Speak BASIC to my Commodore 64”.

What was the first real program you wrote?
What qualifies as a “real program”? I wrote programs in school on the Tandy for projects and on Apple IIe in high school. I wrote a secret message sending program in VB6. The first thing I was paid to write was in Access. It kept track of credit limits of commercial customers for a large bank’s commercial vault network.

What languages have you used since you started programming?
BASIC, VB6, VBScript, VBA, VB.Net (a theme?), C#, T-SQL, C++, Javscript, and PHP.

I have fooled around with (meaning worked through tutorials on) Ruby, F#, Python, and Perl.

What was your first professional programming gig?
As I mentioned above, I worked for a very large bank in their commercial vault division. Basically, customers ordered large amounts of money from the vaults and the money would actually leave the vault via armored cars before the money would be withdrawn from their accounts, leading to a liability. Underwriters determined the amount of exposure that the bank was willing to risk with each customer. My shared Access database program had forms for entering and reporting on all of the information, as well as pulling down data from the Informix system that housed the orders so that we had current information about the state of things. Woo-hoo.

If you knew then what you know now, would you have started programming?
Oh, yeah. I would have gone hardcore earlier and stopped that BASIC trail I was blazing and switched to other languages that would have caused me to learn more about the art of programming.

If there is one thing you learned along the way that you would tell new developers, what would it be?
Seriously, you don’t know as much as you think you do. I understand… I’ve been there. But just because you wrote some app that organizes your MP3 collection, you don’t know that much about programming. You can’t learn programming by sitting in a class and you can’t learn solely by reading books. The books help, for sure, but only by writing code, reading code, and interacting with other coders can you really learn. Trust me, the more you know, the more you’ll realize you don’t know.

Don’t stop learning ever. Technology is always changing and you will be “the new guy” in some piece of the game all the time. Don’t forget that and never be too proud to ask for help. The community by and large loves to share its knowledge. Listen to podcasts, participate in forums, read blogs, and go to conferences and user groups. You can thank me later.

What’s the most fun you’ve ever had … programming?
Every time that I’ve had to do crazy things or solve problems that were really difficult. One that comes to mind was a time that Jeff and I had to work late to work out an interoperability problem between our company’s web service and another company’s web service (the night he literally saved my life). We were using security and encrypting the payload, etc, but we had to pore over these boring OASIS specifications (but what about OASIS?!?!?) in order to figure out exactly why the messages weren’t being accepted. Annoying at the time, but so much fun working out the old grey matter and so rewarding when we succeeded. And, to top it off, I know way more about that topic than I ever would have otherwise.

Podcasts

My Favorite Programmer Podcasts

Road Image From http://www.sxc.hu/photo/973008I use to have an hour long commute to work. It has been reduced to 35 minutes now with my new position, but I still have 5 hours a week where I’m not being at all productive. I used to listen to books on CD to pass the time, but what I really wanted to do was learn more about programming!

Since Code Complete isn’t out as an audio book yet, I had to turn to podcasts. At the time, I still had 10 hours of drive time, so I was really burning through them. At first, all I had was my nerd-crush Scott Hanselman’s podcast “Hanselminutes”. However, I blew through the archive in a hurry and I needed more.

I had a really hard time finding good podcasts that were updated fairly regularly and that talked about the kinds of things that I wanted to learn about. Since that time, I’ve built up a nice little rotation and I thought that I would share my favorites with you. I wish I could have found a list like this when I was searching, so maybe I can be a help to someone else who is starting out.

Here is my list. In order of preference. I don’t waffle and I calls ’em likes I sees ’em.

Hanselminutes RSS Feed
My absolute favorite podcast. When I discovered this, I liked it so much that I went back and listened to every single episode. When a new one comes out, I bump it to the top of the playlist and hear it next. Worth a listen for the theme music alone ;). Description from the site: Hanselminutes is a weekly audio talk show with noted web developer and technologist Scott Hanselman and hosted by Carl Franklin. Scott discusses utilities and tools, gives practical how-to advice, and discusses ASP.NET or Windows issues and workarounds.
StackOverflow Podcast RSS Feed
This is the podcast to discuss Jeff Atwood and Joel Spolsky’s joint business venture of StackOverflow.com. Well, that is what it is intended to do. In reality, they talk about a lot of issues that are tangential to Jeff’s work or things that have annoyed either one of them in the past week. They also take user questions.
Polymorphic Podcast RSS Feed
This podcast isn’t updated as frequently, but I still like to listen to it when it is new. The tagline is “Object Oriented Development, Architecture, and Best Practices in .Net” and that about sums up what the show is about. Craig Shoemaker, the host, also does webcasts over at getpixel8ed.com. A bit of trivia: I won an ASP.Net Infragistics Controls license for answering a trivia question posed on this podcast!
Deep Fried Bytes RSS Feed
Deep Fried Bytes is a new podcast with Keith Elder and Chris Woodruff. It is described as “The show discusses a wide range of topics including application development, operating systems and technology in general”. Some great recent shows have covered .Net development on a Mac and scaling large websites.
.Net Rocks RSS Feed
.Net Rocks. If you don’t know about this one, you’ve been hiding. Carl Franklin and Richard Campbell do an hourlong show and discuss all sorts of topics in the Microsoft world.
Google Developer Podcast RSS Feed
This podcast isn’t updated very frequently at all. It isn’t boring and does let you know what Google is up to for developers, but I use it as “filler” if I’m all caught up on other podcasts and I need something to listen to on the commute.
Alt.Net Podcast RSS Feed
If you haven’t heard of Alt.Net, it is a group of developers who develop using .Net technologies, but they like to have some choice in how they do things, borrowing heavily from what other development communities are doing. This podcast has a lot of information, but is really dry and another one that I use for filler.

I have a few more that I dig deep on if I am totally out of stuff, but by that time, my regulars have churned out some new podcasts and I don’t need to go much further. If you have one that you really enjoy, leave it as feedback in the comments, I’d love to check it out.

Rant

Sql Reference Tables

Reference Book Image from http://www.sxc.hu/photo/1022436
Disclaimer: Personally, I prefer to use uniqueidentifier as my primary key data type. It cuts down on improper joins (similar looking values aren’t in every table, ie 1, 2, 3) and is infinitely portable among environments. I think the extra space and overhead is worth it.

We have some reference tables in our database at work. This itself isn’t abnormal, everyone has these. What made these tables special was that the IDENTITY Primary Key for the table started at 0. At first I thought that this was awesome. I know it is a debate for another day, but I love that my arrays, counters, etc start at 0 in C#. I know it may not be necessary anymore or whatever, but it comforts me, okay? 🙂

Things soon changed for the worse when I realized that 0 being a significant data value was a problem. “Why?”, you may ask. Well, when you just generically “new up” an int, what is the default value? That’s right, 0. So, if someone doesn’t set a property when trying to identify some reference value, in a 1-based table (or a GUID one) you will get an error because that isn’t a valid value. However, in a 0-based table, that “forgetfulness” will match right up with a value and go in no questions asked. You can’t validate it, because 0 is perfectly fine to have.

Lesson Learned: Zeroes are fine for arrays and loops, but keep them out of reference tables!