October 20, 2007

Software Development Essential Practices

I was in an interesting discussion last night: what software development practices do you consider essential? 

While opinions varied, I think there was some consensus on a few items.  In my list I also include some tools.  Some of these were mentioned by the group, but consider them my own additions.  Also, I am making this list specific to .NET, but the list applies to just about every language.

Universally agreed Practices

  • Source Control (1)
  • Local Development -- Every developer should have everything on their computer to run the system.  This includes all of the software and all of the source code.
  • Bug Tracking - nuf said.  There are to many tools available to list here.
  • TDD - Test Driven Development.  There was a little bit of back and forth, but the general consensus was that this should be done.
  • ORM - Object-Relational Mapping
    • NHibernate 
    • SubSonic - My person favorite
    • LINQ to SQL - not yet, but I feel this should be on the list.
    • LLBLGen ($) - Not free, but I've heard many good things about it.
    • More
  • Continuous Integration - Simple process that sits on a server and waits for things to get checked into your source control system.  When it sees something new, it gets all of the latest source code, compiles it, and runs all of the unit tests.  If there are any problems anywhere in that process it alerts the users (email, desktop icon, wave red flag, etc). (3)
  • One Step Build - it is unbelievably cool to be able to click one button and have your entire project compile, run all tests, and possibly create an install in one step.  Personally, I do like it, but with the current set of tools this is one of the hardest parts to setup.

Highly thought of but non-essential practices

I'm sure I have missed some tools in the list, but it is the practices that are more important anyway.  But if you put a comment about any tool that I missed I will add it to the list.

(1) Source Safe was notably not in the list.  While I don't like it either, it is better than nothing.  But if your team is greater than 5 people or you have multiple people working on the same project you really should look at one of the other products on the list.

(2) Not a unit testing library, but a Mock Object library.  Pick a unit testing libarary (NUnit, MBUnit, XUnit), then pick a mock object library (Rhino Mocks, TypeMock, NMock) to use with it.

(3) I really need to talk about continuous integration more.  But it is one of those things that leads you down a path.  First you add source control, then you start adhering to separation of concerns, then you start unit testing and mocking more, then you add continuous integration, and then one step builds are all part of the mix.  One best practice leads to another, but they don't make a bit of sense without some of the prior pieces.

(4) If you are a Code Rush person instead of a ReSharper person -- carry on, you are in good company.

($) The cost money - not just beer, but may have free version versions as well.

October 17, 2007

Testing for Exceptions with NUnit

I came across a testing situation where I had to:
a. Make sure an exception was thrown
b. After it was thrown, make sure nothing else happened.

This is what happens when you throw exceptions from SQL Stored Procedures.

The Problem

The standard way of checking for exceptions in NUnit are thus:
1. ExpectedException attribute on the test method
2. Have your own try/catch block in your test method.

The problem with option 1 is that no assertions can be checked after the exception. The code runs until the exception is thrown, then you are done. That isn't what I need.

The problem with option 2 is that it is ugly. Yes, I'm being a cry baby here. I think the try catch throws more code in the test than I think should be there.

My Solution

So I created a new method called ExpectException. Here is the code:



   1:  public T ExpectException<T>(MyMethod method) where T : Exception
   2:  {
   3:      try
   4:      {
   5:          method.Invoke();
   6:      }
   7:      catch(T e)
   8:      {
   9:          return e;
  10:      }
  11:      return null;
  12:  }


So now in my case, I have a stored procedure that throws an SqlException. I want to call the method and return the exception so I can check the exception for specific values (make sure the message is correct). Also, if any other exception is thrown, say a Exception -- not a SqlException, the test will fail.

Here is my new code:

   1:  SqlException e = ExpectException<SqlException>(delegate { ReplaceUnitCall(oldUnit, newUnit); });
   2:  Assert.IsNotNull(e);

So as long as you are familiar with anonymous delegates, this is a pretty nice solution -- to me.

Current favorite ReSharper shortcuts

I've been experimenting with ReSharper shortcuts again. Here are my new favorites.

Ctrl-- (control-minus): return cursor to previous position.
This is especially useful if you just had ReSharper create a field or do any number of other items that will automatically jump the cursor to some other place -- be it in the current class, or another file. Very useful. I seem to use this most when I'm creating properties.

Ctrl-Alt-V: Introduce Variable.
If I type:
System.IO.File.ReadAllLines(filename);

Then hit the Ctrl-Alt-V, it will create a variable for the return of the function. So you will end up with this:
string[] lines = System.IO.File.ReadAllLines(filename);

Ctrl-Shift-N: Find file by name
I'm used to using Ctrl-N, find type by name. But usually what I was looking for was find file by name. If your classes have the same names as your files, not a big difference, but there is a difference.

What I'm hoping for in the next version of ReSharper
Enhanced Interface support. If my class has an interface, I want to be able to right-click on a method that is not in the interface, and have ReSharper automatically add the method to the interface.

Update:
From my comments I see that this feature already exists, it just has an odd name and no short-cut. The feature is "Push member up".

So put your cursor on a method/property, right-click->Refactor->Push Member Up and you will get a dialog for adding the member to an interface.

The name is the odd part, but if you do think about all the implications, it does make sense. Anyway, the more you know... Thank you Ilya Ryzhenkov

October 05, 2007

MSDN Presentation and the Demo Gods


Everyone who has ever done a presentation in front of a large group of people, with a computer and powerpoint, will have some crack about appeasing the demo gods.

Yesterday I gave a presentation on LINQ for the MSDN Event here in Boise, and apparently I pissed the demo gods off something fierce.

I get up on stage, hook up my laptop, start everything up (powerpoint and VPC) plug in the projector's cable, and...
I hear a lot of beeping. I open Windows explorer and suddenly all of my icons start expanding to enormous proportions. My PowerPoint presentation will not move past the first slide.

I reboot. Restart PowerPoint and VPC. I hear beeping again. I'm supposed to have started 5 minutes ago. Not good.

I start talking anyway. LINQ has a lot to cover. Philosophy, data access, xml, objects, language enhancements, etc.

It is as I start talking, sans PowerPoint, that suddenly the crowd goes: "Ohhh", with a couple of faint "Doh!"s in the mix. My laptop had just Blue Screened.

The demo gods were not happy with me.

So, reboot again, and keep talking about LINQ. Needless to say I was a bit flustered this time, but I kept moving (I had a time limit). Luckily, my laptop booted just fine this time, everything loaded, I was able to breeze through a bunch of slides and get the VPC started and start the actual demo.

After that everything went mostly well. I covered all of my demos, and they all worked. I also knew which of my demos would take a long time to run, and used that time to ask the audience for questions -- and they had a lot. The biggest question to come up, repeatedly, had to do with the misconception that LINQ was only about database access. It isn't, LINQ is about data manipulation with ALL of your data.

The only thing I missed: each of my demos had two parts. Showing how things are probably being coded now, and then showing how they are done with LINQ. I skipped the first part, trusting the audience to believe me that they worked. I don't think that was a bad thing. They came to see new stuff, not old.

Anyway, I'll have to figure out what I need to sacrifice for the demo gods before I give another presentation.

And if anyone managed to get a picture of my blue screen, I would love to have a copy of it.

Start everything back up.

September 24, 2007

NMock as compared to RhinoMocks

At a recent developer group meeting I was asked why we were using Rhino Mocks instead of NMock. He also pointed out that NMock had minor api rewrite that made it nicer to use.

My answer was that Rhino Mocks was standardized before I started with my current team, but I would look into NMock. It never hurts to comparison shop.

So to get get started. If you are not familiar with either framework, I suggest looking at their quick start guides:

Rhino Mocks Quick Start
NMock Quick Start

How to mock an object.

NMock:

Mockery mocks = new Mockery();
IMyInterface aMocked = mocks.NewMock<IMyInterface>();
Rhino Mocks

MockRepository mocks = new MockRepository ();
IMyInterface aMocked = mocks.CreateMock<IMyInterface>();

So far so good, no real difference between them. Rhino Mocks has a minor more typing involved, but frankly, I have code templates for all of that anyway.

Which is better: Tie. They both work just fine.

But lets backup a second. What does IMyInterface look like. This is what we are going to work with:

public interface IMyInterface
{
 int MyProperty { get; set; } 
 int Add(int i, int j); 
 void MyMethod(int i, int j); 
 event EventHandler&lt;EventArgs&gt; MyEvent; 
}

Mock libraries create fake objects to send to your real objects. Your real object can call the fake object's methods and properties, but you have to give the Mocked objects their values (this is called setting expectations). First to note: you aren't testing the mocked object, you are testing the object calling the mocked object.
Anyway, if you need more info on where or when to use a mocked object I'm sure Google will have many excellent examples for you.

OK, so now that we have that part set, lets move on.

Set and get a property:

Quick note: this is telling the mocked object to expect the property to be set to a value. We are not actually setting the value. Also, when we get the property, we have to tell the mock library what to return.

NMock
// set the property
Expect.Once.On(aMock).SetProperty("MyProperty").To(1);
// get the property
Expect.Once.On(aMock).GetProperty("MyProperty").Will(Return.Value (1));
RhinoMock
// set the property
aMock.MyProperty = 1;
// get the property
Expect.Call(aMock.MyProperty).Return(1);

OK, both sets of calls are supposed to be equivalent. The first thing to notice is that whatever typing saving we had in the construction of the mock object has not been completely lost. But I still think amount of typing it takes to do something is somewhat shallow, so lets dig deeper into the syntax.

As you can see, in NMock nothing is implied. The properties setter will be called exactly once, and the value will be retrieved exactly once. In Rhino Mocks, that detail is implied. But more troubling with NMock is the reliance on using strings to specify which property is being called. Where as with Rhino Mocks, you are using the mocked interface itself.

So if I change the name of my property on the interface, both tests will fail. But with Rhino Mocks it will fail at build time, NMock will have to wait for run time. Also, if I'm using Find Usages (a feature of ReSharper) to find every place that MyProperty is being used, it will pick up the Rhino Mocks code, but will not pick up the NMock code. To me that is a usability issue.

Rhino Mocks wins.

Next test: Call a function and return a value; call a method

NMock
Expect.Once.On(aMock).Method("Add").With(1,2).Will(Return.Value(3));
Expect.Once.On(aMock).Method("MyMethod").With(1,2);
Rhino Mock
Expect.Call(aMock.Add(1,2)).Return(3);
aMock.MyMethod(1,2);

The nice thing here is that both libraries are consistent in their approach. I still don't like how you have to specify the method names by a string though. Also, the Will(Return.Value()) does not seem natural to me.

But I do have to nock Rhino Mocks on how it does methods a bit. If there is nothing to return, you just call the method. If there is something to return you use the Expect.Call method. This does not seem as consistent as it should.

Rhino Mocks wins.

Handle multiple calls

This is actually kind of interesting. With the NMock api, specifying multiple calls is actually quite natural, where as Rhino mocks seems like a hack. In NMock the Expect function has the following options:

  • Exactly(int count)
  • AtLeastOnce
  • AtLeast(int count)
  • AtMost(int count)
  • Between(int start, int stop)
  • Never

With Rhino mocks there are two ways to do this, but in both cases you use the Repeat object. Remember if you are calling something that doesn't return a value, you don't have to use the Expect object. So Rhino Mocks adds the LastCall method. LastCall modifies the expectations for the last call you made to a mocked object.

But you are using the Repeat object itself. And here is what you get with that:

  • Any()
  • AtLeastOnce()
  • Once()
  • Twice()
  • Times(int count);
  • Time(int min, int max)
  • Never()

First thing I will note between Rhino Mocks Repeat and NMocks Expect is that they are mostly equivalent. I would like the wording of NMocks Between over the Rhino Mocks Times function though. But, Rhino Mocks is missing the AtLeast(int count) function.

So if I wanted to call both methods of my interface at least 2 times, here is what it would look like.

NMock
Expect.AtLeast(2).On(aMock).Method("Add").With(1,2).Will(Return.Value(3));
Expect.AtLeast(2).On(aMock).Method("MyMethod").With(1,2);
Rhino Mocks
Expect.Call(aMock.Add(1,2).Return(3).Repeat.Times(2, int.Max);
aMock.MyMethod(1,2); LastCall.Repeat.Times(2, int.Max);

As much as I love Rhino Mocks, NMock is the winner on the repeating calls front. The syntax makes more sense and is easier to follow than Rhino Mocks. But to fix Rhino Mocks should be hard. Add an AtLeast function and make it possible to use the Expect function on methods with no return values and I think it is there.

But I still don't completely like NMock as either. I don't like it that you have to set the number of times something is being called before you tell the mock library WHAT is being called. I don't thing that helps readability at all.

Winner: NMock.

Raising Events

All of us have this. Small little routines that are only used when an event is raised. So we need a way to mock the event so we can test that code.

NMock
// First read this article: http://becomingagile.blogspot.com/2007/03/raising-events-in-nmock-20.html
// then do this:
MockEvent myEvent = new MockEvnet();
Expect.Once.On(aMock).EventAdd("MyEvent", Is.Anything).Will(MockEvent.Hookup(myEvent));
myEvent.Raise();
Rhino Mocks
aMock.MyEvent += null;
LastCall.IgnoreArguments();
// tell Rhino mocks not to care who is connecting to event
IEventRaiser eventRaiser = LastCall.GetEventRaiser();
eventRaiser.Raise(null, null); // pass in nulls for both sender and args

Can you raise events in NMock: Yes. Is it directly supported: No.
Can you raise events in Rhino Mock: Yes. Is it directly supported: Yes.

Now working with events can be a bit hard. Working with events on a fake object takes a bit of mental yoga to really make sure you understand what is going on as well. I am not overly ecstatic with how Rhino Mocks does events...but it is supported without doing Google searches and writing another class.

Rhino Mocks wins.

Throwing Exceptions

We also have code that catches exceptions. How often do you test that code? You should. Here is how you do it.

NMock
Expect.Once.On(aMock).Method("MyMethod").With(1,2)
.Will(Throw.Exception(new Exception("Hi There"));
Rhino Mocks
Expect.Call(aMock.MyMethod(1,2)).Throw(new Exception("Hi there");

So again, both do the job. But I still like the Rhino Mocks terseness better.

Rhino Mocks wins.

Summary

In the end I will stick with Rhino Mocks. The Method(string methodName) style still just kills it for me because it breaks compile-time checking, and the fact that you can't set method parameters in a type safe way. If I change a something in an interface I want that to break my build -- even in my test code!

Will NMock do the job: yes. But I still think Rhino Mocks does it better.

September 21, 2007

Rhino Mocks: New syntax

I was browsing though the Rhino Mocks documentation when I found there is an entirely new way to setup a test with mocks.

The old way:

[Test]
public void MyOldTest()
{
// Record your expectations here
Expect.Call(myObject.MyProperty).Return(1);

mocks.ReplayAll();

// do your work here
int i = myObject.MyProperty;

// check you values

mocks.VerifyAll();

Assert.AreEqual(1, i);

}

The new way:

[Test]
public void MyNewTest()
{
// Record your expectations here
using ( mocks.Record() )
{
Expect.Call(myObject.MyProperty).Return(1);
}

// do your work here
int i;
using ( mocks.Playback() )
{
i = myObject.MyProperty;
}

// check you values
Assert.AreEqual(1, i);
}

Now, the most obvious thing about the two code examples is that the new way takes more lines of code. But is that really a valid metric? Not always.

The using statements make a nicer differentiation between the setup and the execution. In the old way, the VerifyAll() method was your differentiator. Sorry, but from four feet back, VerifyAll() just looks like another method. The new way, with the 'with' keyword makes for easier transitions from "what we expect to occur" to "Ok, lets do this thing", and "make sure everything worked as planned."

But wait, there is more!

Now for those of you who think you can NEVER have enough ways to do the same thing, and think that anonymous delegates are the GREATEST THING EVER! There is something for you too.

It is the With statement which gives you a fluent interface (which is all the rage on the blogosphere these days). Anyway, it looks like this:

int i;
With.Mocks(mocoks).Expecting( delegate
{
// Record your expectations here
Expect.Call(myObject.MyProperty).Return(1);
})
.Verify(delegate
{
// do your work here
i = myObject.MyProperty;
}
}
// check you values
Assert.AreEqual(1, i);

Now normally I am all in favor of fluent interfaces. SubSonic, LINQ, and Lambda are all great examples of this. But I worry that the fluent style interface is trying too hard in this case.

That said, sometime soon I'll probably see a use for it and it will be wonderful. But until then.

So now you have seen three ways of doing the same thing with one mocking library. That should be enough to keep everyone busy for a while.

September 20, 2007

No Silverlight for you

There are always problems to be found when dealing with new technologies. Currently, I'm playing with Silverlight.

My first project with silverlight was to convert my header (the flaming computer at the top of the page) to a silverlight header. Rev one would be a straight, look alike, conversion of the existing header. The only really cool part is that I would be able to change the text on the header. I can't do that right now because all of the text is an image.

And I did it. It works beautifully...except on my blog. All I get from there is a blank box.

A bit of digging with FireBug and it appears my web host is blocking all xaml files. And you know you are in for a bad day when you call support and they say "What is xaml?" Answer: it is just like Flash.

Oh well, they are supposed to get back to me today. We will see how that goes.

If you want, check out my sample page. Hopefully it will be working in the next day or two.

September 13, 2007

2 Days in Boise

These are two pictures I took one day apart in Boise, ID. Both pictures were taking in the morning.

Sept 6 is the bottom picture, Sept 7 is the top picture.

The top picture, from Sept 7, is what I would consider a hazy day in Boise.

The bottom is about as bad as it gets. On days like that you can really smell the smoke in the air. That is the type of day that you see asthma sufferers looking for their inhalers.

Now I know that my blog has a reference to fire on it...but this really isn't what I was referring to.

September 11, 2007

Boise MSDN Event on Oct 4

Thursday, October 04, 2007 1:00 PM - Thursday, October 04, 2007 5:00 PM Mountain Time (US & Canada)
Welcome Time: 12:00 PM

Theater - Edwards Boise Stadium 21

7701 Overland Road
Boise Idaho 83709
United States

Language(s):
English.

Product(s):
ASP.NET, Office, Visual Studio and Windows Vista.

Audience(s):
Developer.

Event Overview

MSDN Events are free, live sessions designed to enhance your coding skills and make your life a little easier. By attending you’ll get up –to-the-minute technology delivered by seasoned developers and have lots of time to network and ask questions. Chat with your fellow developers get the latest coding tools and tips and learn how to create rich new applications. Register today for a free live event in your area and get the hands on knowledge you need. For more information visit: http://www.msdnevents.com.

September 05, 2007

JQuery is just cool

I've had the opportunity to play around with JQuery
a bit these days. I'm not exactly a Javascript expert by any means, but
JQuery is just cool -- and a bit odd. We know that Javascript is a functional
language, but it does have some object-like stuff you can do with it as well.
But everything is still a function. JQuery has it's own function that you use to
access everything in it as well. The function is $. I'm not kidding, it is $.
Instead of a JQuery function, we have the function formally known as JQuery now
called $. Just wonderful. Then you find out it plugs into the CSS classes. What
now? How the heck? But a typical script you will write looks like this:

$(document).ready(function(){
$("a").filter(".clickme").click(function(){alert("Hi there");}).end() });

Here is what is going on with that statement:

  1. (first $) Find the document node, set a function to the ready() function (that
    lets you know everything is loaded)

  2. (second $) Find any link ( <a>) with a css classes named "clickme" (e.g.
    <a class="clickme">)

  3. Override that links click function.

  4. When the link is click display "Hi there" to the user in a message box


So what you can do with that silly $ is pretty darn cool. Plus there are
plug-ins for it. I have an ASP.Net GridView on my form. In this case I can
display all of the data on the grid without paging or anything special. But I
want to sort the data. There is a JQuery plug-in called
TableSorter that you can use. This will
sort any table with a theader tag. Which would normally work fine as is, but the
GridView doesn't output a theader tag without some modifications. The following
C# does the trick (note: did not come up with this code, I found it on
DotNetSlackers):

private void MakeGridAccessible(GridView grid)
{
if (grid.Rows.Count > 0)
{
grid.UseAccessibleHeader = true;
grid.HeaderRow.TableSection = TableRowSection.TableHeader;
grid.FooterRow.TableSection = TableRowSection.TableFooter;
}
}

Use that function right after you load your data into your gridview. Next you
need to setup your javascript. You have to include JQuery.js, and
jquery.tablesorter.pack.js, then call tablesorter on your table via javascript.
This works for a GridView named grdData:


<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.tablesorter.pack.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#grdData").tablesorter();
}
);
</script>
And done. Really, that is it. We are done. You can click on any of the headers
on the grid and the grid resorts itself. No other fussing, no ajax calls to get
more data. I like it.