WCF RIA Services
By Microsoft Silverlight Team | September 1, 2010 | Level 300 : Intermediate
Summary
WCF RIA Services simplifies the development of n-tier solutions for Silverlight applications by enabling you to coordinate application logic between the server project and the client project. RIA Services provides framework components, tools, and services that make the application logic on the server available to the client without requiring you to manually duplicate that programming logic. This QuickStart shows you how to use RIA Services to display data from a database, restrict data modifications to authenticated users, and update data.
This QuickStart contains the following sections:
This QuickStart uses the AdventureWorksLT sample database. To download the code and database for this QuickStart, see WCF RIA Services sample and AdventureWorksLT sample database.
Creating a RIA Services-Enabled Application
To use RIA Services in a Silverlight client, you must create a RIA Services link between the Silverlight project and the server project. You can either manually select the Enable WCF RIA Services check box when creating a Silverlight application, or you can create a project using the Silverlight Business Application template, which automatically includes a RIA Services link. This QuickStart uses the Silverlight Business Application template. The following image shows how to create a RIA Services-enabled application using the Silverlight Business Application template.
Creating the Data Model and Domain Service
You can represent your data using any type of data access layer, such as Entity Data Model, LINQ-to-SQL object model, CLR object, or a Web service. To use the Entity Data Model, you add a new item to the server project, and select the ADO.NET Entity Data Model item.
In the Entity Data Model wizard, you select the entities to include in the data model. In the following image, the Customer table from AdventureWorksLT is included.
Next, you add a domain service to expose a set of related operations in the data access layer in the form of a service layer. A domain service is a WCF service that encapsulates the business logic of an application.
After adding the data model, you must build the project. Building the project ensures that the entity classes are created and will be available when you create the domain service. In the server project, you add a new item and select Domain Service Class. The following image shows how to create a domain service named SalesDomainService.
When you add a domain service, the Add New Domain Service Class dialog box appears. In the Add New Domain Service Class dialog box, you select which entities to expose through the domain service, and which operations are permitted. The following image shows how to select the Customer entity and enable editing.
After adding the domain service, you must build the solution. When you build the solution, code is generated in the Silverlight application that you will use to call the domain service. The generated code is located in a hidden folder in the client project. You can view the hidden folder by selecting Show All Files in the client project. The generated code is in a folder named Generated_Code.
In the Generated_Code folder is a file with the extension .g.cs or .g.vb. This file contains the generated code you will call in the client project. The generated code contains a DomainContext class that represents the domain service, and methods that represent the domain operations. You can view this code, but should not modify it because your changes will be lost the next time the solution is built.
Displaying the Data
One way to display data is to use the following controls:
- DataGrid - to display the data in a table
- DataPager - to break the data into smaller pages
- DomainDataSource - to simplify the interaction between the user interface and the data
The DomainDataSource control enables you to specify several values for retrieving the data. For example, you can specify the name of the method to use for the query, the number of records to retrieve in each request, and how to sort, filter, or group the values. The following markup shows how to use these controls in the Silverlight project in the Views\Home.xaml file. These controls use the GetCustomers method in the domain service, retrieve 20 records with each request, and sort by CustomerID.
<riaControls:DomainDataSource Name="domainDataSource1" LoadSize="20" QueryName="GetCustomers" AutoLoad="True"> <riaControls:DomainDataSource.DomainContext> <ds:SalesDomainContext /> </riaControls:DomainDataSource.DomainContext> <riaControls:DomainDataSource.SortDescriptors> <riaControls:SortDescriptor PropertyPath="CustomerID" /> </riaControls:DomainDataSource.SortDescriptors> </riaControls:DomainDataSource> <sdk:DataGrid ItemsSource="{Binding Data, ElementName=domainDataSource1}" IsReadOnly="True" Name="CustomerDataGrid" /> <sdk:DataPager Source="{Binding Data, ElementName=domainDataSource1}" HorizontalAlignment="Left" Height="26" Name="dataPager1" PageSize="10" Width="200" />
For the previous markup to work, you must have references to the System.Windows.Controls.Data and System.Windows.Controls.DomainServices assemblies. You must also have the following namespace declarations in the Page element. For Visual Basic, the ds namespace prefix maps to RIAExampleApp instead of RIAExampleApp.Web.
XAML for C#
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" xmlns:riaControls= "clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.DomainServices" xmlns:ds="clr-namespace:RIAExampleApp.Web"
XAML for Visual Basic
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" xmlns:riaControls= "clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.DomainServices" xmlns:ds="clr-namespace:RIAExampleApp"
When you run the application, the results are displayed in the DataGrid.
Customizing Data Access
When you expose an entity through a domain service and select the Enable editing check box, the RIA Services framework automatically creates query, insert, update, and delete methods. These methods are a starting point, but it is very important that you customize these methods to meet your security requirements. You should remove any domain operations that are not required because other application developers could access the domain operation in a way that you had not intended. You can restrict access to a domain operation by applying either the RequiresAuthentication or RequiresRole attribute to the method.
The following code shows the InsertCustomer and DeleteCustomer methods removed from the domain service (SalesDomainService.cs or SalesDomainService.vb) that was created in the server project. The code also shows the RequiresAuthentication attribute applied to the UpdateCustomer method.
When you create a domain service, a metadata class is automatically created in the server project for any entities that are exposed by the domain service. The metadata class is named with the .metadata.cs (or .metadata.vb) extension. For example, a domain service named SalesDomainService has a corresponding file named SalesDomainService.metadata.cs and in that file are metadata classes for each entity that is exposed.
In the metadata class, you apply attributes that specify behavior and validation requirements for the entity. For example, you apply the Exclude attribute to properties that you do not want to expose in the application, and you apply the Required attribute to properties that users must provide a value for. When you build the solution, the Required attribute is automatically applied to properties of the entity that is generated in the client project. Therefore, the same validation rule is applied to both the client and server projects. The following code shows the metadata class (SalesDomainService.metadata.cs or SalesDomainService.metadata.vb) with the Exclude attribute applied to the ModifiedDate, NameStyle, PasswordHash, PasswordSalt, and rowguid properties, and the Required attribute applied to the Phone property.
Enabling Authenticated Users to Update Data
RIA Services supports authentication. For example, you can specify that only authenticated users can update the data. You can use the IsAuthenticated property to determine whether the current user is authenticated. You can use the LoggedIn and LoggedOut events to initialize values and updated the user interface when the user's authentication status changes. The following code shows how IsAuthenticated, LoggedIn, and LoggedOut can be used in Home.xaml.cs (or Home.xaml.vb). The C# code requires a using statement that specifies the System.ServiceModel.DomainServices.Client.ApplicationServices namespace.
To submit changes made in the DataGrid, you need to add buttons and event handlers that will assist with processing changes. The following shows the XAML to add save and reject changes buttons in Home.xaml.
<StackPanel HorizontalAlignment="Left" Orientation="Horizontal"> <Button Content="Save Changes" Click="SaveButton_Click" IsEnabled="False" Margin="5" x:Name="SaveButton"></Button> <Button Content="Reject Changes" Click="RejectButton_Click" IsEnabled="False" Margin="5" x:Name="RejectButton"></Button> </StackPanel>
In the XAML element for the DataGrid control, you must add the name of the event handler for the RowEditEnded event.
In the XAML element for the DomainDataSource control, you must add the name of the event handler for the SubmittedChanges event.
To submit or reject changes, you use the SubmitChanges and RejectChanges methods on the domain data source. You can use the HasChanges property to determine whether there are any pending changes. The following shows the event handlers in Home.xaml.cs (or Home.xaml.vb) to process changes. The C# code requires a using statement that specifies the System.Windows namespace.
When you run the application, you cannot edit the data until you log in. The Silverlight Business Application template automatically includes a window for logging in and registering users. To log in, you click the login link in the upper right corner.
To create new accounts for authentication, you must have SQL Server Express installed.

To create a new user, you click the Register now link and specify values for the new user.

After you log in, the data in the DataGrid is now editable. The Phone property includes a Required attribute. If you try to delete the existing Phone value, a required message is displayed. The validation rule is applied on the client and does not require a post back to the server.

Validation is automatically enforced for other fields based on the database definition. For example, the FirstName field does not allow null. The field is automatically required if you try to delete the value.

When you click Save Changes, the changes are saved in the database. When you click Reject Changes, the original values are restored.

For more information about WCF RIA Services, see WCF RIA Services on MSDN.
See Also
- Walkthrough: Creating a RIA Services Solution
- Walkthrough: Using the Silverlight Business Application Template

By Microsoft Silverlight Team, Silverlight is a powerful development platform for creating engaging, interactive user experiences for Web, desktop, and mobile applications when online or offline.