José F. Romaniello

Las aventuras y desventuras de un codificador.

Según nos comenta Fabio Maulo, hoy fue liberada la versión 2.1.1GA de NHibernate, lo que a mi criterio es el mejor Framework de ORM sobre la plataforma .Net.

Hace mucho tiempo que vengo posteando en este blog algunas experiencias que tengo con NHibernate.

Qué estas esperando a descargarlo!

| More

Una de las cosas que aprendí de NHibernate.Validator hoy es que puedo definir una constraint en una interface. Y como no encontré mucha información quería comentar lo que hice con un ejemplo típico de mi negocio. (Por cierto al no haber nada en google puedo estar totalmente equivocado)

En el dominio de aplicaciones contables, a menudo nos encontramos con un tipo de estructura que yo llamo “Balanceable”. Balanceable significa que el movimiento debe cerrar, equilibrar, balancear.

Por ejemplo, un asiento contable, tiene que sumar igual importe en su Haber que en su Debe. En un flujo de caja, debe entrar a una o varias cajas el mismo monto que sale de otra/s. Extendiendo este concepto más allá, un movimiento de mercaderías debe descontar la misma cantidad de un depósito que lo que suma en otros. A este punto creo que ya se entiende el dominio.

La interface IBalanceable tiene esta pinta:

public interface IBalanceable
{
    bool EstaBalanceado { get; }
}

La definición de la constraint, usando fluent, es como sigue:

public class BalanceableValidationDef : ValidationDef<IBalanceable>
{
    public BalanceableValidationDef()
    {
        Define(b => b.EstaBalanceado)
            .IsTrue()
            .WithMessage("La entidad no balancea.");
    }
}

Una clase que implementa balanceable es la siguiente:

public class AsientoContable 
        : BaseEntity, IBalanceable
{
    //...un monton de código.
    
    public virtual IList<AsientoContableLinea> 
                Lineas { get; private set; }

    public bool EstaBalanceado
    {
        get
        {
            return Lineas
                .Sum(x => x.Importe * x.Signo.ToValue()) 
                    == 0;
        }
    }
}

Y el test es algo así:

[Test]
public void CuandoAsientoNoBalancea_ViolacionDeConstraint()
{
    var asiento = new AsientoContable();
    asiento.AgregarLinea(new AsientoContableLinea
                             {
                                 Importe = 1000, 
                                Signo = Signo.Debe
                             });
    asiento.GetErrors()
        .Satisfy(c => 
    c.Any(e => e.Message.Equals("La entidad no balancea.")));
    
}

Para los que no estan acostumbrados al estilo de Satisfier (es decir SharpTestEx), el test se lee así: “de este asiento dame los errores, esa colección de errores debe SATISFACER la condición de tener ALGÚN mensaje de error cuya descripción sea igual a “La entidad no balancea”. GetErrors es un extension method que usa IEntityValidator, en algún momento posteare acerca de eso.

La conclusión de este ejemplo, es que a partir de ahora, todo lo que sea IBalanceable tendrá esa constraint que yo definí una sola vez.

Por otro lado, recordar que este es el segundo ejemplo que posteo en español, con el tag MundoReal, esto quiere decir que son ejemplos donde el dominio no es un invento de mi imaginación :D. El primero fue un caso de monedas.

| More

En las reuniones familiares o de amigos, siempre hay 3 o 4 preguntas que seguro alguien nos hace a nosotros “los informáticos”:
-Me aparece un mensaje de error!!! en mi compu que puedo hacer donde esta el virus?
-Qué computadora me tengo que comprar?
-Qué juego conoces?

Realmente esas preguntas no me dan ganas de contestar, además yo soy programador y desconozco la respuesta. Pero en algún momento de la reunión, puede llegar el momento filosófico de la cuestión… Y en ese momento alguien puede disparar esta pregunta, que en mi caso me encanta contestar:

La computadora puede superar o va a superar a la mente humana?

La respuesta como a muchas cosas es “depende”, pero a mi me gusta hablar (característica que compartimos los argentinos)

  • Mi computadora guarda aproximadamente 120 gigas de información y yo no puedo recordar el número de teléfono de mi esposa.
  • Mi computadora puede realizar cálculos bastantes complejos que a mi me llevarían días.. o años.
  • Gracias a la computadora podemos resolver problemas que de otra forma no solo nos costaría mucho trabajo, si no que algunos si quiera podríamos.

Si alguien hubiese preguntado si las computadoras llegarían a este nivel, en la época que estas estaban en pañales, la respuesta probablemente hubiera sido NO.

Paradójicamente, a veces las tareas simples son las mas complicadas; una persona normal al año de vida es capaz de diferenciar entre un perro y un gato apenas viendo alguna parte de la imagen. El solo tratar de pensar en la complejidad de la red neuronal y el entrenamiento necesario me da escalofríos. Tratar de hacer que una computadora realice esta tarea, es algo muy difícil, mas no imposible.

Jimi, mi perro - my dog por Rod Chile 

Si le interesan estos temas puede leer un libro viejito llamado “La era de las máquinas espirituales”.

| More

In this post I will introduce a project under Unofficial NHibernate Addins named ComponentBehaviors. The goal of this project is to inject some goodness of System.ComponentModel through a dynamic proxy framework.

The WHY

Sometimes you need to implement certain interfaces of ComponentModel, for various reasons such as DataBinding, but the code need to accomplish this is tedious and repetitive. This code is called "plumbing code", an the following snippet is an example:

public class Customer : BaseEntity
{
    private string _firstName;
    public virtual string FirstName
    {
        get { return _firstName; }
        set
        {
            if(!_firstName.Equals(value))
            {
                _firstName = value;
                OnPropertyChanged("FirstName");
            }
        }
    }

    private string _lastName;
    public virtual string LastName
    {
        get { return _lastName; }
        set
        {
            if(!_lastName.Equals(value))
            {
                _lastName = value;    
                OnPropertyChanged("LastName");
            }
        }
    }
}

In the above sample, a property declaration took me 12 lines of code. Why I can't use auto properties (1 line)?

My goal was to have the same functionality like the above but with the following code:

public class Customer
{
    public virtual string FirstName {get; set;}
    public virtual string LastName {get; set;}
}

//Somewhere

configuration.For<Customer>()
    .Add<NotifiableBehavior>()
    .Add<DataErrorInfoBehavior>()
    .Add<EditableBehavior>();

A side effect is that classes are not tied to those interfaces and can be used in another project.

The WHAT

By now there are three supported behaviors:

  • DataErrorInfoBehavior
  • EditableBehavior
  • NotifyPropertyChangedBehavior

DataErrorInfo Behavior

The DataErrorInfo behavior is based on the interface IDataErrorInfo, and is described by me in this post. The configuration is as follows:

configuration.For<Customer>()
.Add<DataErrorInfoBehavior>();

You need to plug in your container an IEntityValidator, fortunately we have four implementations in uNhAddIns:

  • NHibernate Validator
  • DataAnnotations
  • Application Validation Block
  • Castle Validations

You can read more in this post of Fabio Maulo.

IDataErrorInfo is described in MSDN :

Provides the functionality to offer custom error information that a user interface can bind to.

Almost any DataBinding infrastructures such as Asp.Net, Asp.Net MVC, Winforms and WPF supports binding to an IDataErrorInfo entity.

Editable Behavior

The Editable behavior is based on the interface IEditableObject. The goal of this behavior is described in MSDN as follows:

Provides functionality to commit or rollback changes to an object that is used as a data source.

Note: Commit or Rollback refers to in-memory operations. Not database.

So a test like this, is self-explanatory:

[Test]
public void session_shouldnot_be_dirty_after_cancelchanges()
{
    var id = CreateNewAlbum();
    using (ISession session = sessions.OpenSession())
    using (ITransaction tx = session.BeginTransaction())
    {
        var album = session.Get<Album>(id);
        ((IEditableObject) album).BeginEdit();
        album.Title = "Dark side of the moon";
        ((IEditableObject) album).CancelEdit();
        session.IsDirty().Should().Be.False();

        tx.Commit();
    }
}

NotifyPropertyChanged behavior

NotifyPropertyChanged behavior is based on the interface INotifyPropertyChanged and is very well described in the MSDN:

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed.

The WHERE

With uNhAddIns.ComponentBehaviors you define the behaviors of a class ONCE and you can get an entity with the behaviors in many ways. I will describe in this section how ComponentBehaviors works with NHibernate.

Transient Entities

We just need an IEntityFactory in our projects as follows:

public class EntityFactory : IEntityFactory
{
    private readonly IComponentProxyFactory _componentProxyFactory;

    public EntityFactory(IComponentProxyFactory componentProxyFactory)
    {
        _componentProxyFactory = componentProxyFactory;
    }

    public T CreateInstance<T>()
    {
        return (T) _componentProxyFactory.GetEntity(typeof (T));
    }
}

Just plug that in your container and now you will be able to inject an IEntityFactory in your services.

Persisted entities

There are two ways to tell NHibernate that every time we return an object, this must come with the behaviors. The first way is with an interceptor as follows:

nhibernateConfig.Interceptor = 
    container.Resolve<ComponentBehaviorInterceptor>();

The second is has a little overhead because it involves to inject your entities in the container and now I'm using vaguely. But you can read more in this thread.

Proxy entities

With the steps described in the previous section, whenever nhibernate return an object, this object will come with the behaviors. But what happen when NHibernate itself need to generate a proxy for lazyloading stuff? Well, we can even specify that we want our behaviors in those proxies.

And the configuration is very easy:

cfg.Properties[Environment.ProxyFactoryFactoryClass] = 
    typeof (ComponentProxyFactoryFactory)
        .AssemblyQualifiedName

 

Final thoughts

If you want to see a working applications that use those concepts, have a look to this example.

I’ve started this project because I need it for my job, this was my first serious experience developing open source and for me has been very positive:

  • I’ve talked with lot of people around the globe, open source developers or not.
  • Some of them are using the library and improving.
  • I’ve learned a lot of Castle DynamicProxy and NHibernate.
  • I’ve participated in the afore mentioned projects.
  • I’ve three new job offers.

A word about NHibernate

For me, one of the interesting things that I found in NHibernate is a lot of “extensions points”. You could plug whatever you want and radically change the behavior of the tool to fit your needs.

Enjoy the NHibernate injection. :-)

| More

Note; this is an English version of my original post.

A few days ago I found a bug in Moq, the Mock framework I am currently using. I had a feeling for the stack trace of the exception was a DynamicProxy error, knowing that Moq uses DynamicProxy Castle and knowing a little DynamicProxy, I decided to investigate Moq inside.

The first thing I did was write a test in Moq that fail, but guess what, this is a very rare type of error related to the Visual Studio debugger, so if the debugger is not hooked, the error does not occur. The second thing I did was to isolate the problem to DynamicProxy, and that's when I really realized it was directly related to DynamicProxy. Then try to reproduce the problem in the trunk of dynamicproxy version, which obviously is not what my Moq version was using. And failed. Everything I have said to this point has been with some help from my friend from Poland, Krzysztof Kozmic. But here is where my involvement with the story ends. And you can read the whole thread here.

I’ve opened then the issue DP-115, and this is where the work of Krzysztof begins. He commented, that along the way, he found bugs on:

  • Reflector
  • Resharper
  • And finally this appears to be a bug in the debugger.

I can only imagine the complexity of the work of Krzysztof. I come closely following the footsteps of Krzysztof, simply because I'm passionate to learning about this subject. I have seen wonderful things like this, which is practically the backstage of DynamicProxy ... In 35 lines of code, my friend has created a type, inheriting an interface, has defined the generics methods of the interface with constraints, has created an assembly and saved the assembly. WAW!

Congratulations to Krzysztof for his amazing job, and thank you for the sparks that let us learn!, now he can read this post that was originally wrote in Spanish.

| More

Hace unos días encontré un error en Moq, el framework de Mock que estoy usando actualmente. Tuve un presentimiento por el stack trace de la excepción que era un error de DynamicProxy, sabiendo que Moq utiliza DynamicProxy de Castle y conociendo un poco DynamicProxy, decidí investigar Moq por dentro.

Lo primero que hice fue escribir un test en Moq que fallará, pero adivine qué?, este es un tipo de error muy raro relacionado al debugger de visual studio, así que si el debugger no esta “enganchado”, el error no aparece. Lo segundo que hice fue aislar el problema a DynamicProxy, y ahí fue cuando realmente me di cuenta que estaba directamente relacionado con DynamicProxy. Acto seguido, intente reproducir el problema en la versión trunk de dynamicproxy, que evidentemente no es la que estaba usando mi versión de Moq. Y también fallaba. Todo lo que he comentado hasta este punto ha sido con alguna ayuda de mi amigo de Polonia, Krzysztof Kozmic. Pero en este punto es donde mi participación en la historia termina. Y se puede leer todo el hilo acá.

A partir de que cargo el caso DP-115 es donde empieza a actuar directamente Krzysztof. Según nos comenta, por la complejidad del error, en su camino a descubrirlo a encontrado bugs en:

  • Reflector
  • Resharper
  • Y parece que finalmente es un error en el debugger.

Imaginó que este trabajo es muy duro ya que implica revisar incluso como ciertas cosas son compiladas. Vengo siguiendo muy de cerca los pasos de Krzysztof, simplemente por que me apasiona aprender. He visto cosas tan maravillosas como esta, es practicamente lo que DynamicProxy hace tras bambalinas… En 35 líneas de código, mi amigo ha creado un tipo, heredando una interfaz, ha definido su métodos genérico con constraints, ha generado un ensamblado dinámicamente, ha guardado el ensamblado. WAW!

Desde ya felicitaciones a Krzysztof. Seguramente él no va a entender nada de este post por que esta en español, a menos que use un traductor.

| More

I will try to explain a way to mock a linq based Dao, as the one introduced by Fabio Maulo here. The interface of the dao is something like this:

public interface IDao<TEntity{
//....
IEnumerable<TEntity> Retrieve(Expression<Func<TEntity, bool>> predicate);

int Count(Expression<Func<TEntity, bool>> predicate);
}

Suppose you have a controller or service, and you want to test a method is using a proper predicate for load the invoices of a given month and year. I’m using Moq for this example:

daoInvoices
    .Setup(dao => dao.Retrieve(Par.IsAnyPredicateOf<Invoice>()))
    .Returns(new List<Invoices> {newInvoice})
    .Callback<Expression<Func<Invoice, bool>>>(
predicate =>
    {
        predicate.Evaluate(invoiceIn)
                .Should().Be.True();

        predicate.Evaluate(invoiceOut)
                .Should().Be.False();
    }
);

Why I’m doing this?, Why validate the predicate in the callback? Because you can't match Expressions . You can read more info here, Moq isn’t exempt of this fact. So, my mock ignores the parameter, but the parameter is checked in the callback.

Evaluate(..) is an extension method for Expressions:

public static class ExpressionsExtensions
{
    public static bool Evaluate<T>(this Expression<Func<T,bool>> expression, T value)
    {
        return expression.Compile()(value);
    }
}

the expression is compiled twice, so?..
Par.IsAnyPredicateOf is another helper:

public static class Par
{
    public static Expression<Func<T, bool>> IsAnyPredicateOf<T>()
    {
        return It.IsAny<Expression<Func<T, bool>>>();
    }
}

"It" comes from Moq.

And maybe this is out of topic but I’m not testing the query itself!!!!!!!!. The query should be tested against the database, and if is possible, the real one. I tend to define my queries in a separated place, so queries are declared as follows:

namespace MyXYZSuperProject.Domain.Predicates
{
    public static class Invoice
    {
        public static Expression<Func<Invoice, bool>> 
                        ByPeriod(int month, int year)
        {
            return invoice => 
                            invoice.Month == month 
                            && recupero.Year == year;
        }
    }
}

Month and year are stored properties in this case, be careful.
AND I didn’t say NHibernate in the whole post!

| More

IMPORTANT NOTE: this code won’t work with WPF. Send me a patch :)

I just make a proof of concept with dynamics, and this is the result.

[TestMethod]
public void should_work()
{
    dynamic obj = new MyNotifiableExpandoObject();
    bool wasRaised = false;

    ((INotifyPropertyChanged)obj).PropertyChanged 
        += (sender, arg) => 
        {
            wasRaised = true;
            arg.PropertyName.Should().Be.EqualTo("Name");
        };

    obj.Name = "José";
    wasRaised.Should().Be.True;
}
 

I'm using C# 4 and the new keyword dynamic, MyNotifiableExpandoObject is a class that inherits from this one, first I tried to use ExpandoObject but.. is sealed.

So, my notifiable expando object is as follows:

public class MyNotifiableExpandoObject  : MyExpando, INotifyPropertyChanged
{
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler eventHandler = PropertyChanged;
        if (eventHandler != null) eventHandler(this, new PropertyChangedEventArgs(propertyName));
    }

    public override bool  TrySetMember(SetMemberBinder binder, object value)
    {
        var result = base.TrySetMember(binder, value);
        OnPropertyChanged(binder.Name);
        return result;
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler  PropertyChanged;

    #endregion
}

I hope you like it. Now ever property you set the propertychanged event will be raised properly.

| More

I will show you a trivial example of mixins with LinFu in this post.
Note: this is the first time I use LinFu stuff.

Sample Scenario

We have a Customer class as follows:

public class Customer
{
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
}

And we have a customer repository that looks as follows:

public interface ICustomerRepository
{
    ICollection<Customer> GetSomeCustomers();
}

Now, we have a user case in WPF, that needs to display the Customer data, but we need an extra bool property named “Selected”, this property will be bound to some checkbox in the GUI. How to solve this, without a CustomerDTO nor SelectableCustomer class?

Mixins

First we start with this:

public interface ISelectable
{
    bool Selected { get; set; }
}

public class Selectable : ISelectable
{
    #region ISelectable Members

    public virtual bool Selected { get; set; }

    #endregion
}

Now, I will create an extension method named “AsSelectable”, this is my test case:

[TestFixture]
public class SelectableTestFixture
{
    [Test]
    public void as_selectable_works()
    {
        var list = new List<Customer>
                       {
                           new Customer {FirstName = "José", LastName = "Romaniello"},
                           new Customer {FirstName = "Juan", LastName = "Perez"},
                           new Customer {FirstName = "Pedro", LastName = "Picolli"}
                       };
        List<Customer> customerList = list.AsSelectable().ToList();

        customerList[0].FirstName.Should().Be.EqualTo("José");
        ((ISelectable) customerList[0]).Selected.Should().Be.False();

        customerList[1].FirstName.Should().Be.EqualTo("Juan");
        ((ISelectable) customerList[1]).Selected.Should().Be.False();
    }
}

And this is the code for AsSelectable with LinFu 1.0:

public static class AsSelectableExtension
{
    private static readonly ProxyFactory refl = new ProxyFactory();

    public static IEnumerable<T> AsSelectable<T>(this IEnumerable<T> enumerable)
        where T : class
    {
        
        
        //Create a type that inherits from customer and implements ISelectable
        Type selectableCustomerType = refl.CreateProxyType(typeof (T), new[] {typeof (ISelectable)});

        foreach (T entity in enumerable)
        {
            var dynCustomer = new DynamicObject();
            dynCustomer.MixWith(entity);
            dynCustomer.MixWith(new Selectable());
            yield return (T) dynCustomer.CreateDuck(selectableCustomerType);
        }
    }
}

And for me… it looks very nice. I don’t know how to implement this with the current version of LinFu, I use the binaries from here.
This works great with WPF. I hope you like it.

| More