Monthly Archives: May 2013

Get Value of Unknown Type From Unknown Object

In a previous post I mentioned a content management system I built for dynamically creating email content to notify users of events.  The system is delivered via a RESTful web service that is called from disparate websites and programs within our software ecosystem.  The basic requirement of the content builder is that those calling systems only need to provide a few key values.  From that information it can determine what database object to gather data from and what content templates to use for building the email notifications.

The design of the system rests on the Abstract Factory design pattern.  This allows the system to determine at run time what objects to create.  In doing this the system uses reflection in a number of ways, one I discussed in a previous post mentioned above.  Another I’m going to share in this post.

The system is passed an object which contains all the possible key fields needed to determine what data and content are needed.  Depending on which key fields are populated, the system will create the needed data objects and apply the correct rules and templates for constructing the template.

Example Class:

     
namespace Extensions
{
    public static class ObjectExtensions
    {
       public static T GetPropertyValue<T>(this object sourceObject, string key)
       {
         if (sourceObject.GetType().GetProperty(key) == null)
            return default(T);
         return (T)sourceObject.GetType().GetProperty(key).GetValue(sourceObject, null);
       }
    }
}

Explanation:

The class is static because I like to write these sort of methods as extensions.  I find them easier to use as a developer and really we just want to extend this method to any object.   The method returns the generic type T because we don’t know what type the property we’re looking up is until run time.

The method first checks to see if the property(key) being requested exists.  If  it does not we return the default value of the generic type.  In my system this works fine.  Returning a null for a string or a zero for an integer will net the same affect because it’s as good as it not being populated.  In other implementation you may want to throw an error here.

If the property exists then the value is returned to the caller it’s all done.  You might ask, what if the property they pass as the “key” does not have a type of “T”?  I contemplated that, one option could be to just return the default of the type T in that scenario.  Instead, I decided not to handle that and allow the .Net framework to bubble the error up to the caller and allow it to make a decision on what to do.  I’m not a big fan of validating methods are being called correctly in my logic layer or adding too much error handling.  If not done correctly errors can be masked from the calling program and hidden. Below are a few unit tests that show how the method works.

Unit Tests:

[TestClass]
public class ObjectExtensionsTests
{
   public class SourceObject
   {
      public int Id { get; set; }
      public string Ids { get; set; }
   }

   [TestMethod]
   public void ValueExistsAndIsReturned()
   {
      var s = new SourceObject {Id = 123456};
      Assert.AreEqual(123456, s.GetPropertyValue<int>( "Id"));
   }

  [TestMethod]
  public void ValueDoesNotExistsAndDefaultIntValueIsReturned()
  {
     var s = new SourceObject { Id = 123456 };
     Assert.AreEqual(0, s.GetPropertyValue<int>("Id2"));

  }

  [TestMethod]
  public void ValueDoesNotExistsAndDefaultStringValueIsReturned()
  {
     var s = new SourceObject { Ids = "123456" };
     Assert.AreEqual(null, s.GetPropertyValue<string>("Id2"));

  }

  [TestMethod]
  public void WrongTypeErrorReturned()
  {
    var error = false;
    try
    {
      var s = new SourceObject { Id = 123456 };
      Assert.AreEqual(null, s.GetPropertyValue<string>("Id"));
    }
    catch (Exception)
    {
       error = true;

    }
    Assert.AreEqual(true, error);

  }
}

There you have it. A simple extension method to get the value of an unknown property on an unknown object.

Advertisements

Why Is One 5K So Important

Do you have a race that always makes it on your race calender every year?  A race that you just can’t see a running season being complete without? Last year I wrote a blog post listing several favorites that I like to run.  On Sunday I ran one of these that has become my “must run” race.   This marked the sixth time I’ve run this particular 5k.  I run it every year, even when it’s not always convenient.   The race takes place right before the City’s Memorial Day parade and in the prior two years I even marched in the parade after running the race.  I was going to do the same thing this year, but a last minute change of heart kept me out of the parade.  But, not out of the race!

As 5ks go this is great race.  It’s a flat, fast, fun course.  Being right before the parade gives you an unusual amount of spectators to cheer you on.  And the flat course seems like an easy 5k, but there’s a twist.  The race is at noon at the end of May in Michigan.  So it gets pretty hot and can take a toll quick if your’re not prepared.  Additionally, the race is for a great cause.  Money raised is used to provide student-athletes from the local high schools with a scholarship.  I’m a huge believer in the importance athletics plays in the education system and in childhood development, I’m glad to be able to support it by participating in the race.

These are all great reasons to run this race.  However, they are not the reason this race has become so important to me.

For me, this race is personal.  It was seven years ago that I was setting up with my family to watch the parade when I saw the runners running the inaugural race.  I looked and thought, I bet I could do that.  And, the next year I did.  And from there I gained the confidence to run more races and longer distances until I was running half marathons.   At the time I didn’t even realize I was a runner.  But, running this 5k that first year gave me confidence to let myself become one.

You can see why the race is important to me and makes my race calendar each year.  But, it’s still not the exact reason this race was so important for me to run this year.  Even more so than the past five.

This year, I felt like I needed to remind myself that I was still a runner.  My running is nowhere near where it was a couple short years ago.  I’ve let things slid and have taken some huge steps backwards.  If I had to discribe my running over the last year I’d say I’ve been like a hamster.  Yes, for the obvious reason, most of my running has been done in the gym on the treadmill.  But, more than that, I’ve sort of caged it.  In that my runs have many times lacked meaning.  Just logging miles.  I’ve had a few workouts recently that felt different, more deliberate, but not yet where I want to be.

Given all that, I felt like I needed to draw a line.  That if I missed this race I may no longer be a runner.   So I did what runners do, I laced up my shoes and ran.  As usual, I had a great time.  Despite the fact that I may have logged the worse official 5k time I’ve had.  I ran it nearly three minutes slower than I had the last two years and almost two minutes slower then I had that first year in 2008.

Nevertheless,I’m glad I ran it.  I was disappointed, I thought I’d do a little better despite my lack of training.  But I finished and succeeded in reminding myself that I’m a runner.  And as runners know, you only get out of running what you put in!


%d bloggers like this: