Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

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

Friday, March 20, 2009

Simple dependency Injector class

It is apparent in todays application development that complexity starts from when we typed the first line of code. Code complexity is one of the code horrors mutilating todays application development. To ensure that we work around these developments show stoppers, many design patterns and software development standards have been built to help come over this poor development approach.

Today we develop software with components in mind, we develop so that we can easily decouple our systems and make it a pluggable system.

Systems are very difficult to decouple when we do not use a strategic and standardized ways of separating component concerns. Over the years, the development and Object Oriented community have realized that there was a need to separate application concerns because of changing business cases and requirements.

As a software developer i have made it a culture to think of software as several functional modules that are independent from one and other but dependent on one and other via a plugable means.

The following code shows an example of code coupling :


public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

Person person = new Person();


There is nothing wrong with the code above really for a simple application. But for a very complex application, we tend to tight couple the Person class with the calling application. Let us assume the person class was imported from a web service proxy, that means our application is relying on the web service proxy for the Person Implementation. What then happens when we are not interested in web service proxy again but in another .dll that has its own Person implementation but with some extra fields and properties, do we start to refactor our code to comply with the new Person class? I bet that is not the easiest way ever.

Let us assume that person class now implements an interface IPerson. The following code depicts the kind of defination :


interface IPerson
{
string FirstName { get; set; }
string LastName { get; set; }
}

public class Person : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
}


Hmm, now that person have implemented an interface IPerson, then we could refer to IPerson all over our code, this is fairly decoupled until the very point where we really initialised the Person class, like the following :



IPerson person = new Person();

person.FirstName = "Ahmed";
person.LastName = "Salako";


now although we ahve succesfully initialised the Person class and because it implements the IPerson interface, we can assign it to the IPerson interface. Our code is still exposed to the point where we did new Person.


A simple Dependency Injector class

The following class will serve as a repository that knows about dependencies of our application :



public static class ModelFactory
{
private static IDictionary <Type, Type> repos = new Dictionary <Type, Type>();

static ModelFactory()
{
repos.Add(typeof(IPerson), typeof(Person));
}

public static T CreateInstance < T>()
{
Type value = repos[typeof(T)] as Type;
return (T)Activator.CreateInstance(value);
}

public static T AsInterface < T>(Type type)
{
Type value = repos.Where(t => t.Value == type).FirstOrDefault().Key;

return (T)Activator.CreateInstance(value);
}
}


So with the class above, we have successfully created a dependency repository class that knows about an interface and its implementations. Here is how to use the simple dependency repository class :



IPerson person = ModelFactory.CreateInstance < IPerson>();
person.FirstName = "Ahmed";
person.LastName = "Salako";



This leaves us very happy and with code decoupling.

Wednesday, September 3, 2008

Asynchronous State Machine Pattern. (The C# Way)

Experienced Software developers/programmers and architects enjoys separation of concern approach when building reusable components using the domain engineering practice.
We all understand that as part of separating application concerns, we need to ensure that our applications are purely decoupled away from dependencies and we need to ensure we properly inject those dependencies without coupling.

As we mature in decoupling our applications and components, we also must understand that, as part of dependency injection, we need to understand the underlying theories behind the publisher and subscriber pattern (Popularly known as fire and forget). Experience have shown that writing application without decoupling in mind is a way of creating problems for the nearer future, this approach is referred to conventional based application engineering. Most developers win and rush to market by launching an application that is very difficult to debug, an application that is overly designed , an application that is very tightly coupled and does not give room to changing and demanding business cases.

We can imagine two processes that handles heavy jobs (like handling about 50,000 calls in a day) coded in a more tightly coupled manner, these processes, by all standards, can handle their concerns differently without one waiting for the other to finish executing. In a service oriented architecture, where business processes are shipped/designed as web services/windows services, we need to carefully understand when to use an asynchronous call and a synchronous call, because of the load involved in processing a request.

Scenario 1
Let us all look at this simple analogy: We have a Business Process Services that handles our business processes like our internal/ and external business concerns. Our business process services comprises of the following functionality :
  1. Register new customer
  2. Register with payment gateway
  3. Send notifications
  4. make periodical payment
  5. Calculate due payment
  6. Daily status monitoring.
Before i go ahead talking more about our area of concern, i would like to introduce a simple architectural diagram of our case study, so that you can catch a glimpse of what big picture i have got in my mind. Here we go, architecture :

The architecture digram above, shows that our business process handles several business functionalities, so it wont be wise to do a synchronous call on our business service's. One of the scenario that we may need to use the separation of concern strategy i have been talking about is when we happen to be in the following scenario :

The daily processor runs.
The status functionality Begins.
The payment is calculated.
Notification is sent. (Based on status).

At the end of each business cycle processing, i mean, our business logic processing, the end task is to send a notification (email). If we have more than 40, 000 status checks, which in turn leads to thousands of business criteria to meet. I mean if we call the method in our service (CheckStatus()) 40, 000 times, a single call will invoke several operations, several operations will launch other legacy stuffs, other legacy stuffs will have their own custom built operations as well, we can see that for a single operations, the load on the Business service is very high, what about for 40, 000 operations. As we must remember, the process calling our business service is also tide with our service until the notifications is sent.

It would be very nice to tell our business process that a customer needs status checks, and thats all, we do not need to wait for our business process to tell us yes or no. All we are satisfied with is that we handled the call to business process. Then asynchronously, our business process will handle all the dirty work without locking its caller. So we now understand where to use asynchronous communication, let us diggit with code :


First of all we need to create the event argument that is raised when a status has been meet. Note* i wont be writing full code here, as readers are assumed to be an experienced developer.



public class StatuChangeEventArgs : EventArgs
{
CustomerState CustomerState{get; set;}

public StatuChangeEventArgs(Customer customer){ //Initialize here. }
}

public enum CustomerState
{
Stateless = 0,
CreditCardDetailsExpired = 100,
PaymentNotice = 200,
PaymentFailure = 300,
CanCalculateFirstPayment = 600,
PaymentChangeNotified = 1000,
DefaultState = Stateless,
}



The code above is the kinds of state that our customer can fall into, in our scenario. No let us see the State engine implementation : First how to we fire an event to our state handlers that need to consume the events and do other processing based on these event/state that was raised. We need a delegate at first :



public delegate void CustomerStateUpdate(object source, StatusChangeEventArgs eventArgs);



Now we have successfully defined our delegate that serve as the template of our event handler. Remember, we are handling different customer state asynchronously, that is, the application or service that send us the customer object will not know about our processing and it wont wait for results.

Now we need to implement the state Publisher, that is the class that scan a customer object, fire the CustomerStateChangeEvent, and also registers interested subscribers to the state event. Here is a simple structure :



public class CustomerStatePublisher
{
public event CustomerStateUpdate CustomerStateEvent;
StatuChangeEventArgs eventArgs;
Customer customer;

public CustomerStatePublisher(Customer customer, StatusChangeEventArgs eventArgs)
{
this.eventArgs = eventArgs;
this.customer = customer;
}

public void AddSubscriber(CustomerStateUpdate subscriber)
{
CustomerStateEvent += subscriber;
}

public void RemoveSubscriber(CustomerStateUpdate subscriber)
{
CustomerStateEvent -= subscriber;
}

public void OnCustomerStateChanged(CustomerState customerState)
{
//We are not processing stateless customer
if (customerState == CustomerState.Stateless)
return;

if (null != CustomerStateEvent)
{
eventArgs.CustomerState = customerState;

//CustomerStateEvent(this.customer, eventArgs);

Delegate[] customerStateHandlers = CustomerStateEvent.GetInvocationList();

foreach (Delegate handler in subscriptionStateHandlers)
{
CustomerStateUpdate eventHandler = (CustomerStateUpdate)handler;
eventHandler.BeginInvoke(this, eventArgs, new AsyncCallback(AsyncReturn), eventHandler);
}
}
}

private void AsyncReturn(IAsyncResult result)
{
CustomerStateUpdate eventHandler =
(CustomerStateUpdate)result.AsyncState;

eventHandler.EndInvoke(result);
}

public void ProcessCustomerState()
{
RaiseStateChangedEvent(customer.CanCalculateFirstPayment());
RaiseStateChangedEvent(customer.CanCreatePendingPayment());
RaiseStateChangedEvent(customer.CheckCreditCardState());
RaiseStateChangedEvent(customer.OweMoney());
}

public void RaiseStateChangedEvent(CustomerState customerState)
{
if (customerState != customerState.Stateless)
OnCustomerStateChanged(customerState);
}

}



The class structure above is very simple to understand, so i will just point out where the asynchronous functionality is our code. The OnCustomerStateChanged method of this class calls all the registered subscriber to this event asynchronously, by getting the invocation list from the CustomerStateEvent (CustomerStateEvent.GetInvocationList();) iterating through it and call the BeginInvoke asynchronously, at this point, in our real world implementation of this, we should just detach from our caller service, and allow the asynchronously operations to run.

Now, since we have fully defined our CustomerStatePublisher class, we need to fully understand how we are going to register subscribers, and how we will begin, processing of our asynchronous state machine. The following code describe how we will register a subscriber to the CustomerStatePublisher, and how we will begin state processing :




//Create an instance of the Customer StateChangeEvent
CustomerChangeEventArgs eventArgs = new CustomerChangeEventArgs();

//Create an instance of the customer state publisher
CustomerStatePublisher publisher = new CustomerStatePublisher(customer, eventArgs);


publisher.AddStateObserver(new CustomerStateUpdate(StateHandler.CalculateFirstPayment));
publisher.AddStateObserver(new CustomerStateUpdate(StateHandler.PendingPaymentChanged));
publisher.AddStateObserver(new CustomerStateUpdate(StateHandler.CreatePendingPayment));
publisher.AddStateObserver(new CustomerStateUpdate(StateHandler.TrialWillExpireNotification));
publisher.AddStateObserver(new CustomerStateUpdate(StateHandler.CreditCardExpiryNotification));
publisher.AddStateObserver(new CustomerStateUpdate(StateHandler.FreeServiceNotice));

publisher.ProcessState();



The rest of the code is to define the subscribers, that is the StateHandlers that handles the state based on the state it can handle. A simple example is an implementation of one of the state handler.



public void CustomerCreditCardExpire(object source, CustomerChangeEventArgs eventArgs)
{
if (eventArgs.CustomerState != CustomerState.CreditCardDetailsExpired)
return;

//Execute statebased functionality here.
}



Having done the following, when control hits the publisher.ProcessState(); method, the whole state processing begins and a befitted state handler is found, the publisher now delegate the handler to handle the state. I would require more suggestions from you all. Thanks.

Monday, September 1, 2008

Introducing .NET Throwable Pattern (The Exception By Contract Class).

If you are a Java developer, do not expect that i am referring to the Java Throwable class, which is the ultimate superclass for all errors and exceptions thrown by the JVM (Java Virtual Machine). I must confess that i love this name, and thats why i am sticking to it in .Net.

Most .NET application developers, architects, programmers etc understand fully well the use of the throw keyword. The throw keyword can be used to throw new exception in a catch block, it can also be used to throw the actual exception while still retaining the stack trace. I may need to explain with code :

Here is an example of the throw keyword :

1. Throw new Exception :


try
{

}
catch(Exception x)
{
throw x; or
throw new IamLovingItException("I am loving it", x);
}


The code above makes use of the throw keyword to throw a new exception different from the originally raised exception. This ignores the stack trace and creates a new exception to be thrown to the caller.

2. Just Throw.


try
{

}
catch(Exception ex)
{
throw;
}


The code above throws the same exception including the stack trace that was raised in the try ... catch block. Whatever situation you find yourself, using option one and two is good but not better, when we are dealing with a business focused application that makes use of throwing and handling of exception to communicate changes or business constraints to the caller application. An example of this will be AccountBlockedException, ZeroBalanceException, TransactionRolledBackException : There is no end to the ways we will be using custom exception handling.

A typical Scenairo. (Scenario One)

You have created a payment webservice (Lets say a WCF service) that serves as an abstraction layer over any kind of third party credit card vendors like PayPal, WorldPay, Nochex etc Our Payment webservice can be configured to use any type of payment gateway because it is very generic and open to extensibility.

Now, any thing can go wrong while processing payment or registring our card details via the Payment service abstraction layer. Lets assume we are trying to process £100 , and along the way, the real payment server shuts down, what do we do in this scenario :

Option 1: we throw the same exception that was thrown by the payment gateway
Option 2: we re-brand that exception and bake a new one from it.
Option 3: we handle that exception in our custom Payment service, and return status (As Enum), to our clients.

Think for a minute, which approach is best in our scenario. Even if the payment gateway did not throw an error, but return a status like Payment Failed to our custom Payment service, do we act upon that status and throw a new exception from there, but how do we act upon the status, the best bet may be to do :


if(paymentGateWayStatus == Status.PaymentFailed)
{
throw new PaymentFailedException("Failed");
}
else if(paymentGateWayStatus == Status.ServerShutDown)
{
throw new PaymentServerShutDownException("Shut Down");
}


There, we can go on and on until we have a very messy if statement with many throw exception block, we can even have this statements in almost all the methods implemented by our Payment service abstraction, if not all. What do we need to do in this case to reduce the amount of redundant code that we have?

I have got an excellent Idea. Why not let us create a pattern for this scenario, at least we are trying to avoid repeatability, we need to slve it with a pattern. To create a pattern, you must have been doing one thing for along time, before you realize that it is time consuming, and you would want to make it re-usable in code wide, applicatuion wide etc.

The New Throwable Pattern.

in our case, we need to create like a factory class called Throwable, this class has the abilities to check a boolean statement and decide on wether to throw an exception or not. This class can navigate through a switch statement to see which status matches the given status, and throw an exception from there. To go strat to the point, the throwable class is defined as follows :


public static class Throwable
{
public delegate bool Is();
private static void Throw(Exception exception)
{
throw exception;
}

public static void CauseThrow(T exception)
{
throw exception as Exception;
}

public static void ThrowWhenIsNull(object instance,string message)
{
if(null == instance)
throw Activator.CreateInstance(typeof(T), message) as Exception;
}

public static void CauseThrowOnTrue(Is anonymous, string details)
{
if (anonymous.Invoke())
throw Activator.CreateInstance(typeof(T), details) as Exception;
}

public static void CauseThrowOnTrue(bool status, string details)
{
if(status)
throw Activator.CreateInstance(typeof(T), details) as Exception;
}

public static void CauseThrowOnFalse(bool status, string details)
{
if (!status)
throw Activator.CreateInstance(typeof(T), details) as Exception;
}

public static void CauseThrowOnFalse(Is anonymous, string details)
{
if (!anonymous.Invoke())
throw Activator.CreateInstance(typeof(T), details) as Exception;
}

public static void CauseThrow(ResponseStatus status, string details)
{
switch (status)
{
case Status.ERROR:
Throw(new PaymentServerErrorException(details));
break;
case Status.INVALID:
Throw(new InvalidPaymentErrorException(details));
break;
case Status.MALFORMED:
Throw(new MalformedPaymentException(details));
break;
case Status.NOTAUTHED:
Throw(new AuthenticationException(details));
break;
case Status.REJECTED:
Throw(new PaymentServerErrorException(details));
break;
default:
return;
}
}
}


The above code is our Throwable class, and we can call the Throwable in our code as the following :


Throwable.CauseThrow(new CardException("Card is not valid"));

Throwable.CauseThrowOnFalse((status == Status.AUTHENTICATED), "Not AUTH");

Throwable.ThrowWhenIsNull(creditCard,"Invalid credit card");


Throwable.CauseThrow(status, "Testing");


We can see that the Throwable approach is more cleaner and reusable across. You can contribute more to the implementation because this is just a simple prototype .

Cheers and enjoy.

Command architecture and dependency injection

On a recent project, we were mapping commands to user intentions, covering all aspects pertaining to the usage of the application from the p...