qSnap: A Cross-browser Snapshot Tool

Our team has just released qSnap, a free product of QASymphony to capture webpage screenshots running as a browser extension on Chrome, Opera and Safari, an add-on on Firefox or a plugin on Internet Explorer.

Image

Here are some features of qSnap:

  • Capture multiple webpage screenshots within a single browser session, either it is a portion or the whole web page
  • Annotate multiple screenshots using qSnap editor
  • Import or drag-drop files from your computer to qSnap editor to annotate
  • Save all captured/annotated screenshots to local files
  • Upload screenshots to our free images hosting service
  • Share links of screenshots to your friends or to social networks like Facebook, Google+, Twitter
  • Browser support: Firefox (latest), Chrome (latest), Safari (5.1 on Windows, 6.x on Mac OS), Internet Explorer 7+, Opera 18+
  • Platform support: Linux, Mac OS, Windows

To be able to share links to your screenshots, you must first register an account with our free hosting service at https://qsnapnet.com/. After registered successfully, you can start to capture any web page screenshot, annotate then upload it to your account. Each uploaded screenshot has an Url that you can share with your friends or to social networks. You can also manage the captured screenshots  by logging into https://qsnapnet.com.

Here is a full page screenshot of my blog captured by qSnap using full page capture mode: https://qsnapnet.com/snaps/wvpm25q57q77gb9

To download and install qSnap to your desired browser, go to: https://qsnapnet.com/#download

Happy snapping and don’t forget to share your comment about qSnap!

Entity Framework POCO, Repository and Specification Pattern [Upgraded to EF 5]

[Updated on Nov 18 2012]: The source code now moved to github @ https://github.com/huyrua/efprs. Let start making pull requests yourself :)

I am happy to announce that the framework has been upgraded to target .NET 4.5, Entity Framework 5 and Visual Studio 2012. This post is also a response to someone asking me when should the framework being upgraded to Entity Framework 5.

Some notes regarding this upgrade:

- The source code is now restructured to two versions: one for .Net Framework 4.0, the other one for .Net Framework 4.5. You can access to the source code at http://ef4prs.googlecode.com/svn/trunk/ef4prs-read-only. However, the download page only shows specific versions for you to choose which version that best fits your need.

- Removed repository implementation against ObjectContext, this means the repository is now interfacing mainly with DbContext (not a Lab version anymore). So, if you prefer to work with DbContext, you can get the framework up and running quickly. On the other hand, if you want to work with ObjectContext, this is also easy by upgrading/migrating code from .NET 4.0 version.

That’s it! Not much changes from this upgrade, but that’s a good sign to me since EF 5 does not break some low level code.

Download links http://code.google.com/p/ef4prs/downloads/list

Cheers.

“Tell the whole story, share a trace”

It’s the statement in the video introducing the product we have been building and just released recently, qTrace.

After many years working on outsourcing projects, I am very excited to be involved in building a product which I myself can be proud of. Now I can talk to my mom: “Look, mom, that’s the one we build. It’s qTrace” :)

For those who interest in the technology stack we use to build qTrace:

- .NET Framework 4

WPF and Caliburn Framework which applies Model-View-ViewModel design pattern.

- Castle Windsor for dependency injection

- Plug-able bug tracker integration with Managed Extensibility Framework (MEF)

-  OpenXML SDK to generate defect report to MS Word format

- Pdf Sharp and MigraDoc to generate defect report to Pdf format

- WCF for communicating with activation server for licensing matters

Visit www.qasymphony.com for more details on the product.

Enjoy tracing!

How We Do Dependency Injection

Dependency Injection (DI) design pattern has become more and more popular in software development recent years. There are many open source frameworks that help us apply DI design pattern out there, like Castle Windsor, NInject, StructureMap, Unity,… just named a few. From my point of view, using a framework for DI means using an Inversion of Control (IoC) container to wire up the dependencies between objects and let it manages their life cycles after registering the object graphs with that container.


Almost softwares I built in recent 2-3 years have been applied DI design pattern with a help of an IoC container. For what? you may ask. Well, I think the benefit of applying DI is that it allows me to design loosely coupled objects to ease unit testing. At run time, the IoC container helps wire up all the dependencies between objects for me.

However, using an IoC container for DI in building softwares doesn’t mean I always use it in a right way. In other words, there was a bad practice applied when using an IoC container. One of the wrong way I can tell you is making an IoC container static or singleton and use it in many places, across layers which is supposed to be a Service Locator (anti-)pattern. If you want to be clear, read this: http://www.devtrends.co.uk/blog/how-not-to-do-dependency-injection-the-static-or-singleton-container, or even if you want to be more serious on the topic, read this article and the comments too: http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx

After reading those two articles and agreed with the authors, I realized that I have used the static IoC container in many softwares I built. So I decided to re-factored our code to avoid doing that wrong thing again. The IoC container that I am familiar with is Castle Windsor. I used it from the time I knew what DI is, and I am still using it just because I like the way to register types with IWindsorContainer using fluent interfaces that is very readable.

To demonstrate, here is an ASP.NET MVC application that used the Service Locator to resolve the services on which a controller depends.

The static IoC container class:

public static class IoC
{
    public static IWindsorContainer Container { get; set; }
}

The IoC.Container static property will be assigned to an instance of WindsorContainer class in the global MvcApplication (Global.ascx.cs) and it as well will be used to register types at web application start up:

public class MvcApplication : System.Web.HttpApplication
{
    static MvcApplication()
    {
        IoC.Container = new WindsorContainer();
        RegisterComponentsWith(IoC.Container);
    }

    private static void RegisterComponentsWith(IWindsorContainer container)
    {
        container.Register(Component.For<IRepository>().ImplementedBy<Repository>().LifeStyle.Transient);
        container.Register(Component.For<IAccountService>().ImplementedBy<AccountService>().LifeStyle.Transient);
        container.Register(Component.For<IEmailService>().ImplementedBy<EmailService>().LifeStyle.Transient);
container.Register(Component.For<IFormsAuthenticationService>().ImplementedBy<FormsAuthenticationService>().LifeStyle.Transient);
        // other type registrations...
    }
}

And this is how we use that IoC container to resolve service types in a controller:

public class AccountController : Controller
{
    public T GetService<T>()
    {
        return IoC.Container.Resolve<T>();
    }

    public AccountController()
    {
    }
    public ActionResult LogOn(LogOnModel model)
    {
        if (ModelState.IsValid)
        {
            IAccountService accountService = GetService<IAccountService>();
            if (accountService.ValidateLogin(model.Email, model.Password))
            {
                // code...
            }
            // rest of the code...
        }
        // rest of the code...
    }
    // rest of the code
}

Now I am using an IoC container badly and _without_ dependency injection. So how to apply DI correctly, you ask? The solution is to get rid of static IoC container and remove the dependency to that container from not only the controller(s) but also anywhere on the code, except the code that instantiates the container and registers the object graphs in the global MvcApplication.

Here is the refactored AccountController that applies DI correctly

public class AccountController : Controller
{
    private readonly IAccountService _accountService;
    private readonly IEmailService _emailService;
    private readonly IFormsAuthenticationService _formsAuthenticationService;

    public AccountController(IAccountService accountService,
        IEmailService emailService,
        IFormsAuthenticationService formsAuthenticationService)
    {
        _accountService = accountService;
        _emailService = emailService;
        _formsAuthenticationService = _formsAuthenticationService;
    }
    public ActionResult LogOn(LogOnModel model)
    {
        if (ModelState.IsValid)
        {
            if (_accountService.ValidateLogin(model.Email, model.Password))
            {
                // code...
            }
            // rest of the code...
        }
        // rest of the code...
    }
    // rest of the code
}

We also need to implement a custom controller factory that is responsible for creating an appropriate controller and also injecting the services on which that controller depends. Here is the custom controller factory which inherits from ASP.NET MVC’s DefaultControllerFactory class:

public class WindsorControllerFactory : DefaultControllerFactory
{
    private readonly IWindsorContainer _container;

    public WindsorControllerFactory(IWindsorContainer container)
    {
        _container = container;
    }

    protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null)
            throw new HttpException(404, string.Format("The controller for path '{0}' could not be found or it does not implement IController.",
                requestContext.HttpContext.Request.Path));

        return (IController)_container.Resolve(controllerType);
    }

    public override void ReleaseController(IController controller)
    {
        _container.Release(controller);
    }
}}

Here is the revised code to instantiate the container and register types with it in MvcApplication class:

public class MvcApplication : System.Web.HttpApplication
{
    private static IWindsorContainer _container = new WindsorContainer();
    static MvcApplication()
    {
        RegisterComponentsWith(_container);
    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_container));
    }

    private static void RegisterComponentsWith(IWindsorContainer container)
    {
        container.Register(Component.For<IRepository>().ImplementedBy<Repository>().LifeStyle.Transient);
        container.Register(Component.For<IAccountService>().ImplementedBy<AccountService>().LifeStyle.Transient);
        container.Register(Component.For<IEmailService>().ImplementedBy<EmailService>().LifeStyle.Transient);
        container.Register(Component.For<IFormsAuthenticationService>().ImplementedBy<FormsAuthenticationService>().LifeStyle.Transient);

        // register controllers with the container
        container.Register(
                AllTypes.FromThisAssembly()
                .BasedOn<IController>()
                .Configure(c => c.LifeStyle.Transient));
        // other type registrations...
    }

    // code...
}

Now I am using DI correctly. But there still is a problem to me: since I want to use dependency injection, I have to list out all the dependencies to services in controller constructor, here I use constructor injection or I may opt to use property injection. Both ways leads me to have a ‘greedy’ controller because there are controller’s action methods being invoked  that do not actually use any of dependent services at all!

After a while looking for a way to solve the problem, I found that Castle Windsor has a feature called TypedFactoryFacility that allows us to define an interface as a factory which, once registered with the container, will resolves the types for us on behalf of container. Note that we don’t need to provide any implementation for that typed service factory interface at all.

Here is the typed factory interface to resolve the service(s):

public interface IServiceFactory
{
    T Create<T>();

    void Release(object service);
}

Register the typed factory with the container:

// code..
container.Register(Component.For<IRepository>().ImplementedBy<Repository>().LifeStyle.Transient);
container.Register(Component.For<IAccountService>().ImplementedBy<AccountService>().LifeStyle.Transient);
container.Register(Component.For<IEmailService>().ImplementedBy<EmailService>().LifeStyle.Transient);
container.Register(Component.For<IFormsAuthenticationService>().ImplementedBy<FormsAuthenticationService>().LifeStyle.Transient);
// code..
container.AddFacility<TypedFactoryFacility>();
container.Register(
    Component.For<IServiceFactory>()
        .AsFactory()
        .LifeStyle.Transient);
// code..

Use the typed factory in the controller to resolve the designed service once we really need it:

public class AccountController : ControllerBase
{
    private readonly IServiceFactory _serviceFactory;
    public AccountController(IServiceFactory serviceFactory)
    {
        _serviceFactory = serviceFactory;
    }

    [HttpPost]
    public ActionResult LogOn(LogOnModel model)
    {
        if (ModelState.IsValid)
        {
            IAccountService accountService = _serviceFactory.Create<IAccountService>();
            if (accountService.ValidateLogin(model.Email, model.Password))
            {
                IFormsAuthenticationService formsAuthenticationService = _serviceFactory.Create<IForsAuthenticationService>();
                formsAuthenticationService.SignIn(model.Email, model.RememberMe);
                _serviceFactory.Release(formsAuthenticationService);
                // rest of code...
            }
            _serviceFactory.Release(accountService);
            // rest of code...
        }
        // rest of code...
    }
    // rest of code
}

From the code, every when you call:

IAccountService accountService = _serviceFactory.Create<IAccountService>();

…is  equivalent of calling:

IAccountService accountService = kernel.Resolve<IAccountService>();

That’s it. I hope you understand how  to apply DI correctly and also find the usefulness of Castle Windsor’s TypedFactoryFacility.

Comments are welcome.

Separate Binary Data Out Of An Entity For Effective Loading

I received an email this morning asking about loading binary data related to an entity, here is the excerpt:

Hello, 

I was reading the following post on your blog and checking the code in Google Code. Entity Framework 4 POCO, Repository and Specification Pattern [Upgraded to EF 4.1]

I found it really interesting and realized that the performance issues where solved.

But how do you handle binary data?

Consider you have an entity with 2 Byte[] fields (varbinary or filestream in the database).

public class Product
{
    public Int32 Id { get; set; }

    public Boolean Available { get; set; }

    public String Name { get; set; }

    public Byte[] Image { get; set; }

    public Byte[] Brochure { get; set; }
}

When N records are loaded you will get N * 2 files being loaded even if you want to display only the names.

One solution to this problem is to apply a projection. For example:

context.Products.Where(x => x.Available).Select(x => new ProductView { Available = x.Available, Name = x.Name, Image = x.Image });

In this case I am leaving out the brochure but including the image … How do you address this with your code?”

—————————–

Here is my answer:

In my experience regarding the binary data, I would create another entity, says, BinaryData which is somewhat like below (of course there will be a corresponding BinaryData table in the database):
public class BinaryData
{
    public Int32 Id { get; set; }
    public Byte[] Data { get; set; }
}
Then within an entity that has binary data, like your Product with Image or Brochure properties, I just add dependencies (or relationship) to the BinaryData entity:
public class Product
{
    // ... other properties
    public BinaryData Image { get; set; }
    public BinaryData Brochure { get; set; }
}

With lazy-loading enabled, you won’t worry about loading binary data (Image, Brochure) when loading Product, but it will be loaded when you access to it like: product.Image”

I myself think it is a good design practice when working with ORM framework, like Entity Framework or NHibernate.

What do you think? If there is a better solution for this, please drop a comment.

Entity Framework 4 POCO, Repository and Specification Pattern [Upgraded to EF 4.1]

I am excited to announce that the framework has been upgraded to the new version to follow up with the final release of Microsoft ADO.NET Entity Framework 4.1 yesterday. The upgrade includes some changes from Entity Framework API itself and also incorporates bug fixed as well many great suggestion/comments for improvement from the readers. You can download the latest version of the framework (1.4 at this writing) at http://code.google.com/p/ef4prs/downloads/list and play around with it. Note that to be able to compile the code, you first need to download and install EF 4.1 using standalone installer or by adding nuget package to your project.

If you are new to this framework and the design idea behind it, take some time to read these posts first:

Happy coding!

Entity Framework 4 POCO, Repository and Specification Pattern [Upgraded to CTP5]

Before reading this, you might want to read these two posts first:

You might have been aware that MS just released Entity Framework 4 CTP5 some days ago. There have been some comments asking me when the data access layer would be upgraded to that version. Since I had been quite busy these days,  the answers for these questions was just a promise that I would do the upgrade when I had time after I finished investigating the new release carefully. However, some readers seem to be anxious waiting for the code updated so they keep asking me for the progress (and I feel good because I know there are some ones who are interested in the framework I built :)).

So, today I decided to fulfill my promise: the source code has been updated in google code. You can download the latest version (1.3 at this  writing) here http://code.google.com/p/ef4prs/downloads/list

Note: to be able to compile the code, you must first download and install EF4 CTP5.

Some implementation notes:

- The assembly is now changed to EntityFramework.dll and located at C:\Program Files (x86)\Microsoft ADO.NET Entity Framework Feature CTP5\Binaries\EntityFramework.dll

- Base mapping class has changed from EntityConfiguration<T> to EntityTypeConfiguration<T>

- Entity Framework team seems to concentrate on implementing DbContext much more than ObjectContext. But if you want to access to ObjectContext from DbContext, here is the way:

ObjectContext ctx = ((IObjectContextAdapter)_dbContext).ObjectContext;

- We do not need to register entity any more, just add mapping class(es) to the ModelBuilder then we are all set. Well, this is for your information only, since this framework will do this automatically in the XContextBuilder class.

- The most and important thing, I think, is EF now will automatically map entity relationships without explicitly writing the mapping code. For example:

I have an entity Customer that has many Orders. These two classes will be defined as below:

public class Customer : Entity
{
    public Customer()
    {
        Orders = new List<Order>();
    }

    public virtual string Firstname
    {
        get; set;
    }

    public virtual string Lastname
    {
        get; set;
    }

    public virtual IList<Order> Orders
    {
        get;
        set;
    }

    public virtual DateTime Inserted
    {
        get; set;
    }
}

public class Order : Entity
{
    public Order()
    {
        OrderLines = new List<OrderLine>();
    }

    public virtual IList<OrderLine> OrderLines
    {
        get;
        set;
    }

    public virtual DateTime OrderDate
    {
        get; set;
    }

    public virtual Customer Customer
    {
        get; set;
    }
}

Here is the mapping classes:

public class CustomerMapping : EntityTypeConfiguration<Customer>
{
    public CustomerMapping()
    {
        HasKey(x => x.Id);

        Property(x => x.Firstname).IsRequired().HasMaxLength(25);
        Property(x => x.Lastname).IsRequired().HasMaxLength(25);
        Property(x => x.Inserted);

        //we dont need to write this code to specify the relationship, this will autolatically done by EF
        //HasMany(x => x.Orders).WithRequired(y => y.Customer).HasForeignKey(c => c.CustomerId);

        ToTable("Customer");
    }
}

public class OrderMapping : EntityTypeConfiguration<Order>
{
    public OrderMapping()
    {
        HasKey(x => x.Id);

        Property(x => x.OrderDate);

        // No need to write mapping code to Customer
        //HasRequired(c => c.Customer);

        ToTable("Order");
    }
}

With these mappings, EF will generate the Order table with a foreign key to Customer table as below:

You can download and check out the test code to see other mapping scenarios like many-to-many or how to change the table name in the mapping code.

Happy coding!

Specification Pattern In Entity Framework 4 Revisited

After the post Entity Framework 4 POCO, Repository and Specification Pattern was published for a while, there have been quite a few of positive comments from readers. At first, I thought that this piece of code should have been used as a prototype to demonstrate the implementation of EF POCO, the Repository and Specification pattern. I known it is not the optimized piece of code to everyone and that if there was suggestion for improvement, I would leave to reader as I thought once they understood the design idea, they could extend/change/use the API in anyway they want.

However, there are also some comments concerning about the way the Specification pattern is applied which might cause the BIG performance problem when used that I was not aware of. Even I am using this API in my current work but it’s a shame that I rarely use Specification to query the data but the other methods are enough for me.

For your information, here are the extracted comments from Jon & Buu (many thanks :)) which pointed out the problem:

Jon: Linq to Entities uses expressions to build the SQL that will be executed on the database server. If you use the specification pattern as designed above, i.e., without expressions, the generated SQL is never impacted. Instead, EF will generate “SELECT * FROM Table,” returning all rows. From there the specification pattern kicks in and filters the data in memory. Your test passed because you got the right result, but not in the right way. it would never work in a real would scenario.”

Buu:  …the cause of the issue as Jon observed is because the method (IsSatisfiedBy) of Specification is fed into the Where method of the query object. That results in LINQ-2-EF loading all records to memory objects and then filter those objects using the passed in method. That’s a huge performance hit.

To fix the issue, you should feed into the Where method an instance of Expression so that the Where overload in IQueryable is invoked (instead of the one in IEnumerable). The Specification already stores an instance of Expression, so the code change should be straightforward. However, since not all expression operations are supported by LINQ-2-EF, you might end up breaking some existing code. Be warned…”

I verified the problem with Entity Framework Profiler and I have to say the problem is there. Here are some tests I made to retrieve a product by name, and also the results from the profiler:

Use standard lambda expression:

private void FindProductByName()
{
    IEnumerable<Product> products = productRepository.Find<Product>(p => p.Name == "Windows XP Professional");
    Assert.AreEqual(1, products.Count());
}

The output from the profiler

EF generated the correct sql and returned the expected result, no thing wrong with this.

Use specification

private void FindBySpecification()
{
    Specification<Product> specification = new Specification<Product>(p => p.Name == "Windows XP Professional");
    IEnumerable<Product> products = productRepository.Find<Product>(specification);
    Assert.AreEqual(1, products.Count());
}

The output from the profiler

As you can see there is a problem with using specification to retrieve a product in which EF loads all the products from the database, then perform filtering a product against the whole set of products in-memory. If the number of products is huge, it really is an issue since the query is not efficient at all.

This is because the specification pattern is implemented incorrectly. To fix it, I change the specification contract as the following:

public interface ISpecification<TEntity>
{
    TEntity SatisfyingEntityFrom(IQueryable<TEntity> query);

    IQueryable<TEntity> SatisfyingEntitiesFrom(IQueryable<TEntity> query);
}

And the implementation of some generic repository’s methods which accepts a specification are as following:

public class GenericRepository : IRepository
{
    // other code...

    public IQueryable<TEntity> GetQuery<TEntity>() where TEntity : class
    {
        var entityName = GetEntityName<TEntity>();
        return ObjectContext.CreateQuery<TEntity>(entityName);
    }

    public TEntity FindOne<TEntity>(ISpecification<TEntity> criteria) where TEntity : class
    {
        return criteria.SatisfyingEntityFrom(GetQuery<TEntity>());
    }

    public IEnumerable<TEntity> Find<TEntity>(ISpecification<TEntity> criteria) where TEntity : class
    {
        return criteria.SatisfyingEntitiesFrom(GetQuery<TEntity>());
    }

    // other code...
}

The implementation of a simple specification is straightforward.

public class Specification<TEntity> : ISpecification<TEntity>
{
    public Specification(Expression<Func<TEntity, bool>> predicate)
    {
        Predicate = predicate;
    }

    public TEntity SatisfyingEntityFrom(IQueryable<TEntity> query)
    {
        return query.Where(Predicate).SingleOrDefault();
    }

    public IQueryable<TEntity> SatisfyingEntitiesFrom(IQueryable<TEntity> query)
    {
        return query.Where(Predicate);
    }

    public Expression<Func<TEntity, bool>> Predicate;
}

Here is the output of the profiler with the new specification implementation:

As you can see EF now generates the expected sql and returns expected result as well, very efficient.

What about the composite specification?

If you already read the previous post, you should have known that the composite specification was being used to chain the specifications. With the new implementation of specification, the composite specification implementation also needs to change. The technique being applied here is to combine the lambda expression (or predicate) of each specification (left and right side of a composite specification) to create a new lambda expression then this new lambda expression is fed to the IQuerable object for querying.

Here is the code of the extension method of lambda expression which is mostly inspired from here:

public static class ExpressionExtension
{
    public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
    {
        // build parameter map (from parameters of second to parameters of first)
        var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);

        // replace parameters in the second lambda expression with parameters from the first
        var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);

        // apply composition of lambda expression bodies to parameters from the first expression
        return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
    }

    public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
    {
        return first.Compose(second, Expression.And);
    }

    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
    {
        return first.Compose(second, Expression.Or);
    }
}

And here is the implementation of the composite specification:

public class AndSpecification<TEntity> : CompositeSpecification<TEntity>
{
    public AndSpecification(Specification<TEntity> leftSide, Specification<TEntity> rightSide)
        : base(leftSide, rightSide)
    {
    }

    public override TEntity SatisfyingEntityFrom(IQueryable<TEntity> query)
    {
        return SatisfyingEntitiesFrom(query).FirstOrDefault();
    }

    public override IQueryable<TEntity> SatisfyingEntitiesFrom(IQueryable<TEntity> query)
    {
        return query.Where(_leftSide.Predicate.And(_rightSide.Predicate));
    }
}

public class OrSpecification<TEntity> : CompositeSpecification<TEntity>
{
    public OrSpecification(Specification<TEntity> leftSide, Specification<TEntity> rightSide)
        : base(leftSide, rightSide)
    {
    }

    public override TEntity SatisfyingEntityFrom(IQueryable<TEntity> query)
    {
        return SatisfyingEntitiesFrom(query).FirstOrDefault();
    }

    public override IQueryable<TEntity> SatisfyingEntitiesFrom(IQueryable<TEntity> query)
    {
        return query.Where(_leftSide.Predicate.Or(_rightSide.Predicate));
    }
}

The test code to find product by name and price which uses the AndSpecification

private void FindByAndCompositeSpecification()
{
    IEnumerable<Product> products = productRepository.Find<Product>(
        new Specification<Product>(p => p.Price < 100).And(new Specification<Product>(p => p.Name == "Windows XP Professional")));
    Assert.AreEqual(1, products.Count());
}

The output from the profiler:

The test code to find product which applies the OrSpecification:

private void FindByOrCompositeSpecification()
{
    IEnumerable<Product> products = productRepository.Find<Product>(
        new Specification<Product>(p => p.Price < 100).Or(new Specification<Product>(p => p.Name == "Windows XP Professional")));
    Assert.AreEqual(2, products.Count());
}

The output from the profiler:

The problem is solved!

The updated source code can be downloaded here.

Once again, comments are welcome.

Entity Framework 4 POCO, Repository and Specification Pattern

Updated (25 Aug 2010): There are some concerns from Jon and Buu about the performance hit when implementing the specification pattern follow the way that this post shows. That said, the implementation of this pattern has been updated and you can read it through at Specification Pattern In Entity Framework 4 Revisited
Updated: The post has a small update with the new release of Entity Framework Feature Community Technology Preview 4 (CTP4) in which the ObjectContextBuilder class changed its base class from ContextBuilder<T> to ModelBuilder. The source code has also been upgraded to CTP4 version. Note that to successfully compile the code, you have to install the EF CTP4 version which can be downloaded here.
After a decent period using NHibernate & SharpArchitecture to build .NET application, I eventually have a chance to work with Entity Framework (EF) in recent project. The client wants to leverage MS technologies as much as possible instead of some OSS frameworks to avoid learning curves and maintenance issues that might occurs later on. No matter what the decision is good or bad which some of you might agree or disagree, I am being put in a position to build the application with the team. And just because I have had some experience on building data access mechanism (mostly with ADO.NET and NHibernate), this more or less leads me to work with this data access layer again. 

Just like those who are going to work with a new technology, I started digging into EF by reading related books, hunting the web to find good articles and blog posts mentioning about building data access on top of EF. Since I have worked with NHibernate and also use Repository Pattern  to build the data access layer, the keywords entered Google should include: “Entity Framework”, “Entity Framework Repository”, “Entity Framework vs. NHibernate”, “Entity Framework POCO and Repository Pattern”  blah blah blah. Luckily I found quite a few of good posts (these will be listed as source of references at the end of this post).

With some sources of reference in hand, I started to build the data access layer using EF. But before talking about how I build it, here is a set of design patterns I want to apply: Repository, Unit of Work, and Specification. Since I also want to use POCOs instead of objects auto-generated by Visual Studio so this, once again, leads me to looking for the technique to write mapping stuff, and I found that it is also very easy.

Repository

Repository is defined as “an abstraction that provides us with persistence ignorance and a separation of concerns where the responsibility of persisting domain objects is encapsulated by the Repository that  leaving the domain objects to deal entirely with the domain model and domain logic.”

The contract for a repository contains operations to perform CRUD and also for querying entity objects.  The general technique is using .NET generic to build the Repository, the code below depicts the contract of repository:

public interface IRepository<TEntity> : IDisposable where TEntity : class
{
    IQueryable<TEntity> GetQuery();
    IEnumerable<TEntity> GetAll();
    IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate);
    TEntity Single(Expression<Func<TEntity, bool>> predicate);
    TEntity First(Expression<Func<TEntity, bool>> predicate);
    void Add(TEntity entity);
    void Delete(TEntity entity);
    void Attach(TEntity entity);
    void SaveChanges();
    void SaveChanges(SaveOptions options);
}

And the common implementation:

/// <summary>
/// A generic repository for working with data in the database
/// </summary>
/// <typeparam name="T">A POCO that represents an Entity Framework entity</typeparam>
public class GenericRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
    /// <summary>
    /// The context object for the database
    /// </summary>
    private ObjectContext _context;

    /// <summary>
    /// The IObjectSet that represents the current entity.
    /// </summary>
    private IObjectSet<TEntity> _objectSet;

    /// <summary>
    /// Initializes a new instance of the GenericRepository class
    /// </summary>
    /// <param name="context">The Entity Framework ObjectContext</param>
    public GenericRepository(ObjectContext context)
    {
        _context = context;
        _objectSet = _context.CreateObjectSet<TEntity>();
    }

    /// <summary>
    /// Gets all records as an IQueryable
    /// </summary>
    /// <returns>An IQueryable object containing the results of the query</returns>
    public IQueryable<TEntity> GetQuery()
    {
        return _objectSet;
    }

    /// <summary>
    /// Gets all records as an IEnumberable
    /// </summary>
    /// <returns>An IEnumberable object containing the results of the query</returns>
    public IEnumerable<TEntity> GetAll()
    {
        return GetQuery().AsEnumerable();
    }

    /// <summary>
    /// Finds a record with the specified criteria
    /// </summary>
    /// <param name="predicate">Criteria to match on</param>
    /// <returns>A collection containing the results of the query</returns>
    public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
    {
        return _objectSet.Where<TEntity>(predicate);
    }

    /// <summary>
    /// Gets a single record by the specified criteria (usually the unique identifier)
    /// </summary>
    /// <param name="predicate">Criteria to match on</param>
    /// <returns>A single record that matches the specified criteria</returns>
    public TEntity Single(Expression<Func<TEntity, bool>> predicate)
    {
        return _objectSet.Single<TEntity>(predicate);
    }

    /// <summary>
    /// The first record matching the specified criteria
    /// </summary>
    /// <param name="predicate">Criteria to match on</param>
    /// <returns>A single record containing the first record matching the specified criteria</returns>
    public TEntity First(Expression<Func<TEntity, bool>> predicate)
    {
        return _objectSet.First<TEntity>(predicate);
    }

    /// <summary>
    /// Deletes the specified entitiy
    /// </summary>
    /// <param name="entity">Entity to delete</param>
    /// <exception cref="ArgumentNullException"> if <paramref name="entity"/> is null</exception>
    public void Delete(TEntity entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException("entity");
        }

        _objectSet.DeleteObject(entity);
    }

    /// <summary>
    /// Adds the specified entity
    /// </summary>
    /// <param name="entity">Entity to add</param>
    /// <exception cref="ArgumentNullException"> if <paramref name="entity"/> is null</exception>
    public void Add(TEntity entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException("entity");
        }

        _objectSet.AddObject(entity);
    }

    /// <summary>
    /// Attaches the specified entity
    /// </summary>
    /// <param name="entity">Entity to attach</param>
    public void Attach(TEntity entity)
    {
        _objectSet.Attach(entity);
    }

    /// <summary>
    /// Saves all context changes
    /// </summary>
    public void SaveChanges()
    {
        _context.SaveChanges();
    }

    /// <summary>
    /// Saves all context changes with the specified SaveOptions
    /// </summary>
    /// <param name="options">Options for saving the context</param>
    public void SaveChanges(SaveOptions options)
    {
        _context.SaveChanges(options);
    }

    /// <summary>
    /// Releases all resources used by the WarrantManagement.DataExtract.Dal.ReportDataBase
    /// </summary>
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    /// <summary>
    /// Releases all resources used by the WarrantManagement.DataExtract.Dal.ReportDataBase
    /// </summary>
    /// <param name="disposing">A boolean value indicating whether or not to dispose managed resources</param>
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (_context != null)
            {
                _context.Dispose();
                _context = null;
            }
        }
    }
}

As you can see, the repository use a generic type of TEntity to represent an entity that we want to manipulate. Suppose we have an entity named Customer, when we need to perform operations on Customer entity we will do something like this:

IRepository<Customer> customerRepository = new GenericRepository<Customer>();

// Gets all customers
IEnumerable<Customer> customers = customerRepository.GetAll();

// Insert a new customer
Customer customer = new Customer { Firstname = "Huy", Lastname = "Nguyen" };
customerRepository.Add(customer);
customerRepository.SaveChanges();

For some specific entity selection, instead of widening the contract of generic repository, the common technique is to subclass the generic repository to implement a specific repository:

public class CustomerRepository : GenericRepository<Customer>, ICustomerRepository
{
    public CustomerRepository(ObjectContext context) : base(context) { }

    public IList<Customer> NewlySubscribed()
    {
        var lastMonth = DateTime.Now.Date.AddMonths(-1);

        return GetQuery().Where(c => c.Inserted >= lastMonth)
        .ToList();
    }

    public Customer FindByName(string firstname, string lastname)
    {
        return GetQuery().Where(c => c.Firstname == firstname && c.Lastname == lastname).FirstOrDefault();
    }
}

But I find it a bit inconvenient since we have to create multiple repository instances in case we want to work with multiple entities at a time. In other words, if we want to perform operations on n entities, we have to create nearly n repository instances (I am saying ‘nearly’ because if an entity is not an aggregate root, we do not implement a repository for it), like the code below:

private void AddOrders()
{
    var context = new NorthwindEntities("connectionString");

    var customerRepository = new CustomerRepository(context);
    IRepository<Order> orderRepository = new GenericRepository<Order>(context);
    IRepository<Product> productRepository = new GenericRepository<Product>(context);

    var c = customerRepository.FindByName("John", "Doe");

    var winXP = productRepository.Single(x => x.Name == "Windows XP Professional");
    var winSeven = productRepository.Single(x => x.Name == "Windows Seven Professional");

    var o = new Order
    {
        OrderDate = DateTime.Now,
        Purchaser = c,
        OrderLines = new List<OrderLine>
        {
            new OrderLine { Price = 200, Product = winXP, Quantity = 1},
            new OrderLine { Price = 699.99, Product = winSeven, Quantity = 5 }
        }
    };

    orderRepository.Add(o);
    orderRepository.SaveChanges();
}

To get rid of that inconvenient, I decide to re-implement the more generic repository by making the repository’s methods generic:

public interface IRepository : IDisposable
{
    IQueryable<TEntity> GetQuery<TEntity>() where TEntity : class;
    IEnumerable<TEntity> GetAll<TEntity>() where TEntity : class;
    IEnumerable<TEntity> Find<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class;
    TEntity Single<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class;
    TEntity First<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class;
    void Add<TEntity>(TEntity entity) where TEntity : class;
    void Delete<TEntity>(TEntity entity) where TEntity : class;
    void Attach<TEntity>(TEntity entity) where TEntity : class;
    void SaveChanges();
    void SaveChanges(SaveOptions options);
}
And here is the implementation for the revised repository contract:
/// <summary>
/// A generic repository for working with data in the database
/// </summary>
/// <typeparam name="T">A POCO that represents an Entity Framework entity</typeparam>
public class GenericRepository : IRepository
{
    /// <summary>
    /// The context object for the database
    /// </summary>
    private ObjectContext _context;
    private readonly PluralizationService _pluralizer;

    /// <summary>
    /// Initializes a new instance of the GenericRepository class
    /// </summary>
    /// <param name="context">The Entity Framework ObjectContext</param>
    public GenericRepository(ObjectContext context)
    {
        _context = context;
        _pluralizer = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en"));
    }

    public IQueryable<TEntity> GetQuery<TEntity>() where TEntity : class
    {
        var entityName = GetEntityName<TEntity>();
        return _context.CreateQuery<TEntity>(entityName);
    }

    public IEnumerable<TEntity> GetAll<TEntity>() where TEntity : class
    {
        return GetQuery<TEntity>().AsEnumerable();
    }

    public IEnumerable<TEntity> Find<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
    {
        return GetQuery<TEntity>().Where(predicate).AsEnumerable();
    }

    public TEntity Single<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
    {
        return GetQuery>TEntity>().Single<TEntity>(predicate);
    }

    public TEntity First<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
    {
        return GetQuery<TEntity>().Where(predicate).FirstOrDefault();
    }

    public void Add<TEntity>(TEntity entity) where TEntity : class
    {
        _context.AddObject(GetEntityName<TEntity>(), entity);
    }

    public void Delete<TEntity>(TEntity entity) where TEntity : class
    {
        _context.DeleteObject(entity);
    }

    private string GetEntityName<TEntity>() where TEntity : class
    {
        return string.Format("ObjectContext.{0}", _pluralizer.Pluralize(typeof(TEntity).Name));
    }
    // ...
}
With this repository we can now create only one repository every time we need to retrieve or persist an entity, we can even make this repository an instance member to be retrieved across class methods. Here is the new AddOrders method using this new repository:
private void AddOrders()
{
    var context = new NorthwindEntities("connectionString");

    var customerRepository = new CustomerRepository(context);
    var repository = new GenericRepository(context);

    var c = customerRepository.FindByName("John", "Doe");

    var winXP = repository.Single<Product>(x => x.Name == "Windows XP Professional");
    var winSeven = repository.Single<Product>(x => x.Name == "Windows Seven Professional");

    var o = new Order
    {
        OrderDate = DateTime.Now,
        Purchaser = c,
        OrderLines = new List<OrderLine>
        {
            new OrderLine { Price = 200, Product = winXP, Quantity = 1},
            new OrderLine { Price = 699.99, Product = winSeven, Quantity = 5 }
        }
    };

    repository.Add<Order>(o);
    repository.SaveChanges();
}
Of course one also creates the specific repository to widen the contract using inheritence (like CustomerRepository above) or narrow it using adapter if she wants to.
Unit of Work
The EF ObjectContext does this work for us in regarding managing UnitOfWork. It is already able to handle transaction across many operations over many different types. All we have to do is to call SaveChanges method on the ObjectContext instance as described in the above test code.
With the current implementation so far, we now have a handy generic repository to be used for data persistence and transaction handling. But there is a slight issue with this implementation. The problem being, if I had multiple POCO objects, for instance, Repository<Customer> and Repository<Product>, we would not able to run queries across both, as they would be created via different instances of ObjectContext and this leads to losing any level 1 caching.
A common solution is to build a object context factory. Every time we need an object context instance, just delegate this work to this factory class. Here is a possible implementation:
public static class ObjectContextFactory
{
    /// <summary>
    /// Gets the default ObjectContext for the project
    /// </summary>
    /// <returns>The default ObjectContext for the project</returns>
    public static NorthwindEntities GetContext()
    {
        string connectionString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;

        return GetContext(connectionString);
    }

    /// <summary>
    /// Gets the default ObjectContext for the project
    /// </summary>
    /// <param name="connectionString">Connection string to use for database queries</param>
    /// <returns>The default ObjectContext for the project</returns>
    public static NorthwindEntities GetContext(string connectionString)
    {
        return new NorthwindEntities(connectionString);
    }
}
To use it, just simply do something like the following:
private void AddOrders()
{
    var context = ObjectContextFactory.GetContext("connectionString");

    var customerRepository = new CustomerRepository(context);
    var repository = new GenericRepository(context);

    var c = customerRepository.FindByName("John", "Doe");

    var winXP = repository.Single<Product>(x => x.Name == "Windows XP Professional");
    var winSeven = repository.Single<Product>(x => x.Name == "Windows Seven Professional");

    var o = new Order
    {
        OrderDate = DateTime.Now,
        Purchaser = c,
        OrderLines = new List<OrderLine>
        {
            new OrderLine { Price = 200, Product = winXP, Quantity = 1},
            new OrderLine { Price = 699.99, Product = winSeven, Quantity = 5 }
        }
    };

    repository.Add<Order>(o);
    repository.SaveChanges();
}
At this time, I again find another inconvenient way to manage the object context. Look at the code above you will easily find that every time we work with another type of object context in another application, we have to rewrite the factory in order for it to return the actual type we need instead of the example NorthwindEntities. Is there a way to make this factory class unchanged so that we can reuse it in every application that works with any concrete instance of object context?
This reminds me about the NHibernate session manager implemented in SharpArchitecture code base. So I decide to write an object context manager which acts like that session manager. Its responsibility is to provide a mechanism to create context on demand, and it also provides a storage mechanism which is context-dependent (http context, wcf, and so on) to store object context.
public static class ObjectContextManager
{
    public static void Init(string[] mappingAssemblies, bool recreateDatabaseIfExist = false)
    {
        Init(DefaultConnectionStringName, mappingAssemblies, recreateDatabaseIfExist);
    }

    public static void Init(string connectionStringName, string[] mappingAssemblies, bool recreateDatabaseIfExist = false)
    {
        AddConfiguration(connectionStringName, mappingAssemblies, recreateDatabaseIfExist);
    }

    public static void InitStorage(IObjectContextStorage storage)
    {
        if (storage == null)
        {
            throw new ArgumentNullException("storage");
        }
        if ((Storage != null) && (Storage != storage))
        {
            throw new ApplicationException("A storage mechanism has already been configured for this application");
        }
        Storage = storage;
    }

    /// <summary>
    /// The default connection string name used if only one database is being communicated with.
    /// </summary>
    public static readonly string DefaultConnectionStringName = "DefaultDb";

    /// <summary>
    /// Used to get the current object context session if you're communicating with a single database.
    /// When communicating with multiple databases, invoke <see cref="CurrentFor()" /> instead.
    /// </summary>
    public static ObjectContext Current
    {
        get
        {
            return CurrentFor(DefaultConnectionStringName);
        }
    }

    /// <summary>
    /// Used to get the current ObjectContext associated with a key; i.e., the key
    /// associated with an object context for a specific database.
    ///
    /// If you're only communicating with one database, you should call <see cref="Current" /> instead,
    /// although you're certainly welcome to call this if you have the key available.
    /// </summary>
    public static ObjectContext CurrentFor(string key)
    {
        if (string.IsNullOrEmpty(key))
        {
            throw new ArgumentNullException("key");
        }

        if (Storage == null)
        {
            throw new ApplicationException("An IObjectContextStorage has not been initialized");
        }

        if (!objectContextBuilders.ContainsKey(key))
        {
            throw new ApplicationException("An ObjectContextBuilder does not exist with a key of " + key);
        }

        ObjectContext context = Storage.GetObjectContextForKey(key);

        if (context == null)
        {
            context = objectContextBuilders[key].BuildObjectContext();
            Storage.SetObjectContextForKey(key, context);
        }

        return context;
    }

    /// <summary>
    /// This method is used by application-specific object context storage implementations
    /// and unit tests. Its job is to walk thru existing cached object context(s) and Close() each one.
    /// </summary>
    public static void CloseAllObjectContexts()
    {
        foreach (ObjectContext ctx in Storage.GetAllObjectContexts())
        {
            if (ctx.Connection.State == System.Data.ConnectionState.Open)
                ctx.Connection.Close();
        }
    }

    private static void AddConfiguration(string connectionStringName, string[] mappingAssemblies, bool recreateDatabaseIfExists = false)
    {
        if (string.IsNullOrEmpty(connectionStringName))
        {
            throw new ArgumentNullException("connectionStringName");
        }

        if (mappingAssemblies == null)
        {
            throw new ArgumentNullException("mappingAssemblies");
        }

        objectContextBuilders.Add(connectionStringName,
            new ObjectContextBuilder<ObjectContext>(connectionStringName, mappingAssemblies, recreateDatabaseIfExists));
    }

    /// <summary>
    /// An application-specific implementation of IObjectContextStorage must be setup either thru
    /// <see cref="InitStorage" /> or one of the <see cref="Init" /> overloads.
    /// </summary>
    private static IObjectContextStorage Storage { get; set; }

    /// <summary>
    /// Maintains a dictionary of object context builders, one per database.  The key is a
    /// connection string name used to look up the associated database, and used to decorate respective
    /// repositories. If only one database is being used, this dictionary contains a single
    /// factory with a key of <see cref="DefaultConnectionStringName" />.
    /// </summary>
    private static Dictionary<string, IObjectContextBuilder<ObjectContext>> objectContextBuilders =
        new Dictionary<string, IObjectContextBuilder<ObjectContext>>();
}
As you can see, ObjectContextManager delegates the job to create an object context to a so-called ObjectContextBuilder class. The main responsibility of this class  is to create an object context using the provided connection string and also to look up and configure the entity mapping classes. This class constructor accepts a connection string name and an array of mapping assemblies, which contain entity definitions and mapping classes, for it to create an object context (these two parameters was provided during application starting up by calling method ObjectContextManager.Init(…)). If you have ever used SharpArchitecture code, you can see it is almost the same as NHibernate’s SessionFactory class.
Here is the code of ObjectContextBuilder class:
public interface IObjectContextBuilder<T> where T : ObjectContext
{
    T BuildObjectContext(bool lazyLoadingEnabled = true);
}

public class ObjectContextBuilder<T> : ContextBuilder<T>, IObjectContextBuilder<T> where T : ObjectContext
{
    private readonly DbProviderFactory _factory;
    private readonly ConnectionStringSettings _cnStringSettings;
    private readonly PluralizationService _pluralizer;
    private readonly bool _recreateDatabaseIfExists;

    public ObjectContextBuilder(string connectionStringName, string[] mappingAssemblies, bool recreateDatabaseIfExists)
    {
        _cnStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName];
        _factory = DbProviderFactories.GetFactory(_cnStringSettings.ProviderName);
        _pluralizer = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en"));
        _recreateDatabaseIfExists = recreateDatabaseIfExists;

        AddConfigurations(mappingAssemblies);
    }

    /// <summary>
    /// Creates a new <see cref="ObjectContext"/>.
    /// </summary>
    /// <param name="lazyLoadingEnabled">if set to <c>true</c> [lazy loading enabled].</param>
    /// <param name="recreateDatabaseIfExist">if set to <c>true</c> [recreate database if exist].</param>
    /// <returns></returns>
    public T BuildObjectContext(bool lazyLoadingEnabled = true)
    {
        var cn = _factory.CreateConnection();
        cn.ConnectionString = _cnStringSettings.ConnectionString;

        var ctx = Create(cn);
        ctx.ContextOptions.LazyLoadingEnabled = lazyLoadingEnabled;

        if (!ctx.DatabaseExists())
        {
            ctx.CreateDatabase();
        }
        else if (_recreateDatabaseIfExists)
        {
            ctx.DeleteDatabase();
            ctx.CreateDatabase();
        }

        return ctx;
    }

    /// <summary>
    /// Adds mapping classes contained in provided assemblies and register entities as well
    /// </summary>
    /// <param name="mappingAssemblies"></param>
    private void AddConfigurations(string[] mappingAssemblies)
    {
        if (mappingAssemblies == null || mappingAssemblies.Length == 0)
        {
            throw new ArgumentNullException("mappingAssemblies", "You must specify at least one mapping assembly");
        }

        foreach (string mappingAssembly in mappingAssemblies)
        {
            Assembly asm = Assembly.LoadFrom(MakeLoadReadyAssemblyName(mappingAssembly));

            foreach (Type type in asm.GetTypes())
            {
                if (!type.IsAbstract)
                {
                    if (type.IsSubclassOf(typeof(StructuralTypeConfiguration)))
                    {
                        StructuralTypeConfiguration instance = Activator.CreateInstance(type) as StructuralTypeConfiguration;
                        this.Configurations.Add(instance);

                        Type entityType = GetEntityType(type);
                        if (entityType != null)
                        {
                            RegisterEntity(entityType);
                        }
                    }
                }
            }
        }

        if (this.Configurations.Count == 0)
        {
            throw new ArgumentException("No mapping class found!");
        }
    }
    // other code
}
Updated: ADO.NET team just announced the release of Entity Framework Feature  Community Technology Preview 4 (CTP4) which splits ContextBuilder into two components, ModelBuilder and DbModel. The definition of the two new classes are as “ModelBuilder is mutable and exposes the fluent API for defining your model. ModelBuilder creates an immutable DbModel type that can be used to construct an ObjectContext or DbContext. DbModel can also be constructed from a Database First or Model First approach where an edmx file is generated.” Here is the updated ObjectContextBuilder class which replaces the inheritance from ContextBuilder to ModelBuilder class. Note that to make the code compilable, you must install the EF CTP4 version
public interface IObjectContextBuilder<T> where T : ObjectContext
{
    T BuildObjectContext(bool lazyLoadingEnabled = true);
}

public class ObjectContextBuilder<T> : ModelBuilder, IObjectContextBuilder<T> where T : ObjectContext
{
    private readonly DbProviderFactory _factory;
    private readonly ConnectionStringSettings _cnStringSettings;
    private readonly PluralizationService _pluralizer;
    private readonly bool _recreateDatabaseIfExists;

    public ObjectContextBuilder(string connectionStringName, string[] mappingAssemblies, bool recreateDatabaseIfExists)
    {
        _cnStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName];
        _factory = DbProviderFactories.GetFactory(_cnStringSettings.ProviderName);
        _pluralizer = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en"));
        _recreateDatabaseIfExists = recreateDatabaseIfExists;

        // we do not want the EdmMedadata table to be generated
        IncludeMetadataInDatabase = false;

        AddConfigurations(mappingAssemblies);
    }

    /// <summary>
    /// Creates a new <see cref="ObjectContext"/>.
    /// </summary>
    /// <param name="lazyLoadingEnabled">if set to <c>true</c> [lazy loading enabled].</param>
    /// <param name="recreateDatabaseIfExist">if set to <c>true</c> [recreate database if exist].</param>
    /// <returns></returns>
    public T BuildObjectContext(bool lazyLoadingEnabled = true)
    {
        var cn = _factory.CreateConnection();
        cn.ConnectionString = _cnStringSettings.ConnectionString;

        // calls ModelBuilder.CreateModel() to create DbModel, then uses it to create ObjectContext
        var ctx = CreateModel().CreateObjectContext<T>(cn);
        ctx.ContextOptions.LazyLoadingEnabled = lazyLoadingEnabled;

        if (!ctx.DatabaseExists())
        {
            ctx.CreateDatabase();
        }
        else if (_recreateDatabaseIfExists)
        {
            ctx.DeleteDatabase();
            ctx.CreateDatabase();
        }

        return ctx;
    }
    // other code are kept the same
}
With this ObjectContextManager in hand, I re-factor the Repository class by removing the dependency to ObjectContext in its constructor, every time it needs a ObjectContext, it will ask the ObjectContextManager to provide.
/// <summary>
/// Generic repository
/// </summary>
public class GenericRepository : IRepository
{
    private readonly ObjectContext _context;
    private readonly PluralizationService _pluralizer;

    /// <summary>
    /// Initializes a new instance of the <see cref="Repository&lt;TEntity&gt;"/> class.
    /// </summary>
    public GenericRepository()
        : this(string.Empty)
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="Repository&lt;TEntity&gt;"/> class.
    /// </summary>
    /// <param name="connectionStringName">Name of the connection string.</param>
    public GenericRepository(string connectionStringName)
    {
        _context = GetObjectContext(connectionStringName);
        _pluralizer = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en"));
    }

    private ObjectContext GetObjectContext(string connectionStringName)
    {
        if (connectionStringName == string.Empty)
            return ObjectContextManager.Current;
        return ObjectContextManager.CurrentFor(connectionStringName);
    }
    // other code
}

So far so good, here is the revisited test code:

[TestFixture]
public class RepositoryTest
{
    private ICustomerRepository customerRepository;
    private IRepository orderRepository;
    private IRepository productRepository;

    [TestFixtureSetUp]
    public void SetUp()
    {
        ObjectContextManager.InitStorage(new SimpleObjectContextStorage());
        ObjectContextManager.Init("DefaultDb", new[] { "Infrastructure.Tests" }, true);

        customerRepository = new CustomerRepository();
        orderRepository = new GenericRepository();
        productRepository = new GenericRepository();
    }

    private void AddOrders()
    {
        var c = customerRepository.FindByName("John", "Doe");

        var winXP = productRepository.FindOne<Product>(x => x.Name == "Windows XP Professional");
        var winSeven = productRepository.FindOne<Product>(x => x.Name == "Windows Seven Professional");

        var o = new Order
        {
            OrderDate = DateTime.Now,
            Purchaser = c,
            OrderLines = new List<OrderLine>
            {
                new OrderLine { Price = 200, Product = winXP, Quantity = 1},
                new OrderLine { Price = 699.99, Product = winSeven, Quantity = 5 }
            }
        };

        orderRepository.Add(o);
        orderRepository.SaveChanges();
    }
}
The Specification pattern
According to Martin Flowler, the idea of Specification is to separate the statement of how to match a candidate, from the candidate object that it is matched against. As well as its usefulness in selection, it is also valuable for validation and for building to order. You can also follow the Specification white paper by Martin Flowler if you want to indulge yourself deeply into this programming pattern.
In simple terms, it is a small piece of logic which is independent and give an answer to the question “does this match ?”. With Specification, we isolate the logic that do the selection into a reusable business component that can be passed around easily from the entity we are selecting.
Okay, it is enough for introducing specification pattern. Here is the specification contract:
public interface ISpecification<TEntity>
{
    bool IsSatisfiedBy(TEntity entity);
}
And the extended repository contract:
public interface IRepository
{
    // other methods..
    TEntity Single<TEntity>(ISpecification<TEntity> criteria) where TEntity : class

    IEnumerable<TEntity> Find<TEntity>(ISpecification<TEntity> criteria) where TEntity : class
}
Now is the implementation of the extended repository:
public class GenericRepository : IRepository
{
    // other code...
    public TEntity Single<TEntity>(ISpecification<TEntity> criteria) where TEntity : class
    {
        return GetQuery<TEntity>().Single<TEntity>(criteria.IsSatisfiedBy);
    }

    public IEnumerable<TEntity> Find<TEntity>(ISpecification<TEntity> criteria) where TEntity : class
    {
        return GetQuery<TEntity>().Where(criteria.IsSatisfiedBy).AsEnumerable();
    }
    // other code...
}
Some of the sample specification implementation:
public class Specification<TEntity> : ISpecification<TEntity>
{
    public Specification(Expression<Func<TEntity, bool>> predicate)
    {
        _predicate = predicate;
    }

    public bool IsSatisfiedBy(TEntity entity)
    {
        return _predicate.Compile().Invoke(entity);
    }

    private Expression<Func<TEntity, bool>> _predicate;
}

public class ProductByNameSpecification : Specification<Product>
{
    public ProductByNameSpecification(string nameToMatch)
        : base(p => p.Name == nameToMatch)
    {
    }
}

public class ProductOnSaleSpecification : Specification<Product>
{
    public ProductOnSaleSpecification() : base(p => p.Price < 100) { }
}
At this point, I think of a technique to chain the specification called composite specification. Why not apply to make the specification flexible and reusable? Here is the code which is mostly inspired from this post:
public class Specification<TEntity> : ISpecification<TEntity>
{
    public Specification(Expression<Func<TEntity, bool>> predicate)
    {
        _predicate = predicate;
    }

    public AndSpecification<TEntity> And(Specification<TEntity> specification)
    {
        return new AndSpecification<TEntity>(this, specification);
    }

    public OrSpecification<TEntity> Or(Specification<TEntity> specification)
    {
        return new OrSpecification<TEntity>(this, specification);
    }

    public NotSpecification<TEntity> Not(Specification<TEntity> specification)
    {
        return new NotSpecification<TEntity>(this, specification);
    }

    public bool IsSatisfiedBy(TEntity entity)
    {
        return _predicate.Compile().Invoke(entity);
    }

    private Expression<Func<TEntity, bool>> _predicate;
}

/// <summary>
/// http://devlicio.us/blogs/jeff_perrin/archive/2006/12/13/the-specification-pattern.aspx
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public abstract class CompositeSpecification<TEntity> : ISpecification<TEntity>
{
    protected readonly Specification<TEntity> _leftSide;
    protected readonly Specification<TEntity> _rightSide;

    public CompositeSpecification(Specification<TEntity> leftSide, Specification<TEntity> rightSide)
    {
        _leftSide = leftSide;
        _rightSide = rightSide;
    }

    public abstract bool IsSatisfiedBy(TEntity entity);
}

public class AndSpecification<TEntity> : CompositeSpecification<TEntity>
{
    public AndSpecification(Specification<TEntity> leftSide, Specification<TEntity> rightSide)
        : base(leftSide, rightSide)
    {
    }

    public override bool IsSatisfiedBy(TEntity obj)
    {
        return _leftSide.IsSatisfiedBy(obj) && _rightSide.IsSatisfiedBy(obj);
    }
}

public class OrSpecification<TEntity> : CompositeSpecification<TEntity>
{
    public OrSpecification(Specification<TEntity> leftSide, Specification<TEntity> rightSide)
        : base(leftSide, rightSide)
    {
    }

    public override bool IsSatisfiedBy(TEntity entity)
    {
        return _leftSide.IsSatisfiedBy(entity) || _rightSide.IsSatisfiedBy(entity);
    }
}

public class NotSpecification<TEntity> : CompositeSpecification<TEntity>
{
    public NotSpecification(Specification<TEntity> leftSide, Specification<TEntity> rightSide)
        : base(leftSide, rightSide)
    {
    }

    public override bool IsSatisfiedBy(TEntity entity)
    {
        return _leftSide.IsSatisfiedBy(entity) && !_rightSide.IsSatisfiedBy(entity);
    }
}
And here is the code to test the composite specification
[TestFixture]
public class RepositoryTest
{
    private ICustomerRepository customerRepository;
    private IRepository orderRepository;
    private IRepository productRepository;

    [TestFixtureSetUp]
    public void SetUp()
    {
        ObjectContextManager.InitStorage(new SimpleObjectContextStorage());
        ObjectContextManager.Init("DefaultDb", new[] { "Infrastructure.Tests" }, true);
        customerRepository = new CustomerRepository();
        orderRepository = new GenericRepository();
        productRepository = new GenericRepository();
    }

    [Test]
    public void Test()
    {
        // setup data code..

        FindBySpecification();
        FindByCompositeSpecification();
        FindByConcretSpecification();
        FindByConcretCompositeSpecification();
    }
    private void FindBySpecification()
    {
        Specification<Product> specification = new Specification<Product>(p => p.Price < 100);
        IEnumerable<Product> productsOnSale = productRepository.Find<Product>(specification);
        Assert.AreEqual(2, productsOnSale.Count());
    }

    private void FindByCompositeSpecification()
    {
        IEnumerable<Product> products = productRepository.Find<Product>(
        new Specification<Product>(p => p.Price < 100).And(new Specification<Product>(p => p.Name == "Windows XP Professional")));
        Assert.AreEqual(1, products.Count());
    }

    private void FindByConcretSpecification()
    {
        ProductOnSaleSpecification specification = new ProductOnSaleSpecification();
        IEnumerable<Product> productsOnSale = productRepository.Find<Product>(specification);
        Assert.AreEqual(2, productsOnSale.Count());
    }

    private void FindByConcretCompositeSpecification()
    {
        IEnumerable<Product> products = productRepository.Find<Product>(
        new AndSpecification<Product>(
        new ProductOnSaleSpecification(),
        new ProductByNameSpecification("Windows XP Professional")));
        Assert.AreEqual(1, products.Count());
    }
}
Conclusion
That’s it. I hope you find something useful with the of generic repository, the way to manage object context, and the composite specification implementation as well. Comments are welcome!
References

The code for this post can be found here.

As a developer, what will you do (or will you be) when you are 40?

I received that question last night that makes me think a lot about it. It is not a simple question, its a big question that I rarely think about.

I think if some of you are being asked that question, you will have different answers. But let me guess, the most answers will be: “I want to become a manager”. Dont get me wrong, I have heard that saying from many people, most are my colleagues who are working on software outsourcing industry playing different roles: developer, business analyst, quality control.

Why do people prefer becoming a manager to a professional on the area they are working on? IMHO, it depends on the current situation of Vietnam. Vietnam is still a developing country and almost companies operating in software development earn money from building software for foreign countries – which is called outsourcing – because it has a benefit of low cost. Being part of outsourcing projects, as a developer, you have to constantly learn various technologies to meet technical specification. That’s good if you – a developer – are learning cutting edge technologies to build software but it’s also not so good that you are assigned to project which uses old technologies and all you have to do is to maintain and to enhance that legacy system. As an example, imagine your skill is .NET but the system have been built using VB6. Or you are very good at ASP.NET 3.5 but the system you are going to build uses ASP.NET 1.1 or even worse, standard ASP. As a business analyst, you have to learn various business domains to understand software requirement, some are good since you are having a chance to learn new business domain which might take a very long time to be available in Vietnam such as Healthcare, e-commerce,… but it is not so good that that knowledge cant be applied in Vietnam at the time we finished building that software.  As a quality control engineer, you have to learn from testing Windows application to Web application and even embedded system or mobile platform as well to master tools to perform automation/performance testing. What if one day you find that your learning ability reaches its limitation that you cannot learn any more or not as fast as you ever were able to?

This leaves you behind people/technologies and you will become not suitable for the job. The ‘solution’ to escape that situation is to become a manager! The other reason for the answer – I mean ‘to become a manager’ – is because vnes people still have an ‘old’ thinking from themselves or their parents that becoming a manager – or ‘boss’ – showing that they have a successful career, or life.

But my answer is: ‘I will be coding, if I cannot code anymore, its a disaster’. Why? the reason is simple, I love coding. Funny huh? Being a developer means you are writing code to get the computer does what you want it to do. However, let the computer does what you want it to do is not the last shot, you have to do it beautifully that someone calls it ‘the art of programming’ and you have to be continuously improving youself to become an ‘artist’. Have you ever felt excited when the software you build not only runs smoothly but also the code you write is easy to read, to understand and is extendable? Have you ever felt happy when someone reviewed your code and said: “Its a beautiful code I’ve ever seen. It applies many good practices out there”? If your answer is ‘Yes’ then you know why I love to be a programmer – and I will when I am 40.

I once worked on a project which my client was a group of technical guys (5 ones, as I recalled) who were very passionate on coding. Some of them were almost over 40, one of them was over 50. What really inspired me was they loved coding crazily. Working with them made me love programming and becoming a professional programmer much more. Well, you might say since they live in a modern country and that their job is more respected, and well paid, compared to in Vietnam that makes them not worry about changing their career path to become a manager. I totally agree and respect your opinion. But please, follow your heart, do what you love to do, live your life, not others.

But if you still want to become a manager, please think about this a bit: skills to manage a software project still need to constantly be improved. It’s  obvious that the software world is changing too fast, not only technical people have to learn new technologies day by day but managers also need to learn new development process and methodologies as well how to apply it effectively, learn how to work with the team of members who are passionate, highly self-respected, learn how to inspire and encourage them, show how you recognize and appreciate their effort. This not only makes an effectively team, but also brings great successes.

Follow

Get every new post delivered to your Inbox.

Join 58 other followers