Sunday, January 9, 2011

Using WCF from Silverlight

This article illustrates a simple example of calling a WCF service from Silverlight application. The common approach will be add a new WCF service first and then creates new Silverlight application that uses the WCF service.

(1) WCF Service

For simplicity, the sample WCF service has one method (OperationContract in WCF). Simplest form of sample will be one method signature with all .NET native data types (string, int, ...) but I intentionally added a composite data type VIP to illustrate DataContract of WCF.
namespace myWcfService
{
   [ServiceContract]
   public interface IVIPService
   {
      [OperationContract]
      List<VIP> GetVIPList();
   }

   [DataContract]
   public class VIP
   {
      string name;
      string phoneNumber;
      [DataMember]
      public string Name
      {
          get { return this.name; }
          set { this.name = value; }
      }
      [DataMember]
      public string PhoneNumber
      {
          get { return this.phoneNumber; }
          set { this.phoneNumber = value; }
      }
   }
}
Actual class implementing the ServiceContract interfacde is as follows. The method simply returns the list of VIP data.
namespace myWcfService
{
    public class VIPService : IVIPService 
    {
           List<VIP> listVIP = new List<VIP>()  {
                        new VIP() { Name = "James", PhoneNumber = "425-323-1234" },
                        new VIP() { Name = "Simon", PhoneNumber = "206-123-1321" }
           };
           public List<VIP> GetVIPList()
           {
               return listVIP;
           }
    }
}
Once the implementation is done, WCF application is published to a Web server by using Build -> Publish menu in VS. I published the WCF application onto http://localhost/vipApp as Web Application. (That is, check [Mark as IIS application on destination])
























If publish is done, one can test the WCF component by simply navigating the web http://localhost/vipApp/VIPService.svc













(2) Silverlight Application

In order to call WCF service, one can use WCF proxy or manually making WCF call with its service contract interface. Since WCF proxy is a little simpler, let's use it in this post. WCF proxy can be added by selecting [Project] -> [Add Service Reference] and then typing .SVC URL as below. If everything is fine, one should see GetVIPList operations.




Once service reference is added, we can call any method in the WCF. GetVIPList will return a list collection, List<VIP>. To display those list data in DataGrid, I did drag & drop a DataGrid onto mainpage.xaml and set AutoGenerateColumns to true.

<Grid x:Name="LayoutRoot" Background="White">
<sdk:DataGrid AutoGenerateColumns="True" Height="245" HorizontalAlignment="Left"
Margin="12,26,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="376" />
</Grid>

So the UI container is ready, we now need to add data onto it. One of doing it is data binding and here is the code snippet.
using mySilverlightApp.ServiceReference1;
namespace mySilverlightApp
{
  public partial class MainPage : UserControl {
     public MainPage()
     {
         InitializeComponent();
         VIPServiceClient wcfClient = new VIPServiceClient();  // create WCF proxy
         wcfClient.GetVIPListCompleted += new EventHandler<GetVIPListCompletedEventArgs>(wcfClient_GetVIPListCompleted);
         wcfClient.GetVIPListAsync();
     }
     void wcfClient_GetVIPListCompleted(object sender, GetVIPListCompletedEventArgs e)
     {
         this.dataGrid1.ItemsSource = e.Result;   // data binding
     }
  }
}
What it does is create a WCF proxy instance from VIPServiceClient and call its GetVIPListAsync() method. Once Async call is complete, GetVIPListCompleted event handler is run where the resultset is bound to DataGrid by setting ItemsSource property.

Now publish Silverlight application (from SL test project) to the same Web Site http://localhost/vipApp and test the silverlight application by navigating test html in a web browser. Here is the output.