Introduction
Recently Windows Communication Foundation (WCF) has generated a lot of interest in the .net world. This tutorial will show you how to create and consume a WCF service in a Silverlight application.
Though Silverlight is used to develop rich internet applications (RIA) which are mostly executed on the client side, it is also ofte required to make server calls in order to query for data which is stored in a database, for example. To serve this purpose, WCF is one of the best approaches.
In this article I have provided sample code for both the WCF service and the Silverlight application. Visual Studio 2010 and Silverlight 4.0 version were used for creating the sample demo application.
The Sample Silverlight Application
I will create a sample application and explain things step-by-step. For our demonstration we will create a Silverlight client application, Silverlight host web application and a WCF service.
The basic idea is to have a DataGrid on the Silverlight client and have the WCF service return a list of Customers which will then be bound onto the DataGrid. This Silverlight call to the WCF service will be an asynchronous call.
As a first step, create a blank page and name it SilverlightAndWcfSolution.
Creating a Silverlight Client
Add a new Silverlight application and name it SilverlightClient. VisualStudio will prompt you to add a host web application. Click on Ok and add it. It should be named SilverlightClient.Web. Open MainPage.xaml and add a Silverlight datagrid to it. The XAML code is shown below:
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″
mc:Ignorable=”d”
d:DesignHeight=”300″ d_DesignWidth=”400″ xmlns_sdk=”http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk”
Below are the controls that should be added:
- Button – To initiate the service call
- DataGrid – To bind the data returned as a result of the WCF service call
- TextBox – To display the status as the call is asynchronous
Creating a WCF Service
In order for your Silverlight client to use a WCF service you could have it created in the host web application or even as a separate WCF project. The easiest approach, however, would be to create the Service in the host web application. Here’s how you would do that.
Right click on the web application and select Add New Item. Under the Silverlight section you will find the template named SilverlightEnabledWCFService. Name it CustomerService.svc and add it. The reason for choosing this template is that it will add all the required WCF settings to the web.config file automatically and it will add the default bindings. Note that many kinds of WCF bindings are not supported by Silverlight client. Below are a couple of bindings that are supported:
- BasicHttpBinding
- PollingDuplexHttpBinding
The WCF contracts for the implementation service are added by the framework automatically during run time.
Create a method called GetCustomers in the file CustomerService.svc.cs. Below is the implementation.
namespace SilverlightClient.Web
{
[ServiceContract(Namespace = “”)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CustomerService
{
[OperationContract]
public IEnumerable GetCustomers()
{
List customerCollection = new List();
customerCollection.Add(new Customer()
{
CustomerId = 1,
FirstName = “John”,
LastName = “Luke”,
Email = “JohnL@domain.com”
});
customerCollection.Add(new Customer()
{
CustomerId = 2,
FirstName = “David”,
LastName = “Bollinger”,
Email = “DavidD@domain.com”
});
customerCollection.Add(new Customer()
{
CustomerId = 3,
FirstName = “Alan”,
LastName = “Whittal”,
Email = “AlanW@domain.com”
});
customerCollection.Add(new Customer()
{
CustomerId = 4,
FirstName = “Kenn”,
LastName = “Gebbert”,
Email = “KennG@domain.com”
});
return customerCollection.AsEnumerable();
}
}
}
The WCF methods should be decorated with the attribute OperationContract.
Calling WCF Service in the Silverlight client
This section will explain how to consume the WCF service that we have created. Now go ahead and add the Service Reference of the CustomerService and name it CustomerServiceReference. As soon as the reference is added, the config file named ServiceReferences.ClientConfig gets created and has the endpoint information.
Below is the code for calling the WCF service from the SilverlightClient.
namespace SilverlightClient
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void LoadButton_Click(object sender, RoutedEventArgs e)
{
CustomerServiceClient cusomerServiceClient = new CustomerServiceClient(“CustomBinding_CustomerService”);
cusomerServiceClient.GetCustomersCompleted += new EventHandler(cusomerServiceClient_GetCustomersCompleted);
cusomerServiceClient.GetCustomersAsync();
StatusTextBox.Text = “Loading customers…”;
}
void cusomerServiceClient_GetCustomersCompleted(object sender, GetCustomersCompletedEventArgs e)
{
if (e.Error == null)
{
CustomerDataGrid.ItemsSource = e.Result.AsEnumerable();
StatusTextBox.Text = “Load completed.”;
}
else
{
MessageBox.Show(string.Format(“Error occured in calling Customer Service: {0}”, e.Error.Message));
}
}
}
}
Now run the application. Click the Load Customers button and you should see the customer data on the screen.
Fig 1.0 below shows the output screenshot.
Fig 1.0
Conclusion
I hope this article clearly explained the practice of consuming a WCF service in a Silverlight application and that the sample code provided was able to help you understand the concepts involved. Please use the comments section below to provide your thoughts.
Happy Reading!