Tuesday 12 March 2013

Validating a POCO DataContract using .NET's DataAnnotations Validator

In order to make sure that the TeamMentor server only creates users with valid data, here is how I implemented data validation into the NewUser class using .NET's DataContract annotations.

The first step was to add the annotations to the NewUser object, which originally looked like this:

image

And like this after adding the the DataContract, DataMember, Required, StringLength and RegularExpression attributes:

image

At it stands, this doesn't do anything , since the ‘DataContract’ is not enforced by anybody (they are 'just' attributes on a class)

At the moment, all the UnitTests are passing (see below why this is relevant):

image

Before we add the validation to the main codebase, lets create a number of tests to make sure the validation behaving as it expected.

UnitTest: Validation_NewUser_RequiredFields:

image

UnitTest: Validation_NewUser_LargeDataInFields:

image

UnitTest: Validation_Email_Format:

image

Now that we have the UnitTests confirming that the validation is working as expected, let’s run all tests again and double-check that all is good (note that there are 4 more tests):

image

Adding the check to the main Codebase

Next step is to add the validation requirement to the method called by the exposed WebService Methods (this will enforce the DataControl rules into every new user request made to TeamMentor):

image

And, as I was expecting , this will break a number of tests (that passed when there was no validation in place)

image

Namely the tests that create test users (and check the new user account creation workflow):

image

Most of the errors where caused by the use of this helper method:

image

Which needs to be updated to:

image

With this change, the tests in this class will pass again (note that all failed before the change shown above):

image

After a couple more changes we have all the Unit Tests back in action.

image

Time to push into GitHub,

image

So that TeamCity can re-execute the tests and publish the new version to the test server :)

image



NOTE: ExtensionMethods

Here are the extension methods I created that help to hide the complexity of the DataAnnotations class

ExtensionMethod Signatures:

image

ExtensionMethod’s code:

image