Try fast search NHibernate

Showing posts with label Patterns. Show all posts
Showing posts with label Patterns. Show all posts

08 July 2010

Enhanced Query Object

One of the annoying thing in our daily work is the modification of the Repository/DAO interface, and implementation, each time a new use-case, of our application, needs a new query.

The three solutions available so far

1.
The Query Object pattern was described by Martin Fowler. I like its short definition:
An object that represents a database query.
What I don’t like so much is its long description:
A Query Object is an interpreter [Gang of Four], that is, a structure of objects that can form itself into a SQL query.
A good example of Query Object is our dear ICriteria with all its classes. The problem is that I can’t expose neither ICriteria nor a concrete class using it because I don’t want expose nothing using NHibernate.
2.
Another possible solution is the Specifications Pattern (by Eric Evans and Martin Fowler).
Specification is again very powerful especially because easy to test. In .NET we have various implementations/interpretations based on LINQ. The advantage is basically that you can test your specification and your specification-composition in RAM… sure… hoping for that your LINQ provider can then efficiently translate it in SQL.
3.
The last is a repository implementing IQueriable (as proposed here) with its pro/cons:
  • Easy to test.
  • LINQ queries, for persistence, wrote every where.
  • Hope that your LINQ provider can then efficiently translate it in SQL.


The fact

In NHibernate we have at least six ways to query our persistence (have a look to this post). I can choose the query-system that best fit my needs of balance between code-readability, code-maintainability and query-performance.
Why I should limit myself in using just one ?
What I need is a solution to avoid the continuous modification of the repository’s interface maintaining the advantage NHibernate gives to me.


Enhanced Query Object

An object that represent a query. The responsibility of a EQO is returns the query results.
In general you will express a EQO as an interface placed in the same assembly where you are putting your IRepository interfaces. An example could look like:
public interface IContactByNameQuery
{
    string PartialFirstNameOrLastName    { get; set; }
    IPagedResults<Contact> GetAll(int pageSize, int pageNumber);
}
because the EQO is responsible to return the results of the query, in its implementation I can use whatever the persistence framework gives to me. I can add EQOs to my system without touch existing code. Because a EQO is an interface I can easily mock it. Perhaps I can’t test it quickly in RAM… perhaps… but in general I prefer to write integration tests (tests hitting a well-known-DataBase) instead test my queries using a fake-database.
The implementation of the above EQO, for NHibernate, could look as:
public class ContactByNameQuery : IContactByNameQuery
{
    private readonly ISessionFactory sessionFactory;

    public ContactByNameQuery(ISessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
    }

    #region IContactByNameQuery Members

    public string PartialFirstNameOrLastName { get; set; }
    public IPagedResults<Contact> GetAll(int pageSize, int pageNumber)
    {
        var query = sessionFactory.GetCurrentSession().QueryOver<Contact>();
        if (!string.IsNullOrWhiteSpace(PartialFirstNameOrLastName))
        {
            query.Where(
                Restrictions.On<Contact>(c => c.FirstName).IsLike(PartialFirstNameOrLastName, MatchMode.Anywhere) |
                Restrictions.On<Contact>(c => c.LastName).IsLike(PartialFirstNameOrLastName, MatchMode.Anywhere)
                );
        }
        query.OrderBy(c => c.LastName).Asc.ThenBy(c => c.FirstName);

        var queryCount = query.ToRowCountQuery();

        var contacts = query.Take(pageSize).Skip((pageNumber -1) * pageSize).Future<Contact>();
        var count = queryCount.FutureValue<int>().Value;
        return new PagedResults<Contact>(count, contacts);
    }

    #endregion
}

but you are completely free to implement it using LINQ, HQL, Criteria, H-SQL, SQL, NamedQuery or whatever you feel comfortable with.

How create a concrete instance of EQO ?

Using exactly the same identical way you are using for your concrete implementation of Repositories or DAOs implementations.
Try it and let me know how you feel.

22 November 2009

The GuyWire

In a afternoon of July I was working refactorizing a web-project. We was using the XML configuration of Castle.Windsor and Santiago Leguiza asked me a way to simplify the configuration.

The natural way to go is the configuration via Fluent-Interface. At that time my opinion about fluent-conf of the IoC was not so good because the fluent-conf needs references to each layer of the application. We have an IApplicationInitializer, for the application startup, but this time I need “something” with a more specific responsibility: wire any application part.

To give a name to a class is not so easy for me… probably because, in my opinion, the name should define the class responsibility. English, other than C#, is not my best, you know… using a mix between internet and my very old Italian-English dictionary, after 15 minutes or so, I have found a pretty good and funny name: GuyWire.

A guy-wire or guy-rope is a tensioned cable designed to add stability to structures. One end of the cable is attached to the structure, and the other is anchored to the ground at a distance from the structure's base.

Happy to have found the name I had twitted it ( first, second )

The interface

The interface is very very simple:

public interface IGuyWire
{
/// <summary>
///
Application wire.
/// </summary>
/// <remarks>
///
IoC container configuration (more probably conf. by code).
/// </remarks>
void Wire();

/// <summary>
///
Application dewire
/// </summary>
/// <remarks>
///
IoC container dispose.
/// </remarks>
void Dewire();
}

Using this interface is easy to realize that you may have different implementation for different IoC or, better, for different scenarios (for example in different test projects or the web-app and the wcf-service).

You can declare the IGuyWire in a separated very simple assembly where the only reference needed is System (nothing more).

Well… the interface is done but if I need to instantiate a concrete implementation I will have again the same problem… my application should know about the IoC and everything about all other parts… hmmm… I’m needing something to inject the injector.

again the solution is so simple as few code lines:

    /// <summary>
///
Helper class to get the <see cref="IGuyWire"/> concrete implementation
/// from application config.
/// </summary>
/// <remarks>
///
The appSetting section should have a key named "GuyWire" (case insensitive)
/// <example>
/// <![CDATA[
/// <appSettings>
/// <add key='GuyWire' value='YourCompany.Product.Wiring.IoC_Fx.GuyWire, YourCompany.Product.Wiring.IoC_Fx'/>
/// </appSettings>"
/// ]]>
/// </example>
/// </remarks>
public static class ApplicationConfiguration
{
private const string GuyWireConfKey = "guywire";
private const string GuyWireConfMessage =
@"The GuyWire was not configured.
Example
<appSettings>
<add key='GuyWire' value='YourCompany.Product.Wiring.IoC_Fx.GuyWire, YourCompany.Product.Wiring.IoC_Fx'/>
</appSettings>"
;

/// <summary>
///
Read the configuration to instantiate the <see cref="IGuyWire"/>.
/// </summary>
/// <returns>
The instance of <see cref="IGuyWire"/>.</returns>
/// <exception cref="ApplicationException">
///
If the key='GuyWire' was not found or if the <see cref="IGuyWire"/> can't be instancied.
/// </exception>
public static IGuyWire GetGuyWire()
{
var guyWireClassKey =
ConfigurationManager.AppSettings.Keys.Cast<string>().FirstOrDefault(k => GuyWireConfKey.Equals(k.ToLowerInvariant()));
if (string.IsNullOrEmpty(guyWireClassKey))
{
throw new ApplicationException(GuyWireConfMessage);
}
var guyWireClass = ConfigurationManager.AppSettings[guyWireClassKey];
var type = Type.GetType(guyWireClass);
try
{
return (IGuyWire)Activator.CreateInstance(type);
}
catch (MissingMethodException ex)
{
throw new ApplicationException("Public constructor was not found for " + type, ex);
}
catch (InvalidCastException ex)
{
throw new ApplicationException(type + "Type does not implement " + typeof(IGuyWire), ex);
}
catch (Exception ex)
{
throw new ApplicationException("Unable to instantiate: " + type, ex);
}
}
}

The ApplicationConfiguration class can stay in the same assembly of the IGuyWire, so, in my application, I will have a reference only to the assembly containing the IGuyWire and the ApplicationConfiguration and, the Global.asax for example, will look like:

private static IGuyWire guywire;

void Application_Start(object sender, EventArgs e)
{
guywire = ApplicationConfiguration.GetGuyWire();
guywire.Wire();
}

void Application_End(object sender, EventArgs e)
{
guywire.Dewire();
}

Doing so my application does not need a strongly reference neither the IoC nor any other concrete implementations of my interfaces.

How use the GuyWire

Some other pieces of the definition:

When steel cable is used, the guys are divided by insulators into multiple sections…

Does it match with something ? Yes it does. We have a web-application a wcf-service and various tests projects… our application is composed by different layers, each layer has its way to be wired and we can re-use the same wiring in different areas. As result of this concept I have an abstract implementation for Castle.Windsor:

namespace YourCompany.YourPrjCodeName.Wiring.Castle
{
public abstract class AbstractGuyWire : IGuyWire
{
protected WindsorContainer Container;

public void Wire()
{
if (Container != null)
{
Dewire();
}

Container = new WindsorContainer();
foreach (var guyWire in GuyWires)
{
guyWire.Wire();
}
}

public void Dewire()
{
if (Container != null)
{
Container.Dispose();
}
Container = null;
}

protected abstract IEnumerable<IGuyWire> GuyWires { get; }
}
}

The concrete class for the web-application is:

public class GuyWire : AbstractGuyWire
{
#region Overrides of AbstractGuyWire

protected override IEnumerable<IGuyWire> GuyWires
{
get
{
yield return new ServiceLocatorGuyWire(Container);
yield return new NhWebSessionManagementGuyWire(Container);
yield return new PersistenceGuyWire(Container);
yield return new ModelsGuyWire(Container);
}
}

#endregion
}

and for the wcf-service (to know where I’m using the ApplicationConfiguration class have a look to this post) :

public class ExternalServicesGuyWire : AbstractGuyWire
{
#region Overrides of AbstractGuyWire

protected override IEnumerable<IGuyWire> GuyWires
{
get
{
yield return new ServiceLocatorGuyWire(Container);
yield return new NhWebSessionManagementGuyWire(Container);
yield return new PersistenceGuyWire(Container);
yield return new WcfServicesGuyWire(Container);
}
}

#endregion
}

in each test-suite you can re-use same GuyWires depending on which layer you are testing and/or the type of the test (integration test or not).

P.S. another pending task was done!! thanks to be patient.

12 November 2009

MVP in web-Forms using Ajax

As you probably know I’m not neither an UX nor UI guy and in general, since the last few years, I’m trying to stay far away from something called “view”.

I’m involved in an existing Web-Forms project as consultant and sometimes as developer. The project has some years of active development and, although its success improves day by day, from the point of view of maintenance of some parts we have a problem: too much logic in the code-behind.

Following the rule of the CTO “business’s target at first” we have made a deal: each time we need to “re-touch” a use-case we will re-factorize each part involved.

The team, so far, has no experience with ASP.MVC and considering converting the whole project to ASP.MVC is not an option. As an example of the new work schema we have developed a small part of the application and deployed it in Windows Azure (webForm-MVP + WCF + NHibernate + SQL-Azure), that means, for us: no HttpSession, no VIEWSTATE… but this is another story. You can see the application here.

Our interpretation of MVP

In my opinion, the MVP pattern is one of the least clear of all patterns. This is so true that even the Passive View description has : “WORK-IN-PROGRESS: - this material is still under development”.

Our interpretation, for webForms, is simple: the Presenter is responsible to provide data to the View in the server side. The View know how render itself and what the client-side expect.

With this definition the Presenter, as most, can provide URL as strings but does not know anything about Request/Response, QueryString, Json, jQuery, HTML, javaScript, flash and any other technology involved in the View.

At this point what is the View, and which are its responsibilities, is simple: from the server-side code-behind to the HTML we are in the view and its responsibility is to render its self, to provide input data and, perhaps, to inform the presenter about some events.

The Ajax issue

Probably the most used solution, to resolve Ajax requests, in web-Forms, is through web-services (classic or WCF) or perhaps through some specific IHttpHandler… I worked with the team to accept MVP, and now ? Where is MVP if I have to separate the View’s needs, away from the Presenter ?

The other option is the usage of PageMethod with static methods marked as [WebMethod] and so on… could be usable but with some limitations.

The proof-of-concept

The intention is make the usage of Ajax as light as possible and of course to work with objects.

In the client-side I'll use what is normal today (including jQuery) and jQuery.form (no update-panel, no VIEWSTATE and so on). In the server side Json.NET.

To don’t make the story too much long here, have first a look to the show:

The use-case has two steps (two pages, apparently). There are 3 multiple-select; the first one is filled at page-load and the others are loaded through Ajax. The list of “Equipamiento” is loaded through Ajax. If you try to public (button “Publica”) and something is wrong the list of invalid values is showed (again through Ajax). You can go back and change any value. When you write something in e-mail input, it will check if the user exists and will show its address (“Calle”) through Ajax. Only when everything is OK the info is saved and you are redirected to a list. That’s all.

Instead of the VIEWSTATE I have used the view-state… not clear ? well… try to think about that the page has state in the browser ;-).

Ok… ok… I know… show me the code!!

The code behind

This is the code-behind (I mean the code behind the page in the server side).

public partial class ClasificadoCreate : View, IPublicationView
{
private PublicationPresenter presenter;

protected void Page_Load(object sender, EventArgs e)
{
presenter = new PublicationPresenter(this);
if(Request.IsAjaxRequest())
{
this.ResolveAjaxCallBack();
return;
}
if (!Page.IsPostBack)
{
presenter.InitView(Request.QueryString);
}
}

public void LoadModelos(int marca)
{
JsonResponse(presenter.GetModelos(marca));
}

public void LoadVersiones(int modelo)
{
JsonResponse(presenter.GetVersiones(modelo));
}

public void LoadEquipamiento(int version)
{
JsonResponse(presenter.GetEquipamiento(version));
}

public void LoadUsuario(string email)
{
JsonResponse(presenter.GetUsuario(email));
}

public IEnumerable<NameValueElement> Marcas
{
set
{
rptMarcas.DataSource = value;
rptMarcas.DataBind();
}
}

public void Publica(ClasificadoInfo clasificado)
{
JsonResponse(presenter.Register(clasificado));
}
}

Who calling those methods with parameters ?… especially the last-one where the parameter is the class ClasificadoInfo… and even more interesting if you think that its implementation is this:

public class ClasificadoInfo
{
public int MarcaId { get; set; }
public int ModeloId { get; set; }
public int VersionId { get; set; }
public IEnumerable<int> Equipamiento { get; set; }
public Usuario Usuario { get; set; }

public override string ToString()
{
var sb = new StringBuilder(300);
sb.AppendLine(string.Format("Marca={0},Modelo={1},Version={2}", MarcaId, ModeloId, VersionId));
sb.AppendLine("Equipamiento:");
if (Equipamiento != null)
{
foreach (int e in Equipamiento)
{
sb.Append(e).Append(',');
}
}
sb.AppendLine(string.Format("Usuario={0}", Usuario));
return sb.ToString();
}
}

public class Usuario
{
public string Email { get; set; }
public string Calle { get; set; }
public override string ToString()
{
return string.Format("Email={0},Calle={1}", Email, Calle);
}
}

As you can see that parameter is a class with a collection and a related class.

The code behind in the client side, changing a selected value, is:

<select name="ModeloId" multiple="multiple" id="listamodelos" size="5" onchange="return modelo_onchange()">
function modelo_onchange() {
var b = getFirstSelectedId("listamodelos");
JsonFromServerAction("LoadVersiones", { modelo: b }, function(a) {
replaceNameValueOptionsList("listaversiones", a)
});
replaceCategoriasEquipamiento(null)
}

The important part there is the function JsonFromServerAction whose implementation is:

function JsonFromServerAction(serverAction, params, onsuccess) {
var parameters = { LookupAction: serverAction };
$.getJSON(this.location.href, jQuery.extend(parameters, params), onsuccess);
}

As you can see LoadVersiones is the name of the method in the server-side-code-behind and modelo is the name of its parameter; pretty easy, clear and under convention.

Perhaps you are thinking that the code to post the entirely page inputs, to the server, will look more complicated… no? well… the answer is NO.

The client-side code is:

$(document).ready(function() {
$("#clasificado").ajaxForm({ url: this.location.href + "?LookupAction=Publica", dataType: 'json', success: showResponse })
});

To call the server-side code what you need is only "?LookupAction=Publica". To create the instance of the ClasificadoInfo parameter, of the method Publica, the convention to follow is simple. Each control name should match with a property name so:

<select name="VersionId" multiple="multiple" id="listaversiones" size="5" onchange="return version_onchange()">

mean that the selected value will be assigned to the property named VersionId and

e-mail:<input type="text" id="email" name="Usuario.Email" onchange="return usuario_onchange()" /><br />
Calle :<input type="text" id="calle" name="Usuario.Calle" /><br />

mean that the input value of email will be assigned to the property name Usuario.Email.

All the “magic” is done by the classes of HunabKu.Web (and obviously thanks to the others frameworks mentioned above).

If you want play a little bit, the code is available here or down load it.




Conclusion

Considering that we are talking about ~300 code-lines, I know that MonoRails and ASP.MVC are good and Web-Forms is evil… peeeero… la culpa no es siempre, y solo, del chancho.

12 October 2009

NHibernate & WCF : session-per-call in uNhAddIns

We have added a new project in uNhAddIns to work with NHibernate and WCF.

As you know the most common, and probably the most recommended, way to manage the NH’s session in WCF is session-per-call. The session-per-call pattern has the same behavior of session-per-request where, in this case, call, NH’s session and NH’s transaction has the same life cycle.

There are various ways to add this behavior to your WCF-service, the one I have used in uNhAddIns is through ICallContextInitializer. In addition there is a trivial IInstanceProvider to instantiate your services through a service-locator (in this case through Common Service Locator).

NhSessionPerCallContextBehavior

As usual, in uNhAddIns, what I’m using, as “Context”, is the implementation of ICurrentSessionContext. To work with session-per-call you must configure NHibernate with the ThreadLocalSessionContext (yes! the same we are using for tests, winForm and WPF applications).

        <property name="current_session_context_class">
uNhAddIns.SessionEasier.Contexts.ThreadLocalSessionContext, uNhAddIns
</property>

XML configuration

The XML configuration is the one I prefer because it is the less intrusive (you don’t need any reference to uNhAddIns.WCF).

Your contract may look as:

[ServiceContract]
public interface IMagazineService

and its implementation may look as

public class MagazineService : IMagazineService
{
private readonly IDaoFactory daoFactory;

public MagazineService(IDaoFactory daoFactory)
{
this.daoFactory = daoFactory;
}

The service configuration should look:

<behaviors>
<
serviceBehaviors>
<
behavior name="YourApp.Services.MagazineServiceBehavior">
<
serviceMetadata httpGetEnabled="true"/>
<
serviceDebug includeExceptionDetailInFaults="false"/>
<
InstanciateThroughServiceLocator/>
<
nhibernateBehavior/>
</
behavior>
</
serviceBehaviors>
</
behaviors>
<
extensions>
<
behaviorExtensions>
<
add name="nhibernateBehavior"
type="uNhAddIns.WCF.NhSessionPerCallBehaviorExtensionElement, uNhAddIns.WCF, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
<
add name="InstanciateThroughServiceLocator"
type="uNhAddIns.WCF.ServiceLocatorBehaviorExtensionElement, uNhAddIns.WCF, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</
behaviorExtensions>
</
extensions>

I’m using the WCF’s behaviorExtensions to inject both behaviors: the service instantiation through the service locator and the NH’s session-per-call.

Attributes configuration

If you don’t like the XML configuration, and you can deal with a strong reference to an “external” assembly, you can use the attribute-way. Doing so your implementation should look as:

[InstanciateThroughServiceLocator]
[NhSessionPerCall]
public class MagazineService : IMagazineService
{
private readonly IDaoFactory daoFactory;

The service locator configuration

To configure the IoC container I’m using the service factory and my dear guy-wire.

public class MyServiceHostFactory : ServiceHostFactory
{
IGuyWire guyWire;
public RoadtripServiceHostFactory()
{
guyWire = ApplicationConfiguration.GetGuyWire();
guyWire.Wire();
}
}

and the Markup of the service

<%@ ServiceHost Language="C#"
Debug="true"
Factory="YourApp.Services.MyServiceHostFactory"
Service="YourApp.Services.MagazineService"
CodeBehind="MagazineService.svc.cs" %>

That’s all… a piece of cake!!

27 September 2009

Testing DAOs : the SetUpFixture Attribute

Usually I’m testing DAOs for CRUD operations. Using NHibernate, as persistent layer, what we are testing, in practice, is the mapping and all behavior we have defined in it (cascade, associations, types, user-types, custom-collections and so on).

For CRUD operation I mean single entity instance CRUD without test complex queries (to test complex-queries I’m using a different test suite with a Well-Known-Data-Base).

Testing NHibernate DAO implementation

The first step is the test of the generic/base implementation of the DAO. To test it I’m mocking NHibernate.

[Test]
public void Get_call_Get()
{
// Arrange
var sessionFactory = new Mock<ISessionFactory>();
var session = new Mock<ISession>();
sessionFactory.Setup(x => x.GetCurrentSession()).Returns(session.Object);

// Act
var dao = new Dao<FakeEntity, int>(sessionFactory.Object);
dao.Get(123);

// Assert
session.Verify(x => x.Get<FakeEntity>(It.Is<int>(id => id == 123)));
}

The CRUD test

A simple integration CRUD test may look like this:

[TestFixture]
public class MagazineTest
{
[Test]
public void MinimalCrud()
{
const int poid = 1;
var m = new Magazine(poid) {Title = "some title"};

var dao = new EntityDao<Magazine>(ServiceLocator.Current.GetInstance<ISessionFactory>());

using (new PersistenceRequest())
{
dao.MakePersistent(m);
ActionAssert.NotThrow(()=> dao.MakePersistent(m));
}

using (new PersistenceRequest())
{
var e = dao.Get(poid);
e.Should().Not.Be.Null();
e.Title.Should().Be.EqualTo("some title");
}

using (new PersistenceRequest())
{
var e = dao.Get(poid);
e.Title = "different title";
}

// should update through NHibernate's UoW
using (new PersistenceRequest())
{
var e = dao.Get(poid);
e.Title.Should().Be.EqualTo("different title");
}

// Delete
using (new PersistenceRequest())
{
var e = dao.Get(poid);
dao.MakeTransient(e);
}

using (new PersistenceRequest())
{
var e = dao.Get(poid);
e.Should().Be.Null();
}
}
}

The PersistenceRequest is an utility class I’m using to simulate the behaviour of the IHttpModule implementing the session-per-request pattern.

Note, the test-fixture does not inherit from a base class and does not have a any SetUp nor TearDown but indeed it need, at least, the configuration of the ServiceLocator, the configuration of NHibernate, the creation of schema, and so on.

For the whole CRUD-test-suite I want execute the configuration of the ServiceLocator, the configuration of NHibernate and its SessionFactory, just only one time and not before execute each test-fixture.

The SetUpFixture Attribute

Since few versions NUnit has a very useful feature: the SetUpFixture Attribute.TestingDaoCrud



To have only one initialization, for all my CRUD-tests, I’m putting all test-fixtures starting from a specific namespace (in the image the namespace is “Cruds”) where I have the implementation of the class, marked with the [SetUpFixture], responsible to create the context for all CRUD tests.


The implementation of the CRUD context look like:
[SetUpFixture]
public class CrudTestContext
{
private WindsorContainer container;

[SetUp]
public void Configure_NHibernate_and_ServiceLocator()
{
container = new WindsorContainer();
container.Register(Component.For<IServiceLocator>()
.Instance(new WindsorServiceLocator(container)));
ServiceLocator.SetLocatorProvider(() => container.Resolve<IServiceLocator>());

container.Register(Component.For<ISessionWrapper>()
.ImplementedBy<FakeSessionWrapper>());
container.Register(Component.For<IConfigurationProvider>()
.ImplementedBy<NhTestConfigurationProvider>());
container.Register(Component.For<ISessionFactoryProvider>()
.ImplementedBy<SessionFactoryProvider>());
container.Register(Component.For<ISessionFactory>()
.Instance(container.GetService<ISessionFactoryProvider>().GetFactory(null)));
}

[TearDown]
public void Close_NHibernate()
{
container.Dispose();
}
}

public class NhTestConfigurationProvider : DefaultSessionFactoryConfigurationProvider
{
public NhTestConfigurationProvider()
{
AfterConfigure += ValidateOrCreateSchema;
}

private void ValidateOrCreateSchema(object sender, ConfigurationEventArgs e)
{
try
{
new SchemaValidator(e.Configuration).Validate();
}
catch (HibernateException)
{
var export = new SchemaExport(e.Configuration);
export.Drop(false, true);
export.Create(false, true);
}
}
}

If you want use the [SetUpFixture] you must use a NUnit2.5 compatible test-runner (ReSharper 4.5 does not support it).

UPDATE : I'm sorry, ReSharper 4.5 does SUPPORT it.

19 September 2009

Repository or DAO?: DAO

such question, no?
DAO is the anachronism of Data Access Object. On the cloud you can find various definitions of what is a DAO. The follow come from Java ecosystem and is the most complete I found:
The DAO implements the access mechanism required to work with the data source. The data source could be a persistent store like an RDBMS, an external service like a B2B exchange, a repository like an LDAP database, or a business service accessed via CORBA Internet Inter-ORB Protocol (IIOP) or low-level sockets. The business component that relies on the DAO uses the simpler interface exposed by the DAO for its clients. The DAO completely hides the data source implementation details from its clients. Because the interface exposed by the DAO to clients does not change when the underlying data source implementation changes, this pattern allows the DAO to adapt to different storage schemes without affecting its clients or business components.
As you can read there isn’t something exactly about how should look a DAO and a DAO can be defined to access data coming from any external source :
Essentially, the DAO acts as an adapter between the component and the data source.
You are completely free to define what each adapter should expose. For example you may have a DAO interface for a UserDAO where its implementations may work with an underling RDBMS, or with Active Directory and so on.
For CRUD operations, with a RDBMS a generic DAO may look as:
public interface IDao<TEntity, TIdentity> where TEntity: IEntity<TIdentity>
{
TEntity Get(TIdentity identity);
TEntity MakePersistent(TEntity entity);
void MakeTransient(TEntity entity);
}
I have used a DAO like that with an ADO.NET implementation. Write the generic implementation for NHibernate is a simple joke.

The problem with DAO is that was defined before powerful persistent-layers, as NHibernate, come in place. Modern persistent layer are tracking any modification you are applying to a persistent Entity and may auto-persist the modification without an explicit call to the DAO. Try to think the difference you have between an implementation using ADO.NET and using NHibernate; using ADO.NET nobody will update an entity state without an explicit call to the MakePersistent method where with NHibernate the modification can be persisted even without call it… a problem ? may be, all depend on how you are writing high layers.

Because the pattern does not define how a DAO should look, two DAOs as the follows are perfectly legal and may coexist in the same application:
public interface IProductDao
{
Product Get(int id);
IEnumerable<Product> FindByDecription(string template);
IEnumerable<Product> FindByPrice(IRange<decimal> priceRange);
void Save(Product product);
void Update(Product product);
void Delete(Product product);
}

public interface ICustomerDao
{
Customer Get(string id);
IEnumerable<Customer> FindByName(string name);
Customer Update(Customer customer);
}
As you can see there are various difference and there isn’t a common interface.

As said in the previous post you can use the Query object pattern to easy extend a DAO but, again, you can even not use it (nobody wrote “Client objects construct query specifications declaratively and submit them to Repository for satisfaction”). If you does not have time to define a good generic IQuery<TEntity> interface, you can use a more simple Criteria object. A Criteria object may look as:
public class CustomerAddressCriteria
{
public string PartialCustomerName { get; set; }
public string StreetName { get; set; }
public CustomerOrder Order { get; set; }
}
public enum CustomerOrder
{
ByNameAscending,
ByNameDescending
}
The DAO is responsible to create the correct query for the underling data-source so construct an SQL, an HQL or even use LINQ is a matter solved inside the DAO implementation (probably this was the reason because many of us are not so worried about a powerful LINQ provider).

Which is the end of this “powerful” and “flexible” pattern ?

As said before the DAO was born some years ago and the IT evolving very fast. If you want stay with a completely switchable interface there is no problem but if you want stop writing methods as FindByDecription, FindByPrice, FindByName, FindByCriteria the next step, at least, is something like:
IEnumerable<TEntity> Retrieve(Expression<Func<TEntity, bool>> predicate);
int Count(Expression<Func<TEntity, bool>> predicate);
and here is where our old friend DAO die because “switchable”, in this case, mean switch between underling system are supporting LINQ… perhaps in these days it mean again any systems… long life to DAO ? ;)

Previous post Repository.

13 September 2009

Repository or DAO?: Repository

such question, no?
The definition of Repository pattern is extremely clear (as usual coming from where it come). What was not absolutely clear is how developers are using it… perhaps my interpretation of these words is a little bit extreme.
A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection.
In .NET a Repository should look like:
public interface IRepository<T> : ICollection<T> { }
You may have just one implementation or you may have more than one especially to prevent the calls to Clear.
For example:
public class ProductRepository : IRepository<Product>
{
private readonly ISessionFactory sessionFactory;

public ProductRepository(ISessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}

public void Add(Product item)
{
sessionFactory.GetCurrentSession().Save(item);
}

public void Clear()
{
throw new NotSupportedException();
}
...
}
The other part of the pattern definition say:
Client objects construct query specifications declaratively and submit them to Repository for satisfaction.
With .NET3.5 the Repository should look like:
public interface IRepository<T> : ICollection<T>, IQueryable<T> { }
And the generic implementation for NHibernate should look like:
public class Repository<T>: IRepository<T>
{
private readonly ISessionFactory sessionFactory;

public Repository(ISessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}

#region Implementation of IQueryable

public Expression Expression
{
get { return sessionFactory.GetCurrentSession().Linq<T>().Expression; }
}

public Type ElementType
{
get { return sessionFactory.GetCurrentSession().Linq<T>().ElementType; }
}

public IQueryProvider Provider
{
get { return sessionFactory.GetCurrentSession().Linq<T>().Provider; }
}

#endregion
...
}
That’s all ? … yes that’s all… or that’s should be all.
LINQ is a powerful OO query language but was not designed, in specific, for persistence; in many cases we will must divide the execution in two parts: the part to run in the server and the part to run in RAM. Actually NHibernate has the same concept, through IQuery/ICriteria (server-side) and IResultTransformer (client-side), the main difference is that you are in charge of the decision about “where-run-what”. Implement a LINQ-provider, which is able taking such decisions, is the real feat (I have shown an simple example in this post). So far I didn’t see a persistent-layer that is in condition, always, to take some of these decisions and, frankly, I think it will be very hard; probably, in some cases, we will back to “user decision” with an explicit separation of a linq-sentence in two parts.
Using a Repository interpretation like the above there is another side effect: the responsibility of “how query the persistence” is completely delegated to the business-logic developer. There is no problem because, in general, he is the same guy ? perhaps… I’m not the same guy when I’m implementing the BL than when I’m implementing a DAO (I have tried to explain the problem to my psychologist but he doesn’t understand the problem). In practice Fabio-BL is worried only by OO matters where Fabio-DAL is worried by some OO-matters and, over all, by RDBMS issues. If Fabio-BL has a request like “give me a way to have all Products”, Fabio-DAL will give him a IPaginable<Product> with some restrictions about page-size, or, after some negotiations, an IEnumerable<Product> limited to the first 500 products (no more negotiable).
And before LINQ come in play ?
Here is where I saw everything else than Repository. For example:
public interface IProductRepository
{
Product GetById(int id);
IEnumerable<Product> FindByDecription(string template);
IEnumerable<Product> FindByPrice(IRange<decimal> priceRange);
void Add(Product product);
void Remove(Product product);
}

public interface ICustomerRepository
{
Customer GetCustomerById(string id);
IEnumerable<Customer> FindByName(string name);
void AddCustomer(Customer customer);
}
We can call the two implementations Repository as we can call it Juan, John or whatever; obviously “Repository” sound cool.
The correct way to implements Repository, before LINQ come in play, is using another pattern (the same defined for DAO) : Query object pattern.
The methods in your generic repository may look like:
IEnumerable<T> Retrieve(IQuery<T> query);
long Count(IQuery<T> query);
The challenge, here, is write a good generic IQuery<T> interface.
A little step back : “Repository mediates between the domain and data mapping layers”
Which “data mapping layers” ?
As the DAO even the Repository shouldn’t expose the implementation of the persistent-layer outside the Repository implementation itself and for that reason you shouldn’t use directly “a cooked” query object as NHibernate.ICriteria.
From here on any consideration we can make over “how query the domain” using Repository is applicable to DAO.

Next post DAO.

07 January 2009

Aspect Conversation-per-BusinessTransaction

Part I : Conversation-per-Business-Transaction
Part II : Implementing Conversation per Business Transaction
Part III (without AOP) : Using Conversation per Business Transaction

Introduction

For this post I’ll use the same example of the Part III but using a real IoC framework (Castle Windsor). To abstract “aspect” the conversation stuff, from its implementation, I will use some custom Attribute defined in uNhAddIns.Adapters assembly. As you can see, downloading the example, there are few classes changed from the previous example, that are the more simple, and less intrusive, implementation of the FamilyCrudModel and, obviously, the implementation of ServiceLocatorProvider.

Important

The implementation of “Aspect Conversation-per-BusinessTransaction” presented here is only one of the possible implementations. Gustavo Ringel (blog link not available so far) are working in a real-world example using Conversation-per-BusinessTransaction pattern in a Win-Form application with its implementation of uNhAddIns (the example is available here).

“Model” implementation comparison

The new FamilyCrudModel complete implementation is:
[PersistenceConversational]
public class FamilyCrudModel<TAnimal> : IFamilyCrudModel<TAnimal> where TAnimal : Animal
{
private readonly IAnimalReadOnlyDao<TAnimal> animalDao;
private readonly IFamilyDao<TAnimal> familyDao;

public FamilyCrudModel(IDaoFactory factory)
{
animalDao = factory.GetDao<IAnimalReadOnlyDao<TAnimal>>();
familyDao = factory.GetDao<IFamilyDao<TAnimal>>();
}

#region Implementation of IFamilyCrudModel<TAnimal>

[PersistenceConversation]
public IList<TAnimal> GetExistingComponentsList()
{
return animalDao.GetAll();
}

[PersistenceConversation]
public IList<Family<TAnimal>> GetEntirelyList()
{
return familyDao.GetAll();
}

[PersistenceConversation]
public Family<TAnimal> GetIfAvailable(int id)
{
return familyDao.Get(id);
}

[PersistenceConversation]
public Family<TAnimal> Save(Family<TAnimal> entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
return familyDao.MakePersistent(entity);
}

[PersistenceConversation]
public void Delete(Family<TAnimal> entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
familyDao.MakeTransient(entity);
}

[PersistenceConversation(ConversationEndMode = EndMode.End)]
public void AcceptAll() { }

[PersistenceConversation(ConversationEndMode = EndMode.Abort)]
public void CancelAll() { }

#endregion
}
Differences, from the previous implementation are:
  1. don’t need to inherits from any kind of base class.
  2. the constructor injection is more simple
  3. the implementation of each method don’t have boiled code
  4. the class and each persistent-method are marked with a custom attribute
I can avoid the point (4) depending on the AOP framework features, using Castle, for example, I can inject the behavior using XML or Fluent-Interface-Configuration.
The point(3) is, for example, this comparison:
ImplComparison
From the point of view of Conversation-per-Business-Transaction usage that it’s all.

A more deep view

Behind the AOP I’m using, in this example, uNhAddIns.CastleAdapters. For who are familiar with Castle, the CastleAdapters assembly contains:
  • The TransactionProtectionWrapper and its factory; it is a ISession wrapper to ensure the transaction usage for certain ISession methods. The wrapper is used in all session-handlers implementations available in uNhAddIns (a NoWrappedSessionWrapper implementation is available in uNhAddIns core).
  • The AutomaticConversationManagement Castle-Windsor-Facility.
  • uNhAddIns-PersistenceConversation-nh-default.config file to use it as an include in the Windsor configuration, if you want use XML configuration.
If you want use Fluent-Castle-configuration a possible implementation is:
container.AddFacility<PersistenceConversationFacility>();
var sfp = new SessionFactoryProvider();
sfp.AfterConfigure += ((sender, e) => new SchemaExport(e.Configuration).Create(false, true));
container.Register(Component.For<ISessionFactoryProvider>().Instance(sfp));
container.Register(Component.For<ISessionWrapper>().ImplementedBy<SessionWrapper>());
container.Register(Component.For<IConversationFactory>().ImplementedBy<DefaultConversationFactory>());
container.Register(Component.For<IConversationsContainerAccessor>().ImplementedBy<NhConversationsContainerAccessor>());
Note that the class SessionFactoryProvider is the implementation for one-db application and I’m explicit instancing it only because I’m using the AfterConfigure event to create the DB (in production you don’t need to do it).
For who are not familiar with ICurrentSessionContext NHibernate's feature is important to remember that it need a specific NHibernate configuration property:
<property name="current_session_context_class">
uNhAddIns.SessionEasier.Conversations.ThreadLocalConversationalSessionContext, uNhAddIns
</property>
If you want download the example of this post, as usual, the code is available here.


kick it on DotNetKicks.com


06 January 2009

Using Conversation per Business Transaction

The point I leave the pattern, in previous post, was its implementation.
Before show how use it with AOP, I think is better to show how it work because my AOP implementation is only one of the possible implementations and you can write yours (and hopefully share it).

Introduction

In this post, you will see a persistent-conversation which theory was introduced in here. Remember that what I want do is abstract the persistent-conversation-handling from the DAO/Repository implementation. The persistence-layer, I’ll use, is NHibernate2.1.0 (trunk) and the UoW is the NHibernate’s session. The use of NH2.1.0 mean that you must know this, by the way in this example I’ll show how use the conversation avoiding any kind of DynamicProxy, IoC and AOP framework (I hope you would use one).
Even if the target of the example is a win-form or WPF application I don’t want spent a single second writing a GUI so you will see a console application.

The example core

To understand how use the pattern implementation you should study two implementations: PersistenceConversationalModel, FamilyCrudModel
Let me show only one method:
public IList<TAnimal> GetExistingComponentsList()
{
try
{
using (GetConversationCaregiver())
{
return animalDao.GetAll();
}
}
catch (Exception e)
{
ManageException(e);
throw;
}
}

The real action here is animalDao.GetAll(); . The action is enclosed in a “Resume” – “Pause”. In the try-catch I’m discarding the persistence conversation in case of an exception.
If you don’t use AOP you must enclose all DAOs/Repository actions with the same structure (obviously you can call more than one action between  “Resume” – “Pause”).
The two methods to End or Abort the conversation are respectively:
public void AcceptAll()
{
try
{
EndPersistenceConversation();
}
catch (Exception e)
{
ManageException(e);
throw;
}
}

public void CancelAll()
{
try
{
AbortPersistenceConversation();
}
catch (Exception e)
{
ManageException(e);
throw;
}
}

From the point of view of Conversation-per-Business-Transaction usage that it’s all.

A more deep view

To have a more deep view, and understand what a possible AOP implementation must do (remember that you have one implemented and usable here), I must explain what are doing the PersistenceConversationCaregiver each time you call the method GetConversationCaregiver().


   1:         private class PersistenceConversationCaregiver : IDisposable
   2:         {
   3:             private readonly ConversationEndMode endMode;
   4:             private readonly PersistenceConversationalModel pcm;
   5:  
   6:             public PersistenceConversationCaregiver(PersistenceConversationalModel pcm, ConversationEndMode endMode)
   7:             {
   8:                 this.pcm = pcm;
   9:                 this.endMode = endMode;
  10:                 string convId = pcm.GetConvesationId();
  11:                 IConversation c = pcm.cca.Container.Get(convId) ?? pcm.cf.CreateConversation(convId);
  12:                 pcm.cca.Container.SetAsCurrent(c);
  13:                 c.Resume();
  14:             }
  15:  
  16:             #region Implementation of IDisposable
  17:  
  18:             public void Dispose()
  19:             {
  20:                 IConversation c = pcm.cca.Container.Get(pcm.GetConvesationId());
  21:                 switch (endMode)
  22:                 {
  23:                     case ConversationEndMode.End:
  24:                         c.End();
  25:                         break;
  26:                     case ConversationEndMode.Abort:
  27:                         c.Dispose();
  28:                         break;
  29:                     default:
  30:                         c.Pause();
  31:                         break;
  32:                 }
  33:             }
  34:  
  35:             #endregion
  36:         }

In the constructor (form line 6 to 14):
line 10 : I’m getting the conversationId from the “model” instance. The conversationId is a Guid in a string and the “model” is the conversationId-holder.
line 11: I’m getting the existing conversation, from the container, or I create a new one.
line 12: I’m setting the conversation as the current conversation.
line 13: I’m starting or resume the conversation.
In the dispose (from line 18 to 33):
line 20: I’m getting the conversation (it must exists)
line 30: I’m pausing the conversation.
To End or Abort the conversation the implementation is:
protected void EndPersistenceConversation()
{
IConversation c = cca.Container.Get(GetConvesationId());
if(c!=null)
{
c.Resume();
c.End();
}
}

protected void AbortPersistenceConversation()
{
IConversation c = cca.Container.Get(GetConvesationId());
if (c != null)
{
c.Abort();
}
}
Note the Resume before the End of the conversation; to be ended the conversation must be active.
The GetConvesationId() have no secrets:
protected virtual string GetConvesationId()
{
if (conversationId == null)
{
conversationId = Guid.NewGuid().ToString();
}
return conversationId;
}
What is more important, perhaps, is the ManageException method:
protected virtual void ManageException(Exception e)
{
IConversation c = cca.Container.Unbind(conversationId);
if (c != null)
{
c.Dispose();
}
}
Here I’m unbinding the conversation from the container and disposing the conversation. In term of NHibernate this mean the Rollback of the transaction and the dispose of the session. After this operation you can continue working in the same “Model” instance, what you must know is that you will use a new NHibernate-session.

The Example

The example show how the pattern work in tow cases:
  1. A simulation of an input in one Form
  2. A simulation of an input in two opened Form
If you download the code you can see a Diagram in each “layer”.
To have fun, writing the example, I have implemented a HomeMadeServiceLocator and I hope it can be useful to who are scared by IoC, Dependency Injection and AOP words.
The code of the example is available here.
If you have some question, about the example, feel free to ask.


kick it on DotNetKicks.com