Showing posts with label ahmed salako. Show all posts
Showing posts with label ahmed salako. Show all posts

Friday, January 14, 2011

Demystifying Drag and Drop in ASP.NET (Part 1)

This is not particularly and fully related to ASP.NET but the main project which I extracted this concept from is an asp.net project, so I have decided to present an asp.net example.

As a requirement for one of my pet projects, I am required to create drag and drop event handler on an scheduler/events calendar. This threw me into the dark side of javascripting, ASP.NET ICallBackEvent interface, post back/viewstate dodging.

I searched the web for an existing solutions that will enable me drag events memo from a date to another date using JavaScript. Most of the approaches that I encountered are either too complex or overly complicated for the simple scenario

Then I stumbled on this particular script at Web Tool kit which blew my mind away, this JavaScript particularly simplifies the cross browsers headache when trying to handle mouse events across browsers. And its simple object oriented approach to handling and delegating event for drag and drop is just fantastic.

Then something happened
I was looking for a solution that will enable me to drag an event from one data point to another. The solution i am talking about above though perfect but it has not fulfilled the entire drag and drop functionality. I can drag and drop, but when droping, the element being dragged should be attached to the object in the drop zones.

For clarity, try the drag drop sample below. Please note that the two drop zones can allow drag gable elements to be dropped upon them, and that you cannot drop items outside of the drop zones. To give a clear comparison then try the example given in the original script, located here , then you can understand the concepts of drop zones and drop targeting.
















Drop Zone 1 Drop Zone 2 Collection Area




Draggable 1




Draggable 2





The above drag and drop simulates the drop zone functionality which allows drag able elements to be dropped into the zones without hassles.

The missing points in original JavaScript, is the fact that drop zones are not recognized. I will take you bit by bit into how I have improved and added new functionality to the original code :

Identifying the container

The container element for this page example is a table with id = 'main'. A container is an HTML element which will contain the drop zones, note, any html which can contain other elements (p, div, table li etc.)element within the body section of an HTML document can be used as a container. This example makes use of a table as the container.


<table id="main" cellpadding="6" cellspacing="6" border="1">
<thead>
<tr class="style1">
<th class="style1" valign="top"> Drop Zone 1 </th>
<th class="style1" valign="top"> Drop Zone 2 </th>
<th class="style1" valign="top"> Collection Area </th>
</tr>
</thead>
<tbody>
<tr>
<td class="zone">

</td>
<td class="zone">


</td>
<td class="zone">
<div id="dragable1" class="element-class">
<h3 class="box-head">Draggable 1 </h3>
</div>

<div id="dragable2" class="element-class">
<h3 class="box-head">Draggable 2 </h3>
</div>
<span id="writtable">

</span>
</td>
</tr>
</tbody>

</table>


Some table cells within the table main's table row have the class name zone identifying them as the drop zones. Any element with the class name = "zone" can contain draggables.

Any element can also be dragged (except td, th etc. ), so far they are registered using the following javascript snippet.


DragHandler.attach(document.getElementById('dragable element'));


Registering/Preparing the Container and Drag able objects
We needed to look up the DOM and hook events on the drag gable's and retain drop zones into a Position object created below.


var zonesArray = new Array();
var index = 0;

window.onload = function () {

var dragable1 = DragHandler.attach(document.getElementById('dragable1'));
var dragable2 = DragHandler.attach(document.getElementById('dragable2'));

var main = document.getElementById('main');

for (var j = 0; j < main.childNodes.length; j++) {

PrepareDropZones(main.childNodes[j], zonesArray, "zone");
}
}


function Position(element) {
this.X = findPosX(element);
this.Y = findPosY(element);
this.Element = element;
this.Width = (this.X + element.offsetWidth);
this.Height = (this.Y + element.offsetHeight);

this.IsInCordinate = function (XCord, YCord) {
if (XCord > this.X && XCord < (this.Width) && YCord > this.Y && YCord < (this.Height)) {
return true;
}

return false;
}
}


The above code is the missing point in the original code, and the part where elements are dropped. As soon as an element is dropped, the mouse coordinates X and Y are checked against the drop zones X + width and Y + height , if the mouse is within coordinate, then the element is dropped. Shown below is the code for checking drop zones when an element is dropped.


// private method. Stop drag process.
_dragEnd: function (e) {
var oElem = DragHandler._oElem;

var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);

oElem.dragEnd(oElem, x, y);

var evt = e || window.event;
var evtTarget = evt.target || evt.srcElement;

for (var i = 0; i < zonesArray.length; i++) {

var dZone = zonesArray[i];
var cursor = getMousePosition(e);

if (dZone.IsInCordinate(cursor.x, cursor.y)) {
dZone.Element.appendChild(oElem);
oElem.style.left = 0;
oElem.style.top = 0;
break;
}
else {
oElem.style.left = DragHandler._beginX;
oElem.style.top = DragHandler._beginY;
}
}

document.onmousemove = null;
document.onmouseup = null;
DragHandler._oElem = null;
oElem = null;
}


Download the source code (VS 2010):

Tuesday, December 15, 2009

Consume RestFul Service as Object using WCF.


As an enterprise software engineer, i deal with disparate systems. I deal with several impedance mismatches between these systems, i built several integration components to glue these systems together. Many of these systems have its domain semantics (They speak different languages ), my daily work life activities is to build abstractions over semantics of different and disparate systems. I am one of those software engineers that believe in domain engineering paradigm , separation of concerns (A dog is a dog not a dogcat) , inversion of control e.t.c I enjoy spending time on a solution to see how it could be done better.My daily work is so challenging that bringing systems together from multiple domain is my strength and i have used aspect orientation to my advantage.

Recently, i entered a problem, we have an application that exposes objects as pure xml , the application supports soap 11 . The soap envelope does not have an action (Simply put in in WCF terms, it does not have an OperationContract , so when you consume this service, there is no web service operations to call on it ), This application only accepts pure XML as request and returns xml as response.

This is chaos, i know some hackers would say there is no biggy here, just construct an string as xml, send it over to the REST service and get the response as string and use linq or manually tranverse the string and construct an object from it. Wao! this indeeed is a hacky packy solution (Forgive me hackers brothers, i do not intend to cross the line). We are now in the world of objects, things have changed, newer platforms have emerged.

The diagram above speaks more of my scenarios, XML input and XML output using the good old REST Service approach. How am i suppose to translate these XML returned as string into object , how does WCF Channel Factories come into play with these. Keep focus, i will explain how i did the magic ...

First : Call the service from web browser , or get the schema of all the objects returned by the service. I chose the first option for my scenario as there was no schema, so what did i do, i called the web service from a browser , saved it as anything.xml , then i opened visual studio command prompt , ran the XSD.EXE command using the following parameters :

xsd anything.xml /outputdir:mydir



The command above, generates the schema from the xml which i saved from the browser called anything.xml. Now that i have my .xsd file handy, i can generate a .net class using the same xsd.exe command but with different parameters. Thats the price to pay.

Now i have anything.xsd in my output directory , i would like to generate .net classes using the follwoing command :

xsd /c anything.xsd

This generates C# classes for me. Now i am equiped with the object representations of the XML that the REST service sends to my consuming applications.

Second : How do i send request and recieve response from the REST Service ?

To do this, you would need to understand how to use low level WCF communication classes to send soap messages back and fort. First i want to have a mechanism that will enable me to serialize and de-serialize my soap messages Request messages : The following is an example request object :

Sample XML Request

<hellorest>
<message>Get Hello world </message>
</hellorest>

Now that we have carefully reviewed the generated c-sharp class we can proceed to creating the request object. Since we have the request xml above, we will have to hand code this as a c-sharp class. Using the good old System.Xml.Serialization namespace, we would decorate our request class with xml attributes for pure serialization. Here is our sample request object and a Serialization method :


[XmlRoot( "hellorest" )]
public class RESTWebRequest
{
[XmlElement( "Message" )]
public string Message
{
get;
set;
}

public RESTWebRequest( )
{

}

public XmlElement SoapSerialization( )
{
XmlSerializer serializer = new XmlSerializer( typeof( RESTWebRequest ) );
StringWriter writer = new StringWriter( );

serializer.Serialize( writer , this );

XmlDocument xmlDocument = new XmlDocument( );
xmlDocument.Load( new StringReader( writer.ToString( ) ) );

return xmlDocument.DocumentElement;
}
}


Having done that, we are ready to use the communication classes within WCF from the lower level to send our request object and receive our response as object too. To do this, we need to understand the following classes with the System.ServiceModel namespace :

1. Message : Wraps the request/response in a soap envelope.
2. BasicHttpBinding : Communication ensured via HTTP .
3. IRequestChannel
4. IChannelFactory

The listed interfaces and classes would be used to send and recieve , serialize and de-serialize soap messages. Now the long awaited class, the RestAgent which will be used to send and recieve messages is defined below :





internal class RESTAgent : IDisposable
{
IChannelFactory channel;

internal string EndPoint { get; set; }

internal RESTAgent( string EndPoint )
{
BasicHttpBinding basicHttpBinding = new BasicHttpBinding( );
basicHttpBinding.MaxReceivedMessageSize = 1000;
this.EndPoint = EndPoint;

channel = basicHttpBinding.BuildChannelFactory
(
new BindingParameterCollection( )
);

channel.Open( );
}

internal GeneratedFromXSD GetResponset( RESTWebRequest webRequest )
{
Message requestMessage = CreateIncomingMessage( webRequest );
IRequestChannel requestChannel = GetRequestChannel( );

requestChannel.Open( );

//Hey. time out here is ugly.
Message responseMessage = requestChannel.Request( requestMessage , new TimeSpan( 1 , 20 , 00 ) ); //1 hour

requestMessage.Close( );

GeneratedFromXSD anything = DeserializeXMLStream( GetMessageContent( responseMessage ) );

responseMessage.Close( );

return anything;
}

private GeneratedFromXSD DeserializeXMLStream( string xmlStream )
{
XmlSerializer serializer = new XmlSerializer( typeof( GeneratedFromXSD ) );

return ( GeneratedFromXSD ) serializer.Deserialize( new StringReader( xmlStream ) );
}

private string GetMessageContent( Message message )
{
XmlDictionaryReader xmlReader = message.GetReaderAtBodyContents( );

return xmlReader.ReadInnerXml( );
}

private System.ServiceModel.Channels.Message CreateIncomingMessage( RESTWebRequest request )
{
XmlNodeReader reader = new XmlNodeReader( request.SoapSerialization( ) );
return Message.CreateMessage( MessageVersion.Soap11 , "" , reader ); //Give us the real thing. Wrap up with soap envelope without a specific action = ""
}

private IRequestChannel GetRequestChannel()
{
return channel.CreateChannel( new EndpointAddress( EndPoint ) );
}

public void Dispose( )
{
channel.Close( );
}
}


You can use the RESTAgent class to send and recieve soap message from our Restful service by using the follwoing :



RESTWebRequest request = new RESTWebRequest();
request.Message = "Hello world";

RESTAgent agent = new RESTAgent( "http://localhost/restapi" ); //Parameter is the endpoint address

GeneratedFromXSD anything = agent. GetResponset( request );

Wednesday, November 11, 2009

Google is Ready to "GO"

There is a new addition to the Object Object Oriented programming platform , codenamed GO (A new addition and descendant of the C family) by Google. It is said to take advantages of new trends in the software versus hardware community. Go will take advantage of dynamic languages like python, it is said to have an efficient Garbage collection, runtime speed close to C language and full support for multi-core processor from ground up.

Go is blessed with true closures and reflection (Programmers delight to extending the framework). The reasons behind the introduction of GO is that the older languages have failed to include current computing trends like fast programming, expressiveness (Functional), multi-processors, true closures . I personally love the idea of methods/functions returning multiple values. Although i struggle with the return type after the method parameter.

Is Go the future that we all want?

The problems claimed to be solved by Go is already taken care of by mature object oriented programming languages. Go should not be seen as a replacement for C# or Java etc but a language introduced specifically to solve specific computing problems. C# is still in its infants and we have experienced more powerful programming concepts and constructs that Go claims to be a silver bullet for.
Dynamic language integration is already a number one citizen of todays languages, Java has the Rhino (Integrates with JavaScript), and C# 4.0 is coming with the dynamic keyword to solve Com inter op problems and integration with more dynamic language. .NET is a platform that cannot just be thrown away, because it already blends with todays problems and it is constantly being updated to support features required to develop todays application.

What does programmers want?
We want a unified programming platform, we would like to see all object oriented programming languages to have very easy integration and it is not wise to introduce new language to address specific problems. If you are a system integrator and an advance developer, you would realize that bringing platforms together is more fury. We would love to see a bridge across platforms, enough of this chaos.

Will Go Make it?
well, it is still experimental and we are all allowed to contribute to it because its completely free. Go still have a lot of hurdles to pass through like every other new language, it will survive most of this hurdle but if it is focused on the right direction. I personally does not see it as a replacement for any of the more matured and advanced languages.
Share your views. and Go for Go here.

Monday, September 14, 2009

Software Development Can be Green Too. (Part 1)

The new wave in our industry "GREEN IT" , is rapidly becoming the IT buzz of the moment. Almost anything you do in computing nowadays needs to under go the green scrutiny. In other to cut cost and save our ecosystem. Recently i went on a computer gadget parade at Soho (down town London west-end), i noticed a gadget that i loved, asked for the price, the store assistant had to check records to confirm the new price is not different from the one on the sticker. I asked why they could not use an electronic price indicator, he answered : "We want to be green".

Most people, organization and professionals read meanings to the definition of "GREEN Computing" just like any other computing phrase and jargon, it can mean differently when used in different context. We need to exercise caution when we form our own theories around the "GREEN Computing" word, because wanting to be green should not mean you would disregard what is efficient over what is not. Because you need to be green does not mean you would not provide your customers, staffs with what will make life easier in the workplace and as a product.

Nowadays, every organizations (large and small) are going into green computing foray to utilize resources and energy. The green aspect is to ensure that, there is adequate resources and that project leads/managers/technical leads/architects/business analysts proactively utilizes what is left of them in a cost effective way. Green must ensure resources are maximized and reused accordingly during project development.

What exactly is "GREEN" Computing or IT

Green IT is a computer word that favors efficient production/use of computer resources without any dangerous impacts on our environment. It also mean cutting cost on what we can reuse (It favors Re usability over Recycle - New ). Most computing resources consume a great deal of energy and the cost run into millions to maintain yearly, if we try to be green we can save a lot on environment and cost.

Is That all. No! "GREEN IT" also means

We change our practices, we obey our ethical responsibilities to the society at large. We need to be green before encouraging it. (For example i am green about my spending habbit).

Cloud Computing will take us to the greener pastures

With the Internet becoming so powerful and broadband s are becoming cheaper everyday. It is now wise to take big advantage of the next revolution of our industry, the cloud. Although i can always argue that we are already in the cloud era, right from the 50s and early 60s when the US military used Internet to boost their military operations, and since then, the skies have become the limit, we have experienced the advancing Internet revolution, and within the same era, here come the cloud.

More development should be targeted at the cloud, their is a green advantage on the usage of software systems over the wire compared to conventional run from local system. This approach will reduce cost of installations, cost per head of users and of course the cost of maintaining a server will be taken of you and it will be the responsibilities of the cloud provider. In short cloud computing will take us to the greener pastures.

Now we need GREEN Software Development

Computer hardware does not exist alone, they are produced to complement and supplement the software written by us. You may start to think, that if hardware is useless without a software, that means the software itself consumes resources from the hardware, and the more resources a software consumes the higher the rate of electricity, network packets that the hardware will be forced to use.

To be greener in development, we should try to write code that can be reused across our application domain. We should try and employ domain driven engineering principles (Most organizations write the same code over again because they could not define their domain).

Software as an assets, if you define your domain well, and everything you need are in place and you have a catalogs of domain artifacts assets, this mean your organization is practicing green development.

Get experienced developers to influence the in-experience one, make awareness about the importance of modularizing your components. Use AOP (Aspect Oriented Programming) like you have never done before.

We need to embrace greener coding styles, which will include more focus on software performance, the exploitation of multi threaded and parallel computing. We need to retrain and ensure that software development standards are used to build software and not just delivering crappy software. If we want to be greener in software development approaches, then we have to imbibe the culture of using standards. This will take us back to the days scarce hardware resources.

Green Coding Standards

1. If you are building large tree structure of objects which requires recursion or the visitor pattern, then you will need to cache your output to by pass the same recursion when you require the same output. A slower system makes use of resources.

2. Use design patterns effortlessly. A pragmatic developer would appreciate that common and recurring problems can be solved using a library of knowledge. It is wise for software houses to document that knowledge.

3. Agile developers believes that TDD (Test Driven Development), when practiced to its fullest represents the full specification of a software. In fact TDD believes that tests are the documentation, I am also a strong believer of this. If you make use of scenario based TDD, you will understand that TDD can cover all aspects of your application. If TDD can represent your documentation, why write another bogus documentation wasting paper resources, and re-writing such documentation when something simple changes in own code.

4. Make use of Code Generators, ORM facilities, this will bring you very close to the market place. They are an existing strategies proven to be successful, and reduces code bloat. A good one is this : Rapid Entity Framework.

5. Use Open source : Open source will make you greener and there is no hidden cost the software is completely free to distribute. Open source projects are delivered on time and patches are made on time.

6. Ensure your program does not have bottlenecks. Ensure your code does not take long to achieve its aspect.

7. Be performance aware, an application that consumes resources alot consumes electricity, and so therefore such applications are not green.

We cannot help it, we only develop what works.

Many developers, especially those who are much more around in IT industry today, are more focused on getting faster to the market and during the process, they end up with a product that misses its deadline, a product that is fragile and breaks down every hour, an un-maintainable code base. I can hear some developers already throwing blames at their managers for not allowing them to follow industry standards before software is delivered. Well some managers do not understand (Make them understand and let them know its importance), some managers do understand but their superiors do not understand. These are the problems that IT is facing today.

If we keep focusing on hardware alone in other to be green, then we are half way in reaching the greener pastures. Software development can be green too.

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.

Wednesday, June 3, 2009

Going to the Clouds with windows AZURE. (A platform for cloud computing)

Access to software, services and applications over the Internet, with/without you having an idea of the original location, such services is referred to be living in the cloud. Users need not bother about where the software is located.

With cloud computing, you do not have to worry about the technologies that supports your virtual environment. You don't have to wait too hard for your service providers who have to setup/install and configure components for your server environment before using cloud computing, all the components that you require for smooth running of your cloud business, are already in the cloud.

Cloud computing is mixture of other existing buzzes in the INTERNET jargon, these are :

1. Iaas : Infrastructure as a service
2. Paas : Platform as a service
3. Saas : Software as a service

These existing services are incorporated together to form what we refer to the cloud. They all are functionally Dependant on one and other to give a breath taking user experience.

Is cloud computing the new IT Jargon?
In today's IT complexity driven world, reliance or dependencies on technology resources are becoming cumbersome for large and small enterprises, while maintaining large infrastructures of computing resources are becoming an cost issues to organisations, there is a newly born term (Cloud computing) to wash away our worries. Doing business on the web is not as easy as it seem when you have to worry about all the infrastructures, security, maintenance and continuous up gradation of these infrastructures, it would be nice when several providers take charge of the technology backing and the rest is for you to leverage an existing API's/Frameworks to complement your business.

The cloud buzz is already attracting bigger IT providers like Google, IBM, Sun, Microsoft. What does all these mean to us all, the future is in the cloud (with the exception of propriety based technologies).

Microsoft answered with Windows AZURE
Windows Azure is Microsoft first step into the cloud computing foray. Azure is a Microsoft initiative in providing services on the cloud. This is an operating system that is used for deploying azure services on Microsoft owns data centers.

In our day to day deployment/development experience, we overcome several challenges in application configurations, server prerequisites, and configurations.

The windows Azure is an assurance that all these server components (MS-MQ, WCF Host, WWF host, SOAP, XML, REST, ASP.NET etc) will be available without you worrying.

The good thing is that Microsoft is providing SDK's for windows azure, and there is already a Visual Studio integration. Although, Microsoft technologies will be supported (As these are core to the heart of the software giant) , windows Azure will also host non-microsofts technologies. (infact there is already an effort on codeplex for PHP Azure .


The Azurance Provided by windows Azure
  1. Provisions for Binary large object (Blob) tables hosted in the cloud.
  2. Full .NET Framework support.
  3. Available security polices.
  4. Support for other platforms languages (PHP)
  5. Message queuing.
  6. SDk's available everywhere
To azure yourself on the next IT jargon using Microsoft platforms and technologies you will need to go here http://www.microsoft.com/azure/default.mspx. Do not panic, because your development will still be the same, and you can continue to use your existing applications. Infact, your applications can be made azure compliance.

Good thing for .NET developer
Microsoft is not forgetting us and we are already cloud compliant as Microsoft, already provides an SDK for integration into Visual Studio development environment. In fact, our existing developments can be converted to azure services (Its just a matter of configurations). Download the Visual Studio Tools for windows Azure, and reassure yourself of the future of computing.

If you wait on this channel, i would be providing a simple .NET application that is windows Azure compliant.

Friday, April 10, 2009

Building quality and bug free software : Leverage Design By Contract

Since inception, the advent of Object orientation development gave birth to chains of concepts in recent years, and all these had positive impacts on the ways we develop robust, reliable and scalable systems that passes the test of time. One of this concept is designing software component and allowing components interaction based on contracts. These contracts are the full agreements that each components must satisfy before the system can run successfully.

A simple analogy is smashing a bottle on the floor, what do we expect? of course, we'd expect the bottle to break, and scattered all over the floor. The fact that the action smashing a bottle on the floor requires a bottle (Pre-conditions) and bottle must scatter on the floor (Post- condition). The pre-conditions and post-conditions are the contract agreement in our analogy. Now lets dig into what really is design by contract:

What is Design By Contract (DBC)

Design by contract is the ability of software components to satisfy obligations that are required for the smooth running of a software systems. Was introduced into the Eiffel programming language designed by Bertrand Meyer in 1988.


Now, the word design by contract is used to associate software contracts/specifications with the software development itself, by so doing, we described what the software component expects from calling component or client. This approach makes the development of software and its specification to be interwoven and changed when either changes.

Again What is Design By Contract

Design by contract is a software development standards that enforces a pre-conditions and post-conditions on the ways software components/ methods and libraries communicate with one another. An object oriented class should depict what it represents. If you have a class called AccountValidator, the job of that class is to validate an Account not to withdraw from that account, another class or service will handle the withdraw aspect.

To validate an account, we will Require an Account Details object, and the algorithms for validating an account, and also Ensure that the account is valid, and there is no invalid data supplied. Note the two words Require and Ensure , these are analougous to the pre-conditions and post-conditions that we have been refering to. So if you are developing the AccountValidator class, the methods should require that parameters meets its demand and ensure that valid validation response is sent to the consumer.

Why all this, what about TDD (Test Driven Development)

Yeap, TDD allows you to pre-verify your code against certain conditions too. And if you have been using Assert statements to verify outputs from your test, you are near design by contract. But DBC allows you to have the assertions into your code not outside your code. Your methods should be strict enough and only bound to its part of the contract.

All talk and no code : Tell me more

Now lets consider the following class AccountValidator, and its contract obligations :


interface IAccountValidator
{
bool ValidateAccount(IAccountDetails account);
}


//IAccountValidator Implementation

public class AccountValidator : IAccountValidator
{
public bool ValidateAccount(IAccountDetails account)
{
if (ValidateAccountNumber(account.AccountNumber))
{
if (ValidateNameOnAccount(account.NameOfAccount))
{
//Now ensure that the value is in the database

if(ValueIsInDataBase(account))
return true;
}
}

return false;
}

private bool ValidateAccountNumber(string accountNumber)
{
if (string.IsNullOrEmpty(accountNumber))
throw new InvalidOperationException("Invalid Account Number");

if (accountNumber.Length != 8)
throw new InvalidOperationException("Account number must be exactly 8 characters long");

return true;
}

private bool ValidateNameOnAccount(string name)
{
if (string.IsNullOrEmpty(name))
throw new InvalidOperationException("Invalid Account Name");

return true;
}

private bool ValueIsInDataBase(IAccountDetails account)
{
//Database calls here
}
}




The class above specifies to pre-conditions, these are valid account number and valid account name. The post-conditions of this class would have been checking that the actual data submitted is valid in the database. This class is just a simple and classic design by contract example, more advanced frameworks has been produced using aspect weaving or aspect oriented programming to solve the contract issues.

DBC is comming in .NET 4.0

Code contracts will be part of the Rosairo project (VS 2010). This will allow you to have the ability of static time checking of contract violations, API documentation, improve your testability.

Sunday, March 29, 2009

Democratizing Software Development (A Promise from Rosairo) .NET 4.0

Microsoft is making a big change in its .NET suites of technologies. The Visual studio development environment will experience additional functionalities that will make life a sweet one for all of us. An application server code named "Dublin" will be introduced to compliment IIS (Internet Information Service) . WF and WCF will experience another quantum changes, and we will all be happy.

The .NET framework is not left behind, as we will see more API changes like : dynamic (supports for COM interop and dynamic languages), Named parameters, default parameters, BigIntegers, covariance and contra variance of generic list : as IList string will now be equals to IList object , also Code contracts.


Democratizing Software Development Life Cycle

There is now a big quantum leap from programming focused development environment to software life cycle development environment.

In an Agile driven development environment, the key practices there is collaboration, software developers needs to collaborate with architects, testers, project managers and database administrators. This collaborative means ensures that products are delivered on time and risks are noted on time. The collaboration amongst team of professionals already in an agile environment leveraging the .NET platform will be a plus when the new Visual Studio 2010 finally ships.

Use case, activity, architectural diagrams are other integrated features of Rosairo, developers, architects will enjoy new ways of architectural designs because all of this forms parts of the new change in VS 2010.

Ever thought about using test data to validate the efficacy of software solution. There is an added test tool that will ensure a proper scenario based documentation which is useful to application testers.

Black box testing recorder will be integrated into the Visual studio 2010, where testers can interrogate the call stack and record debug sessions for replay later. This gives the developers to watch the replay of the black box when a bug is found.

Let us fold our arms and experience the new changes to the developers number ones platform. Derio to Microsoft, Visual Studio Bomayee!!!

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.

Tuesday, January 6, 2009

LINQ And Interpreter Pattern : A tale of datasources

In a service oriented (SOA) environment, larger systems communicate/handshake with one and other with different varieties of data and formats.

These systems leverage different Data formats, contracts and pure XML (The RESTFULL way) hosted in a multi - platform environment.

Recently, in the real life, i came across a situation that i needed to fetch information from different data sources. The consuming application(s) does not want to know where these data's are being imported from and the producing application does not want to let go of the secret of the source to data. All it is concerned about is that the format must be consistent wherever it may be coming from.

I am supposed to fetch data from the following sources :

1. XML stored in a file system.
2. DataSet from another WebService
3. Service contracts from another service.

At first, this seems to be a mundane tasks, because you may have to create different code for different datasources and different translation for those datasources because an xml data is not the same as object data until we have a translator, we would not get anywhere near what we want to achieve.

First thing that comes to my mind was to leverage the Linq API and architecture to archive the above problem, how do i program my WCF service so that it will be extensible to other datasources, how do i ensure that the translation is not ambiguous (hence finding a better approach and framework that is consistent enough to do the job of translating data coming from different sources.

The Proposed architecture

I dig my hands into the dirty chests of patterns, i traveled from Gang of four to Microsoft pattern, i moved from different community, but there seem not to be a proper way of ensuring a consistent data translation strategy. After sometime, of digging, i eventually choose to use the interpreter pattern (Since it is used to interpret sentences in language elements). The reason for this choice is because i need a consistent language lexical structure that i can use for different data sources (as explained above) and Interpreter pattern seem to be the best choice to define my language grammar.


In this example, we want to interpret a Customer detail data structure coming from different sources, here is the C# structure of our Customer Poco class.



public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public int Age { get; set; }
}


We want to be able to translate several data sources to the Customer class defined above. This example will focus on the following data sources :

1. XML
2. Database
3. DataSet
4. object

If we are familiar with the Linq API, we would know that it supports for language elements across the named data sources above.

Interpreter Pattern Structure

The base interpreter is the interface to which we will use to interpret our language elements, because we need not know about the child classes or how they do their interpretations. The code snippet below is our base Interpreter.


public abstract class CustomerExpression
{
public Customer Customer { get; set; }
public abstract void Interpret();
}


The code above defines the CustomerExpression class and this class will define the structure of its child classes, the following child classes will be created :

  1. CustomerXMLExpression
  2. CustomerSQLExpression
  3. CustomerDataSetExpression
  4. CustomerObjectExpression
I will be discussing the first one only which is the CustomerXMLExpression. The code below is the snippet for the CustomerXMLExpression :



public class CustomerXMLExpression : CustomerExpression
{
public override void Interpret()
{
Customer = TranslateCustomer();
}

private Customer TranslateCustomer()
{
StringBuilder customerXML = new StringBuilder("XML Data");
XDocument customers = XDocument.Parse(customerXML.ToString());

return (from customer in customers.Descendants("Customers")
select new Customer
{
FirstName = customer.Element("FirstName").Value,
LastName = customer.Element("LastName").Value,
Age = (int) int.Parse(customer.Element("Age").Value),
Address = customer.Element("Address").Value,
}).FirstOrDefault();
}
}

We can use the same idea for the rest of the remaining data sources, for example we can search each data sources as follows :



CustomerExpression expression = new CustomerXMLExpression();
Customer customer = expression.Interpret();

CustomerExpression expression = new CustomerSQLExpression();
Customer customer = expression.Interpret();

CustomerExpression expression = new CustomerDataSetExpression();
Customer customer = expression.Interpret();

CustomerExpression expression = new CustomerObjectExpression();
Customer customer = expression.Interpret();



There is a long way you can go with this practise because it makes you to centralise your code and hides several dirty works away from developers.

Thursday, November 27, 2008

Enum can now have method

Thanks to Extension method.

Have you ever programmed against enum in the .NEt framework. Have you realized that the .NEt enum is not as efficient as other enum living in other platforms like the Java Land. Still the .NET enum is suffering from advance ways of using constants. An .NET enum cannot even have a method (Thats how bad it is) this is referred to constants specific method in Java.

But with the method extension in the .NET framework 3.5, we can pro grammatically extend an enum with methods that makes us think that they are actually defined within the enum scope.


public enum MyEnum
{
Name,
Age,
}

public static string RealName(this enum myEnum)
{
return Enum.GetName(typeof(MyName), myEnum);
}

MyEnum enn = MyEnum.Name,

enn.RealName();

Monday, September 8, 2008

How to implement a generic WCF message interceptor:

In a changing business environment and business processes; changes affects not only the entire work force, cooperate partners, the way businesses are done and of course our tools that makes our work life better. We are left with the choice of ensuring that our legacy or existing system inter-operate well into our new ways of life and they deliver the expected result that yields expected ROI. Because for today's business to survive, we need to carry along with us our efforts of yesterday, we need to have decoupling in mind when we are integrating services for a wider business sector. These were the thoughts in Microsoft when it first launched the framework (WCF) that shook the whole distributed computing industry.

Windows Communication Foundation is a Microsoft initiative of building Service Oriented Applications that leverages yesterdays and todays technologies, in fact it complements existing distributed technologies. The WCF (Windows Communication Foundation) infrastructure is built into .NET 3.0/3.5 and can be leveraged for different kinds of communication types/endpoint, that ranges from Message Queue, TCP communication, standard webservices, service based webservices. The most commonly used approach is the Service based where you can host it as .asmx or .svc.

In a typical WCF implementation, we have the following :

  • Datacontract. Represents the data that will be wired from one endpoint to the other. Any CLR compliant type marked as datacontract can be serialized and wired over the communication protocol.
  • Message Contract : Think of messages as envelopes, that wraps up our data/data contracts over the wire. Our message have a body and header section. It is analogous to SOAP envelope, in-fact it is converted to a SOAP envelope when the message serialization begins at runtime.
  • Service Contract : Here is the interface that is marked [ServiceContract] which can be called remotely by clients of the service. In our service, we will implement this interface and provide business functionalities that clients will consume and call remotely. Services can expose one - To - Many endpoints (Listener point), and more than one service operations can be exposed by an endpoint.
  • Service Endpoint : Think of an endpoint as message gateways for services that are hosted. A service can be configured to listen for request in different endpoints. A service Endpoint has an Address, a Binding, and a Contract.
  1. An address that describes the location where messages can be sent.
  2. A Binding specifies the type of communication that an endpoint can make using protocols such as HTTP, TCP, MSMQ and security requirements such as SSL, WS-Security etc.
  3. Contract : The binding contract are sets of messages that defines sets of operations that can be accessed by the service clients.

Message Oriented Concept In WCF
I mentioned above that the service contract defines operations that are used to send request and response messages over the transport layer defined by the service endpoint. In a simple client/server architecture, messages can be coupled between sending interface and the receiving end. That is there is a stub and skeleton relationship between the service and the consumers. Although, there is noting wrong in the stub and skeleton approach, that is a client\consumer keeps a stub or proxy of the services that it can talk to. This means when a service changes the client is regenerated using svcutil.exe tool for re-generation of the service stubs.

In an ever changing world of buisiness, we need to build services with simplycity in mind, conformance to changes. How do we allow a generic communication between our service and the rest of the world. Thinking about generic-ability of our services, we need to create an interceptor service that sits in between our clients and services, although the contract binding will be between our client and service, but the address binding will be between our client and the interceptor.

Having understood the basics of the WCF fundamentals, we need to now understand how to pass messages in a generic context.

The Interceptor Pattern
This pattern came into mind when i fell deeply into a WCF scenario that requires changing of service messages or re-delegating a service request to other service other than the requested one. Also you can use this pattern to achieve load-balancing amongst services.

One of the reason's why you might want to use an interceptor pattern is the following :
  • Expose a single entry to the entire world with the interceptor/facade.
  • Do load - balancing with the interceptor.
  • Expose a REST (Representational State Transfer) to the world while your back - end service supports WCF semantics, so you need an interceptor to bridge the gap between the pure xml and soap messages required by the WCF services.
  • Manipulating/ validation on the facade/interceptor end before delegating to the actual service.
  • A form of clean architecture design pattern
  • Securability as single entry is used as the entry point. Security is focused on that single entry instead of all
  • etc
The list above goes on and on without end, and there isnt a limit to what our services mediator can achieve. So how do we do the coding (Good Question) : so lets start with defining our service contract :


[ServiceContract(SessionMode = SessionMode.Allowed)]
public interface IRequestDispatcher
{
[OperationContract(IsOneWay = false, Action = "*", ReplyAction = "*")]
System.ServiceModel.Channels.Message ProcessMessage(System.ServiceModel.Channels.Message message);
}


Note the ProcessMessage operation in our IRequestDispatcher contract, this operation accepts and return a Message from the System.ServiceModel.Channels namespaces and it is the only operation that we need to generically or intercept message calls from client and server.

You will also note that the ProcessMessage method is decorated with [OperationContract(IsOneWay = false, Action = "*", ReplyAction = "*")]. This is to tell our service that our method (ProcessMessage) can process any operation call from different client, by marking it Action = "*" and ReplyAction = "*" . This is the basic of our interceptor strategy.

The Big Picture
Lets have a simple picture of what we want to achieve. We have two WCF services one accepts a string and returns a string, the other accepts an object and returns a string. This services are our back office operations that is open to services that are within our domain. Assuming we want to expose this services to the entire world, we will end up exposing two services. So, if any of the services changes, that means the entire world will have to change with it, this is quite burden some. So, instead of exposing the two services, we have to expose only one service that is generic to all other services, and this service communicates in REST - FUL manner (pure XML and no soap messaging).

Lets define the big picture of



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.

Friday, August 29, 2008

.NET Primitive Wrapper Classes Where are thou?

In my day-to-day experience with code, forum users, other developers, i have been asked this question (Wrapper classes for primitive type) a thousand times before and now. Most developers especially the one's coming from Java Land (Like me, i am a Java Lander and still i am) seems to bring with them the Jar of Java coffee, and when they successfully arrive NLand, they realize its a different ball game here, because NPeople are not coffee drinkers, they are business men. Lets cut the story of N and J short, because the similarity and the dissimilarity of both lands is what makes them different.

We will not argue about the two lands today, but try to work around a simple primitive Wrapper for int, lets call our wrapper BigInteger or Integer (I will choose Integer or something like IntegerWrapper since .NET people may want to include Integer class as part of the base class libraries in the upcoming and not so far future. In Java, int is mutable because you are allowed to change the value of int anywhere in your code.

In Java we have several Wrapper classes which i will like to metion below, they wrap-up primitive data - types and have an object representation of it. The following class are some of the primitive wrapper classes in Java.

  1. BigDecimal
  2. BigInteger
  3. Byte
  4. Double
  5. Float
  6. Long
  7. Integer
  8. Short
All of these wrapper classes described above inherit from an abstract class called Number (You can sense some intuitiveness of java here). So in java, a primitive integer type can be used as follows :


int value = 200;
Integer bigInt = value;
value = bigInt;


Although wrapping and un-wrapping or autoboxing and unboxing (NLand calls it Boxing and UN-Boxing. But to object) primitive data types has a performance implications, but there are some situations that we cannot do without them. So how to we bring this type of functionality to .NET, how do we ensure that our primitive types can be treated as a reference type. First let me point out some few facts about what we have in the .NET API (Application Programming Interface).

Boxing and UNBoxing

Well, with the little approach we described above, we can fully understand that in .NET we have the term boxing and unboxing. This allows us to use an value type as an object and re-casting the value type from an object to its primitive state : The following is valid :


object value = 200; //Store an integer
int intValue = (int) value; //returns the value 200 to an int via type casting. It
is not automatic casting.


The above snippets shows how we can do boxing and unboxing in .NET, but where is the performance implications in this? of cos there is, when you cast a primitive type to object in .NET, an reference is allocated in the garbage-collected heap, that means an object memory is allocated for it. Let us take another simple approach :


object value = 200;
object value2 = value;

value2 = 500;
value still remains 200.


The code above retains the content of value and creates a new object in the memory heap when we assigned value to value2. We would have thought that the two objects would have a reference to a single object in memory, but the data is duplicated. So we need to be carefull when dealing with boxing amd unboxing this way.

Also we can use the System.ValueType class, which is the base class for all .NET value types, still this approach does not guarantee type safety and and it encourages more type casting and also incur the performance implications as the boxing and un-boxing approach.

So what are we going to do?

we are going to create a custom Integer Wrapper for .Net, and we will ensure that it is used like its java counterpart. So here our code goes :


public class Integer
{
int value = 0;

public Integer(int value)
{
this.value = value;
}

public static implicit operator Integer(int value)
{
return new Integer(value);
}

public static implicit operator int(Integer integer)
{
return integer.value;
}

public static int operator +(Integer one, Integer two)
{
return one.value + two.value;
}

public static Integer operator +(int one, Integer two)
{
return new Integer(one + two);
}

public static int operator -(Integer one, Integer two)
{
return one.value - two.value;
}

public static Integer operator -(int one, Integer two)
{
return new Integer(one - two);
}
}


The code above is a representation of the Integer wrapper class in java in .NET. So, having created our class above, we need to see how we can utilize it. Below is how we can make use of it.


Integer integer = 345;

integer = 10 * 11;

int value = integer;


Now we have our a reference type for integer type in .NET. Note, you can overload other operators to make sure your reference type can be used with other operators. Enjoy your Wrapper.

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...