February06

Using a custom attribute to determine type at runtime

On a Windows Phone 7 project I am currently building I had a need to build a factory that instantiates different concrete classes depending upon an object at runtime.   I have a number of information feeds, that all have different classes built to actually go get their data.  One for RSS Feeds, one for Twitter, etc.  Each Feed has a property for the FeedType, this is the information needed to determine what class to instantiate at runtime.

I have written this pattern many times, but I ran across an interesting post on StackOverflow where Steven gave a different approach to solving this without the classic giant switch statement in the Create method.   I thought it was neat enough to use in my application and share here.

There are a couple of steps you have to take, but none of them are difficult.

  • Decorate your objects with a custom attribute
  • Build the object types using reflection
  • Implement your factory method

Custom Attribute

The attribute I added is called FeedTypeAttribute, I then add it to the concrete feed processor classes.

class FeedTypeAttribute : Attribute
{
private int _feedType;

public FeedTypeAttribute(int feedType)
{
_feedType = feedType;
}

public int FeedTypeId
{
get
{
return _feedType;
}
}
}

Adding the attribute to a class looks like the following.
 
[FeedTypeAttribute(1)]
public class StaticFeedProcessor : IFeedProcessor
{
public StaticFeedProcessor()
{

}

public void ProcessFeedModel(FeedModel feedModel)
{
throw new NotImplementedException();
}
}

Note that this class would be a FeedType of 1 in my data, but how do you determine what class that is during runtime?  The answer is reflection (and yes, this does work on Windows Phone 7).
 

Factory Method Using Custom Attributes

public class FeedProcessorFactory : IFeedProcessorFactory
{
private static Dictionary<int, Type> processorList = new Dictionary<int, Type>();

static FeedProcessorFactory()
{
// Get the types in this assembly that implement our custom attribute
var targetTypes = from type in Assembly.GetExecutingAssembly().GetTypes()
where type.CanBeTreatedAsType(typeof(IFeedProcessor))
where !type.IsAbstract && !type.IsInterface
let customAttributes = type.GetCustomAttributes( typeof(FeedTypeAttribute), false)
let attribute = customAttributes[0] as FeedTypeAttribute
select new { type, attribute.FeedTypeId };

processorList = targetTypes.ToDictionary(p => p.FeedTypeId, p => p.type);
}

public IFeedProcessor CreateProcessorByFeedType(int feedId)
{
Type feedType = processorList[feedId];

return Activator.CreateInstance(feedType) as IFeedProcessor;
}
}

The key here is the type.GetCustomAttributes() call.  The linq expression gets all the type of the current assembly where the type can be assigned from the IFeedProcessor class.  We have to ensure the class is not abstract or an interface, and then get the custom attributes. 

The let clause in the linq expression can be thought of like a local temporary variable.  Assigning the attributes to it, and then processing them in the final select.

Consuming the Factory

Consuming the factory is then as simple as instantiating a factory object and calling the CreateProcessorByFeedType function.  A fully allocated processor is returned ready to handle the feed.

// This is in my container object
private static IFeedProcessorFactory _feedProcessorFactory = new FeedProcessorFactory();


// This is in the function to process the feeds
IFeedProcessor processor = _feedProcessorFactory.CreateProcessorByFeedType(feed.FeedType);
processor.ProcessFeedModel(feed);

Less Coupling is Good

This code allows for the addition of new processor classes just by building the class and adding the custom attribute.  Of course you should check if the feedtype is not supported before trying to use the object (I omitted some code used for safety checking).
 
If a newer class is created in the future to replace a current one I only have to change the custom attribute to handle it.  No switch statements, or remembering to update a config somewhere.

February09

10 things to make your desktop database apps better

NOTE: This article was originally published on the VistaDB blog, but has been moved to this location permanently.

Each of these items could be a blog post unto themselves, but I am going to try really hard to not be too verbose and just cover the core of the concept and why you need to do it.

Data driven applications rely on their databases

Everyone knows that any app driven by data is much more than just the app.  In most cases the app without a database doesn’t even function, or fails to function properly.  If a database is an integral part of your application, then shouldn’t you be doing all you can to ensure it stays healthy and prepare for the worst case events of corruption or dead drives?

This week we have been contacted by 5 long time users who suddenly lost or corrupted their data.  Two of these were end user data that is going to cost a huge amount of labor to reproduce.  In all of these cases the following simple procedures would have prevented the situation entirely.

More...