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!

Logging using Decorator

In an earlier post I described some thoughts on tracing and applying it using interception to utilize AOP for tracing and instrumenting application objects without cluttering them with tracing code.

Mentioned also that there is another type of logging needed which is not just tracing of method calls and parameter, but it is custom logging to log verbose information or custom details to be shown in logs.

For this type of logging there are many options, you may inject the logger interface in constructor of your target classes which will introduce a dependency to logging interface polluting the constructor of the target classes while logging is infrastructural aspect which should not be a dependency in that explicit way.

public class OrderService : IOrderService
{
    private readonly IOrderRepository _orderRepository;
    private readonly IOrderValidator _orderValidator;
    private readonly ILogger _logger;

    public OrderService(IOrderRepository orderRepository, IOrderValidator orderValidator, ILogger logger)
    { ... }

    public void PlaceOrder(Order order)
    {
       // ...
       _logger.Info("Placing Order ...");
       // ...
}
//...
var orderService = new OrderService(orderRepository, orderValidator, new TextLogger());
orderService.PlaceOrder(myOrder);

Another option would be to use Service Locator which is debatable to be anti-pattern, although in this case it should not be an anti pattern when used for logging as logging is not a dependency to be accidentally hidden by service locator, but it will introduce the service locator back door in the application which will engage developers to use it for resolving other dependencies as well.

public class OrderService : IOrderService
{
    private readonly IOrderRepository _orderRepository;
    private readonly IOrderValidator _orderValidator;

    public OrderService(IOrderRepository orderRepository, IOrderValidator orderValidator)
    { ... }

    public void PlaceOrder(Order order)
    {
       // ...
       ServiceLocator.Resolve.Info("Placing Order ...");
       // ...
}
//...
var orderService = new OrderService(orderRepository, orderValidator);
orderService.PlaceOrder(myOrder);

A better approach than Service Locator could be used for logging which is Static Factory, this way the factory will be limited and strongly typed for Logging and developers can not use it for resolving other dependencies.

public class OrderService : IOrderService
{
    private readonly IOrderRepository _orderRepository;
    private readonly IOrderValidator _orderValidator;

    public OrderService(IOrderRepository orderRepository, IOrderValidator orderValidator)
    { ... }

    public void PlaceOrder(Order order)
    {
       // ...
       LoggerFactory.GetInstance().Info("Placing Order ...");
       // ...
}
//...
var orderService = new OrderService(orderRepository, orderValidator);
orderService.PlaceOrder(myOrder);

Coming across this post by Simon about Supporting inversion of control in framework and after a small conversation with Mark he opened my eye to using decorator pattern to wrap around the class which needs to be logged using a logging decorator.

This way you explicitly hide the logging dependency using a decorator and leave your regular services and classes clean.

public class LoggedOrderService : IOrderService
{
    private readonly IOrderService _orderService;
    private readonly ILogger _logger;

    public LoggedOrderService(IOrderService orderService, ILogger logger)
    { ... }

    public void PlaceOrder(Order order)
    {
       _logger.Info("Placing Order ...");
       _orderService.PlaceOrder(order);
    }
}
//...
var orderService = new OrderService(orderRepository, orderValidator);
var loggedOrderService = new LoggedOrderService(orderService, new TextLogger());
loggedOrderService.PlaceOrder(myOrder);

Of course you still have a dependency between decorated class and logging interface but this time it is an explicit dependency as the decorated class is all about logging version of the original class this way it would be suitable to put the logging interface as dependency in the constructor for injection. also note that the decorator constructor will just need two parameters one for taking the original instance to be decorated and the other would be the logging interface so no chance to clutter the constructor with many parameters.

So for me as a conclusion I would implement a tracing interceptor for automatically inject tracing info (the AOP style), and if needed to log custom information I would wrap a logging decorator around the target class.

Plain Old DDD with a twist from CQRS

I’ve been investigating CQRS recently, trying its interesting stuff like event sourcing, task based UI and other stuff.

I like the idea of separating read/query model from write/business model which separate the real domain from the corruption of querying and data representation in UI, also a big gain in scalability is achieved by the use of event sourcing and separating work load of querying vs commands and operations on the domain.

Although all these stuff are very interesting but it increases the complexity of implementation and adds additional event storage and complicates the architecture a little, so for small to medium applications the Pure Old Domain Driven Design would be more convenient, maybe it could be used in parts of the application as a separate bounded context.

For small to medium less complex solution where PODDD is more convenient I don’t neglect all the idea of CQRS, I try to take some insight from it by separating query model from domain model, and separating query model repository (I prefer to call it Finder) from domain model repository, also the same apply to application layer.

Thus the solution will have one database with two ORM projects, one to map domain entities which are rich business entities, and another project to map query model entities (DTOs) which is more flat and more customizable to presentation or consumer.

The domain model has the domain repository with crud operations with limited read to what is required by domain. and the query model has Finders with many read only queries which returns DTOs and collections of DTOs.

I’m trying to put this architecture into test and analyze the pros and cons, also it is a slight transition phase into more CQRS solution.

Trying to apply it to my Sample and see where is it going.

NHibernate 3.2 Mapping Entities and Value Objects by Code

One of the major new features of NHibernate 3.2 is Mapping by Code, this is one of the features I waited for long time ago, I don’t like mapping by xml files, it is not strongly typed, error prone, and not programmer friendly.

Most of developers like me who prefer mapping by code used to use FluentNhibernate to map their classes by code.

In this post I will introduce the initial domain model of the sample application SellAndBuy and how it is mapped using the new mapping by code feature of NHibernate 3.2.

The Model:

The model consists of five main entities:

  • Customer: A very simple entity describing a customer, has no associations or any complex constructs.
  • Item: An item entity description to describe item to be advertised for, the item is associated to a category as a many to one association. The item can contain one or more pictures through the association to a set of PictureInfo value object through the base class PicturableBase.
  • ItemCategory: Category entity describes the category of the item, a category contains a set of available conditions as a one to many aggregation.
  • ItemCondition: A value object describing a condition (New, Good, Broken, …).
  • Ad: A relatively complex entity describing the ad transaction, it is associated to a customer as many to one association, associated to an item as many to one association, and associated to a condition value object describing the item’s condition. The ad can contain one or more pictures through the association to a set of PictureInfo value object through the base class PicturableBase.
Now to the mapping code:

To map any entity you need to create a class that inherits from ClassMapping<T> and define the mapping behavior in the constructor as method calls with lambda expression parameters.

Lazy() method sets the lazy loading behavior.

Id() method defines the key of the table.

Property() method defines a property mapping to database field.

ManyToOne() method defines association to an entity with many to one cardinality.

Bag() method defines a collection of objects.

Component() is used to map a grouping of fields that is not an entity, it is very suitable for mapping value objects as they don’t have identity and they are immutable.

The following are mappings of the sample domain model.

  • CustomerMap:
    public class CustomerMap : ClassMapping<Customer>
    {
        public CustomerMap()
        {
            Lazy(false);
            Id(x => x.ID, map => map.Generator(Generators.HighLow,
                          gmap => gmap.Params(new {max_low = 100})));
            Property(x => x.FirstName, map => map.NotNullable(true));
            Property(x => x.LastName, map => map.NotNullable(true));
            Property(x => x.Email, map =>
                                       {
                                           map.Unique(true);
                                           map.Length(50);
                                           map.NotNullable(true);
                                       });
        }
    }

This mapping code first mark the class as non-lazy loaded, define the int Id field with a generation strategy, defines three properties.

  • ItemMap:
    public class ItemMap : ClassMapping<Item>
    {
        public ItemMap()
        {
            Lazy(false);
            Id(x => x.ID, map => map.Generator(Generators.HighLow,
                          gmap => gmap.Params(new {max_low = 100})));
            Property(x => x.Name,
                          map => { map.Length(150); map.NotNullable(true); });
            Property(x => x.Description,
                          map => { map.Length(1000); map.NotNullable(true); });
            ManyToOne(x => x.Category, map =>
                                           {
                                               map.Column("CategoryID");
                                               map.NotNullable(true);
                                               map.Lazy(LazyRelation.NoProxy);
                                           });
            Bag(x => x.Pictures,
               collectionMapping =>
               {
                   collectionMapping.Table("ItemPictures");
                   collectionMapping.Access(Accessor.NoSetter);
                   collectionMapping.Cascade(Cascade.All);
                   collectionMapping.Key(k => k.Column("ItemID"));
                   collectionMapping.Lazy(CollectionLazy.NoLazy);
               },
               mapping => mapping.Component(PictureInfoMap.Mapping()));
        }
    }

This mapping code mark the class as non-lazy loaded, define the Id field with a generation strategy, defines name and description simple properties.

Then comes the association of many to one to category entity through Category property, and define the mapping column name in the database, and define the lazy loading strategy of the collection.

The association to a list of PictureInfo value objects is done through Bag given the property name Pictures, and a collection mapping which describes the database table to be mapped to, the cascading strategy, the key name, and lazy loading strategy, and the accessor strategy to state that this collection will have no setter.

As the PictureInfo is a value object and not an entity, there is no separate mapper class for it and it does not have identity, so the mapping would be in place through Component, but for modularity the behavior of component mapping for PictureInfo is encapsulated in PictureInfoMap.Mapping() method which is defined as the following:

    public class PictureInfoMap
    {
        private const int MaxImageLength = 3145728; // = 3 MB

        public static Action<IComponentElementMapper<PictureInfo>> Mapping()
        {
            return c =>
            {
                c.Property(p => p.Title, map => map.Length(150));
                c.Property(p => p.FileName, map => map.NotNullable(true));
                c.Property(p => p.IsMain, map => map.NotNullable(true));
                c.Property(p => p.Picture, map =>
                               {
                                    map.NotNullable(true);
                                    map.Length(MaxImageLength);
                               });
            };
        }
    }
  • ItemCategoryMap:
        public ItemCategoryMap()
        {
            Lazy(false);
            Id(x => x.ID, map => map.Generator(Generators.HighLow, gmap =>
                                 gmap.Params(new {max_low = 100})));
            Property(x => x.Name, map => { map.Length(150); map.NotNullable(true); });
            Bag(x => x.AvailableConditions,
                collectionMapping =>
                    {
                        collectionMapping.Access(Accessor.NoSetter);
                        collectionMapping.Cascade(Cascade.All);
                        collectionMapping.Key(k => k.Column("ItemConditionID"));
                        collectionMapping.Lazy(CollectionLazy.NoLazy);
                    },
                mapping => mapping.Component(ItemConditionMap.MappingElements()));
        }
    }

This mapping code mark the class as non-lazy loaded, define the Id field with a generation strategy, defines name property.

And again it defines a bag of component for ItemCondition value object.

  • AdMap:
    public class AdMap : ClassMapping<Ad>
    {
        public AdMap()
        {
            Lazy(false);
            Id(x => x.ID, map => map.Generator(Generators.HighLow, gmap =>
                                 gmap.Params(new {max_low = 100})));
            ManyToOne(x => x.Customer, map =>
                                           {
                                               map.Column("CustomerID");
                                               map.NotNullable(true);
                                               map.Lazy(LazyRelation.NoProxy);
                                           });
            ManyToOne(x => x.Item, map =>
            {
                map.Column("ItemID");
                map.NotNullable(true);
            });
            Property(x => x.Description, map => { map.Length(1000);
                                                  map.NotNullable(true); });
            Property(x => x.Price, map => map.NotNullable(true));
            Property(x => x.CreationDate, map => map.NotNullable(true));
            Component(x => x.Condition, ItemConditionMap.Mapping());
            Bag(x => x.Pictures,
                collectionMapping =>
                    {
                        collectionMapping.Table("AdPictures");
                        collectionMapping.Access(Accessor.NoSetter);
                        collectionMapping.Cascade(Cascade.All);
                        collectionMapping.Key(k => k.Column("AdID"));
                        collectionMapping.Lazy(CollectionLazy.NoLazy);
                    },
                mapping => mapping.Component(PictureInfoMap.Mapping()));
        }
    }

Two many to one associations to customer and item, one value object association to Condition as a component, and like Item a bag of PictureInfo value object.

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.

Entities and Value Objects

One of the building blocks of a Domain Driven Design application are entities and value objects.

Entity is an object with identity, it is defined by its identity and continuity not its attributes, for example a person is an entity with identity (maybe it is social security number, maybe a user id, maybe Guid) but this person remains the same even after changing his address or even his name. two instances of person objects with the same identity are the same even if they are not the same object in memory, even if they have different attributes (Properties and Fields) thus it is a mutable type, you can change its attributes and it remains the same entitiy.

Value Object on the other hand is an object that contains attributes with no conceptual identity, two value objects with the same attributes are the same. thus it is immutable type, when you change any attribute of value object it becomes a different value object. an example of value object is address (unless your application domain states that address is a key information with identity like shipping applications), the address is a value object attached to the person, you can not identify address on its own, you just can fetch a person entity and get the address.

When developing a DDD application in .net usually I create a Layer Super Type for entities and value objects as follows:

EntityBase: Each entity should have Identity, this identity could be an int (auto number), a Guid, a string, custom identity object, or any type. this identity should be the base of object hash code, equality, and comparing operators. the following base class handles these aspects:

    public abstract class EntityBase<TEntity, TID> :
        IEquatable<EntityBase<TEntity, TID>>
        where TEntity : EntityBase<TEntity, TID>
    {
        #region Identity

        public virtual TID ID { get; protected set; }

        #endregion

        #region Overrides

        /// <summary>
        /// Indicates whether the current object
        /// is equal to another object of the same type.
        /// </summary>
        /// <returns>
        /// true if the current object is equal
        /// to the <paramref name="other"/> parameter;
        /// otherwise, false.
        /// </returns>
        /// <param name="other">An object to compare with this object.</param>
        public bool Equals(EntityBase<TEntity, TID> other)
        {
            if (other == null)
                return false;

            // Handle the case of comparing two NEW objects
            var otherIsTransient = Equals(other.ID, default(TID));
            var currentIsTransient = Equals(ID, default(TID));

            if (otherIsTransient && currentIsTransient)
                return ReferenceEquals(other, this);

            return other.ID.Equals(ID);
        }

        /// <summary>
        /// Equality
        /// </summary>
        public override bool Equals(object obj)
        {
            var other = obj as TEntity;

            return Equals(other);
        }

        /// <summary>
        /// Get hash code
        /// </summary>
        public override int GetHashCode()
        {
            var thisIsTransient = Equals(ID, default(TID));

            // When this instance is transient, we use the base GetHashCode()
            return thisIsTransient ? base.GetHashCode() : ID.GetHashCode();
        }

        /// <summary>
        /// Equal operator
        /// </summary>
        public static bool operator ==
            (EntityBase<TEntity, TID> x, EntityBase<TEntity, TID> y)
        {
            return Equals(x, y);
        }

        /// <summary>
        /// Not equal operator
        /// </summary>
        public static bool operator !=
            (EntityBase<TEntity, TID> x, EntityBase<TEntity, TID> y)
        {
            return !(x == y);
        }

        #endregion
    }

The entity base has two generic parameters, one for the type of entity TEntity, and the other for identity type TID, it implements IEquatable .net interface.

ID field is defined in line 7 using the TID type.

Implementation of strongly typed IEquatable Equals method and Object override Equals methods are provided to handle equality of two entities given and check their transient state. transient means that the entity has been created without setting the ID yet, thus the ID have a default value based on type (if reference type will be null, if primitive type will hold the default value), of course there should not be an entity defined with an id of null or default value. if both entities are transient then we have to check if they point to the same memory address thus they are the same object in terms of .net, otherwise we shall compare the identities.

The equals and not equals operators are also implemented and the GetHashCode also should return the identity’s hash code.

ValueObjectBase: Value object have no Identity, object hash code should represent the hash code of all it’s attributes, equality, and comparing operators should compare all and each field in the object:

    public class ValueObjectBase<TValueObject> :
        IEquatable<TValueObject>
        where TValueObject : ValueObjectBase<TValueObject>
    {
        #region Overrides

        /// <summary>
        /// Indicates whether the current object
        /// is equal to another object of the same type.
        /// </summary>
        /// <returns>
        /// true if the current object is equal
        /// to the <paramref name="other"/> parameter; otherwise, false.
        /// </returns>
        /// <param name="other">An object to compare with this object.</param>
        public bool Equals(TValueObject other)
        {
            if (other == null)
                return false;

            // Compare all public properties
            var publicProperties = GetType().GetProperties();

            if (publicProperties != null && publicProperties.Any())
                return publicProperties
                    .All(item => item.GetValue(this, null)
                    .Equals(item.GetValue(other, null)));

            return true;
        }

        /// <summary>
        /// Equality
        /// </summary>
        public override bool Equals(object obj)
        {
            // If both are null, or both are same instance, return true
            if (ReferenceEquals(obj, this))
                return true;

            if (obj == null)
                return false;

            var item = obj as ValueObjectBase<TValueObject>;

            if (item == null)
                return false;

            return Equals((TValueObject) item);
        }

        /// <summary>
        /// Get hash code
        /// </summary>
        public override int GetHashCode()
        {
            var hashCode = 31;
            var changeMultiplier = false;
            const int index = 1;

            // Compare all public properties
            var publicProperties = GetType().GetProperties();

            if (publicProperties != null && publicProperties.Any())
            {
                foreach (var value in publicProperties
                    .Select(item => item.GetValue(this, null)))
                {
                    if (value != null)
                    {
                        hashCode = hashCode * ((changeMultiplier) ? 59 : 114)
                            + value.GetHashCode();
                        changeMultiplier = !changeMultiplier;
                    }
                    else
                        hashCode = hashCode ^ (index * 13); // Support order
                }
            }

            return hashCode;
        }

        /// <summary>
        /// Equal operator
        /// </summary>
        public static bool operator ==
            (ValueObjectBase<TValueObject> x, ValueObjectBase<TValueObject> y)
        {
            return Equals(x, y);
        }

        /// <summary>
        /// Not equal operator
        /// </summary>
        public static bool operator !=
            (ValueObjectBase<TValueObject> x, ValueObjectBase<TValueObject> y)
        {
            return !(x == y);
        }

        #endregion
    }

This implementation is taken from Cesar de la Torre which uses reflection to compare all the fields of the value object.