[This topic is pre-release documentation and is subject to change in future releases of Microsoft Silverlight.]

Building a WCF Web Service and Accessing It by Using a Proxy

Introduction

This topic describes how to create a Windows Communication Foundation (WCF) service that a Silverlight client can access and how to create the Silverlight client that can access that service. Such a service is restricted to using certain protocols to exchange messages and not using certain others. SOAP 1.1 must be used and the Web Service (WS-*) protocols such as WS-Addressing cannot be used. These requirements are satisfied if the WCF service is configured with the BasicHttpBinding.

WCF Service

Run View
Language:

Silverlight Client

Run View
Language:

Prerequisites (available from the Silverlight download site):

  • Microsoft Silverlight 2.0 Beta 2.

  • Microsoft Visual Studio 2008.

  • Microsoft Silverlight Tools Beta 2 for Visual Studio 2008.

  • Microsoft Silverlight SDK 2.0 Beta 2.

For more resources on Web service support in Silverlight, see Silverlight Web Services Samples.

To create and configure a WCF service to work with Silverlight

  1. Open Microsoft Visual Studio 2008.

  2. From the File menu, select New, then Project, then Web, and then select WCF Service Application.

  3. Name the Project CustomerService and click OK.

  4. To define the service contract for this WCF service in the IService1.cs file, remove the interface already defined in the file and add a new interface called IService1 within the CustomerService namespace and apply the ServiceContractAttribute attribute to it. Define the following operations for this service contract: CountUsers and GetUser. The CountUsers Operation should return a primitive int type and the GetUser operation should return a complex (user-defined) User type. Declare these methods within the interface and apply the OperationContractAttribute attribute to each of them. The interface should now contain the following code.

    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        int CountUsers();
    
        [OperationContract]
        User GetUser(int id);
    
    }
  5. Create a data contract within the CustomerService namespace for the User class returned by the GetUser method in the service contract. Apply the DataContractAttribute attribute to the class. Define the following properties for the class: IsMember, Name, and Age. The IsMember property should return a bool, the Name property a string, and the Age property an int. Apply the DataMemberAttribute attribute to each property. The class should now contain the following code.

    [DataContract]
    public class User
    {
        [DataMember]
        public bool IsMember { get; set; }
    
        [DataMember]
        public string Name { get; set; }
    
        [DataMember]
        public int Age { get; set; }
    } 
  6. To implement this service contract, replace the class already defined in the file Service1.svc.cs with the following code.

    public class Service1 : IService1
    {
      public int CountUsers()
      {
          return 2;
      }
      public User GetUser(int id)
      {
        if (id == 1)
        {
        return new User() { IsMember = true, Name = "Paul", Age = 24};
        }
        else
        {
        return new User() { IsMember = false, Name = "John", Age = 64};
        }
      }
    }
  7. For Silverlight accessibility, the constraint on the CustomerService project requires that the default binding (WsHttpBinding) be reset in the Web.config file to BasicHttpBinding in the <endpoint> element within the <service> element of the <system.serviceModel> element. The following line of code accomplishes this reconfiguration.

    <endpoint address="" binding="basicHttpBinding" contract="CustomerService.IService1">
  8. Modify the service implementation to provide any additional functionality as required.

  9. To test the service implementation, select the Service1.svc file in Solution Explorer, right-click and select View in Browser (or press Ctrl + F5) to display a test page for the service. You should see the Service1 Service test page, which confirms the service is available.

Conclusion

Run View
Language:

To create the Silverlight client application

  1. Create a new project for the Silverlight client within the current solution for the client in Microsoft Visual Studio 2008 by doing the following steps:

    1. In Solution Explorer (on the upper right) within the same solution that contains the service, right-click the current solution (not the project), select Add, and then New Item….

    2. In the Add New Item dialog, select the Silverlight category, choose the Silverlight Application template, and name it CustomerClient.

    3. Click Add.

  2. In the Add Silverlight Application Wizard, accepting the default values for the name and location options. Ensure all options are selected under Linked Web options.

  3. Click Add.

To add a reference to the HelloWorldService created

  1. Right-click the CustomerClient project in Solution Explorer and select Add Service Reference.

  2. Click the Discover button to find Service1.svc just created. It should appear in the Services: box. Type ServiceReference in the Namespace field and click OK. Make a note of the address provided in the Address text box as it is required in a later step.

  3. Notice that Solution Explorer has added a folder called Service References. You can explore the reference in that folder using Object Browser from the View menu. Note that it contains the CustomerClient.ServiceReference.Service1Client class and its methods. The methods in this class are used to call the service.

To construct a proxy to the service

  1. Go to the Page.xaml.cs (code-behind) file in the client application and add the following using statements at the top of the page.

    using System.ServiceModel;
    using System.ServiceModel.Channels;
  2. Instantiate the Web service proxy in the Page() constructor.

    ServiceReference.Service1Client proxy  = new ServiceReference.Service1Client();

To call operations on the Web service

  1. All Web service calls in Silverlight are asynchronous. Silverlight supports both the asynchronous pattern using the IAsyncResult interface, as well as the event-driven asynchronous pattern. To enable the event-driven pattern, the proxy contains two members for each operation in the service: an asynchronous method and a completed event. For example, see the GetUsers service operation. It can be called asynchronously by adding the following EventHandler to the Page() constructor defined in the Page.xaml.cs file.

    proxy.CountUsersCompleted += new EventHandler<CustomerClient.ServiceReference.CountUsersCompletedEventArgs>(proxy_CountUsersCompleted); 
    proxy.CountUsersAsync();
  2. Define and add the proxy_CountUsersCompleted handler for the completed event in the Page class.

    void proxy_CountUsersCompleted(object sender, CustomerClient.ServiceReference.CountUsersCompletedEventArgs e)
    {
        userCountResult.Text = "Number of users: " + e.Result;
    }
  3. Follow a similar procedure to call the second CountUsers operation offered by the service asynchronously from the client. Add the EventHandler code to the Page() constructor.

    proxy.GetUserCompleted += new EventHandler<CustomerClient.ServiceReference.GetUserCompletedEventArgs>(proxy_GetUserCompleted);
    proxy.GetUserAsync(1);
  4. Define and add the proxy_GetUsersCompleted handler for the completed event in the Page class.

    void proxy_GetUserCompleted(object sender, CustomerClient.ServiceReference.GetUserCompletedEventArgs e)
    {
        getUserResult.Text = "User name: " + e.Result.Name + ", age: " + e.Result.Age + ", is member: " + e.Result.IsMember;
    }
  5. To display the result of the Web service calls in a client control, open Page.xaml and add two TextBlock controls to the <Grid> element to display the result of the Web service calls.

    <StackPanel>
        <TextBlock x:Name="userCountResult" />
        <TextBlock x:Name="getUserResult" /></StackPanel>
  6. Your control is now ready to use. Right-click on the (automatically generated) CustomerClientTestPage.aspx client page in Solution Explorer and select View in Browser. You should see the lines "Number of users: 2" and "User name: Paul, age: 24, is member: True" in the browser window.

Conclusion

Run View
Language: