Data validations in Silverlight RIA applications
After a lot of reading, I have finally sort of figured out how to do data validations in Silverlight applications that use WCF RIA services.
Data validations should be performed both on the Silverlight application (that runs on the browser) as well as WCF RIA Service layer that runs on the web server. As of now, RIA applications support DataAnnotations as the main way of validating data. When a RIA service is created (say. CategoryService), a CategoryService.metadata.cs is also created. Within this file, a partial Entity class (Category) is defined. This is the place where you put all your data annotations.
When a Silverlight app is built, the Silverlight side entity classes are generated. This includes the data annotations defined in the server. Also, the class is derived from Entity abstract class which implements INotifyDataErrorInfo interface.
CustomValidation attributes are used whenever a validation requires access to the database. Here is a golden blogpost which describes exactly how it works: http://jeffhandley.com/archive/2010/05/26/asyncvalidation-again.aspx
CustomValidation when triggered from the Silverlight side is asynchronous. If you look at the above post, the service returns a Sucess. And then, if it finds any error, it asynchronously updates the ValidationErrors for the Entity. If the user does a Submit or Save before the async operation completes, the same validation should be performed at the server using the same CustomValidation attribute. Again, the above post is just amazingly cool as it explains how to do it.
There are other things you have to handle. The SubmitChanges of the DomainContext is asynchronous. So, any failures or success should be handled asynchronously in the callback method.
Validations using Data Annotations (in Silverlight or service) raise exceptions. In the Silverlight side, the framework knows how to invalidate the control state. When validations fail in the server, you will have to add the error to the ValidationErrors collection of the Entity class. This will invalidate the control.
While using data annotations, you will have to somehow let the ViewModel or the Entity know that there are errors. This is not automatically done.
Final tip: Do not try to roll your own custom framework using IDataErrorInfo or INotifyDataErrorInfo. It costs a lot of money. And you will have to do it at the service layer also.
Category : Silverlight