Feb 17, 2009

WPF Validation

Up until recently the mechanisms that Windows Presentation Foundation provided to implement validation were quite unsatisfying.

Starting with .NET 3.0 there was a way to do simple field validation:

<Binding Path="SemanticId" UpdateSourceTrigger="PropertyChanged">

    <Binding.ValidationRules>

        <XyValidationRule/>

    </Binding.ValidationRules>

</Binding>



For most applications this is not enough, however. Usually several fields from an entity are bound to several elements on a form and they have to be validated as a whole to be consistent.

A new approach came with .NET 3.5 where an POCO entity could implement an interface to be used by :


public class Contact : IDataErrorInfo



What I don't like is messing up my entities with validation code. I would prefer a separated (aspect-oriented? and) configurable way.

Rather unnoticed yet another approach came with 3.5 SP1, where you can group several element bindings to one or more entities and define validation rules for this named group:

<Grid.BindingGroup>

    <BindingGroup Name="TrainValidationGroup">

        <BindingGroup.ValidationRules>

            <my:TrainValidationRule ValidationStep="CommittedValue"/>

        </BindingGroup.ValidationRules>

    </BindingGroup>

</Grid.BindingGroup>



It is used in each binding

<TextBox Text="{Binding Path=SemanticId, BindingGroupName=TrainValidationGroup, ValidatesOnDataErrors=true}"/>



Not to forget to explicitely calling

RootElement.BindingGroup.CommitEdit();



Check out the excellent posts I had as source:
MSDN blog
Vincent Sibal

Feb 2, 2009

WCF behaviors on callback channel

Adding behaviors to a WCF channel is widely used and easy.

For an IEndpointBehavior the following code can be used:

public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)

{

    // add endpoint behavior to service side

    endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);

}



A less documented way is to add the same behavior to the callback of a duplex channel:

public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)

{

    // add endpoint behavior to callback

    clientRuntime.CallbackDispatchRuntime.MessageInspectors.Add(this);

}



You just need to know ...