Building Business Applications With Silverlight 4 and WCF RIA Services

Friday May 7th 2010 by Jani Jarvinen

Microsoft Silverlight has progressed with big steps since the initial version only a few years ago. Today, Silverlight 4 is suitable for building even business applications. Read on to learn how you can use Silverlight 4 and Windows Communication Foundation (WCF) RIA Services to build compelling applications.


Web applications have been a great enabler for business needs, because for one thing, the users are not anymore tied to physical location. However, building web applications has often required more work compared to traditional desktop applications. Especially if you wanted to have good-looking graphics and slick user interfaces with complex controls, then you often had to plan for a slower development cycle.

Microsoft developed original Silverlight originally to be a "Flash killer", but this only applied to the initial version of the technology. Today, Silverlight 4 is here, and it is capable of delivering way more than just fancy animated banners. Instead, Silverlight allows you to write line-of-business applications (LOB) with complex interactivity and visually stunning user interfaces. All this is possible through the web browser, and programming is still done with the familiar .NET technologies and Microsoft Visual Studio. Silverlight training material often focuses on graphics, animation and visual design. While all these can be important in business applications, all business applications require some form of data access and user interface conventions that are present in all those applications. To get developers up to speed quickly, Microsoft has lately focused more on business developer's needs.

Silverlight applications are often only the client-side part of a complete solution, and thus, a backend or server-side application is also required to supply data to the client. To help building the server-side part of the solution, Microsoft has developed a technology called WCF RIA Services, the non-abbreviated name being over-long "Windows Communication Foundation Rich Internet Application Servives". Talking about just RIA Services is much easier.

In this article, you are going to learn the basics of both Silverlight 4 and WCF RIA Services, and also see how you can use them to build business applications for the web. The tools you need are the latest ones, which is no surprise. Microsoft Visual Studio 2010 is a requirement, on top of which you need to install both the Silverlight 4 runtime and the SDK kit, and also the WCF RIA Services with tooling support. All the necessary download links are provided in the Resources section at the end of this article. At this writing, the latest versions are the RC ones.

What's New in Silverlight 4?

Many of the new features in Silverlight 4 are geared towards business applications. New features such as printing support, better localization especially for Asian languages and the RichTextBox control are three of such examples. For instance, the RichTextBox control supports advanced text formatting, but also can display pictures inlined with text, and include embedded controls such as a DataGrid to display tabular data along with document text.

Speaking of the DataGrid control, this useful workhorse has been enhanced in Silverlight 4. For instance, columns can now be auto-sized, meaning that their width can be based on the content. Additionally, whole rows of data can now be copied to the clipboard, allowing easy access in other programs, such as Excel. Interfaces such as IDataErrorInfo and INotifyDataErrorInfo allow improved support for data validation.

In addition to working inside the browser window, Silverlight 4 applications can also work outside the browser, much like more traditional stand-alone applications. This feature is called Out-of-Browser, and you can easily check if your application is running in this fashion by checking the AppCurrent.IsRunningOutOfBrowser property. The Out-of-browser feature can give your Silverlight application additional rights on the target system, in which case it is called a trusted application.

For instance, a trusted out-of-browser Silverlight 4 application can have access to the computer's file system, but of course in a limited fashion. Access is mostly restricted to folders under the user's own profile. Accessing files can be useful for many business applications, but Silverlight 4 contains also one feature that is highly regarded to many line-of-business solutions: native integration.

Native integration gives your Silverlight 4 out-of-browser application access to the COM interoperability features in Windows. For instance, you might use this feature to control Microsoft Office applications such as Word or Excel. But native integration isn't limited to these two products only; instead, you could even control an embedded device from a Silverlight application provided that a suitable COM interface is available.

What is WCF RIA Services?

Building multi-tier web applications with a Silverlight client has previously been, if not particularly difficult, at least time-consuming. Also, most business applications have had the need to connect to a data source, and writing the server back-end to support this is often similar repetitive work, no matter which application your are writing the backend for.

With this in mind, WCF RIA Services tries to address this common need and makes building n-tier applications easier. RIA Services allows you to expose an object model through a server application, and then allows your Silverlight client application to access that object model through the Internet. The object model can be exposed in variety of formats, including an efficient binary format, or in Atom based OData format, or even in JSON (JavaScript Object Notation) encoded format. OData is an open specification by Microsoft written to support transfer of relational database data. Microsoft has published the specifications under the company's Open Specification Promise (OSP); previously the project was known as codename "Astoria".

In addition to being a set of class libraries, RIA Services also provides tools inside Microsoft Visual Studio to help in building the application that contains both server-side code and the Silverlight client. The Visual Studio tools include parts that build classes, reflect changes from one project to another, and also automatically generate code.

In addition to just supporting basic data retrieval from the server-side WCF application, RIA Services also supports many more advanced features, such as using LINQ for data retrieval and DomainDataSource components on the client-side to support nice drag-and-drop client application development in Visual Studio 2010. Security support is also built in to RIA Services, which means you can restrict access to certain features with a conventional username and password, or even Windows authentication.

Related to security features, you can also build validation features into your RIA Services applications. By default, RIA Services copies validation rules from the server to the client. This allows rich validation on the client, but does not let invalid data to be stored in the database, as the rules are validated on the server as well. In this respect validation in RIA applications is similar to that in traditional ASP.NET web forms applications with client-side validation enabled.

Building Your First RIA Services Application

To get hands-on experience with Silverlight 4 and RIA Services, it is best to start developing a sample application. Before you can start however, you need to make sure you have all the pre-requirements installed. This includes Visual Studio 2010 Release Candidate (RC), Silverlight 4 SDK, and the WCF RIA Services package and the Visual Studio tools. Be sure to download the correct versions for your Visual Studio version: for the RC one, download the RC releases of Silverlight 4 and RIA Services from March (Figure 1).

[Figure 1 - Installation.png]
Figure 1. The Silverlight 4 package is required before you can work with RIA Services.

Assuming you have all these before-mentioned packages installed on your computer, you can start Visual Studio 2010, and go to the New Project dialog box. Under the Silverlight group, you should find a template named "Silverlight Business Application" (Figure 2). If not, then make sure you've installed everything correctly.

[Figure 2 - New Project.png]
Figure 2. Starting a new Silverlight business application project.

Once you have started a new project using the business application template, you should see a familiar twin-project solution in Visual Studio's Solution Explorer. The first project is the Silverlight client application, and the other the web project that hosts the Silverlight application, and provides data services to it, as you will soon see.

The next step is to add a database connection to the web host project. For example, if your Silverlight project is called RiaServicesDemo, then the web host project will be named RiaServicesDemo.Web (Figure 3). It is important to make sure you add the database connection to this web project.

[Figure 3 - Project Structure.png]
Figure 3. Two projects form a business application solution.

To add the connection, in Solution Explorer, right-click the project node of the web project, and choose Add/New Item from the popup menu. Add a new Entity Data Model to the project, and connect it to the database of your choice. For instance, you could use the Northwind sample database for your initial testing purposes, as is done in this article.

Note that if your database contains many foreign key references between tables, the RC version of RIA Services might not cope well with your data source. Thus, it is a good practice to first create entity data models with only a few tables, and test that everything works as expected.

Once you have added your entity data model to the web project, be sure to save all files and then build the project. Then it is time to start working with RIA Services in particular. Make sure you are still within the web project, and then return to the Add New Item dialog box by choosing the Add/New Item menu command from the Solution Explorer's popup menu. The Add New Item dialog box again appears.

In the dialog box, navigate to the Web template group on the left. From there, you should find a Domain Service Class icon. Select the icon, and enter a descriptive name for the so-called domain service. Do not enter just "DomainService.cs", instead give a more descriptive name, such as NorthwindDomainService.cs (Figure 4).

[Figure 4 - New Domain Service.png]
Figure 4. Adding a new domain service class to the web project.

Once you have clicked OK, a new dialog box will be displayed (Figure 5). This dialog box is implemented by the RIA Services tools that extend Visual Studio's functionality. In this dialog box, you can select all the entity data tables you wish to expose through the RIA Services web application. In the case of the sample application, all three tables were selected, and all tables also have editing functionality enabled. Also, the OData endpoint is exposed, and metadata is created. Shortly put, all available options have been checked.

[Figure 5 - Select Tables.png]
Figure 5. Selecting which tables to expose to client applications.

Note that sometimes, the Add New Domain Service Class dialog box might not display any tables even if you select the correct data source. This appears to be a bug in the RC edition, and there's an easy remedy: simply click Cancel, restart Visual Studio, and try adding the domain service class again.

Once you are through the Add New Domain Service Class dialog box, you are essentially done with the web project, i.e. the server part of the solution. Make sure to (re)build your solution again, and then start to work with the client application, i.e. the Silverlight project. If any errors occur during the build, you must fix them before proceeding.

A common error seems to be implying that an "entity type NNN is exposed by multiple DomainService types". If this occurs, you need to expose fewer tables through your entity model, or alternatively create multiple domain services. It is perfectly possible to expose multiple domain services in a single server project.

Accessing Data on the Silverlight Client

Developing client side code is very straightforward once you have successfully created the server application. Since you are working with database data and want to display it on your Silverlight client, it is best to open for example the Home.xaml file from the Views folder inside the project. Note that the business application template for Silverlight contains a layout based on navigation pages, and a "frame" can be found around them displaying the application title. This is much like in ASP.NET 4.0 Web Forms and MVC applications.

With the Home.xaml file open in the designer, go to the Data Sources window by choosing the Data/Show Data Sources command from Visual Studio's main menu. Because you are working with the business application template, after each build of the solution, the Data Sources window is automatically updated to reflect the available data sources in the web project. Thus, your window should look similar to the one in Figure 6.

[Figure 6 - Data Sources.png]
Figure 6. Automatically created domain data sources in the Silverlight client.

A new feature in Visual Studio 2010 allows easy drag-and-drop of data sources onto WPF and Silverlight windows. Thus, the easiest way to display a grid of database table data on a window is to simply drag and drop a table from the Data Sources window to your Silverlight application. For instance in the sample application, the Customers table under the NorthwindDomainContext is dragged and then dropped to the Home.xaml navigation pane (you could also try dragging and dropping individual table fields to see what you get). The end result is a grid showing the database data, with built-in features such as sorting. Figure 7 shows how the application would look at this point.

[Figure 7 - Sample App Step 1.png]
Figure 7. The sample application with just a grid in place.

Technically, a Silverlight data grid accessing data from a remove server without a line of code is very nice in itself, but as far as the application goes, a single grid cannot do miracles. Thus, you might want to try your skills with some additional functionality. For instance, you might want to see how you can use LINQ queries against a domain source, i.e. the service-side data source trough the wire protocol. You could add for example a button to show only customers from a specific country. On the button click event handler, you could execute the following code:

NorthwindDomainContext context =
  new NorthwindDomainContext();
EntityQuery<Customers> query =
  from cust in context.GetCustomersQuery()
  where cust.Country == "USA"
  select cust;
LoadOperation<Customers> loadOp = context.Load(query);
customersDataGrid.ItemsSource = loadOp.Entities;

In this code listing, you are first creating an instance of the NorthwindDomainContext object. You might wonder where this class is defined, and this is a valid question. The answer lies in the special build tasks part of the Silverlight business application template. Whenever a domain service class is added to the web project and the solution is built, a domain context class is automatically created in the Silverlight client project.

You can find the code file from the hidden Generated_Code folder inside the client project. For instance, in the case of the sample application, the generated code file is named RiaServicesDemo.Web.g.cs, and this file contains the definition for the entity objects and the domain context class used in the code listing.

Note that the file also contains a reference to the service endpoint URL. You can find the pointer if you look for the string ".svc" in around the middle of the generated code file. For instance in the sample application, the URL would end in "RiaServicesDemo-Web-NorthwindDomainService.svc". You can try to access this URL through your browser while the service application is running, and see what happens.

Updating Data and Accessing Word

Previously, you saw how you can use LINQ to query for details from the domain context object, part of the Silverlight client project. The domain context can be used in much the same way as a regular ADO.NET entity model context. This also applies to data updates and submitting changes, as you will see next.

For instance, if you wanted to programmatically update a field in the selected customer row on the grid, you could use the following code in a button click event handler:

private void changePhoneButton_Click(
  object sender, System.Windows.RoutedEventArgs e)
  DomainContext context =
  Customers selectedCustomer =
  selectedCustomer.Phone = "+1 (492) 832 441";
  context.SubmitChanges(DatasetUpdated, selectedCustomer);

Here, the aim is to read the selected customer object, set the phone number to a new one, and then submit the changes back to the database. When you dragged and dropped the table from the Visual Studio Data Sources window to your Silverlight window, Visual Studio automatically created a customersDomainDataSource object for you. Through this object, you can retrieve the original domain context object that was used to read the data into the grid.

You must use this context object to submit the changes, as an entity object cannot be attached to multiple domain contexts. Thus, you cannot simply create a new instance of the domain context and try to update changes through that instance, as there would be no changes to submit.

After setting the new phone number, it is time to commit the changes back to the database. In this case, you would call the SubmitChanges method, passing a System.Action<T> delegate that will be called once the submit operation has finished. This is necessary as the submit operation works in an asynchronous manner. The selected customer entity object (this can be retrieved directly from the data grid's SelectedItem property after a typecast) is passed to the DatasetUpdated method as a user state object. This is how the DatasetUpdated method looks:

private void DatasetUpdated(SubmitOperation callback)
  Customers customer = (Customers)callback.UserState;
  MessageBox.Show("Changed the phone number of " +
    customer.CompanyName + ".");

Updating database data from the Silverlight application is easy. If you already know how to use Entity Framework, then you are on fast-track to master the RIA Services way of manipulating database data in your Silverlight applications.

The third and final operation implemented in the sample application shows you how you can use Silverlight 4's native integration to control COM automation server, such as Microsoft Word. For instance, you might wish to export data from your Silverlight application to Word, for instance for reporting or convenience purposes.

Following the lines of the previous data updating example, you will next see how you can export the selected customer's details to Word. The code shown next has been tested with Microsoft Office Word 2007, but might work also with Word 2003 and Word 2010. A button named exportToWordButton was added to the Silverlight client, and when the button is clicked, the following code is executed:

private void exportToWordButton_Click(object sender, RoutedEventArgs e)
  if (AutomationFactory.IsAvailable)
    Customers selectedCustomer =

    string details = string.Format("Customer Name: {0}\r\n" +
        "City: {1}\r\nCountry: {2}\r\n",
        selectedCustomer.CompanyName, selectedCustomer.City,

    dynamic word = AutomationFactory.CreateObject(
    word.Selection.Text = details;
    word.Visible = true;
    MessageBox.Show("Word automation interface is " +
      "not available. Make sure you are running " +
      "your Silverlight application in the " +
      "Out-of-Browser mode.");

As you will recall from the introduction, Silverlight 4 contains a new feature called native integration that allows you to control any COM or OLE automation server, security settings permitting. This is naturally a Windows-only feature, and also requires the Out-of-Browser mode to be used. Thus, the code first checks the AutomationFactory.IsAvailable property to see if the correct security settings are in place, and that the operating system is Windows. This property internally checks if the Silverlight application is already running out-of-browser, so you do not need to check this separately.

Note that you must specifically enable your Silverlight application to be used in out-of-browser mode. This can be done from the Silverlight project's options in Visual Studio. First, make sure the "Enable running application out of the browser" option is checked (it should by default). Then, click the Out-of-Browser Setting button to open the dialog box shown in Figure 8.

[Figure 8 - OOB Options.png]
Figure 8. Silverlight project options contain Out-of-Browser settings.

In this dialog box, you can customize the options that the user can make when running your application out-of-browser. The most important option to select is the bottom-most one: you need to check the option "Require elevated trust when running outside the browser" for native integration to be available. You can also select the two other options, GPU acceleration and enable install menus if you like.

When you now run your Silverlight application, it will still appear inside the browser. But if you right-click your application, you can see a popup menu with an Install command. Select this command, and soon enough, your application should appear outside the browser window, and also a desktop shortcut should be created for your application is you enabled that option (Figure 9).

[Figure 9 - Standalone Application.png]
Figure 9. The sample application running outside the browser.

Note that if you wish to remove the locally installed application, simply return to the web application, right-click, and choose Remove. Also make sure you are installing the Silverlight application locally only when you have launched your browser outside Visual Studio, or the installation might silently fail.

Once you are running your application successfully outside the browser, it is time to select a customer from the grid and click the Export To Word button. If all goes well, you should see Word on your screen with the selected customer's details shown (Figure 10).

[Figure 10 - Export To Word.png]
Figure 10. The sample application has exported data to Word

Cool, isn't it?


One of the biggest development areas in Silverlight 4 is the support for traditional business applications. Along with the equally new WCF RIA Services technology, building line-of-business (LOB) applications with Silverlight 4 is a breeze. In this article, you saw a walkthrough of using Silverlight 4 and RIA Services RC in Visual Studio 2010 to build business applications that can display SQL Server database data with ease.

Along the way, you learned what domain services and domain contexts are, how they are created, and how you can use them to retrieve and update data in your client applications. Finally, you also saw how you can use Silverlight 4's native integration features to control business ubiquities such as Word.

As you can see, Silverlight starts to be a very compelling platform for many types of applications, not just those requiring fancy graphics and animation. The possibilities are many nowadays, and once the final RTM versions are available (very soon!), then also the small bugs mentioned are hopefully ironed out. After this, there's no reason to exclude Silverlight from your choices of business application platforms.

Happy development with the latest tools!
Jani Jarvinen


Silverlight 4 start page
Silverlight 4 Tools download link, includes the SDK
WCF RIA Services download link
WCF RIA Services Toolkit for Visual Studio download page
Open Data home page

Related Articles

Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved