Software // Enterprise Applications
News
1/14/2010
02:55 PM
Connect Directly
RSS
E-Mail
50%
50%

What's New With Silverlight

Microsoft simplifies distributed data access.

Among the promises of frameworks such as Silverlight, Microsoft's plug-in for developing rich Internet applications, are lower development costs and shorter development cycles--not to mention much more engaging and interactive Web content. But Silverlight also provides a broad range of networking features that can be used to access distributed data. Standard SOAP services such as those created using Active Server Methods Extension (ASMX) and Windows Communication Foundation (WCF) technologies can return a specific contract, and REST services can return custom data structures. Silverlight also supports direct socket communication for applications that require data to be pushed to them in real time.

While these features work well, there's a price in terms of complexity because they rely on an asynchronous programming model and require code to be synchronized between Silverlight and server projects. Microsoft recognized the challenges of the asynchronous model and that sharing data validation rules between projects could be tricky. To simplify the process, it has developed WCF RIA Services, a data exchange and validation framework for Visual Studio 2008 and Visual Studio 2010.

Calling WCF RIA Services

Once WCF RIA Services is downloaded from www.silverlight.net/riaservices and installed, the domain service class can be called from a Silverlight application without having to go through the process of generating a client-side proxy object using Add Service Reference. After compiling the solution, the Silverlight project adds a Generated _Code folder that contains all of the code needed to call the domain service.

To call a WCF RIA Services operation, you can use a client-side domain context class that's named after the domain service class that lives on the server side. This client-side class is automatically generated and added to the Generated_Code folder. If the server-side class is named NorthwindDomainService, then by default the client-side domain context class is named NorthwindDomainContext. The domain context class can be used directly in the Silverlight code-beside file or integrated into a ViewModel class in cases where the Model-View-ViewModel pattern is being used.

Looking through the example code that uses the domain context class to retrieve data from a WCF RIA service, you see that the Customers collection property stores an EntitySet<T> type as opposed to ObservableCollection<T> (see box, below). EntitySet<T> is provided by WCF RIA Services and is used to track changes that are made to objects. You also see that as the CustomersViewModel object's constructor is called, an instance of the domain context class is created and used to hook the Customers entity to a local Customers property.

How To Retrieve Data From A WCF RIA Service
public class CustomersViewModel : ViewModelBase
{
  EntitySet _Customers;
  NorthwindDomainContext_Context = null;
  public CustomersViewModel()
  {
    _Context = new Northwind DomainContext();
    this.Customers = _Context.Customers;
    GetCustomers();
  }
  public EntitySetCustomers
    {
      get { return _Customers; }
      set 
      { 
        if (_Customers != value)
          {
            _Customers = value;
            OnPropertyChanged ("Customers");
          }
      }
    }
    private void GetCustomers()
      {
        _Context.Load (_Context.GetCustomersQuery());
      }
}

Once the entity is assigned to the property, a call is made to GetCustomers that invokes the domain context object's Load<T> method. The type of query to load is passed into the method. GetCustomersQuery is automatically generated by WCF RIA Services based upon a domain service query named GetCustomers. The query executes asynchronously behind the scenes and automatically assigns the returned value to the CustomersViewModel object's Customers property. The sample application available at informationweek.com/1254/mdev/wcf demonstrates other features such as the ability to access a customer's orders and edit the data using a DataForm control.

Validating Data

WCF RIA Services provide a simple way to leverage .NET 3.5 data annotations to validate data as it's 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:

internal sealed class OrderMetadata
{
  [Required]
  public string CustomerID;
  [Required]
  public int OrderID;
}

 
Code Sample:
Custom Validation Code
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.");
   }
  }
}
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.

In situations where custom validation is needed, the CustomValidation attribute can be added above appropriate metadata class fields. As data is assigned to the corresponding property, the metadata class can validate the data using a validation class. For instance, a DateValidator class can be used to perform custom date validation to make sure the year entered is less than or equal to the current year (see box, above). Here's an example of applying the DateValidator class to a metadata class field:

[CustomValidation(typeof(Date
Validator), "ValidateDate")]
public Nullable<DateTime>
ShippedDate;

Once the project is compiled, the data annotations, including the custom annotation, are included in the Silverlight project. Controls such as the DataForm can detect whether data is valid for a given property and show error messages as appropriate.

Dan Wahlin is a Microsoft most valuable professional for ASP.NET and XML Web Services and founder of The Wahlin Group (thewahlingroup.com).

Read more about Windows development at ddj.com/windows

Comment  | 
Print  | 
More Insights
Building A Mobile Business Mindset
Building A Mobile Business Mindset
Among 688 respondents, 46% have deployed mobile apps, with an additional 24% planning to in the next year. Soon all apps will look like mobile apps and it's past time for those with no plans to get cracking.
Register for InformationWeek Newsletters
White Papers
Current Issue
InformationWeek Tech Digest - July 22, 2014
Sophisticated attacks demand real-time risk management and continuous monitoring. Here's how federal agencies are meeting that challenge.
Flash Poll
Video
Slideshows
Twitter Feed
InformationWeek Radio
Live Streaming Video
Everything You've Been Told About Mobility Is Wrong
Attend this video symposium with Sean Wisdom, Global Director of Mobility Solutions, and learn about how you can harness powerful new products to mobilize your business potential.