Archive

Posts Tagged ‘Linq’

Linq to Events : .Net Reactive Framework

July 26th, 2009 stiiifff No comments

Within the Silverlight 3 Toolkit, there’s a hidden gem called the Reactive Framework (System.Reactive.dll), the new baby of Erik Meijer.

Read more about it here and there.

Although the examples given focus on asynchronous UI, I’m sure people will find very interesting uses for it. This is the kind of tool you wanna add to your framework tool-belt and keep it ready for when the needs come.

Categories: Patterns, Silverlight Tags:

NHibernate 2.1 RTM + Linq : What else ?

July 26th, 2009 stiiifff 2 comments

Just in case you haven’t heard of it yet … NHibernate 2.1 has been released !!! Check here for the most notable new features (and the change log of course).

Another great piece of news is that the most requested missing feature has been released today : Linq for NHibernate ! Woohooooo !

Get the bits while they’re still hot :)

Double congrats to the NHibernate Team !!!

Categories: ORM Tags: ,

DDD Specifications

June 24th, 2008 stiiifff 4 comments

Specifications is an interesting pattern as it allows reuse of expressions on entities for filtering, querying, validation … going further, it could also be used to present users with smart composite filters in the UI (instead of the usual 'type a filter value for this field').

I was thinking about writing a lenghty post on specifications but others have done it, and probably much better than I could, so … I'm just going to gather some links for you to dig deeper in what specifications are and what they can be used for.

Ok, the Specification pattern looks good … but is it really usefull ? Well, yes ;) If you combine it with a Linq-friendly Repository, it is indeed quite usefull:

SpecificationModel

SpecificationModel

Let me describe the various components that appear on this diagram:

  • ISpecification<TEntity>: This is the base interface for Specification. It has one method 'IsSatisfiedBy' that takes an entity (a class without any other specific constraint) as argument and return a bool indicating if the entity matches the specification or not.
  • ILambdaSpecification<TEntity>: A specialized base interface for Specifications expressed as a Lambda expression. It has members returning the Lambda expression, an equivalent Predicate and a String representation.
  • LambdaSpecification<TEntity>: The implementation class of ILambdaSpecification<TEntity>. Contains implicit conversion operators from & to an untyped Lambda expression.
  • IRepository<TEntity>: The base interface for a Linq-friendly repository … and as Specifications can be expressed as Lambda expressios (= ILambdaSpecification<TEntity>), they can also be used as query filters on the Repository.
  • LambdaSpecificationExtensions: Extension method that allows conversion of a Lambda expression to a ILambdaSpecification<TEntity>.

That's just the base model for Specifications and the link with Repositories. Other aspects such as specification compositions must be taken into account, Linq supporting natively some of the necessary capabilities. Advanced specification concepts such as Subsumtion & Partially satisfied specifications can be implemented if needed only (don't make things more complex than they need to be for your project).

I hope this little introduction on specifications gave you an idea of the level of expressivenes your domain model can reach when using named specifications & specifications-friendly repositories !!! ;)

Categories: DDD, Patterns Tags: , , , ,

Ado.Net Entity Framework – Vote of no confidence – NO !

June 24th, 2008 stiiifff No comments

Just stumbled on the new soap opera of summer 2008: the so-called Ado.Net Entity Framework Vote of No Confidence (that I will nicely abbreviate ANEFVONC). Come on, we have Euro 2008 Cup, the Olympic Games in China … isn't that enough ? ;)

The open letter describes the main problems that, following the Alt.Net community, currently prevent the Entity Framework from being a great DDD Tool:

  • INORDINATE FOCUS THE DATA ASPECT OF ENTITIES LEADS TO DEGRADED ENTITY ARCHITECTURES: Yes, EF is currently mainly about data access … let's hope it will evolve and introduce more & more 'Entity services'. Concerning Business Rules, is there a standard way of expressing Business Rules that EF could include ? Not sure about that but anyway I don't believe that EF currently prevents you to define your BR … because in a system with numerous & complex BR, your BR logic wouldn't be coded right inside your Entities. ;)
  • EXCESS CODE NEEDED TO DEAL WITH LACK OF LAZY LOADING: I remember EntitySet<T> has Lazy Loading built-in … but yeah, then you're not 100% PI compliant anymore. And no, I don't need Lazy Loading to keep my business logic free of Data Access concerns. I can use specific Repositories that will contain custom Linq queries if my base Linq-generic Repository is not enough. Lazy Loading is very appeling at first, but frankly, is only applicable to simple cases. 'Transparent data access' is a myth … you need to express a query in some form. Defining relations in order to benefit from Lazy Loading is a very simplistic view of the task of Querying on a Domain Model.
  • SHARED, CANONICAL MODEL CONTRADICTS SOFTWARE BEST PRACTICES: Haven't tested EF on that point … but indeed, support for Partial Models (see here, and here) is needed for complex Domain Models (especially when split in many Modules).
  • LACK OF PERSISTENCE IGNORANCE CAUSES BUSINESS LOGIC TO BE HARDER TO
    READ, WRITE, AND MODIFY, CAUSING DEVELOPMENT AND MAINTENANCE COSTS TO
    INCREASE AT AN EXAGGERATED RATE
    : Last time I checked, the EF Team had written a post on its blog to express its commitment to making EF as close to PI as possible … did they changed their mind ? Or is the Alt.Net community not patient enough? lol :)
  • EXCESSIVE MERGE CONFLICTS WITH SOURCE CONTROL IN TEAM ENVIRONMENTS: Well, let's hope it can be fixed.

Although, I think I understand most of the concerns expressed in the letter, I still feel that it focus too much on the data access part of Domain Driven Design … and DDD is so much more than that, right? IMHO, here are some key problems that must be adressed for DDD to hit mainstream:

  • Bridge the gap between DDD & MDD: I want to do DDD, but I don't want to know 100 patterns and tricks and tips in order to work efficiently … Gotta focus on defining the Ubiquitous Language right ? ;) What we need is a Meta-Model for DDD that allow us to create our Domain Models more easily than with Code, Unit Tests, Refactoring … I want to work at a higher level of abstraction, please. Give me DDD domain-specific languages !!! (a textual one for purists and a graphical one for realists, both being SCM-compliants).
  • DDD Best Practices Validation Rules: Create Generic DDD-specific rules that can be verified on the Domain Model created using the DDD DSL. Allow to define Domain Model-specific rules (= Business Rules) directly at the Model level, using a Business Rules DSL.
  • ORM-free DDD Code Generation: Well, if my first wish is realized (DDD DSL), then generate the code for me based on what I have described using the DSL. One way code generation would be fine (if they are enough extension points otherwise, we are back to square one with open letters and blah blah). Bi-Directional DSL would be great, but much much harder. Also, make the code generator pluggable … so that, any ORM-specific artefacts can be generated (keep the core DDD DSL free of any ORM-specifics). Also, generate Business Rules code.
  • Relationship as first-class elements of the language: let's get rid of those horrible Add / Remove methods hiding the fact that we are still not able to manage bi-directional relationships correctly & consistently. Make the concept of relationship an integral part of the language (Linq 2.0 ?). A great article on the subject (in french, sorry).

Other interesting (old !) posts that also shed light on the fact that DDD still has a long way to go: here and there.

Personnally, I think that EF is the first building block for more DDD goodness to come … so, give feedback, but be patient. I believe an annoucement like this one can only bring good things. Like NHibernate, Rome wasn't built in just one day.

Or did I miss something ? :)

Reminder: Never a sign a paper just because a lot of other people did it before you. ;)

Domain-Driven Design with Linq & ORM – Part 2

June 19th, 2008 stiiifff 2 comments

In my last post about DDD & Linq (1.5 month ago … oops), I showed the following piece of code:

ServiceLocator.Register<IUnitOfWorkFactory, NHibernateUnitOfWorkFactory>();

using (UnitOfWork.Start())
{
    ITransaction tx = UnitOfWork.Current.BeginTransaction(IsolationLevel.ReadCommitted);
    try
    {
        IRepository<Customer> cr = UnitOfWork.Current.GetRepository<Customer>();
        Customer customer = cr.FindOne(c => c.Id == "AROUT");
        customer.Address = "125 Hanover Sq.";
        cr.Save(customer);
        tx.Commit();
    }
    catch
    {
        if (tx != null) tx.Rollback();
    }
    finally
    {
        if (tx != null) tx.Dispose();
    }
}

After thinking about it, refactoring it 10 times, I sat down this morning and finally got it the way I wanted (don’t ask me why it took so long lol):

// Configure your favorite IoC container:
// - Register an IUnitOfWorkFactory
// - Register an IRepositoryFactory
// - Register a generic IRepository<TEntity>
//   (your container must support open generic types).
// - Configure your container to use the IRepositoryFactory
//   to create instances of the IRepository<TEntity> component
//   (your container must support factories).
// Once your IoC container is set up, configure it as the ServiceProvider
// (must implement the IServiceProvider interface or use a wrapper) for the ServiceLocator helper
ServiceLocator.ServiceProvider = container;

// Start a unit of work
using (IUnitOfWork uow = UnitOfWork.Start())
{
    // Get an instance of repository
    IRepository<Customer> cr = ServiceLocator.GetService<IRepository<Customer>>();

    // Retrieve data with a Linq query
    Customer customer = cr.FindOne(c => c.CustomerID == "AROUT");

    // Modify retrieved entity
    customer.Address = "000 Hanover Sq.";

    // Ask repository to save changes
    cr.Save(customer);

    // Mark the unit of work as complete to propagate changes to data source
    uow.Complete();
}

The re-worked IRepository<T> looks like this:

public interface IRepository<TEntity> : IDisposable where TEntity : class
{
    long Count();
    long Count(Expression<Func<TEntity, bool>> predicate);
    void Add(TEntity entity);
    void Add(IEnumerable<TEntity> entities);
    void Remove(TEntity entity);
    void Remove(IEnumerable<TEntity> entities);
    void RemoveAll();
    void RemoveAll(Expression<Func<TEntity, bool>> predicate);
    void Save(TEntity entity);
    void Save(IEnumerable<TEntity> entities);
    TEntity FindOne(Expression<Func<TEntity, bool>> predicate);
    IEnumerable<TEntity> FindAll();
    IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> predicate);
    IQueryable<TEntity> QueryAll();
    IQueryable<TEntity> QueryAll(Expression<Func<TEntity, bool>> predicate);
}

I think it looks better ;) I currently have UoW & Repository factories for the following ORM:

  • NHibernate
  • ActiveRecord
  • LinqToSql
  • EntityFramework

The code is still very experimental, relies a lot of Castle Project‘s libraries (some might view it as a pro, others a con …), and I unfortunately don’t have much time to work more on it. If there is any interest for it, I might drop it online in its current state (basic samples, no unit test, code analysis spitting out a lot of warnings).

Feedback is welcomed. :)

Possible Improvements:

  • For simplification purpose, I might remove the dependency to a ‘ServiceProvider‘ and instead define a simple ‘UnitOfWork.Configure‘ method where we can specify the type of the IUnitOfWorkFactory & IRepositoryFactory.
  • Should the IUnitOfWork interface expose a ‘GetRepository<TEntity>‘ method to get rid of the ugly static call to ‘ServiceLocator.GetService<IRepository<T>>‘ ?

ActiveRecord & Repository pattern

May 19th, 2008 stiiifff 1 comment

Hammett has a post where he, among others, advises:

I don’t encourage people to use AR with the AR base class. Use the
ARMediator and use the repository pattern or a dao pattern to increase
isolation and testability.

Yes ! It seems not many people knew it (I did, I'm a Reflector addict lol) but you can use ActiveRecord without base classes for your entities (ActiveRecordBase), just use the [ActiveRecord] attribute.

That way, you get:

  • Attribute-based mapping declaration (instead of manual edition of NHibernate mapping files, which can be cumbersome).
  • Well-tested plumbing code like session & transaction scopes.
  • Easy querying through ActiveRecordMediator static methods, instead of direct use of NHibernate ISession.

Now, if you want the best ORM experience in a DDD-context:

  • Use the Repository pattern, to get an additional layer of abstraction between your application code & your particular ORM.
  • Use Linq queries in your repositories, for rich ORM-independent querying capabilities (your ORM has to support Linq of course).

I've been refactoring & cleaning up some code lately, I will soon drop the first draft of Yoot.DomainDriven, a non-intrusive framework for pragmatic Domain-Driven Design with nice abstraction of Units of work & Linq-friendly repositories, and implementations for mainstream ORM tools. :)

Domain-Driven Design with Linq & ORM

May 1st, 2008 stiiifff 2 comments

We all now that an ORM plays an important role in a DDD architecture … but it would be nice if we could write our Domain Model without being tightly coupled to our favorite ORM tool, especially the code we write in Repositories. Thanks to Linq, we already have a way to abstract our queries (our ORM 'just has to' support Linq, anyway that's a requirement for a good ORM nowadays). The other thing we should be able to abstract is the object, specific to each ORM, that is the interface with the persistence layer, that keeps track of the changes on entities, the 'context' or the 'session' object.

Well, most ORM tools are implementing similar Patterns, namely UnitOfWork, IdentityMap, LazyLoad … so it is fair to assume that it should be possible to build an abstract layer that would allow us to work at a higher level, and have providers for our favorite ORM tools.

Here is a sample from some early code I wrote:

ServiceLocator.Register<IUnitOfWorkFactory, NHibernateUnitOfWorkFactory>();

using (UnitOfWork.Start())
{
    ITransaction tx = UnitOfWork.Current.BeginTransaction(IsolationLevel.ReadCommitted);
    try
    {
        IRepository<Customer> cr = UnitOfWork.Current.GetRepository<Customer>();
        Customer customer = cr.FindOne(c => c.Id == "AROUT");
        customer.Address = "125 Hanover Sq.";
        cr.Save(customer);
        tx.Commit();
    }
    catch
    {
        if (tx != null) tx.Rollback();
    }
    finally
    {
        if (tx != null) tx.Dispose();
    }
}

The Repository interface, which makes heavy use of Linq to express query criterions, looks like this:

public interface IRepository<TEntity> where TEntity : class
{
    long Count();
    long Count(Expression<Func<TEntity, bool>> predicate);
    void Delete(TEntity entity);
    void Delete(IEnumerable<TEntity> entities);
    void DeleteAll();
    void DeleteAll(Expression<Func<TEntity, bool>> predicate);
    void Save(TEntity entity);
    void Save(IEnumerable<TEntity> entities);
    TEntity FindOne(Expression<Func<TEntity, bool>> predicate);
    IEnumerable<TEntity> FindAll();
    IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> predicate);
    IQueryable<TEntity> ProjectAll();
    IQueryable<TEntity> ProjectAll(Expression<Func<TEntity, bool>> expression);
}

Wanna use LinqToSql or EntityFramework instead of NHibernate … well, that’s easy, just change the first line to:

ServiceLocator.Register<IUnitOfWorkFactory, LinqToSqlUnitOfWorkFactory>();

or

ServiceLocator.Register<IUnitOfWorkFactory, EntityFrameworkUnitOfWorkFactory>();

Nice isn’t it ? ;)
We can also have:

ServiceLocator.Register<IUnitOfWorkFactory, ActiveRecordUnitOfWorkFactory>();

or

ServiceLocator.Register<IUnitOfWorkFactory, EussUnitOfWorkFactory>();

Well, I think you get the point.
So, what you think ? Suggestions & remarks are welcome.

“Not invented here” disclaimer: This code is largely inspired and based on code from Castle Project & Rhino.Commons. I just generalized it.

“Pre-Pre-Pre-Pre-Pre Alpha code” disclaimer: This code is quite experimental, it is not (yet) fully unit-tested and doesn’t support (yet) all the capabilities of the different ORM tools presented here.

My top 5 technologies for 2008

January 27th, 2008 stiiifff No comments

Those are the technologies I will definitely try to master in 2008, because they add a real value to the art of software development and allow developers / architects to work at a higher level (less dirty code on the hands lol):

1. Visual Studio DSL Tools : I recently got interested in Domain-Specific Development especially with the wonderfull Visual Studio DSL Tools. Definitely have to practice this more. Guess I will order the book 'Domain-Specific Development with Visual Studio DSL Tools'.
2. WCF : The great (r)evolution that Microsoft delivered as part as .Net 3.0. Any .Net developer should know about it. Need to finish the book 'Programming WCF Services'.
3. WF : The 'unknown sibling' of WCF. I already have some advanced practice with that one (advanced custom activities) as I had a course & used it on a project for several months. Still have to finish reading the book 'Essential Windows Workflow Foundation'.
4. Linq : Definitely need to check the inner workins of Linq to gain a better understanding of it and be able to use it correctly with abstract Repositories & ORM.
5. DDD : Already got a good knowledge of that one, but I want to become an expert as it is gaining more & more popularity as well as visibility while Microsoft is adopting it slowly but surely (Linq to SQL, Entity Framework). 'Applying Domain-Driven Design and Patterns: With Examples in C# and .NET' is a real eye-opener on the subject.

Well, it seems that my schedule for 2008 is already full :) lol

Categories: DDD, DSL, WCF, WF Tags: , , , , ,