Silverlight has built-in support for communicating with Web services. This QuickStart provides an introduction to using Web services in Silverlight.
This QuickStart contains the following sections:
To understand Web services, it is helpful to start with a simple example. The example Web service used in this QuickStart is named CustomerService. This service provides customer information to a business. The information includes the number of customers, customer name, customer age, and whether the customer is a member.
The following code show the CustomerService contract in CustomerService.scv.cs (CustomerService.scv.vb). The CustomerService contract contains two operations that a
Silverlight client can access. The CountUsers operation returns the number of customers. The GetUser operation returns the customer's name, age, and whether he is a member.
GetUser returns a User type, which is defined
and implemented as part of the contract.
To download the Web service and client code for this QuickStart, see Web Services QuickStart download.
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Text;
namespace SilverlightApplication1Web
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements
(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CustomerService
{
[OperationContract]
public int CountUsers()
{
return 2;
}
[OperationContract]
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 };
}
}
}
[DataContract]
public class User
{
[DataMember]
public bool IsMember { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
}
}
Imports System
Imports System.Linq
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.Collections.Generic
Imports System.Text
Namespace SilverlightApplication1Web
<ServiceContract([Namespace] := "")> _
<AspNetCompatibilityRequirements _
(RequirementsMode := AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class CustomerService
<OperationContract> _
Public Function CountUsers() As Integer
Return 2
End Function
<OperationContract> _
Public Function GetUser(id As Integer) As User
If id = 1 Then
Return New User()
Else
Return New User()
End If
End Function
End Class
<DataContract> _
Public Class User
<DataMember> _
Public Property IsMember() As Boolean
Get
End Get
Set
End Set
End Property
<DataMember> _
Public Property Name() As String
Get
End Get
Set
End Set
End Property
<DataMember> _
Public Property Age() As Integer
Get
End Get
Set
End Set
End Property
End Class
End Namespace
In Silverlight, you communicate with a Web service through a proxy. You can generate a proxy with a tool, such as Add Service Reference in Visual Studio 2008. The proxy is generated by using the metadata that the service makes available. The metadata describes its functionality and how to access this functionality. The following illustrations show the communication between components. The arrows going to the right represent method calls from the client. The arrows going to the left represent return values from the service.
Because all Web service calls in Silverlight are asynchronous,
the proxy contains two members for each operation in the service: an asynchronous method and a completed event.
For example, consider the CountUsers service operation in the CustomerService service.
You add an EventHandler to the CountUsersCompleted event. This event is invoked when the service returns the requested data.
After the event is set up, you can make a call to the service by calling CountUsersAsync.
The event handler specifies that the proxy_CountUsersCompleted method is called when the service returns some data.
Similar remarks apply to the GetUsers operation.
The following code shows the Page.xaml.cs (or Page.xaml.vb) file for the Silverlight client.
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 SilverlightApplication1.ServiceReference1;
namespace SilverlightApplication1
{
public partial class Page : UserControl
{
public Page()
{
// Required to initialize variables
InitializeComponent();
}
void OnClick(object sender, EventArgs args)
{
CustomerServiceClient proxy = new CustomerServiceClient();
proxy.CountUsersCompleted += new
EventHandler<CountUsersCompletedEventArgs>(proxy_CountUsersCompleted);
proxy.CountUsersAsync();
proxy.GetUserCompleted += new
EventHandler<GetUserCompletedEventArgs%gt;(proxy_GetUserCompleted);
proxy.GetUserAsync(1);
}
void proxy_GetUserCompleted(object sender, GetUserCompletedEventArgs e)
{
getUserResult.Text = "Property values of user with ID = 1 are: Name:" +
e.Result.Name + ", Age:" + e.Result.Age + ", IsMember:" +
e.Result.IsMember;
}
void proxy_CountUsersCompleted(object sender, CountUsersCompletedEventArgs e)
{
userCountResult.Text = "The number of users is: " + e.Result;
}
}
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Net
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Imports SilverlightApplication1.ServiceReference1
Namespace SilverlightApplication1
Public Partial Class Page
Inherits UserControl
Public Sub New()
' Required to initialize variables
InitializeComponent()
End Sub
Private Sub OnClick(sender As Object, args As EventArgs)
Dim proxy As New CustomerServiceClient()
proxy.CountUsersCompleted += New _
EventHandler(Of CountUsersCompletedEventArgs)(proxy_CountUsersCompleted)
proxy.CountUsersAsync()
proxy.GetUserCompleted += New _
EventHandler(Of GetUserCompletedEventArgs)(proxy_GetUserCompleted)
proxy.GetUserAsync(1)
End Sub
Private Sub proxy_GetUserCompleted(sender As Object, _
e As GetUserCompletedEventArgs)
getUserResult.Text = "Property values of user with ID = 1 are: Name:" + _
e.Result.Name + ", Age:" + e.Result.Age + ", IsMember:" + _
e.Result.IsMember
End Sub
Private Sub proxy_CountUsersCompleted(sender As Object, _
e As CountUsersCompletedEventArgs)
userCountResult.Text = "The number of users is: " + e.Result
End Sub
End Class
End Namespace
The following XAML from Page.xaml shows how to initiate access to the CustomerService service and display the results.
The return values for CountUsers and GetUser are displayed in two TextBlock controls.
<UserControl x:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="600" Height="110">
<Grid x:Name="LayoutRoot" ShowGridLines="True" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
<RowDefinition Height="25"/>
<RowDefinition Height="25"/>
</Grid.RowDefinitions>
<Button
Grid.Row="0"
Margin=" 5"
Height="50"
Content="Click Here to Access the Web Service"
Click="OnClick"/>
<TextBlock Text="The number of users."
x:Name="userCountResult"
Grid.Row="1"/>
<TextBlock Text="Property values of user with ID = 1."
x:Name="getUserResult"
Grid.Row="2"/>
</Grid>
</UserControl>
CountUsers and GetUser return the following data.
The following illustration shows an example of the output after clicking the Click Here to Access the Web Service button.
To download the Web service and client code for this QuickStart, see Web Services QuickStart download.
Comments (0)