Using Data in Silverlight 2 Applications - II

Introduction:

In this article, we will make use of the WCF service created in the previous part of this article and access data in the Silverlight application, DBDemo.

We begin with adding a service reference to MovieService. To do this, right click on the project, DBDemo and select Add Service Reference. Click Discover and then select MovieService.svc after it is shown in the Add Service Reference dialog box. Rename the service reference to MovieServiceReference. To generate a client class that can consume the service, use the SvcUtil tool as shown in Figure 5. This tool is typically found in the C:\Program Files\Microsoft SDKs\Windows version xx folder where xx may change based on your machine configuration. To use it in your current application directory, give the following:

path=%path%;C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin;

Then type the command similar to the one in Figure 1 in your application directory, that is, SvcUtil *.wsdl *.xsd /language:C#



Figure 1: Using SvcUtil

This will generate client code from the local metadata service document.

You will see MovieService.cs now in the MovieServiceReference directory as a result of the above command.

Now, the final step. Edit Page.xaml.cs as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DBDemo.MovieServiceReference;

namespace DBDemo
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var client = new MovieServiceClient();
            client.GetMoviesCompleted +=
            new EventHandler<GetMoviesCompletedEventArgs>(client_GetMoviesCompleted);
            client.GetMoviesAsync(this.txtLang.Text);
        }

        void client_GetMoviesCompleted(object sender, GetMoviesCompletedEventArgs e)
        {
            this.dgMovieData.ItemsSource = e.Result;
            this.dgMovieData.Visibility = Visibility.Visible;
        }
    }
}

The last two methods are the most important. One is an event handler for Button Click and one is the custom event handler method to assign the retrieved data to the data grid.

When you save, build and execute and specify language as English, you will get results similar to Figure 2.



Figure 2: Output

Now, that you know how to retrieve data using a WCF Service, you can tweak the code to make many changes and perform different kinds of data operations.

Conclusion: Thus, in the second part of this article series, you explored how to create a LINQtoSQL class, a WCF service and consume the service in Silverlight 2 to access data.


Similar Articles