Skip to main content

Microsoft Silverlight

MicrosoftWritten by:
Microsoft
Microsoft

Web Services

0 0

Summary

Provides an introduction to using Web services in Silverlight.

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:

For a complete description of Web services in Silverlight, see Accessing Web Services in Silverlight in the Silverlight documentation on MSDN.

Building a Service for a Silverlight Client

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.

Note

To download the Web service and client code for this QuickStart, see Web Services QuickStart download.

C#

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; } } }

Visual Basic

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
 

Accessing a Service from a Silverlight Client

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.


Silverlight Client <--> Proxy <--> Web Service illustration

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.

C#

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; } } }

Visual Basic

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.

XAML

<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 number of users is: 2.
  • Property values of user with ID = 1 are: Name:Paul, Age:24, IsMember:True

The following illustration shows an example of the output after clicking the Click Here to Access the Web Service button.

Output of CustomerService

Note

To download the Web service and client code for this QuickStart, see Web Services QuickStart download.


See Also


Send Feedback

Leave a Comment Comments (2) RSS Feed


matt....

Member

Member

3 Points

#1 October 06, 2009 3:32 PM

When I ran your example and clicked the button I got this error:

An error occurred while trying to make a request to URI 'http://localhost:45402/CustomerService.svc'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details.

It's the same one I've been getting every time I've tried to connect any web service to any silverlight app. I've found two sites saying how to fix it, but one didn't make any sense and the other didn't work. Please help!


humpherj

Member

Member

1 Points

#2 October 23, 2009 3:46 PM

I had the same problem.... for anyone else who gets this have a look at:

http://timheuer.com/blog/archive/2008/10/14/calling-secure-services-with-silverlight-2-ssl-https.aspx

The problem is that a call from the file:// domain to the http:// domain will be counted as a cross domain call. You just need to add a clientaccesspolicy.xml file to your web project in visual studio, which will allow these calls. There's an example in the article.

  • 1

You must be logged in to leave a comment. Click here to log in.

Quickstarts

Microsoft Communities