beaucrawford.net

Give me data or give me death

About the author

Author Name is someone.
E-mail me Send mail

Recent comments

Don't show

Authors

Tags

Don't show

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2010

    Red Ring of Death Strikes Again

    Yesterday I wanted to let my brain discharge a little so I decided to fire up some Guitar Hero III on the XBox 360. I was seriously looking forward to playing a little "Wanted Dead or Alive" by Bon Jovi. To my dismay, I fired up my console and the screen froze. I shrugged it off and pressed the power button. On the next boot, I got nothing. Well, nothing except for three flashing red lights on the "Ring of Light" and an orange light on the power brick.

    Thankfully, I think I'm still within my warranty. Time to order a coffin. The weird part is that I haven't touched my 360 for a couple weeks. The last time I was playing it, all was well. That is definitely not the case today.  What changed between then and now?


    Categories: Gaming
    Posted by Beau on Friday, June 20, 2008 11:16 PM
    Permalink | Comments (0) | Post RSSRSS comment feed

    Dynamically creating an aspect using TypeBuilder

    In my last post I gave example of where you might want to dynamically create a type that implements a given interface.  Doing this is not extremely difficult but it took some digging around.  It is obviously going to involve the System.Reflection.Emit.ILGenerator class.  I am definitely not an IL guru but, with the use of Reflector, I can usually hack together what I need.  This post was close to what I wanted but it only worked for interfaces that contained properties and methods.  It did not handle indexers and event handlers.

    The most complicated piece of code involves adding IL that forwards a method call to an arbitrary method from the internal field in our “aspect”. 
    (Please note, for the sake of brevity, I have removed almost all error checking and Exception throws)


    private static MethodBuilder DefineMethod(MethodInfo methodInfo, TypeBuilder typeBuilder, FieldBuilder fieldBuilder, 
    Type objectType) { MethodAttributes attributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual; Type[] parameterTypes = methodInfo.GetParameters().Select(p => p.ParameterType).ToArray(); MethodBuilder methodBuilder = typeBuilder.DefineMethod ( methodInfo.Name, attributes, methodInfo.ReturnType, parameterTypes ); ILGenerator generator = methodBuilder.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, fieldBuilder); if (parameterTypes.Length > 0) { for (int i = 0; i < parameterTypes.Length; i++) { generator.Emit(OpCodes.Ldarg, i + 1); } } generator.EmitCall(OpCodes.Callvirt, methodInfo, null); generator.Emit(OpCodes.Ret); return methodBuilder; }


    Once we have this code in place we can then add code to dynamically forward calls for methods, properties, events, and indexers.  You should first know that properties, events, and indexers actually get compiled as methods.

    • Properites – get compiled with methods named get_PropertyName (if the property is readable) and set_PropertyName (if the property is writable)
    • Events – get compiled with two methods, namely add_EventName and remove_EventName (both always exist)
    • Indexers – are treated as a special property named “Item”, so they end up having get_Item and set_item properties.  More on this later.

    The fact that everything is actually a method greatly simplifies our code.  All we need is the respective MethodInfo instance, which we will then send to the above DefineMethod method.

    Events:

    private static void DefineEvents(Type objType, TypeBuilder typeBuilder, FieldBuilder fieldObj, Type interfaceType) 
    {
        foreach (EventInfo eventInfo in interfaceType.GetEvents()) 
        { 
            EventInfo existingEventInfo = objType.GetEvent(eventInfo.Name, BindingFlags.Public | BindingFlags.Instance); 
            
            EventBuilder eventBuilder = typeBuilder.DefineEvent(eventInfo.Name, EventAttributes.None, eventInfo.EventHandlerType); 
            
            MethodInfo eventAdd = objType.GetMethod("add_" + eventInfo.Name, BindingFlags.Public | BindingFlags.Instance); 
            
            MethodBuilder addMethod = DefineMethod(eventAdd, typeBuilder, fieldObj, objType); 
            
            eventBuilder.SetAddOnMethod(addMethod); 
            
            MethodInfo eventRemove = objType.GetMethod("remove_" + eventInfo.Name, BindingFlags.Public | BindingFlags.Instance); 
            
            MethodBuilder removeMethod = DefineMethod(eventRemove, typeBuilder, fieldObj, objType); 
            
            eventBuilder.SetRemoveOnMethod(removeMethod); 
        } 
    }

    So, here you can see that we are reaching into the Type for our internal field and grabbing the add_ and remove_ MethodInfo instances for each event handler.  From there we are simply injecting a method using our DefineMethod method that forwards the calls to our internal field.  If you were to actually type this code out it would look something like:

    public class MyClassAspect
    {    
        MyClass _field;     
    
        public event EventHandler MyEvent    
        {
            add { _field.MyEvent += value; }
            remove { _field.MyEvent -= value; }    
        }
    }

    Indexers:

    private static void DefineIndexer(PropertyInfo interfaceProperty, Type objectType, TypeBuilder typeBuilder, FieldBuilder fieldObj, 
    Type interfaceType) { Type[] parameterTypes = interfaceProperty.GetIndexParameters().Select(p => p.ParameterType).ToArray(); PropertyInfo existingProperty = objectType.GetProperty(interfaceProperty.Name, interfaceProperty.PropertyType, parameterTypes); PropertyBuilder propertyBuilder = typeBuilder.DefineProperty
    (
    interfaceProperty.Name,
    PropertyAttributes.None,
    interfaceProperty.PropertyType,
    parameterTypes
    ); if (interfaceProperty.CanRead) { MethodInfo getMethod = objectType.GetMethod("get_" + existingProperty.Name, parameterTypes); MethodBuilder getMethodBuilder = DefineMethod
    (
    getMethod,
    typeBuilder,
    fieldObj,
    objectType
    );


    propertyBuilder.SetGetMethod(getMethodBuilder); } if (interfaceProperty.CanWrite) { List<Type> setMethodParameters = new List<Type>(parameterTypes); setMethodParameters.Add(interfaceProperty.PropertyType); MethodInfo setMethod = objectType.GetMethod("set_" + existingProperty.Name, setMethodParameters.ToArray()); MethodBuilder setMethodBuilder = DefineMethod(setMethod, typeBuilder, fieldObj, objectType); propertyBuilder.SetSetMethod(setMethodBuilder); } }

    Forwarding the calls for indexers is similar to events except that the methods are prefixed get_ and set_.  Two things initially threw me for a loop here:

    • For indexers, the compiler adds a property named “Item”.  This means that you have methods name get_Item and set_Item. Interestingly enough, if you add your own property named “Item” to a class and then try to add an indexer you will get a compile error telling you that a property named “Item” already exists.
    • For the set_Item method, the compiler adds the incoming value as the last parameter of the method.  For example, although not very common, you can have indexers with multiple parameters.  An interface signature for one might look like:
    public interface IExample
    {
        string this[string x, Guid y, int z]    
        {
            get;
            set;    
        }
    }

    If you look at this interface in Reflector you will see that the compiler adds the Item property, along with the get_Item and set_Item methods:

     

    So, you can see the set_Item method actually has four parameters.  If you look in the above DefineIndexer method you will notice that I tack the indexer’s return type onto the parameter signature before attempting to reference the existing method in the internal field.  Another important note is that, for indexers, the compiler adds an instance of the System.Reflection.DefaultMemberAttribute attribute to the class to associate the default member with the Item property.

    Next time I will cover properties and methods, and provide the full code for the DynamicAspect class.


    Posted by beau on Monday, June 16, 2008 8:03 PM
    Permalink | Comments (0) | Post RSSRSS comment feed

    C# Wrapper classes for dependency injection

    Imagine you’re working on a Web application and you have a situation where you need to resolve a directory path relative to the application’s root.  Well, the System.Web.HttpServerUtility class obviously contains a method named MapPath that does this very thing.  So, you write some code that looks like this:

    public static void SomeMethod(HttpServerUtility server)
    {
    string path = server.MapPath("~/Some/Directory");


    // ...
    }

    The problem?  You have just made this method difficult to test outside the context of a Web application. What you really need is to allow the caller to inject their own implementation (dependency injection).  This would make things much easier to test. The bad news is that HttpServerUtility is actually the worst case scenario for this approach because:

    • It derives directly from System.Object – There is no base class (with, perhaps, an abstract MapPath method) that you could also derive from for testing purposes
    • It is sealed – You can’t derive from it and override the MapPath property for testing purposes (assuming it were virtual)
    • Its constructors are internal – You can’t create instances specifically for testing purposes
    • It does not implement any interfaces – If MapPath were a interface method you could create a new class for testing purposes and then implement the same interface

    (These items are why I chose to use this class for the above example)

    Some people might be quick to suggest using a delegate instead (or having the caller specify the directory path directly).  You could certainly do that but what if my method has many dependencies on HttpServerUtility?  I would either have to create a DTO (which would be used as the delegate’s return type) or you would have to perform a lot of setup work just to call my method.  In my experience it is usually the right call to abstract the dependency into an interface.  This provides limitless flexibility moving forward and allows for easy testing.

    The next approach is to define your own interface:

    public interface IHttpServerUtility
    {
    string MapPath(string virtualPath);
    }

    However, since you can obviously not apply this interface to the existing HttpServerUtility class, your only choice is to create a new class that provides an “aspect” around a instance of HttpServerUtility stored in a field (this is also known as "Duck Typing"):

    public class HttpServerUtilityAspect : IHttpServerUtility
    {
    public HttpServerUtilityAspect(HttpServerUtility serverUtility)
    {
    _serverUtility = serverUtility;
    }


    HttpServerUtility _serverUtility;



    public string MapPath(string virtualPath)
    {
    return _serverUtility.MapPath(virtualPath);
    }
    }

    This would allow you to both inject an actual instance of HttpServerUtility and to create a mock implementation (that implements the IHttpServerUtility interface) for testing purposes.

    This. admittedly, is a contrived example of a problem I encounter quite often – wanting to apply an interface to an existing class.  Why is it a common problem?  Well, because it should be if you are coding to an abstraction, not an implementation.  And, at least in C#, you should favor interfaces over base classes.  Creating simple wrapper classes that forward the property, event, indexer, and method calls to an internal field certainly works but they are a pain to write and maintain.  The solution to help you avoid having to manually create these types of classes?  Dynamically generate a Type that does it for you.   With this approach, you could create an instance of the wrapper class with a single line:

    IHttpServerUtility serverUtility = DynamicAspect.Create<IHttpServerUtility>(Server);

    Doing this is not extremely difficult but it does require a working knowledge of .NET Reflection and the System.Reflection.Emit.ILGenerator class.  More on that next time.


    Categories: C#
    Posted by beau on Monday, June 16, 2008 1:44 PM
    Permalink | Comments (0) | Post RSSRSS comment feed

    New Blog

    This is my new blog, which is powered by BlogEngine.NET .  I did not like any of the built-in themes so I am in the process of hacking my own together.

    I will be posting primarily about topics that deal with the Microsoft .NET Framework and programming in general.  Check back soon.


    Categories: General
    Posted by Beau on Sunday, June 15, 2008 1:32 PM
    Permalink | Comments (0) | Post RSSRSS comment feed