Thursday, July 30, 2009

Generating PROXY from interfaces (Using Reflect Emit) : The flexible way to reduce code

Whats is a Proxy
A proxy is a class object, that acts as the original class type. Lets assume we have an interface ICustomer and we need to get implementations of this interface from different datasources (XML, flat file, soap object). Before we could assign data to the instance of this interface, we need a concrete type that implements the interface i.e XMLCustomer implements ICustomer . If what we need is to represents what is defined in the ICustomer interface, then we do not need the extra type XMLCustomer instead we will make a proxy from the interface, i can hear you say why, well, read on .....

I have been doing a lot of code reduction lately, in fact all my years as a software engineer, i have been seeking ways to make development a happy hour for myself and my peers. Tell you what, domain driven development is the future of wring software components that is fail prove, it is also the future that will bring us closer to the market place.

Interface is a very powerful programming construct which reduces dependencies between applications and components. With interface, your code is not far away from TDD (Test Driven Development) and you can test first before writing any code. So if we want to write a code that is targeted at the future, we need to focus on interface.

Much blabbing, how do i generate proxy from interface

Here, i will be revealing some powers of the Reflection.Emit namespace of the .NET framework. Using components/classes of this namespace, will allow you to programmatically examine types and creating code at runtime, what we are going to do in this section is runtime code injection and code generation.

Now back to our ICustomer interface, let us assume the class definition is as follows :


public interface ICustomer
{
string FirstName {get; set;}
string LastName {get; set;}
}


Yep, the example above is very simple, we will use this in our PROXY generation pattern. Did i just here you say where is the class that will implement this interface, nope is the answer, there is none for today because we are trying to avoid more code.

Now The PROXY Maker

We would like to do something like the following :


ICustomer customer = PROXY.CreateProxy();


yep, this is cool, we do not have an implementation class, but our proxy maker creates one for us behind the scene while examining the structure of the interface ICustomer.


public class PROXY
{
internal const string VIRTUAL_ASSEMBLY_NAME = "our.proxy.us";
const string version = "1.0.0.0";

static AssemblyName assemblyName;
static ModuleBuilder moduleBuilder;

static AssemblyBuilder assembly;
static AppDomain curAppDomain;
static IDictionary cache;

static PROXY()
{
assemblyName = new AssemblyName(VIRTUAL_ASSEMBLY_NAME);
assemblyName.Version = new Version(version);
curAppDomain = Thread.GetDomain();
assembly = curAppDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
moduleBuilder = assembly.DefineDynamicModule(VIRTUAL_ASSEMBLY_NAME);
cache = new Dictionary();
}

private static ModuleBuilder ModuleBuilder
{
get { return moduleBuilder; }
}

public static T CreateProxy()
{
if (!cache.ContainsKey(typeof(T).Name))
{
TypeBuilder proxy = PROXY.ModuleBuilder.DefineType(typeof(T).Name, TypeAttributes.Class | TypeAttributes.Public, typeof(Object), new[] { typeof(T) });
proxy = Emit(proxy);
Type type = proxy.CreateType();
cache.Add(typeof(T).Name, type);

return (T)Activator.CreateInstance(type);
}
return (T)Activator.CreateInstance(cache[typeof(T).Name]);
}

private static TypeBuilder Emit(TypeBuilder proxy)
{
foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
{
FieldBuilder field = proxy.DefineField(string.Concat("_", propertyInfo.Name), propertyInfo.PropertyType, FieldAttributes.Public);
PropertyBuilder propertyBuilder = proxy.DefineProperty(propertyInfo.Name, PropertyAttributes.HasDefault, propertyInfo.PropertyType, new[] { propertyInfo.PropertyType });

if (propertyInfo.CanWrite)
{
MethodBuilder setMethod = proxy.DefineMethod("set_" + propertyInfo.Name, MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.HasThis, null, new[] { propertyInfo.PropertyType });
GenerateSetMethodBody(field, setMethod.GetILGenerator());
propertyBuilder.SetSetMethod(setMethod);
}

if (propertyInfo.CanRead)
{
MethodBuilder getMethod = proxy.DefineMethod("get_" + propertyInfo.Name, MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.HasThis, propertyInfo.PropertyType, Type.EmptyTypes);
GenerateGetMethodBody(field, getMethod.GetILGenerator());
propertyBuilder.SetGetMethod(getMethod);
}
}

return proxy;
}

private static void GenerateSetMethodBody(FieldBuilder field, ILGenerator iLGenerator)
{
iLGenerator.Emit(OpCodes.Nop);
iLGenerator.Emit(OpCodes.Ldarg_0);
iLGenerator.Emit(OpCodes.Ldarg_1);
iLGenerator.Emit(OpCodes.Stfld, field);
iLGenerator.Emit(OpCodes.Ret);
}

private static void GenerateGetMethodBody(FieldBuilder field, ILGenerator iLGenerator)
{
iLGenerator.Emit(OpCodes.Nop);
iLGenerator.Emit(OpCodes.Ldarg_0);
iLGenerator.Emit(OpCodes.Ldfld, field);
iLGenerator.Emit(OpCodes.Ret);
}
}


Now the deed has be done. We have the proxy class above using the Reflection.Emit, to emit code at runtime for our interface properties. For each properties defined in the interface, a method body is created for it in the proxy class

Sunday, July 26, 2009

Chartered Me (The Hallmark of my commitment to IT)

I received the Chartered IT Professional Status award from The British Computer Society. The award is part of professional achievement that gives satisfaction in your career, and a re-assurance that you are doing the right thing and keeping yourself up-to date on current trends in your area of expertise. There are many of these awards, but the CITP award stand for the Gold standard for a true IT professional.

A professional without a clue of where he/she will belong in years to come is wasting time and awaiting to become obsolete which will lead to their inability to keep up with the pace in technological advancements. There are gains in career developments (Learning new things), and setting achievable goals yearly. There are gains in standing out from the crowd.

The IT industry have suffered from lack of professionalism in the past, this then lead to many failures in IT projects and over budget, because of poor project management, outdated software tools and platform, and of course, obsolete people working on the project. In this current economic climate condition, the last thing an organization would like to face is failing and over budget projects. Some projects do fail because most people are obsolete and they have been blinded by daily routines that they cannot see the advancement in the technology world and how these advancements will help shape their businesses. Most don't even understand their business.

There is now a chance for likely minded, to share their experiences and the pros and cons in using the following paradigms:
  1. project management,
  2. development standards,
  3. risk assessment,
  4. software quality assurance,
  5. software measurement and
  6. agile system.

An organization that is doing the right thing will have to bring together as a single component, the listed practices above (Although i agree that there are many more but for brevity we will mention just few).

Why Professional Membership is Good?
Like Accountants, Surveyor, Engineers, professional membership and status is an achievement that tells about your competence and your interest in developing your career. The best place to get the latest information in your profession will be through the membership of your profession. There are many professional bodies out there and The British Computer Society is just one of them which i am proud to be a member.

You have the opportunity to meet people of like minds. For example i am an Open source developer and also an advance software engineer my professional body will present me with people of like minds that we can discuss and help ourselves in emerging trends in technology. This will peer you with people around the world and you will be the first to know the latest gist in town.

Continuing Professional Development (CPD)
Being a member of a professional body will enable you to learn from experience. You will tailor your career progression with what new thing you have to learn. In this fast paced technological driven world continuous development should be an attribute that enable you become a respected and true IT professional. Then you can measure yourself/skill sets against an SFIA level (The Skill Framework For Information Age). This will tell you were you are at the moment and areas you have to work on to get to the next level.

It will enable you and your organization to see beyond your company alone and keep you at the edge in this competitive market.

Is IT so polluted that we need a professional body?
well, some section of IT is overly polluted that we need measures in our industry to stop these pollution. Just like a doctor, you cannot be a newly graduate doctor and be given a chance to perform surgery, you need to be validated in so ways (Medical schools and year of experience) before you are given a chance.

In IT anybody can write a piece of program so far it works but not everybody will write a program that will conform to best practices etc. Anybody can manage a project because they feel project management is just overseeing (This is wrong). An IT project manager should have been an enthusiast software developer that will enable such person to strike a balance between delivering quality products and conforming to standards in our industry.