2011 What a Year!

As we are at the end of the year I thought to summarize the major events that happened during this year, and I discovered that this year was like 5 years compressed in one year.

Sorted by time The first major event is the Egyptian Revolution which is still in progress now, I have engaged in multiple protests most noticeable 28th of January and multiple other protesting days. It is still in progress as the bloody #scaf is still ruling Egypt the old stupid uncivilized barbarian way, hope this end soon, we are still in the revolution till it ends.

The second major event is that I got married to my lovely lady, relocated to our new apartment in 5th settlement in Cairo, went to Thailand for our honeymoon and had wonderful time there.

The third major event is that we are expecting a baby soon next June, which moves us to a new parental territory. Excited about being a father!

The fourth major event is that we have relocated to Sydney in Australia as I have joined Readify! very smart and friendly people at this company.

So it is a total lifestyle change for us with much changes, events and expertise compressed in one year!

I hope the next year would be as nice and eventful year, who knows what will happen the next year!

BDD with Specflow

This post will be part of a series about developing my sample application (Sell and Buy).

Starting from very initial documentation describing Ubiquitous Language and User Stories.

As described in Wikipedia, BDD encourages collaboration between team members and business stakeholders.  It describes a cycle of interactions with well-defined outputs, resulting in the delivery of working, tested software that matters. Behavior-driven developers use their native language in combination with the ubiquitous language of domain driven design to describe the purpose and benefit of their code.

Recently I’ve played with SpecFlow, and found it very appealing in defining behaviors specially end-to-end tests. So I started my solution by creating a SpecFlow project taking the first user story and apply it then start to build the walking skeleton.

It is not very much walking skeleton, as I had to invest a little more time designing the infrastructure and basic layers of the applications.

Story 1.1: List recent ads

As a buyer, I want to find recent ads, so that I can find something interesting.

This very first user story states that when a user first open homepage, he should see a list of recent ads. The following is the implementation using SpecFlow:

A feature in SpecFlow is mapped to a user story using the same syntax of user story.

A Background describes the givens, it is very beneficial here because in this user story, we assume that there are already definitions in the system. We assume that there is a customer (seller), a category (Books), some available conditions for the ad type, some items definitions, and finally a list of ads published.

Each feature in SpecFlow is mapped to Steps definition file which is a class bound to the feature with methods bound to elements in the feature to execute it.

for example “Given the following customers” will be mapped to a method  with Table as parameter filled with customers in the feature.

        [Given(@"the follwing customers")]
        public void GivenTheFollwingCustomers(Table table)
        {
            var customers = new List<Customer>();
            foreach (var tableRow in table.Rows)
            {
                var customer = new Customer
                                   {
                                       FirstName = tableRow["First Name"],
                                       LastName = tableRow["Last Name"],
                                       Email = tableRow["Email"]
                                   };
                customers.Add(customer);
            }

            GetCustomerRepository().Add(customers);
            GetCustomerRepository().UnitOfWork.Commit();
        }

The first scenario starts with the condition “When I enter homepage” would be mapped to:

        [When(@"I enter home page")]
        public void WhenIEnterHomePage()
        {
            var AdService = GetAdService();

            var controller = new HomeController(AdService);

            _actionResult = controller.Index(null, null);
        }

This code instantiates a new ASP.Net MVC HomeController passing it AdService instance and calling Index method which will return ActionResult.

Then comes the expectation “Then the home page shows ads …” which is mapped to:

        [Then(@"the home page shows ads")]
        public void ThenTheHomePageShowsAds(Table table)
        {
            var adsViewModel = _actionResult.Model();

            foreach (TableRow row in table.Rows)
            {
                CustomAssert.Any(adsViewModel.PageItems,
                                 a =>
                                 a.Item.Name == row["Title"] &&
                                 a.Description == row["Description"] &&
                                 a.Price == Decimal.Parse(row["Price"])&&
                                 a.Customer.FirstName == row["Customer First Name"]&&
                                 a.Customer.LastName == row["Customer Last Name"]);
            }

            Assert.AreEqual(table.Rows.Count(), adsViewModel.PageItems.Count(), "The list contains other ads too");
        }

This code gets the view model from the actionresult and assert that it includes expected fields.

This very first user story started to give us an idea of end to end test, at this stage we are in the phase of creating the walking skeleton which will include infrastructure layers and domain entities, persistence, services … In later posts we will discuss the rest of implementation.

Logging (Service locator, DI, or AOP)

One of the most common cross cutting infrastructure aspect of enterprise applications is Logging, It can be categorized to two different types:

  • Tracing: Usually used to debug application by tracing method calls and sequence of execution.
  • Logging: When you want to deliberately log some informative message to the log.
The first type of logging always cluttering application code and introduce a redundant dependency upon logging interface whether this interface is consumed using static Factory, Service Locator, or Dependency Injection Container).
Using dependency injection in constructor will clutter the constructors of almost all application classes where each one will add a constructor parameter for the logger interface.
Using setter injection or service locator or static factory will resolve this issue but we still have logging code in each method beside the problem of hiding dependency.
The best solution to tracing is to use Aspect Oriented Programming to inject tracing code to all required method calls, there are many types of AOP tools you can use one of these tools to inject tracing code in your project.
A sample implementation using Unity is provided in this sample.
As the project already use Unity for dependency injection, I used interception to intercept method calls:
    public class TraceCallHandler : ICallHandler
    {
        #region Fields

        private readonly IUnityContainer _container;

        #endregion

        #region Properties

        public int Order { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="container"></param>
        public TraceCallHandler(IUnityContainer container)
        {
            _container = container;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Invoke method
        /// </summary>
        ///input">method invacation info
        ///getNext">next handler delegate
        /// <returns></returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            var className = input.MethodBase.DeclaringType.Name;
            var methodName = input.MethodBase.Name;
            var arguments = GetCommaSeparatedArgumentList(input.Arguments);

            var preMethodMessage =
                string.Format("{0}.{1}({2})", className, methodName, arguments);
            ServiceLocator.Current.GetInstance<ILogger>().
                Debug(className, preMethodMessage);

            var methodReturn = getNext()(input, getNext);

            if (methodReturn.Exception != null)
                _container.Resolve().Debug(className,
                  String.Format("Exception intercepted: {0}",
                                       methodReturn.Exception));
            else
            {
                var postMethodMessage = string.Format("{0}.{1}() -> {2}",
                                                      className, methodName,
                                                      methodReturn.ReturnValue);
                _container.Resolve().Debug(className, postMethodMessage);
            }

            return methodReturn;
        }
This code creates a call handler interceptor to intercept method calls, it print call with its parameter types, values, returned value, and exception if happened.
    public class AnyMatchingRule : IMatchingRule
    {
        public bool Matches(MethodBase member)
        {
            return true;
        }
    }
A matching rule is to match the criteria of selecting methods to inject in.
Finally you need to configure Unity to register these extensions and inject it to the given interfaces:
  xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <sectionExtension type="...InterceptionConfigurationExtension, ...Interception.Configuration" />
    <typeAliases>
      <typeAlias alias="AnyMatchingRule" type="Extensions.Unity.AnyMatchingRule"/>
      <typeAlias alias="TraceCallHandler" type="Extensions.Unity.TraceCallHandler"/>

      <typeAlias alias="ILogger" type="Logging.ILogger, Infrastructure.Core"/>
      <typeAlias alias="Log4NetLogger" type="Logging.Log4NetLogger, Infrastructure.Core"/>

      <typeAlias alias="IMyService" type="IMyService"/>
      <typeAlias alias="MyService" type="MyService"/>
      </typeAliases>

    <container>
      <extension type="Interception" />

      <register name="Any"
         type="IMatchingRule"
           mapTo="AnyMatchingRule" />
      <register
         type="ICallHandler"
           mapTo="TraceCallHandler" />

      <register
         type="ILogger"
           mapTo="Log4NetLogger" />

      <register
          type="IMyService"
          mapTo="MyService" >
        <interceptor type="InterfaceInterceptor" />
        <policyInjection />
      </register>

      <interception>
        <policy name="All">
          <matchingRule name="Any" />
          <callHandler name="TraceCallHandler" type="TraceCallHandler" />
        </policy>
      </interception>
    </container>
  </unity>
Now you can get rid of all calls of logger in all the methods.
About logging extra or custom information you will still need to get the logger, either using DI or Service Locator.

New blog

I decided to start a new blog, I used to have account in Blogger with a couple of posts every long while, So I decided to create a new blog, after studying blogging platforms I decided to use WordPress.