May 30
MbUnit’s ThreadedRepeat Attribute
icon1 Darrell Mozingo | icon2 Testing | icon4 May 30th, 2008| icon3No Comments »

I ran into some old code in a utility library the other day that would open an XML file on a network share, read a few settings, and close it. This particular piece of code is called quite often in many situations, and often in larger loops, as the calling developer just sees a string being returned and is oblivious to the fact that it’s pretty damn expensive to get that string.

So I figured I’d go ahead and implement some quick caching around this by storing the strings in generic static Dictionary, especially as the method itself was static. As I’m still trudging up the steep hill that is the learning curve of Test Driven Development (TDD), I thought I’d get a failing test in there first, then make it pass. An interface for dependency injection and a mock or two later and it works. All is good and well in the world.

Unfortunately, it didn’t take long for me to realize there were some serious threading issues going on. Whoops. So I started writing up a unit test to fail on the bug before I fixed it, and in the process of creating a bunch of worker threads to hit the method at the same time, I stumbled across a nifty feature in MbUnit: the ThreadedRepeate Attribute. Behold, a fake example:

[Test]
[ThreadedRepeat(5)]
public void Should_handle_multithreaded_access()
{
	Assert.IsNotEmpty(MyClass.GetExpensiveString());
}

Just like the normal [Repeat(5)] attribute, which would simply call the test 5 consecutive times back to back, the [ThreadedRepeat(5)] attribute will call the test 5 times in parallel, firing off a separate thread for each one.

Pretty freakin’ nifty if you ask me, and a whole lot easier than having to write your own code to spin up a bunch of worker threads.

May 26
C# 3.0 Automatic Property Gotcha
icon1 Darrell Mozingo | icon2 Quickie | icon4 May 26th, 2008| icon3No Comments »

One of the neat new features of C# 3.0 is the automatic properties syntax. It’s basically a quicker and simpler way to declare properties, as you don’t need to create a private backing object for each one as you’ve always had to. Here’s an example:

public class Person
{
	// Original way:
	private string _name;
	public string Name
	{
		get { return _name; }
		set { _name = value; }
	}
 
	// New, automatic property, way:
	public int Age { get; set; }
}

Using the second example, the compiler will basically create a private Age member in the background and use in the generated getter/setter of the new property. If it’s a numeric type, as Age is, it will default to 0. If it’s a reference type, such as another class or a Nullable type (i.e. int?), it’ll default to null.

Now for the semi-gotcha: strings are reference types, so they’ll default to null. This may not be a problem in your situation, but I personally like to default all of my string to string.Empty (unless the situation calls for a null, which I find isn’t very often). I just don’t like the hassle of dealing with null strings, though the string.IsNullOrEmpty() method helps mitigate that.

So there ya go. Take it for what it’s worth – something to keep in mind when using the new automatic property feature.

May 20
Cleveland Day of .NET Review
icon1 Darrell Mozingo | icon2 Reviews | icon4 May 20th, 2008| icon33 Comments »

Cleveland Day of .NETI attended the first annual Cleveland Day of .NET this past Saturday, the 17th. Other than a few Microsoft launch-type events, I’ve never attended an actual community get together like this before, so it was a new experience for me.

Do I think it was worth it, in terms of the time (7 AM to 6:30 PM on a Saturday with decent weather) and money (gas for a 100 mile round trip and lunch) invested? Well, lets take a look at each of the six presentations I attended and then at an overview of the whole event:

  1. Why Ruby?Joe O’Brien
    • Joe started off by saying this wouldn’t be a talk about specifics in Ruby or a 100 level intro, and he delivered on that. Instead, he focused on some neat features of Ruby that’d make a seasoned developer want to dabble with it and potentially jump ship. I’ve seen a bit of Ruby glancing through blogs and articles, and even wrote one or two very basic learning applications in it, so I was glad he skipped the syntax basics and instead focused on things such as catching missing methods and then relating that to O/RM and enterprise development uses.Ultimately, I thought this was a great talk. Joe was quite the funny presenter, kept me engaged the whole time, recovered very gracefully from a few presentation hiccups, showed some neat examples, and renewed my appetite for Ruby. It was a nice presentation to start out the day, for sure.
  2. Introduction to Test Driven Development with the ASP.NET MVC FrameworkAlan Stevens
    • Alan began with an intro to the ASP.NET MVC Framework and followed up with a few live coded unit tests. While I liked his presentation style (his excitement for this stuff was contagious), I wasn’t too impressed with the content. It was very solid information, but I had some higher expectations going in, and he only got around to doing basic unit tests to check the rendered view and such things. Nothing really new for me there, unfortunately, but it was still nice to hear the MVC architectural pattern explained from a different point of view.
  3. Software Ninjitsu: Designing for ChangeNate Kohari
    • Focusing on the foundation of object design – cohesion and coupling – then moving onto the basics of Inversion of Control (IoC) using his Dependency Injection (DI) framework, Ninject (which I’ve looked at before and is actually pretty neat), Nate delivered an awesome presentation. Admittedly his first large one, he handled a failing projector halfway through the presentation with ease, and the room was packed with standing room only. He touched briefly on a few other aspects of his framework such as Aspect Oriented Programming (AOP), but he stuck to the basics of IoC very well and presented them, at least I thought, in a very logical fashion. His gratuitous use of ninja references was actually pretty funny (although you couldn’t expect anything less with a session title like that) and was a nice change of pace.The only thing I would have liked to see was some more live code. He stuck to Power Point (or whatever the Mac equivalent he was using was) pretty good, though a bit of Visual Studio and bigger examples might have helped a bit, I think. Overall it was a great presentation though.
  4. Ouch, that hurt! Lessons Learned from an Agile ProjectMichael Eaton
    • I was looking forward to this session the most. My team is currently shifting into a RUP/Agile methodology (and actually had a nice 2 hour discussion on this the Friday before this event), so I asked Michael if I could tape the talk with the hopes of showing it to the rest of my team when I got back to work. It was a good talk, reminding everyone about the major pain points in project management: communication, buy-in, estimating, etc. Some were client specific while some were more common. It spurred some interesting discussion from the crowd though, and Michael’s slide deck was a pretty funny addition. Also, while I could also see where he was coming from in the talk, the fact that he concentrated on one single job as an example, out of the many I’m sure he’s worked on, made parts of the presentation seem like a rant instead being informational.Unfortunately, in the end the presentation wasn’t exactly what I’d thought it’d be. While we did hit a lot of common pain points, to me they weren’t really related to, or caused by, any particular Agile methodology. They were just general issues that most everyone – including my team – has dealt with in the past. Helpful to be sure, but I was looking for issues relating specifically to a flavor of Agile, such as TDD acceptance, short iteration deliverables, pair-programming acceptance, stand-up meeting issues, planning problems, etc.
  5. Data Access with NHibernateLen Smith
    • Len started off with a quick intro to O/RMs in general and why you’d want to use one, then jumped into talking about various aspects of NHibernate interlaced with live code examples. His examples were pretty decent, using unit tests as quick code harnesses to show off various features like batch queries, lazy loading, SQL query inspection, etc. Pretty standard stuff, and I thought he did a good job explaining it, along with answering a few questions that popped up through the session such as the ability to use NHibernate along side current data access code during a transition period (to which Len just suggested rewriting your data layer). Like Nate Kohari’s talk, he used a lot of pirate and ninja references which I thought was pretty cool.
  6. Intro to the IronPython Flying CircusSarah Dutkiewicz
    • Sarah began by making a case for Python then jumping right into some examples of IronPython, using gratuitous amounts of Monty Python references of course (Ni!). She showed a few basic features of Python and IronPython using the interactive command line tool, including how to use those little animated people from the Windows XP first install wizard. She did a really good job presenting a high-level overview of the features, I thought.

There’s a few other presentations that sounded really interesting and I would have loved to see, and in hindsight I should have floated between some of these sessions to get in a little more more material. I’ll have to keep that in mind for next time.

  1. Silverlight in ASP.NET John Stockton
  2. IronRuby, the DLR and Silverlight Carey Payette
  3. A Look at F# Amanda Laucher

Now, as for the event as a whole I’d have to give it a thumbs up. Everyone got a free, decent quality, tee-shirt upon sign-in, which was neat (standard logo + sponsors white tee). They were giving away books in nearly all the sessions for various reasons, and also gave out licenses to some nice software and an XBox 360 at the end, but I didn’t win anything 🙁

I met a few people there from the Akron area, though I wished I would have networked a bit more. As Michael Eaton put in his review, the small hallways and constant moving of hotel staff made it tough to talk to anyone between sessions.

Attending this event has also peaked my interested in presenting on a topic at some point, perhaps starting with one to my co-workers (though I sort of did one on Linq To SQL a while ago). I’d love to have something to present, and the ability to do it, at a future event like this.

Overall I thought the event was well worth the time and money invested (it being free and getting free swag sure helped). I met some nice people and picked up a lot of new information, and I’m looking forward to attending next year.

Too bad Cleveland is the nearest .NET user group, and they usually start at like 6 PM, as I’d love to attend a few of those but scheduling is usually too tuff. That’s why I’d like to get the ball rolling on the CantonALT.NET user group, so we can spark some local discussion and interest.

May 16

The strategy pattern is a way to inject algorithms into a chunk of code, or as I like to think of it, basically a way to refactor out multiple lines of code and pass them into a method. Let’s look at an example.

Say you have a method with some hard coded strings:

public string WrapWithSingleQuote(string text)
{
	return "'" + text + "'";
}

Now in your next iteration you’re asked to wrap any needed text in double quotes and/or parenthesis. Being the awesome developer that you are, you generalize the method like so:

public string WrapWithString(string text, string wrapper)
{
	return wrapper + text + wrapper;
}

See that? The wrapper parameter that allowed you to pass whatever you want to wrap the text in? That’s a simplistic and primitive example of the strategy pattern, but an example nonetheless. Now the method allows you to wrap the given text in whatever characters your heart desires.

Now for a bit more robust and real world example of the pattern. Let’s consider the .NET WinForm’s TextBox control. This control has auto-complete functionality built into it to, able to suggest completed entries based off the currently entered text from a variety of sources: file system, URL’s, a custom source, and more.

A few requirements come in stating that the users want auto-completion for the company text box in their mythical application, so you whip up the following user control:

public partial class CompanyFindTextBox : TextBox
{
	public CompanyFindTextBox()
	{
		InitializeComponent();
		this.AutoCompleteMode = AutoCompleteMode.Suggest;
		this.AutoCompleteSource = AutoCompleteSource.CustomSource;
	}
 
	public CompanyFindTextBox(IContainer container)
		: this()
	{
		container.Add(this);
	}
 
	protected override void OnKeyUp(KeyEventArgs e)
	{
		HandleAutoComplete(this.Text.Trim());
		base.OnKeyUp(e);
	}
 
	private void HandleAutoComplete(string searchText)
	{
		if(searchText != string.Empty)
		{
			using(DatabaseDataContext db = new DatabaseDataContext())
			{
				var matchingCompanies =
					from c in db.Companies
					where c.Name.ToUpper().StartsWith(searchText)
					orderby c.Name
					select c.Name;
 
				this.AutoCompleteCustomSource.AddRange(matchingCompanies.ToArray());
			}
		}
	}
}

Now, of course, the users want the same functionality on their job, candidate, contractor, and who knows what other text boxes. Looks like a refactoring is in order. Ah, but this time there isn’t a simple string to extract as a parameter to fix the problem! You need to generalize your LINQ statement, but each text box type is searching on different databases, fields, etc.

This where the power of the strategy pattern comes in. With it, you can tell the control/method how to go about executing a certain algorithm. Specifically, in C# we usually use delegates (which are nothing more than methods passed into other methods as parameters – or function points from lower level languages). Since C# 3.0 introduced lambdas (simply more concise ways to declare delegates), let’s go ahead and use those. Here’s a more generalized user control which uses the strategy pattern to pull out the specific database accessing code:

public partial class EntityFindTextBox : TextBox
{
	public Func AutoCompleteStrategy { get; set; }
 
	public EntityFindTextBox()
	{
		InitializeComponent();
		this.AutoCompleteMode = AutoCompleteMode.Suggest;
		this.AutoCompleteSource = AutoCompleteSource.CustomSource;
	}
 
	public EntityFindTextBox(IContainer container)
		: this()
	{
		container.Add(this);
	}
 
	protected override void OnKeyUp(KeyEventArgs e)
	{
		HandleAutoComplete(this.Text.Trim());
		base.OnKeyUp(e);
	}
 
	private void HandleAutoComplete(string searchText)
	{
		if(AutoCompleteStrategy != null && searchText != string.Empty)
		{
			this.AutoCompleteCustomSource.AddRange(AutoCompleteStrategy(searchText));
		}
	}
}

Notice how this implementation has a function property named AutoCompleteStrategy. This says we’re looking for a method that takes in a string and returns an array of strings. Now in the HandleAutoComplete method, we make sure this isn’t null and call it with the text box’s contents. This abstracts out the actual database searching algorithm so the new user control can be used with any type of entity the system needs, be it companies, jobs, contractors, etc. That’s the strategy pattern in all its glory.

After dropping the new control on a form, you might set it up for a company like so:

txtCompanies.AutoCompleteStrategy = (searchTerm =>
	{
		using(DatabaseDataContext db = new DatabaseDataContext())
		{
			var matchingCompanies =
				from c in db.Companies
				where c.Name.ToUpper().StartsWith(searchText)
				orderby c.Name
				select c.Name;
			return matchingCompanies.ToArray();
		}
	});

Now we’re setting the AutoCompleteStrategy property to a new lambda expression (think quick method declaration) that’s accepting a string parameter named searchTerm and using it in the same LINQ query from before, ultimately returning an array of company names which contain whatever was passed in. We could do this for a job text box just as easily, simply swapping out the LINQ statement for a new one (or even XML file searching, a web service call, whatever).

Simple enough, right?

May 9

The background

A Data Transfer Object (DTO) is a plain old CLR object (POCO) mainly used to pass data between tiers and remote calls. They’re basically classes with getters, setters, and perhaps a constructor or two, but no methods. They’re dumb objects that simply hold data.

So why would you use these? A few reasons:

  1. They flatten your data. DTO’s can contain information from a multitude of sources (database, XML, web service, etc) all neatly packaged together, including any large hierarchies of data from your relational (SQL) store.
  2. They more easily allow parameters to be passed into and out of methods, especially expensive ones like web services. You’re not forced to break a web service’s signature if you need to add/remove parameters if you pass in a DTO. The DTO can change and clients aren’t forced to immediately update. They also help keep method signatures nice and tidy.
  3. They help decouple your layers by remaining technology and location agnostic. If your relational data moves around, you simply have to modify your data layer (or your business layer if you’re passing DTO’s back for presentation reasons) to get the needed information. The consuming layer won’t care that the data is coming from somewhere else, they’re just looking at the DTO’s copy.

The setup

Let’s look at a simple scenario. We’re loading a business object and calling out to our data layer for the information, which we’ll get from SQL using LINQ to SQL. The following DTO will be passed back:

public class PersonDTO
{
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public int Age { get; set; }
	public decimal HourlyWage { get; set; }
}

The code

Let’s look at the GetPerson method from the data layer, which uses LINQ to SQL to retrieve the needed information from SQL:

public PersonDTO GetPerson(int personID)
{
	using(DatabaseDataContext db = new DatabaseDataContext())
	{
		return (from p in db.Peoples
			    join pw in db.PeopleWages on p.PersonID equals pw.PersonID
			    where p.PersonID == personID
			    select new PersonDTO
			    {
					FirstName = p.FirstName,
					LastName = p.LastName,
					Age = p.Age,
					HourlyWage = pw.HourlyWage
			    }
			   ).SingleOrDefault();
	}
}

The key bit is the select new PersonDTO and its four accompanying lines. It might look a bit odd, but it’s the new object initializer syntax added to C# 3.0. The compiler is basically creating a constructor in the background, taking in the specified parameters, and setting their respective property values.

This keeps your simple select methods such as this visually clean. No need to return a LINQ object and set each property in a separate call. OK, not a huge positive, but hey, it’s the small things that count. I personally love clean, slick, code.

Also note the SingleOrDefault() call at the end, which will return a single object from the LINQ statement (which in this case is of type PersonDTO) or a default value for that object if one isn’t found (and since we’re selecting a reference type, it’d return null). SingleOrDefault() will throw an exception if more than one record is returned from SQL, but since we’re looking for a primary key here, it shouldn’t be a problem.

As a side note, one of the neat features of Visual Studio 2008 is the IntelliSense’s ability to filter the already assigned properties within the object initializer portion of the LINQ statement. For instance, notice how it’s hiding the FirstName property in the pop-up since I assigned it in the line above:

IntelliSense filtering the available properites

To wrap up, here’s the CreatePerson method, on the Person object in the business layer, that would consume the above GetPerson method:

public Person CreatePerson(int personID)
{
	using(PersonDTO personDTO = DataLayer.GetPerson(personID))
	{
		return new Person
		{
			FirstName = personDTO.FirstName,
			LastName = personDTO.LastName,
			Age = personDTO.Age,
			HourlyWage = personDTO.HourlyWage
		};
	}
}

Notice how it too is making use of the new object initializer feature.