Beware of Static Constructors

Filed Under (Bunian, Development) by Emad Alashi on 07-02-2009

Tagged Under : , ,

In Bunian we needed to use a static constructor for some reason, it was all going good; we tested the code and it ran smoothly…excellent (Code Coverage anyone?!).
But when I came across this situation, it appeared that the static constructor wasn’t invoked!even when “Class.Method();” is called! so lets examine it.

I have two simple classes as an Example:

public class Parent

{

    public static string DoSomething()

    {

        return “Parent: DoSomething() called”;

    }

}

public class Child : Parent

{

    static Child()

    {

        Console.WriteLine(“Child Static constructor called”);

    }

 

    public static string DoSomethingDifferent()

    {

        return “DoSomethingDifferent() called”;

    }

}

As it may be obvious, Child inherits from Parent, Child has a static constructor that we need to be executed when ever a method is invoked by Child. Now lets check the main program executing these two lines:

Console.WriteLine(Child.DoSomething()); //This code will NOT invoke the static constructor

Console.WriteLine(Child.DoSomethingDifferent());//This code WILL invoke the static constructor

The surprise (at least to me) when calling “Child.DoSomething()” the static constructor isn’t invoked! because it is in the parent!! aaaaaah! bad!! that was serious for our architecture  and we had to do lots of fixes to turns things around the right way (which I think it was for our own good for other reasons :P )

This brings up the Code Coverage topic as well; in our case that static constructor’s job was to create an instance of a member that is only needed once, and we check on it in other times by “if _instance != null”. It always ran ok because all the test code we created used to call an original Child before calling any other method that resided in the Parent.

bottom line: be ware of static constructors, and check your test code…it maybe hiding “surprises” for you ;)

Get On With It!

Filed Under (Bunian, Development, software management) by Emad Alashi on 16-01-2009

Tagged Under : , , ,

clockWhen we started gathering requirements from the charity organizations for Bunian, it appeared that there are other kinds of people who benefit from the charity organization; there are “needy families” whose father is still alive but can’t sustain their families, and “students” who can’t afford their study. 

So Bunian needs to support all these Beneficiaries in smart way; we solved the problem by creating the IBeneficiary interface. But the problem is that in order to get out with the best solution ever (damn perfectionism!), we kept coming up with different solutions, and overriding them with other solutions every once in a while, and this kept going like forever!

Though we agreed from the beginning that we shall keep it as simple as possible and then add up to it as we get out with the first phase, yet it kept sliding “ok only we have to do this, oh and that too”. Until one day I thought I came up with the silver bullet everyone talks about 4 , and sent an email to the group about the changes I wanted to make, when a colleague caught me online and showed her objection about the new solutions, and proposed another. Only then I woke up!! “OMG…WE ARE STILL HERE!!”
Instantly, I remembered my oldest brothers comment  (Mohammad, very wise brother) about Bunian “It’s great that you want to build the greatest architecture ever, but remember that Orphans are waiting!!

So LET’S JUST GET ON WITH IT!! ship it!! do it!! let version one come out, let “customers” benefit from it, then you take your time doing your silver bullet. So this is one of the challenges facing the Project Managers, something we developers rarely think about :) ; today…I learned my lesson!

Importance of Documentation

Filed Under (Bunian, Development, NHibernate, software management) by Emad Alashi on 26-12-2008

Tagged Under : , ,

 

documentation

Lately we have decided in Bunian to move on to NHibernate 2.0, and the contributor assigned to the move started out, only to send an email one day after: “THERE IS NO DOCUMENTATION!’.
We had errors as a result to the move which couldn’t be fixed without a documentation explaining why this happened.

After searching for a while, we found two resources of the new documentation:

Neither links were included anywhere in the NHibernate zipped file.

I didn’t realize how important a documentation is until it stopped us from moving on in our project; Only after we made sure that the documentation is available we decided to move on to version 2.0. The lesson to be learned is that if you are an enthusiast developer and want to add another piece of code to the world, keep in mind that your project is not only code; it is people, resources, community, ease of use, documentation, and any other simple thing that people need while you think it’s not important.

Of course I couldn’t find developers or contributors to open source projects greater than the NHibernate team, having such a project in the first place is awesome, and I thank each and everyone of them. I hope one day I can really contribute back to NHibernate. Thanks again guys.

HttpApplication EndRequest Event Invoked Many Times In Single Request?

Filed Under (Bunian, Development, NHibernate) by Emad Alashi on 14-12-2008

Tagged Under :

The other day I was putting the last touch of a temporary way to manage the NHibernate session (ISession) in Bunian. So part of the task was to bind a method to the HttpApplication EndRequest event (in the Global.asax.cs file) like the following:

public override void Init()

{

       this.EndRequest += WorkContext.NHibernateSessionManager.Instance.HttpRequestEnded;

}

By doing this, at the end of each page request the NHibernateSessionManager.Instance.HttpRequestEnded() will be called and I can clean the session then. But to my surprise this method was called at least 10 times!! So I thought maybe the Global.Init() method is called many times for some reason and I ended up binding the same method to the EndRequest event many times, so I set a breakpoint at the Global.Init() method and…it’s called one time only.

That was strange, ok so it’s only the HttpRequestEnded() mehtod that is called many times, but I am requesting only one page!! how come there are 10 requests!

So I opened Firefox which is already “armed” with the magnificent add-on Firebug, and I requested the page again, Firebug showed the following:

CropperCapture[1]

And that was it!! the page contained 10 resources (1 CSS file and 9 images), OH! so it is one page, but for each resource referenced on the page you get a request, hence a raise of the EndRequest event.

I couldn’t love Firebug more; I am not only happy that I wasn’t doing something wrong, but yet I learned something new about the ASP.NET internals. awesome.

Data Access Within Business Objects -Bunian Design-

Filed Under (Bunian, Development) by Emad Alashi on 10-11-2008

Tagged Under : , , , ,

In a previous post I showed the general architecture of Bunian. I’d like, in this post, to touch on the Data Access part and how it interacts with the Business Objects.

In traditional architectures there are 3 known layers: Data Access, Business, and Presentation. DTO’s (Data Transfer Objects) are used to carry the data back and forth between the layers. Look to the following diagram:

DTO

Bunian contributors seemed to have the same experience developing against such architecture, so we have decided to go with something different; smart Business Objects with more toward OOP.

The way I’d present the current architecture is like the following:

BusinessObjectsRelations

As you can see from the diagram, the architecture revolves around one core unit, the Business Objects; because it’s the essence of the application, it’s where all the real things happen. Being the core, the interaction will happen in different ways depending on the nature of the service the component provides (or requires). Those can be divided into three categories:

  1. Interacting with components that provide services consumable by many other applications; like logging for example. Here our core can reference the component directly without any worries because the component is absolutely independent of the core (represented in the previous graph as solid arrow). Of course it would be better if there is simple abstraction layer so we can manage any change of components.
  2. Interacting with components that consume services from our core directly; like the User Interface. The interface will merely represent the business behavior in a way the end user will understand, no dependency what so ever from the core on the UI, it should be even representable through console application if needed (also represented in a solid arrow)
  3. Interacting with components that are providing a special need to the business, like the Data Access. This should be done via interfaces and Dependency Injection; that is because it is the business who determines the needs to be fulfilled, it is the one who states it needs to be able to Save, Delete, Update..etc.., and the component willing to fulfill this need should adhere to the contract the core dictates. (represented by the dotted line meaning indirect dependency)

We are concentrating on the 3rd interaction, specifically the data access component.

The main thing to note here is that by using Interfaces and Dependency Injection, we will be eliminating any circular dependencies; even if the candidate component will require parts of the core (like our example: the data access will want to return strong types that reside in the business objects, or take types as parameters), even if that so, we will make sure that the core is independent of the component (references wise).

The best way to understand is by an example, I will try to make it as simple as possible first, and in future post I might include more real scenarios (like the one we are using in Bunian) so lets get our sleeves folded:

we have a simple class MyBusinessObject with a simple property DisplayName:

public class MyBusinessObject

    {

        private string _displayName;

        public string DisplayName

        {

            get

            { return _displayName; }

            set

            { _displayName = value; }

        }

    }

This class needs to have a way to access the database and bring an instance, but on the other hand, it doesn’t want to do anything with the implementation. So it declares that it will need a component that should adhere to the IRepository interface which will have the Get method. It will have this component as a static member:

public static IRepository _repository;

IRepository definition is:

public interface IRepository

    {

        MyBusinessObject Get();

    }

So a component volunteers, MyConcreteRepository:

class MyConcreteRepository : IRepository

    {

        public MyBusinessObject Get()

        {

            MyBusinessObject myObject = new MyBusinessObject();

            myObject.DisplayName = “ConcreteRepository”;

            return myObject;

        }

    }

Ok great, now all what we need is to assign an instance of this concrete class to the _repository static member in MyBusinessObject static constructor. but if we do so the following it will be wrong:

static MyBusinessObject()

        {

            _repository = new MyConcreteRepository(); //wrong!

        }

simply because if MyConcreteRepository resides in different project/dll (and mostly it will), then you will have circular dependency between the Business Objects and the Data Access. So the answer is to use reflection and get an instance of class without referring to dll. Using Windsor we will do the following:

 static MyBusinessObject()

        {

            IWindsorContainer container = new WindsorContainer(new XmlInterpreter(new ConfigResource(“castle”)));

            _repository = container.Resolve<IRepository>(“anotherConcrete.repository”);

        }

The lines above, in the simplest explanation, will check in a configuration file, and see which class we will use to create instance of to assign a property of type IRepository. supplying the key “anotherConcrete.repository” tells Windsor which class to use. The config file is like the following:

<castle>

    <components>

      <component

          id=concrete.repository

          service=BusinessObjects.IRepository, BusinessObjects

          type=ConcreteRepository.MyConcreteRepository, ConcreteRepository />

 

      <component

          id=anotherConcrete.repository

          service=BusinessObjects.IRepository, BusinessObjects

          type=AnotherConcreteRepository.MyOtherConcreteRepository, AnotherConcreteRepository />

    </components>

  </castle>

By that we will have achieved our data access within our business objects without circular dependencies and in a way that will make it easy to change data access component with another in the future.

Of course in real life you would use inheritance for example to manage similar code, this will be postponed in another post by god willing, hopefully soon.

Note that we didn’t use essence of “dependency injection”, since it means more than the Resolve<T>(key) part.Â
For more information about dependency injection read this excellent series of articles here.

Source code of the example above is available here.

[digg=http://digg.com/programming/Data_Acces_within_Business_Objects]

Bunian Basic Design

Filed Under (Bunian, Development) by Emad Alashi on 23-10-2008

Tagged Under :

Well, it’s moving on, very slow, but it’s moving!

If you have been following this blog, then I think you are familiar with Bunian, the open source project for charity organizations. During the last Bunian team meeting at the beginning of this week, the basic design emerged (still being discussed and subject to changes till the minute of this post); we have decided to skip the dummy DTO objects, and to try Business Objects (BO), where most of the business logic lays, rather than in a separate Business Service.

The design will be like the following:

  • Business Object classes: like Child, or Family. These classes will have the correspondent business logic within, including the data access (although some may object) but data access will be through repository interface data member.
  • Repository interfaces: each BO will hold an interface data member specific to the data access needs of that BO. For example, the Family BO will have the interface data member IFamilyRepository. These repository interfaces will have a parent repository interface IRepository.
  • Concrete repository classes: as it may be obvious, it implements the repository interfaces mentioned above. These classes will be in different project, in order to be able to change the behavior depending on the Database (Microsoft SQL server, MySql, etc…)
    Note here that there will be no direct dependency on these concrete classes; they will be injected through IoC container which we haven’t chosen yet (most likely would be Windsor,  available to discussion).
  • MVP infrastructure: a project will host Views interfaces and their Presenters.

The following diagrams are examples of the discussed above:

- Business Objects using repository interfaces:

BO having repository interfaces as members 

- Concrete classes implementing repository interfaces:

BunianDesgin2

Of course all of this might be changed so let’s not hold our breath! so stay tuned if you want to know the end of the story ;)

Any suggestions? comments?

Announcing open source project Bunian

Filed Under (Bunian, Development) by Emad Alashi on 29-08-2008

Tagged Under :

What could be better, as an Open Source project, than a charity application! where your code is really worth something valuable; a smile on an innocent orphan face, or new clothes for a needy family in Eid.

Announcing new open source project Bunian; the excitement is indescribable! eager to reach with it a stage when it’s really alive, doing something good out there for needy people. I understand it’s going to take so much to drive a successful project, but with the right contributions from the right people like you…I am sure things will just work fine.

Here is the summary I came up with to describe the project in the least amount of words:

Bunian is a charity web application that will make it easy for the generous people, who want to give, to reach for the poor, who need and yet cannot be reached.
Charity organizations who use Bunian, will enable Sponsors to browse through list of Beneficiaries already registered with the organization, depending on different criteria, giving the Sponsors the ability to Request to sponsor certain Beneficiary, who can be Orphan, Family…etc.
For the time being, there will be no handling for charity transactions, the web application is only meant for communication.

The basic target technology is ASP.NET 3.5, NHibernate, and Microsoft SQL database, the initial structure and code is already uploaded on the source control over codeplex (an open source project hosting website), you can download the source code here.

There are lots to do, and lots of ideas that can enrich the project, I surely cannot do it alone, so if you think you have the time and skills, then you are more than welcome to join the project. Even if you don’t want to join, your comments and advices are still highly appreciated, and thanks in advance.

More posts will be coming concerning Bunian, there is still lots to say which I will postpone till its right time.