Try fast search NHibernate

25 December 2009

SharpTestsEx 1.0.0Beta : Satisfy your test

SharpTestsEx 1.0.0 was released today. You can download it from here.

More than few improvements, regarding some assertions and its failure message, and some internal refactoring, the mayor change is about the satisfier.

To talk about the syntax of the satisfier is something hard basically because there is no syntax. From user side of view, using the satisfier, the assertion is a simple and pure Func<TA, bool>.

From our side of view, the satisfier is the challenge of show an understandable failure message and, perhaps, help you to understand own much readable and self-explained is the name of some method.

Let me show you some example to understand how the satisfier works.

Example 1

Given this empty class

public class Session
{
public bool IsOpen { get; private set; }
public void Open() {}
public void Close() {}
}

The test to pass is:

var session = new Session();
session.Satisfy(s => !s.IsOpen);
session.Open();
session.Satisfy(s => s.IsOpen);
session.Close();
session.Satisfy(s => !s.IsOpen);

The test fail with this message:

SharpTestsExExamples.Session Should Satisfy (s => s.IsOpen)

Implementing the Open method the failure message is:

SharpTestsExExamples.Session Should Satisfy (s => !(s.IsOpen))

Example 2 (using Enumerable and LINQ)

In this case the value under test is a IEnumerable<int>:

var ints = new[] { 1, 2, 3 };
With
ints.All(x => x.Satisfy(a => a < 3));

The failure message is : 3 Should Satisfy (a => a < 3)

As you can see the extension Satisfy can be used even as a predicate inside a LINQ expression and, in this way, only the value breaking the test will be showed.

With
ints.Satisfy(a => a.All(x => x < 3));

The failure message is : [1, 2, 3] Should Satisfy (a => a.All(x => x < 3))

The same result using Any
ints.Any(x => x.Satisfy(a => a > 5));

The failure message : 1 Should Satisfy (a => a > 5)

Example 3 (method call)

var actual = "sometXing";
actual.Satisfy(a => a.ToUpperInvariant().Contains("TH"));

Fail with : "sometXing" Should Satisfy (a => a.ToUpperInvariant().Contains("TH"))

Example 4 (LINQ method call)

var ints = new[] { 1, 2, 3 };
ints.Satisfy(a => a.SequenceEqual(new[] { 3, 2, 1 }));

As you know SequenceEqual is a LINQ extension method included in .NET 3.5 and the satisfier will recognize it and will show:

[1, 2, 3] Should Satisfy (a => a.SequenceEqual(new[] {3, 2, 1}))
Values differ at position 0.
Expected: 3
Found : 1

Example 5 (equal)

var amount = 135.25m;
amount.Satisfy(a => a == 135m);

Fail with: 135,25 Should Satisfy (a => a == 135)

but

var name = "ErmAnegildo";
name.Satisfy(a => a == "Ermenegildo");

Fail with :

"ErmAnegildo" Should Satisfy (a => a == "Ermenegildo")
Strings differ at position 4.
ErmAnegildo
Ermenegildo
___^_______

Example 6 (complex predicate)

var actual = "somexxing";
actual.Satisfy(a => a.StartsWith("some") && a.Contains("TH") && a.EndsWith("ing"));

As you can see the assertion is composed by three conditions where only one will fail. The failure message will be:

"somexxing" Should Satisfy (a => a.Contains("TH"))

The same assertion but using “somexxING”, as actual value, will fail with:

"somexxING" Should Satisfy (a => a.Contains("TH"))
And
"somexxING" Should Satisfy (a => a.EndsWith("ing"))

Another example using a more “real” case:

var users = new UsersRepository();
users.Where(u => u.IsActive)
.Satisfy(a => a.Count() == 3 && a.Any(u => u.Name == "John") && a.Any(u => u.Name == "Fabio"));

The class UsersRepository is a IRepository<User> and the User class implements ToString returning the Name property. The repository contains three active users and does not contain an active User named Fabio. The failure message is:

[John, Frank, Marcus] Should Satisfy (a => a.Any(u => u.Name == "Fabio"))

Conclusions

If you are involved in various projects where one use MsTests another use xUnit another use NUnit you don’t need to remember which is the name of the Assertion class nor the syntax of the assertion itself, nor if the first parameter is the expected or the actual… what you need is only write “.Satisfy(” and continue writing pure C# predicate.

Satisfy your test with Sharp Tests Ex.

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.

19 November 2009

The .NET’s Attribute hole

Reading this post try to imagine how much I have worked, with my code, before create a test to test the behavior of the class Attribute.

Assertion

In .Net an Attribute is a class as any other and may have state and behavior.

True ? so and so… first of all, as class, it has some restriction as: it must inherit from System.Attribute and can’t be a generic class; second as any class it was implemented by a human with his fantasy (and this is the problem).

Perhaps, add behavior to an Attribute is not so common but, since even Microsoft is doing it, we can assume that it is a legal usage… anyway this is not the problem.

The Equal and GetHashCode issue

[AttributeUsage(AttributeTargets.Property)]
public class MyMarkerAttribute: Attribute
{
}
var attribute = new MyMarkerAttribute();
var another = new MyMarkerAttribute();
Console.WriteLine("Using == the result is: " + (attribute == another));
Console.WriteLine("Using Equals the result is:" + attribute.Equals(another));
Console.WriteLine("attribute hash:" + attribute.GetHashCode() + " another hash:" + another.GetHashCode());

This is the output:

Using == the result is: False
Using Equals the result is:True
attribute hash:10001680 another hash:10001680

Note: I haven’t implemented neither Equals nor GetHashCode. Every thing is as expected ? In a normal class this is not the expected behavior, by the way so far I can accept the situation.

Now I will change the attribute adding a integer property (about integer you know that its hash-code is its value):

[AttributeUsage(AttributeTargets.Property)]
public class MyMarkerAttribute: Attribute
{
public int Min { get; set; }
}

and now the output is:

Using == the result is: False
Using Equals the result is:True
attribute hash:0 another hash:0

What ? The HashCode now is cero ? … wait… wait… it does not end here.

[AttributeUsage(AttributeTargets.Property)]
public class MyMarkerAttribute: Attribute
{
public int Min { get; set; }
public int Max { get; set; }
}
var attribute = new MyMarkerAttribute { Min=5, Max= 456 };
var another = new MyMarkerAttribute { Min = 5, Max = 123 };

And the output is:

Using Equals the result is:False
attribute hash:5 another hash:5

As you can see the hash code is the hash of the first property (the same if it would be a field) and the most important inconsistence is that the two instance result as NOT EQUALS but they has the same HashCode.

[AttributeUsage(AttributeTargets.Property)]
public class MyMarkerAttribute: Attribute
{
private int myBergamota = 123;
public int Min { get; set; }
public int Max { get; set; }
}
var attribute = new MyMarkerAttribute {Min = 5, Max = 456};
var another = new MyMarkerAttribute { Min = 5, Max = 456 };

The output is:

Using Equals the result is:True
attribute hash:123 another hash:123

So the HashCode is the hash-code of the first property and the Equals work using the state of each property of instance of the attribute… such fantasy…

[AttributeUsage(AttributeTargets.Property)]
public class MyMarkerAttribute: Attribute
{
private int myBergamota = 123;
private int min;
public int Min
{
get { return min; }
set { min = value; }
}

public int Max { get; set; }

public void SetFieldValue()
{
myBergamota = 789;
}
}
var attribute = new MyMarkerAttribute {Min = 5, Max = 456};
var another = new MyMarkerAttribute { Min = 5, Max = 456 };

Console.WriteLine("attribute hash:" + attribute.GetHashCode() + " another hash:" + another.GetHashCode());

another.SetFieldValue();

Console.WriteLine("Using Equals the result is:" + attribute.Equals(another));
Console.WriteLine("attribute hash:" + attribute.GetHashCode() + " another hash:" + another.GetHashCode());

And the output is:

attribute hash:123 another hash:123
Using Equals the result is:False
attribute hash:123 another hash:789

What ? The hash changing at run-time ? but one of your recommendation is not that the hash-code should never change during execution ? what happen with Attribute ?

Wait a minute… who said that the hash-code change at run-time; it depend!!! depend about what… try to guess…

Now I will change only the position of the declaration of the private field:

[AttributeUsage(AttributeTargets.Property)]
public class MyMarkerAttribute: Attribute
{
private int min;
private int myBergamota = 123;
public int Min
{
get { return min; }
set { min = value; }
}

public int Max { get; set; }

public void SetFieldValue()
{
myBergamota = 789;
}
}

As you can see the only change is the position of the declaration, of the field myBergamota, from the first position to the second inside the class implementation; nothing more than the position inside the implementation!!! and now the output is:

attribute hash:5 another hash:5
Using Equals the result is:False
attribute hash:5 another hash:5

Re WHAT!???!!???! now I have the same hash-code ?!?!?!?!? only moving a declaration inside the class ?!?!?!?

Now you know that there is an ugly issue inside the .NET’s Attribute implementation and you may have a very very ugly surprise if you are writing a framework using attribute to cache metadata especially if the Attribute has behavior changing the internal state of the instance.

Resuming
The Attribute class override Equals and GetHashCode. The Equals is using the whole internal state, the GetHashCode is using only state of the first field and its value may change during execution.

The workaround
If you want a deterministic behavior the solution is simple and is the same you are applying in your classes: override Equals and GetHashCode.

If you don’t need a special behavior the implementation to use the Reference (the base of any other class) is:
public override bool Equals(object obj)
{
return ReferenceEquals(this, obj);
}

public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}

Conclusion

I like the application of your fantasy during software development, but be moderate please.

17 November 2009

NHibernate.Validator: Tags

At the begin of NHibernate Validator we have talked about the exigency of assign a “gravity level” to each validation (for instance Error, Warning, Information). In the last year we had requests for “validation grouping” and “different validation, for the same entity, in different contexts”.

Our answer is: validation tagging

What is a tag

In NHibernate Validator a tag has de same meaning you are giving to a tag in your blog, bookmarks, feed reader, Wave and so on. This mean that each validation-constraint may have none, one or more tags.

The type of the Tag is your choice; you can use System.Type, string, enum, int or whatever you want implements IEqualityComparer and… yes!! even altogether:

public class Error { }
public class Warning { }

public enum MyEnum
{
Error,
Warining
}

public class Entity
{
[Min(Value = 20, Tags = typeof(Error))]
[Max(Tags = new[] { typeof(Error), typeof(Warning) }, Value = 100)]
public int ValueUsingTypes { get; set; }

[Min(Value = 20, Tags = "error")]
[Max(Tags = new[] { "error", "warning" }, Value = 100)]
public int ValueUsingStrings { get; set; }

[Min(Value = 20, Tags = MyEnum.Error)]
[Max(Tags = new[] { MyEnum.Error, MyEnum.Warining }, Value = 100)]
public int ValueUsingEnums { get; set; }

[Min(20)]
[Max(100)]
public int ValueWithoutTags { get; set; }
}

If you are using the XML mapping (to configure the validation), all Tags are strings but using attributes or Loquacious you can use anything you want.

Even the follow declaration is possible:

[Min(Value = 20, Tags = new object[] {typeof(Error), 1, "warning"})]

The usage of an array of objects is a language limitation but, at the end, we can read it as a feature ;-) (have a look to the end of this link).

How validate using Tags

Tags are available in any method used, in the ValidatorEngine, to validate a property or an entity. To explain how work with Tags I prefer to show you some examples:

Example 1:
var entity = new Entity();
validatorEngine.Validate(entity);

This is the “normal” usage without tags. In this case we have four invalid values (one for each property) because without specify a tag we will use all constraints, and in this case, we are breaking all Min constraints.

Example 2:
var entity = new Entity();
validatorEngine.Validate(entity, typeof(Warning));

We have only one constraint tagged with typeof(Warning) : the property ValueUsingTypes should be less than or equal to 100. As default ValueUsingTypes=0 so, using the example2, we will have a valid entity (none invalid values).

Example 3:
var entity = new Entity {ValueUsingTypes = 101};
validatorEngine.Validate(entity, typeof (Warning));

Similar situation of the previous example but this time ValueUsingTypes is greater than 100 so we will have one invalid value.

Example 4:
var entity = new Entity();
validatorEngine.Validate(entity, typeof (Error), null);

Here I’m using two tags: typeof(Error) and the other tag is null. In this case we are selecting all constraints tagged with typeof(Error) and all constraints without tags so we will have two invalid values: ValueUsingTypes is less than 20 and ValueWithoutTags is less than 20.

In practice null is a special reserved tag used to select those constraints without a specific tag.

Example 5:
var entity = new Entity();
validatorEngine.Validate(entity, typeof(Error), MyEnum.Error, "error");

I’m using three Tags: typeof(Error), MyEnum.Error, "error". We will have three invalid values: ValueUsingTypes is less than 20 and ValueUsingStrings is less than 20 and ValueUsingEnums is less than 20.

Example 6:

To validate only those constraint without a tag the syntax is:

var entity = new Entity();
validatorEngine.Validate(entity, new object[] {null});
In this case we will have only one invalid value: ValueWithoutTags is less than 20.

Consideration

In the examples above I have used a really strange way to use Tags only to show you the freedom you having. My personal advise is to define one, two or as most three “meaning” tags. Take care with tagged and no-tagged constraints: in my opinion you should work with all tagged constraint or without tags; if you want mix tagged with no-tagged, don’t forget example-1, example-4 and example-6. If you have some constraints involving the persistence and you want run it only when all others constraints does not have invalid values, the "constraint tagging" is a good candidate to solve the issue.

The result InvalidValue with Tags

The InvalidValue class now has a new property: MatchTags. The new property will contain the intersect between the tags declared for a constraint and the tags used for a specific validation.
Example :
public static class Tags
{
public static readonly string Error = "Error";
public static readonly string Warning = "Warning";
public static readonly string Information = "Information";
}
public class Entity
{
public int ValueMinMax { get; set; }
public int ValueMin { get; set; }
}
public class EntityValidator : ValidationDef<Entity>
{
public EntityValidator()
{
Define(x => x.ValueMinMax)
.Satisfy(v => v >= 20).WithTags(Tags.Error)
.And
.Satisfy(v => v <= 100).WithTags(Tags.Error, Tags.Warning);

Define(x => x.ValueMin)
.GreaterThanOrEqualTo(20).WithTags(Tags.Warning, Tags.Information);
}
}

running a validation as

var entity = new Entity { ValueMinMax = 101 };
validatorEngine.Validate(entity, Tags.Information, Tags.Warning);

For the InvalidValue related to ValueMinMax property the MatchTags is “Warning

For the InvalidValue related to ValueMin property, the MatchTags is [“Warning”, “Information”]

15 November 2009

Refactorizing tests

I had read, in some place on the cloud, that SharpTestsEx make the test more verbose even if it is more readable.

In NHibernate.Validator (NHV) we are using #TestsEx. After implements some new features I’m improving some stuff where I’m needing a little breaking change.

This is an existing test using classic NUnit syntax:

[Test]
public void CreditCard()
{
CreditCard card = new CreditCard();
card.number = "1234567890123456";
IClassValidator classValidator = GetClassValidator(typeof(CreditCard));
InvalidValue[] invalidValues = classValidator.GetInvalidValues(card);
Assert.AreEqual(1, invalidValues.Length);
card.number = "541234567890125"; //right CC (luhn compliant)
invalidValues = classValidator.GetInvalidValues(card);
Assert.AreEqual(0, invalidValues.Length);
card.ean = "9782266156066";
invalidValues = classValidator.GetInvalidValues(card);
Assert.AreEqual(0, invalidValues.Length);
card.ean = "9782266156067";
invalidValues = classValidator.GetInvalidValues(card);
Assert.AreEqual(1, invalidValues.Length);
}

The breaking change is about the return value of GetInvalidValues : in NHV1.2.0 the method will return IEnumerable<InvalidValue>.

Refactoring step 1

Same but compileable.

[Test]
public void CreditCard()
{
CreditCard card = new CreditCard();
IClassValidator classValidator = GetClassValidator(typeof(CreditCard));

card.number = "1234567890123456";
Assert.That(classValidator.GetInvalidValues(card), Is.Not.Empty);

card.number = "541234567890125"; //right CC (luhn compliant)
Assert.That(classValidator.GetInvalidValues(card), Is.Empty);

card.ean = "9782266156066";
Assert.That(classValidator.GetInvalidValues(card), Is.Empty);

card.ean = "9782266156067";
Assert.That(classValidator.GetInvalidValues(card), Is.Not.Empty);
}
Refactoring step 2
[Test]
public void CreditCard()
{
CreditCard card = new CreditCard();
var classValidator = GetClassValidator(typeof(CreditCard));

card.number = "1234567890123456";
classValidator.GetInvalidValues(card).Should().Not.Be.Empty();

card.number = "541234567890125"; //right CC (luhn compliant)
classValidator.GetInvalidValues(card).Should().Be.Empty();

card.ean = "9782266156066"; //right EAN
classValidator.GetInvalidValues(card).Should().Be.Empty();

card.ean = "9782266156067"; //wrong EAN
classValidator.GetInvalidValues(card).Should().Not.Be.Empty();
}

Now, using SharpTestsEx, we can run the same test with xUnit, MsTests, MbUnit (if/when we will need/want change the unit test framework) and I can’t see where it is more verbose.

Refactoring step 3
[Test]
public void GivingValidState_NoInvalidValues()
{
var card = new CreditCard {Number = "541234567890125", Ean = "9782266156066"};
var classValidator = GetClassValidator(typeof(CreditCard));

classValidator.GetInvalidValues(card).Should().Be.Empty();
}

[Test]
public void GivingInvalidState_HasInvalidValues()
{
var card = new CreditCard {Number = "1234567890123456", Ean = "9782266156067"};
var classValidator = GetClassValidator(typeof(CreditCard));

classValidator.GetInvalidValues(card).Should().Have.Count.EqualTo(2);
}

Perhaps SharpTestsEx is a little bit more verbose, in some cases, but with your help we can improve it.

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.

02 November 2009

Validation Abstraction: Custom

If you have read this post you know I’m having some psychological problem at work: multi-personality.

My dear friend Fabio-NHV said me: hey man! I have a very good OSS validation framework strongly recommended if you are validating entities you are using with NHibernate.

And I said: Cool!! but your framework is only an option for me… soon or later I’ll use something else and, btw, I need to mix the validation done by your framework with my BL and/or UI validation.

The IEntityValidator

The IEntityValidator is part of uNhAddIns because José asked me how I’m abstracting the validation stuff from my application, during the implementation of the ChinookMediamanager example (the same happened with the IGuyWire and, a year ago, with the CpBT and Gustavo).

public interface IEntityValidator
{
bool IsValid(object entityInstance);
IList<IInvalidValueInfo> Validate(object entityInstance);
IList<IInvalidValueInfo> Validate<T, TP>(T entityInstance, Expression<Func<T, TP>> property) where T : class;
IList<IInvalidValueInfo> Validate(object entityInstance, string propertyName);
}
public interface IInvalidValueInfo
{
Type EntityType { get; }
string PropertyName { get; }
string Message { get; }
}

any good validation-framework should give me the way to implement an adapter for, at least, these methods.

The implementation for NHibernate.Validator

We having an implementation of IEntityValidator in uNhAddIns… by the way, in an application in production, I’m using a more simple implementation:

public class NhVEntityValidator : IEntityValidator
{
private readonly ValidatorEngine validatorEngine;

public NhVEntityValidator(ValidatorEngine validatorEngine)
{
this.validatorEngine = validatorEngine;
}

#region Implementation of IEntityValidator

public bool IsValid(object entityInstance)
{
return validatorEngine.IsValid(entityInstance);
}

public IList<IInvalidValueInfo> Validate(object entityInstance)
{
InvalidValue[] iv = validatorEngine.Validate(entityInstance);
return
new
List<IInvalidValueInfo>(
from invalidValue in iv
select (IInvalidValueInfo) new InvalidValueInfo(invalidValue));
}

#endregion
}

public class InvalidValueInfo : IInvalidValueInfo
{
private readonly InvalidValue iv;

public InvalidValueInfo(InvalidValue iv)
{
this.iv = iv;
}

#region Implementation of IInvalidValueInfo

public Type EntityType
{
get { return iv.EntityType; }
}

public string PropertyName
{
get { return iv.PropertyName; }
}

public string Message
{
get { return iv.Message; }
}

#endregion
}

The Usage
As you can imagine the usage is simple. Where you need the IEntityValidator you must inject it:
public UsuarioParticularNuevoService(
    IDaoFactory factory,
IUserSessionContext context,
IMailSender mailSender,
IMailMaker mailMaker,
IEntityValidator entityValidator)

and then simply use it

public IInvalidValueInfo[] Register(UsuarioNuevoInfo usuarioInfo)
{
var usuario = GetUsuario(usuarioInfo);

AddPais(usuario);
AddDireccion(usuario, usuarioInfo);
AddTelefono(usuario, usuarioInfo);
AddNewsletter(usuario, usuarioInfo);
AddNegocio(usuario);

var errors = validator.Validate(usuario);

if (errors != null && errors.Count > 0)
return errors.ToArray();

usuarioDao.SaveOrUpdate(usuario);
mailSender.Send(GetMailMaker(usuarioInfo, usuario).Make());
return new IInvalidValueInfo[0];
}

The chunk, of the IoC’s configuration (in this case Castle.Windsor), in my dear IGuyWire look like:

ValidatorEngine validatorEngine = ConfigureNHibernateValidatorEngine();

container.Register(Component.For<ValidatorEngine>().Instance(validatorEngine));
container.Register(Component.For<ISharedEngineProvider>().ImplementedBy<SharedEngineProvider>());
NHibernate.Validator.Cfg.Environment.SharedEngineProvider =
container.Resolve<ISharedEngineProvider>();
container.Register(Component.For<IEntityValidator>().ImplementedBy<NhVEntityValidator>());

Options

In uNhAddIns you can find two more options, for the IEntityValidator, implemented for ValidationApplicationBlock and for DataAnnotation (thanks to José Romaniello for his implementation).

31 October 2009

Validation through persistence: not synchronized

In this series you saw mostly the configuration of NHibernate.Validator through Loquacious (our configuration based on fluent-interface).

What is the ValidationDef<T> ?

If you are using the Satisfier (validation through lambdas) the ValidationDef become the class whose responsibility is validate a instance of T.

If you need some validation, involving the persistence, and you want do it through NHV, which is the best candidate class where implement the validation ?

Let me show you how much easy is it:

public class BlogPostSofValidation : ValidationDef<BlogPost>
{
private readonly ISessionFactory factory;

public BlogPostSofValidation(ISessionFactory sessionFactory)
{
factory = sessionFactory;
ValidateInstance.By((bp, c) => !Exists(bp));
}

private bool Exists(BlogPost post)
{
if (ReferenceEquals(post, null))
{
return true;
}
using (var session = factory.OpenStatelessSession())
{
var criteria = session.CreateCriteria(typeof(BlogPost));
criteria.Add(Restrictions.Eq("Title", post.Title));
criteria.Add(Restrictions.Eq("Date", post.Date));
return criteria.UniqueResult() != null;
}
}
}

Here I’m showing only the part involving the persistence but you know… there you can define the validation of any other property as usual.

To register this definition the work to do is very easy:

var veConfig = new FluentConfiguration();
veConfig.Register(new BlogPostSofValidation(sessionFactory))
.SetDefaultValidatorMode(ValidatorMode.UseExternal);
validatorEngine = new ValidatorEngine();
validatorEngine.Configure(veConfig);

and that it’s all (the usage is identical of the previous post).

30 October 2009

Validation through persistence: synchronized

This post is about one possible answer to the question mememem ask me in this post (ah… nice nick).

The task is create a validator to validate the uniqueness, of an entity instance, using some properties’ values instead its POID (Persistence Object ID).

The implementation

public class BlogPost
{
public string Title { get; set; }
public DateTime Date { get; set; }
public string Content { get; set; }
}

we want check the uniqueness using the value of Title and the value of Date obviously without use both properties as composite-PK; so, we can’t have two posts with the same title in the same day.

Since NHibernate2.1.0GA we can instruct NH about our concept of uniqueness in a very explicit, self documented, and nice way:

<class name="BlogPost">
<
id type="guid">
<
generator class="guid.comb"/>
</
id>
<
natural-id mutable="true">
<
property name="Title"/>
<
property name="Date" type="Date"/>
</
natural-id>
<
property name="Content" type="string(10000)"/>
</
class>

clear no ? we are defining explicitly which is our natural-id, that mean we want a unique key with Title and Date. The result DDL is:

create table BlogPost (
id UNIQUEIDENTIFIER not null,
Title NVARCHAR(255) null,
Date DATETIME null,
Content NVARCHAR(MAX) null,
primary key (id),
unique (Title, Date)
)

We having NHibernate and the DataBase synchronized with the same rule and now we want create a validator to use with NHibernate.Validator to synchronize even our business logic (and prevent ADO.NET exceptions).

First the attribute to “mark” my classes:

[AttributeUsage(AttributeTargets.Class)]
[ValidatorClass(typeof(NaturalIdUniquenessValidator))]
public class NaturalIdUniquenessAttribute : Attribute, IRuleArgs
{
public string Message { get; set; }
}

then the validator implementation with NHibernate integration. In this implementation I’m using the Stateless-Session but you can use, a new statefull session or factory.GetCurrentSessionContext or whatever you have as session-provider. The matter is not from where you get the session but how create the query in a generic way that can be used for any entity without need any kind of “invasion” in my existing implementation.

Note: this is a classic usage of the stateless-session but take care with the BestGuessEntityName method.

public class NaturalIdUniquenessValidator : IValidator
{
private readonly ISessionFactory factory;

public NaturalIdUniquenessValidator(ISessionFactory sessionFactory)
{
factory = sessionFactory;
}

public bool IsValid(object value, IConstraintValidatorContext constraintContext)
{
if (ReferenceEquals(value, null))
{
return true;
}
using (var session = factory.OpenStatelessSession())
{
var entityName = ((ISessionImplementor) session).BestGuessEntityName(value);
var meta = factory.GetClassMetadata(entityName);
if (ReferenceEquals(meta, null) || !meta.HasNaturalIdentifier)
{
return true;
}
var propsValues = meta.GetPropertyValues(value, EntityMode.Poco);
var propsNames = meta.PropertyNames;
var criteria = session.CreateCriteria(entityName);
foreach (var propIdx in meta.NaturalIdentifierProperties)
{
criteria.Add(Restrictions.Eq(propsNames[propIdx], propsValues[propIdx]));
}
return criteria.UniqueResult() == null;
}
}
}

In the implementation I’m using some NHibernate advanced information to create a ICriteria with the properties defined as natural-id; the implementation is working with any entity of your domain. The strange thing, there, is another: the validator does not have a default constructor… where is the trick ?

Well… first the implementation with an home-made-2-minutes-IoC:

public class ConstraintValidatorFactory : DefaultConstraintValidatorFactory
{
public override IValidator GetInstance(Type type)
{
var persistenceCtor = type.GetConstructor(new[] {typeof (ISessionFactory)});
if(persistenceCtor != null)
{
return (IValidator)
persistenceCtor.Invoke(new object[] { NHibernateStaticContainer.Factory });
}
return base.GetInstance(type);
}
}

The IConstraintValidatorFactory is the factory for classes implementing IValidator and you can inject the concrete implementation through NHV configuration.

var nhvConfig = new FluentConfiguration();
nhvConfig.SetConstraintValidatorFactory<ConstraintValidatorFactory>();

Another, more generic, implementation of the IConstraintValidatorFactory could be:

public class ServiceLocatorValidatorFactory : DefaultConstraintValidatorFactory
{
#region Implementation of IConstraintValidatorFactory

public override IValidator GetInstance(Type type)
{
ConstructorInfo defaultConstructorInfo = type.GetConstructor(new Type[0]);
if (defaultConstructorInfo == null)
{
return (IValidator) ServiceLocator.Current.GetInstance(type);
}
return base.GetInstance(type);
}

#endregion
}

here you can use your preferred IoC framework as the factory/container of validators instances (take care with statefull validators).

The usage

Well… it is completely transparent, you can use this entity-validator as you are using any other.

the definition

public class BlogPostValidation: ValidationDef<BlogPost>
{
public BlogPostValidation()
{
ValidateInstance.Using(new NaturalIdUniquenessAttribute());
}
}

a simple test

var blogPost = new BlogPost
{
Title = "something new",
Date = DateTime.Today,
Content = "there is something new to say."
};

validatorEngine.IsValid(blogPost).Should().Be.True();

using (var s = sessionFactory.OpenSession())
using (var tx = s.BeginTransaction())
{
s.Save(blogPost);
tx.Commit();
}

var otherBlogPost = new BlogPost
{
Title = "something new",
Date = DateTime.Today,
Content = "bha?!?."
};

validatorEngine.IsValid(otherBlogPost).Should().Be.False();

otherBlogPost.Title = "very new";

validatorEngine.IsValid(otherBlogPost).Should().Be.True();

Conclusion

The implementation of the entity BlogPost was NEVER TOUCHED (I did it my way)… now :

  • go to your system
  • copy&paste the implementation of NaturalIdUniquenessAttribute and NaturalIdUniquenessValidator
  • change the implementation of the ConstraintValidatorFactory according to your system
  • change the mapping defining your natural-id in the entities where needed
  • Enjoy NHibernate.Validator, its flexibility, its injectability and its easy integration with NHibernate.

Tomorrow, perhaps, the no synchronized implementation.

29 October 2009

NHibernate visual Class and mapping generator integrated with VisualStudio2010

Do you remember this post ?

Now Microsoft gave us a step-by-step guide : POCO Templates for the Entity Framework

Fantastic!!!

Now we need a good soul starting the integration with NHibernate to generate POCO and mappings.

There will be a little difference:

The POCO template generates Entities that supports change notification.

NHibernate.Validator & NHibernate

The validation is defined as a classic cross cutting concern… well… if we are talking about that we need to validate something everywhere I can agree with that definition, but if we are talking about the validation of domain entities I don’t agree.

The validation of a domain-entity shouldn’t happen in the persistence-layer nor in the presentation-layer and even less in the persistence itself.

Validate something in the DB (persistence) is too late and you will have some unneeded round-trips, by the way, in some very special cases is acceptable and even inevitable (read it as optimistic-lock for example).

Validate in the persistent-layer can be useful if you want a “short-cut” where put the validation (for example if you modify an entity instance, somewhere, and you don't exactly know where put the validation of the new state).

Validate in the UI, well… there you can validate only what you are showing.

The natural place for the entities-validation is the service-layer (service in DDD meaning).

If I think so, why I like NHibernate.Validator so much ?

The matter is that, in the service-layer, I’m needing to validate entities-instances provided by NHibernate and I need a validation system that know how NHibernate work with entities (perhaps, soon, somebody will realize it for EF4).

warnIf you are using something else, than NHV, to validate complex-entities-graph (with valid associations, valid collections and so on), be careful and have a look to what is happening with SQL-Queries (activating log4Net for the SQL, or testing NH-Statistics, or using NHProf, or whatever).

That said I can begin explaining some integration points leaving you the choice of its usage.

The “integrator”

The class you must use to perform the integration is NHibernate.Validator.Cfg.ValidatorInitializer.

In the ValidatorInitializer there are only two extension-methods and before write this post I wrote the documentation of both methods; now you can read it there.

A full integration may look like:

var nhvConfiguration = new FluentConfiguration();
nhvConfiguration
.SetDefaultValidatorMode(ValidatorMode.UseExternal)
.Register(Assembly.Load("Dll.Where.ValidationDefAre")
.ValidationDefinitions())
.IntegrateWithNHibernate
.ApplyingDDLConstraints()
.And
.RegisteringListeners();

var nhibernateConfig = new Configuration().Configure();

validatorEngine = new ValidatorEngine();
validatorEngine.Configure(nhvConfiguration);

nhibernateConfig.Initialize(validatorEngine);

About the ValidatorEngine and the Shared-Engine-Provider you can read in: Diving in NHibernate.Validator.

Events integration

The integration of events is basically the registration of a IPreInsertEventListener and a IPreUpdateEventListener. If you, or the NHibernate’s auto-flush, are going to save or update an invalid instance you will receive an InvalidStateException (there is happening something else, but don’t worry).

DDL integration

The DDL integration is more DBA oriented than everything else… yes DBA oriented… even to make happy the DBA in yourself (I mean some old-school DBA).

In practice, having something like this:

public class Entity
{
public int Value { get; set; }
public string Description { get; set; }
}

public class EntityValidation : ValidationDef<Entity>
{
public EntityValidation()
{
Define(e => e.Value).IncludedBetween(10, 99);
Define(e => e.Description).NotNullableAndNotEmpty().And.MaxLength(50);
}
}

with a poor persistence mapping like this

<class name="Entity">
<
id type="int"/>
<
property name="Value"/>
<
property name="Description"/>
</
class>

if you will create the schema, using NHibernate’s SchemaExport, the script will be:

create table Entity (
id INT not null,
Value INT null check( Value>=10 and Value<=99) ,
Description NVARCHAR(50) not null,
primary key (id)
)

as you can see you have a perfect tuning, like in a concert, with the DataBase, even for the CHECK-CONSTRAINT of the property Value, and, if you want, you can even create some special Trigger (your old-school DBA will be euphoric with that).

What is wrong there ?

First of all, now you have transformed a very nice and flexible software validation in something written in the stone (now somebody should maintain the constraints, even in the DB, when you will need to change the range of allowed values).

Second, and perhaps even more catastrophic… in the past week I saw a NHibernate’s user euphoric because he found a way to integrate DataAnnotations, with NHibernate, through Fluent-NHibernate; his example was using the RequiredAttribute (NotNullable in NHV)… very cool!!! no ? well… now try to apply it in a graph mapped with table-per-class-hierarchy, where some subclass have a not-nullable property, and let me know which will be the result (only for this reason we should have a SoftNotNullableAttribute).

The matter is that, for the same reason you are not using stored-procedures to do everything, you shouldn’t integrate your nice software validation with the underling DDL of your RDBMS.


The Fashion

The fashion/elegant part, of the integration, is that you can start defining your domain model with POCOs then externally map the persistence, then externally map the validation integrated with persistence, and, as a kind of magic, your POCOs will checked before persist anything; all without any kind of invasion in your existing code.

but it’s only a kind of magic, I’m not so sure that it’s so beautiful.