Channels ▼
RSS

Web Development

What's New With Silverlight


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;
} 

Listing 5: A metadata class generated by WCF RIA Services.

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.");
        }
    }
}

Listing 6

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.

Figure 6: The Silverlight interface gets its data from WCF RIA Services.

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.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 
Dr. Dobb's TV