Try fast search NHibernate

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).