Validating Data using WCF RIA Services
WCF RIA Services provides a simple way to leverage .NET 3.5 data annotations to validate data as it is assigned to properties in entities. Data annotations located in the System.ComponentModel.DataAnnotations namespace such as Required, RegularExpression, StringLength, and CustomValidation can be added into a metadata class and used to validate data. The metadata class is added to the Web project automatically if the Generate associated classes for metadata checkbox is checked when the domain service is initially created (see Figure 4).
Listing 5 shows a portion of an OrderMetadata class that is generated by WCF RIA Services. Some of the fields within the class are decorated with the Required and CustomValidation data annotation attributes:
internal sealed class OrderMetadata
{
[Required]
public string CustomerID;
[Required]
public int OrderID;
public string ShipAddress;
public string ShipCity;
public string ShipCountry;
public string ShipName;
[CustomValidation(typeof(StarterSample.Web.DateValidator),
"ValidateDate")]
public Nullable<DateTime> ShippedDate;
}
The CustomValidation attribute added above the ShippedDate field allows custom validation logic to be applied as data is assigned to the ShippedDate property in the Order entity. As data is set the DateValidator class's ValidateDate method is called which ensures that the year entered is less than or equal to the current year. If the year is correct a ValidationResult success value is returned whereas if the year is wrong a new ValidationResult object is returned containing a custom error message. The code for the DateValidator class is shown in Listing 6. The class is located in a file named NorthwindDomainService.shared.cs. Any files ending with "shared.cs" are automatically copied to the Silverlight project when the solution is built.
public static class DateValidator
{
public static ValidationResult ValidateDate(DateTime dt,
ValidationContext context)
{
if (dt.Year <= DateTime.Now.Year)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("The date must be less than " +
"or equal to the current year.");
}
}
}
Once the project is compiled the data annotations (including the custom annotation) will be included in the Silverlight project. Controls such as the DataForm can detect if the validation is valid or not for a given property and show error messages as appropriate as in Figure 6.
Conclusion
WCF RIA Services provides a framework for exchanging data between Silverlight applications and services. In this article you've been introduced to some of the fundamentals of WCF RIA Services including creating a domain service class, using a domain context class to call remote service operations and validating property data. WCF RIA Services supports additional objects and features that weren't covered such as using the DomainDataSource control and performing authentication.


