Code Samples

A quickie MySQL tip:

I’ve been working on creating a standard testbed of data (more on that someday) for one of our apps, and the issue of dates came up.  Dates can be a problem in test data if they’re being compared to today’s date, i.e. if it matters if the date field represents something in the past, present or future.

No problem, I thought, instead of setting something up with a string literal, like

date_field = "2008-03-04 12:00:00"

(Assume that’s inside an insert or update command…)

I’d build the string based on the current date, so a field would always be, say, 5 days in the future (assuming the testbed is repopulated daily through an automated job):

date_field = date(date_add(now(), interval 5 day)) + " 12:00:00"

That, as it turns out, doesn’t work so well.  (Oh, another quick tip, check your data after setting up a test suite before going nuts over where your code might be failing).  A quick, easy, and “should have done this in the first place” check reveals:

+-----------------------------------------------------+
| date(date_add(now(), interval 5 day)) + " 12:00:00" |
+-----------------------------------------------------+
|                                                2020 |
+-----------------------------------------------------+

I ended up going with something like this:

date_field = date_format(date_add(now(), interval 5 day), "%Y-%m-%d 12:00:00")

Much better…

Converting values from one type to another in C# is generally pretty straightforward: most objects contain a ToString() method which handles conversion to strings (at least for simple value types), and most value types have a Parse() method to read a string representation of their type.

Of course, dealing with invalid inputs can be a pain – the Parse() method will throw an FormatException if you, for example, pass “a zillion” to int.Parse(), so you need to wrap the code in a try/catch block:

   1:  int output = 0;
   2:  try
   3:  {
   4:      output = int.Parse("a zillion");
   5:  }
   6:  catch(FormatException)
   7:  {
   8:      // error handling goes here
   9:  }
  10:  Assert.AreEqual(0, output);

Version 2.0 of the .NET Framework made this a lot simpler with the addition of the TryParse() method:

   1:  int output;
   2:  int.TryParse("a zillion", out output);
   3:  Assert.AreEqual(0, output);

Note that it wasn’t necessary to initialize output here – if the call to TryParse fails, the output variable is set to 0. In the case of DateTime, the variable is set to DateTime.MinValue.)

Sadly, converting strings to Enums is still a pain, but doable – the try/catch concept still holds, but you need to watch out for ArgumentExceptions, and there are some casting and parameters to consider:

   1:  public enum Stuff
   2:  {
   3:      Something,
   4:      SomethingElse
   5:  }
   6:   
   7:  [Test]
   8:  public void EnumParsingTest()
   9:  {
  10:      Stuff output = Stuff.SomethingElse;
  11:      try
  12:      {
  13:          output = (Stuff) (Enum.Parse(typeof (Stuff), "Something"));
  14:      }
  15:      catch(ArgumentException)
  16:      {
  17:          // error handling
  18:      }
  19:      Assert.AreEqual(Stuff.Something, output);
  20:  }

C#, List.Find() and Predicates

by Jason on October 30, 2007 · 7 comments

Because I use this just infrequently enough to have to look it up every time…

I’m a huge (ab)user of the .NET generic collection classes, but I hate cluttering code with foreach() loops every time that I need to find an item in a collection. Enter the Find() method, which takes a predicate and does the work for you so you can keep focusing on the stuff that’s actually interesting:

List<SomeObject> myObjects = new List<SomeObject>();
/* .. load objects up somehow .. */
SomeObject desiredObject =
    myObjects.Find(delegate(SomeObject o) { return o.Id == desiredId; });