|
|
[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
Silverlight Client
Prerequisites (available from the Silverlight download site):
-
Microsoft Silverlight 2.0 Beta 1.
-
Microsoft Visual Studio 2008.
-
Microsoft Silverlight Tools Beta 1 for Visual Studio 2008.
-
Microsoft Silverlight SDK 2.0 Beta 1.
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
-
Open Microsoft Visual Studio 2008.
-
From the File menu, select New, then Project, then Web, and then select WCF Service Application.
-
Name the Project CustomerService and click OK.
-
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);
}
-
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; }
}
-
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};
}
}
}
-
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">
-
Modify the service implementation to provide any additional functionality as required.
-
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.
To create the Silverlight client application
-
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:
-
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 Project.
-
In the Add New Project dialog, select Silverlight, choose the Silverlight Project template, and name it CustomerClient. Use the default Location.
-
Click OK.
-
In the Silverlight Application Wizard, select Link this Silverlight control into an existing Web site. Ensure all options are selected under Linked Web options and click OK.
To add a reference to the HelloWorldService created
-
Right-click the CustomerClient project in Solution Explorer and select Add Service Reference.
-
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.
-
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
-
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;
-
Create a binding element in the scope of the Page constructor. Bindings specify the details required for a client to communicate with the service. As mentioned in the list of limitations in the first procedure, the only binding that is currently supported is BasicHttpBinding, so add the following line of code to create this binding.
Binding binding = new BasicHttpBinding();
-
Create an EndpointAddress. The endpoint address gives the address of the service to be accessed. Use the location where you hosted your service. This is the address that you were asked to take note of when designing the service. Do not use the address provided in the following line of code as it will not work for your service.
EndpointAddress address = new EndpointAddress("http://localhost:51854/service1.svc");
-
Instantiate the Web service proxy.
ServiceReference.Service1Client proxy = new ServiceReference.Service1Client(binding, address);
To call operations on the Web service
-
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 following service operation.
The service operation results in the following client members.
public event System.EventHandler<CountUsersCompletedEventArgs> CountUsersCompleted;
public void CountUsersAsync();
-
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>
-
Open Page.xaml.cs, go to the end of the Page constructor and add the following code to invoke the CountUsers operation asynchronously.
proxy.CountUsersCompleted += new EventHandler<CustomerClient.ServiceReference.CountUsersCompletedEventArgs>(proxy_CountUsersCompleted);
proxy.CountUsersAsync();
-
Define the proxy_CountUsersCompleted event handler.
void proxy_CountUsersCompleted(object sender, CustomerClient.ServiceReference.CountUsersCompletedEventArgs e)
{
userCountResult.Text = "Number of users: " + e.Result;
}
-
Similarly, the GetUser operation can be called by adding this to the end of the Page constructor.
proxy.GetUserCompleted += new EventHandler<CustomerClient.ServiceReference.GetUserCompletedEventArgs>(proxy_GetUserCompleted);
proxy.GetUserAsync(1);
-
Define another event handler.
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;
}
-
Your control is now ready to use. Press Ctrl + F5 in Visual Studio to open the CustomerClientTestPage.aspx client page, which was automatically generated to test the Silverlight control. You should see the lines "Number of users: 2" and "User name: Paul, age: 24, is member: True" in the browser window.
|