Archive

Archive for the ‘ORM’ Category

Random thoughts

May 18th, 2010 stiiifff 3 comments

I’ve been fairly busy lately, working on interesting things at work, getting ready for an imminent birth, preparing some sessions as well … and also, thinking about a dozen of blog posts I wouldn’t have time to write. So anyway, here’s a quick & dirty cheap list of ramblings, not sure if it’s gonna be of any use, but it’ll hopefully free up some memory slots in my brain :-)

  • Complex Data Model != Domain Model : don’t get the “Let’s do DDD because it’s trendy. And, woohoo, that CQRS thingie would look nice on my CV as well” tendency too quickly. Knowing when not to apply DDD is almost as important as knowing how to apply it properly.
  • WCF RIA Services : I played a bit with it at work … and I like it. It was designed to address 80% (more ?) of the needs of developers writing n-tiers Data-Driven applications (also known, in the .Net world, as ‘Business applications’), and it does … just that. And that’s good. Sure, it can be misused and it’s bad because it doesn’t use Pattern ‘Blah’ and it violates Rule ‘MoreBlah’, but you’re smart right, so you’ll know when to use it, and when not to. I’m just a bit annoyed that the attributes, I mean, data annotations, are scattered in 25 different namespaces. “Bah, just press ‘Alt-Enter’ dude, API design is so overrated these days”.
  • Agatha : Using it, works well, like it. I’m a fan, it’s WCF for mere mortals. Keep up the good work Davy.
  • RavenDB : This will deserve a post of its own to describe just how cool I think this NoSQL-for-.Net-written-by-guess-who is. Not only it makes domain-modeling and application prototyping dirt cheap (no more mapping & OR impedance mismatch bro !), it will also give a run for their money to the existing NoSQL databases out there (I mean, how can you compete with 25 blog posts & 12 releases per week ;) lol). Oh, and if you’re into it, DDD will be most welcome as well (“But Ma, there’s no lazy-loading ! How can I do DDD without lazy-loading & bi-directional navigation properties ?” … “Kiddo, lazy-loading sucks. Big time”).
  • Frameworkitis : It’s a nasty disease, I had it in the past, went through a long detox and now (I think) I’m clean. Unfortunately, I still have a lot of peers that are addicts. Wish they could see the light.
  • “KISS-Mantra” : Repeat 5 times per day “I’m a complexaholic, I will not generify, I will simplicate”. Anybody has a nice wallpaper with a giant yellow Bath duck ? :-)

Ah, I feel lighter now.

Categories: DDD, DotNetHub, ORM, WCF Tags: , ,

Donate for NHibernate

March 1st, 2010 stiiifff No comments

A donation campaign has started in order to help a great open source tool become even better : NHibernate.

If you are reading those lines, the probability that you or your customers have been using NHibernate, and leveraging its powerful features, is quite high. In a way, you have benefited from Open Source software at its best.

It is therefore a great opportunity for you or your customers (encourage them !) to show support to the people who have spent countless hours crafting a great free tool, and who will, hopefully, continue to do so ;)

Donate !

Categories: ORM Tags:

Stepping onto the Bus

October 12th, 2009 stiiifff No comments

I recently had the chance to follow the Advanced Distributed Systems Design with SOA course with Udi Dahan in Brussels, a rejuvenating experience for various reasons : I had no real-world SOA or Messaging Bus experience, it helped me clear out some misunderstandings I had about DDD and also, although painful at first, Udi finger pointed all the bad habits & misconceptions I had accumulated over the years (I can still hear him squeaking “Northwind ! Northwind !“).

So here I am, entering the realm of SOA, EDA & DDD that might well be heaven on earth for both business people & software-makers, the place we all heard of but never saw. But let’s start slowly, and discover my first endeavor with NServiceBus, shall we? :)

For a good introduction on NServiceBus, I suggest you to read the post from Jan who has been doing research on the same aforementioned topics as well.

This post will focus on how well NServiceBus, NHibernate, FluentNHibernate & Castle Framework play together and how to make them fly in a DDD context. Ok, ok, enough talking, show me the code man !!! :D

To manage my NHibernate sessions (ISession), I like to use the Castle’s NHibernate Integration facility, as it gives me a nice abstraction in the form of the ISessionManager component:

ISessionManager

Next to that, a little more than a month ago, the 1.0 version of FluentNHibernate was released, and it’s really neat for both NHibernate configuration & mappings. So, I like to use it as well:

Fluently.Configure(config)
  .Database(MsSqlConfiguration.MsSql2008
    .DefaultSchema("dbo")
    .ConnectionString(c => c
      .FromConnectionStringWithKey("Northwind"))
    .QuerySubstitutions("true 1, false 0")
    .DoNot.UseOuterJoin()
    .ShowSql())
  .Mappings(m => m
    .FluentMappings.AddFromAssemblyOf<CatalogMap>()
    .ExportTo(System.Environment.CurrentDirectory))
  .BuildConfiguration();

One very nice thing about NServiceBus (and its Generic Host) is that it acknowledges from the start that our softwares have to operate in different environments and for that, it offers a very clean solution : Profiles.

Wrapping it all up, wouldn’t it be nice if I could use Castle‘s NHibernate Integration facility for useful components like ISessionManager (and others, more on that later), FluentNHibernate for configuration & mappings and take advantage of NServiceBus Profiles ? Hell yeah !!! Well, that’s actually quite easy & clean. :)

First, configure the NH facility in your config file:

<castle>
  <facilities>
    <facility id="nhibernate.facility" type="Castle.Facilities.NHibernateIntegration.NHibernateFacility, Castle.Facilities.NHibernateIntegration">
      <factory id="nhibernate.factory"/>
    </facility>
  </facilities>
</castle>

Notice that the configuration for the factory is empty … indeed, we want to configure it fluently in the code.

Create a Profile Handler class (implements a IHandleProfile role interface) which simply registers an object into the container (NSB is container-agnostic) :

public class IntegrationProfileHandler : IHandleProfile<Integration>
{
  public void ProfileActivated()
  {
    Configure.Instance.Configurer
      .RegisterSingleton<IConfigurationContributor>(
        new IntegrationNHibernateConfig());
  }
}

… and finally, an implementation of the IConfigurationContributor interface … which is part of Castle‘s NHibernate Integration facility, and will be called before NH‘s SessionFactory is built in order to, well, contribute to the configuration. :)

public class IntegrationNHibernateConfig : IConfigurationContributor
{
  public void Process(string name, Configuration config)
  {
    Fluently.Configure(config)
      .Database(MsSqlConfiguration.MsSql2008
        .DefaultSchema("dbo")
        .ConnectionString(c => c
          .FromConnectionStringWithKey("Northwind"))
        .QuerySubstitutions("true 1, false 0")
        .DoNot.UseOuterJoin()
        .ShowSql())
      .Mappings(m => m
        .FluentMappings.AddFromAssemblyOf<CatalogMap>()
        .ExportTo(System.Environment.CurrentDirectory))
      .BuildConfiguration();
  }
}

Ok, very nice … but I’m not done yet.

A nice concept that we want to use when querying in a true DDD fashion is the notion of Fetching Strategy (read more about it here & there). We need Fetching Strategies for a very simple reason:

Make sure that once we call into the Domain Model to perform a certain action, it has everything it needs to do its job, without causing lazy-loading to trigger and possibly N+1 select problems.

For that matter, I define a simple interface IFetchingStrategy (IEntityRole is just a marker interface):

public interface IFetchingStrategy<TEntityRole>
    where TEntityRole : IEntityRole
{
  string[] FetchList { get; }
}

… that I can then implement to define a fetching strategy per entity role:

public interface IRegisterProductInCatalog : IEntityRole
{
  void RegisterProduct(string category,
         string productName, string productDescription);
}

public class RegisterProductInCatalogStrategy : IFetchingStrategy<IRegisterProductInCatalog>
{
  public string[] FetchList
  {
    get { return new[] { "Categories.Products" }; }
  }
}

Now, it would be nice if I could get an easy access to those fetching strategies … well, that’s what you use an IoC container for ;) Here is the configuration of Castle’s Windsor container in NServiceBus endpoint’s configuration class:

public class EndpointConfig : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization
{
  public void Init()
  {
    var container = new WindsorContainer(new XmlInterpreter());

    Configure.With()
      .CastleWindsorBuilder(container)
      .XmlSerializer();

    container.Register(
      AllTypes
        .Of(typeof(IFetchingStrategy<>))
        .Pick(Configure.TypesToScan)
        .WithService.FirstInterface()
    );
  }
}

Fluent configuration for the Bus & the Container ! Woohoo, my head is turning ! :D

Now, for the final part, the MessageHandler that makes use of all those cuties & with the help some little extension methods:

public class ProductManager : IHandleMessages<RegisterProductInCatalogRequest>
{
  public virtual IBus Bus { get; set; }
  public virtual ISessionManager SessionManager { get; set; }
  public virtual IFetchingStrategy<IRegisterProductInCatalog> Strategy { get; set; }

  public virtual void Handle(RegisterProductInCatalogRequest message)
  {
    using (var session = SessionManager.OpenSession())
    {
      var catalog =
            session.For<Catalog>(message.CatalogId)
                   .Apply(Strategy)
                   .UniqueResult<IRegisterProductInCatalog>();

      catalog.RegisterProduct(message.CategoryName,
                              message.ProductName,
                              message.ProductDescription);
    }
  }
}

I don’t know you, but that’s the kind of code that makes me happy (like a hippo). :)

Comments, feedback, suggestions are all welcome ! ;)

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: ,

Coarse-grained Lock & ORM : Followup

May 31st, 2009 stiiifff No comments

Ayende has a followup post concerning support for Coarse-grained locks in NHibernate.

All I want to be able to do is to define my coarse-grained locks (=> optimistic-lock on aggregate root) in NHibernate’s mapping files … and then forget about it when I know that NHibernate can handle it for me. :)

I will then be confident that changes performed within an aggregate are done in a consistent manner and that concurrency problems are detected without using expensive database locks but using optimistic locking on just 1 table for the whole aggregate.

Categories: DDD, ORM, Patterns Tags: , ,

Clearing the Linq2Sql cache

March 27th, 2009 stiiifff No comments
var clearCacheMethod = context.GetType().GetMethod("ClearCache", BindingFlags.Instance | BindingFlags.NonPublic);
if (clearCacheMethod != null) clearCacheMethod.Invoke(this, null);

Usefull when you’re bypassing Linq2sql to do some hacky stuff and you need Linq2Sql to pick up, at the next query, the changes you’ve made in the database using plain old SqlCommand or the context’s ExecuteCommand method.

As usual with Reflection & internal members … Use at your own risk ;)

Categories: ORM Tags:

Cool stuff

February 23rd, 2009 stiiifff No comments

Entity Framework => Entity Base Class Library

November 23rd, 2008 stiiifff 5 comments

A few days ago the Entity Framework Team released a proposed solution for N-Tiers change tracking on entities … or should I call it a no-solution?

Basically, they will provide a low-level API that will allow YOU to do change-tracking the way YOU prefer.

5 months ago, I was writing a big NO to the Vote of no confidence. Well, now that I had to use Entity Framework on a real project, I must say that I was wrong. I really tried my best using it, thinking that it would be a safe bet for future evolution … and I know what I'm talking about when using ORMs, I'm a very advanced user of NHibernate (multi-tenancy, dynamic filters, dynamic mappings, partial domain models anyone?) … but my only conclusion to the Entity Framework is : WTF are they doing ?! Is that all you could come up with after months of research, brainstormings, experts meetings ?!

If someone give me a set of classes that doesn't bring a A to Z solution to a problem, sorry but I don't call it a Framework … I call it a Base Class Library. I've been vey supportive to the Entity Framework Team (I gave design feedback through multiple channels) but now I think I'm done. And it seems that others have the same feeling : Frans Bouma, author of the LLBGenPro ORM tool, goes in that direction too with its answer to the original post, and a full post on his blog, wich I both totally agree with.

I mean, come on, all those abstractions and discussions are very interesting but after some extensive periods of time trying to make this thing become useable, you have to ask yourself some serious questions. Even the now defunct Linq2Sql is more pleasant & easier to use.

Anyway, I will now go back using something that is customizable, extensible, that allow me to work the way I want (Domain-Driven Design) and most importantly that actually works : NHibernate. I recently discovered that it's moving full speed to version 2.1 with great new features such as Entity Modes : see here and there to know what I'm talking about. Also, a great workshop video on advanced use cases of NHibernate by Ayende.

Update: Ayende's reaction to the Entity Framework Team's design post.

Coarse-grained Lock & ORM : Not Supported ?

July 2nd, 2008 stiiifff No comments

A while ago, I tried to apply a coarse-grained lock using NHibernate. I didn’t succeed, although I tried several options. This is a pity as I consider this pattern essential to be able to develop real-world applications (not just pet projects) using DDD. Indeed, how do you handle concurrency on your aggregates if you cannot use a coarse-grained lock ?.

More practically described, your ORM must be able to mark the aggregate root as dirty if one of its (direct or indirect) child is dirty, even though the root itself is not dirty … which implies that the ORM, or at least its change-tracking algorithm, must understand the concept of Aggregate (or let you manually configure all the ‘cascades‘).

By the way, I’m not the only one who tried: check here and there. Unfortunately, up to now, I wasn’t able to find an ORM that natively such a locking pattern … I would be very happy if someone could prove me wrong. :)

Note: I actually had a very good implementation of it working on a project I was working on, more than 1 year ago … It used a custom abstract persistence layer sitting on top of NHibernate. To get this to work I had to write the following:

  • Custom Change-Tracking algorithm.
  • NHibernate Interceptor to plug in the custom Change Tracking algorithm (bypass the default one from NHibernate).

Digressing a bit from the main subject of the post, they are other advanced functionalities of NHibernate that can easily be customized:

Categories: DDD, ORM, 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. ;)