Sunday, January 8, 2012

Beauty and the Beast


Days ago was navigating on web and met an old post from Ayende Rahien, the really cool challenge.
It was so cool, that decided to share it together with solution.

The basic idea is. Given the code provided in C#


public class Program
{
    private static void Main(string[] args)
    {
        CanThisHappen<MyFunnyType>();
    }

    public static void CanThisHappen<T>() where T : class, new()
    {
          var instnace = new T();
          Debug.Assert(instance!= null);
    }
}



What we can do in order to break this code. ?
In practice what we can do in order to make Assert work ?
Or, what we can do in order to make:  instance==null ???

Wow, it seems impossible, but it is not.
And here is the name of the Beast: ProxyAttribute

In practice it's enough to

1. Define special Proxy
2. Override in that Proxy class CreateInstance method, where we will return a null.
3. Derive our class from ContextBoundObject
4. Bind our custom Proxy to that class

Better to see how it works.


Here is special proxy:

 public class MyProxyAttribute : ProxyAttribute
 {
        public override MarshalByRefObject CreateInstance(Type serverType)
        {
          //  return base.CreateInstance(serverType);
            return null;
        }   
  }
 with an override of the CreateInstance object, where we return null.


Here we define MyFunnyType :

 [MyProxyAttribute]
 public class CustomServer : ContextBoundObject
 {
        public CustomServer()
        {
            Console.WriteLine("CustomServer Base Class constructor called");
        }
        public void HelloMethod(string str)
        {
            Console.WriteLine("HelloMethod of Server is invoked with message : " + str);
        }
  }

which derived from ContextBoundObject.

And that is. ! In this way we can intercept new() call on our type (MyFunnyType) and not only ! We can change return type of the constructor ! So no more the constructed object will be return , but the null, as we defined.

Excellent explanation on ContextBoundObject is here.

Real Beauty! Truly Beast !


Things I wish I would known 
 The absolute awesome talk of Rob Johnson, one of creators of  Spring framework.

 Talk about business in IT.

 Enjoy :)

Things-I-Wish-I-d-Known