by April 1, 2009 0 comments



There area number of ways that a Silverlight client can access external data
like a typical scenario, where data is in a relational database with Silverlight
interface to it. Another interesting scenario is consumption of data as a web
service by a Silverlight client. Again there are two different ways in which one
can access web services. In this implementation, we are describing how to access
web services via proxy generated from metadata published by the service. One can
also access these services directly.

Direct Hit!

Applies To: Web Developers
USP: Accessing Web services using
Silverlight
Primary Link:
www.silverlight.com
Keywords:
Silverlight 2

Implementation
Here we are using Visual Studio 2008 SP1 with C# as programming language.
There are two things to be done, creating Silverlight enabled web service and a
client that consumes these web services. Start with creating new Silverlight
project using ‘Silverlight Application’ template (‘SilverlightApplication4’ in
our case). In the ‘Add Silverlight Application’ wizard, accept default values.
Next step is to add Silverlight enabled Windows Communication Foundation service
to default web application. Right click on ‘SilverlightApplication4.Web’ in
solution explorer and click on Add>New Items. Select ‘Silverlight’ from ‘Catogories’
and then add ‘Silverlight-enabled WCF Service’ template with ‘PcquestService.svc’
as name of service. Now one needs to define and implement contracts that define
functionality provided by the service to clients. Here we are defining two
contracts that will allow clients to retrieve number of users and individual
user information. Here is the content of ‘PcquestService.svc.cs’:

using System.ServiceModel;
using System.ServiceModel.Activation;

namespace SilverlightApplication4.Web
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
public class PcquestService
{
[OperationContract]
public int CountUsers()
{
return 2;
}
[OperationContract]
public User GetUser(int id)
{
if (id == 1)
{
return new User() { IsMember = true, Name = "Sandeep", Age = 95 };
}
else
{
return new User() { IsMember = false, Name = "Sandy", Age = 55 };
}
}
}

One important point here is to use valid type and the simplest way to achieve
this is to make types public with public members and public constructures.

This is the
browser window acting as Silverlight client. Click on the button to get data
available as web service.

[DataContract]
public class User
{
[DataMember]
public bool IsMember { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
}
}

To test if this service is working properly simply right click on ‘PcquestService.svc’
file in solution explorer and click on ‘View in Browser’. This will display test
page for the service. Now as we have service, we need to access it. We will
start with adding service reference to service. In the same project, right click
on ‘SilverlightApplication4’ in solution explorer and select ‘Add Service
Reference’. In pop up window, click on ‘Discover’ button, this will show ‘PcquestService.svc’
service we have just created. Accept ‘ServiceReference1’ in the ‘Namespace’
field and click on ‘OK’. Next step is to create proxy to the service. Go to ‘Page.xaml.cs’
and add followimg reference:

using System.ServiceModel;
using SilverlightApplication4.ServiceReference1;

Before one can use service, web service proxy needs to be initated. Here this
is done inside ‘OnClick()’. Web service calls in Silverlight are asynchronous.
The proxy contain two members for each operation in the service; an asynchronous
method and completed event. For example, in our implementation in ‘CountUser’
service operation, we first add ‘EventHandler’ to ‘CountUserCompleted’ event.
This event would be invoked when service returns data. After event is setup, we
can make call to service by calling ‘CountUserAsyn()’. The event handler
specifies that ‘proxy_CountUser Completed()’ is called when the service returns
some data.

namespace SilverlightApplication4
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
}
void OnClick(object sender, EventArgs args)
{
PcquestServiceClient proxy = new PcquestServiceClient();
proxy.CountUsersCompleted += new EventHandler<CountUsersCompletedEventArgs>(proxy_CountUsersCompleted);
proxy.CountUsersAsync();
proxy.GetUserCompleted += new EventHandler<GetUserCompletedEventArgs>(proxy_GetUserCompleted);
proxy.GetUserAsync(1);
}
void proxy_GetUserCompleted(object sender, GetUserCompletedEventArgs e)
{
getUserResult.Text = "User name: " + e.Result.Name + ", age: " + e.Result.Age +
", is member: " + e.Result.IsMember;
}
void proxy_CountUsersCompleted(object sender, CountUsersCompletedEventArgs e)
{
if (e.Error == null)
{
userCountResult.Text = "Number of users: " + e.Result;
}
else
{
userCountResult.Text = "Error getting the number of users";
}
}
}
}

Here we are showing the content of ‘Page.xaml’ file. This is done to display
results. Here results are shown in ‘TextBlock’:

<UserControl x:Class="SilverlightApplication4.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" 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>

All in all, this shows how easy it is to access web services using Silverlight
client. This can help web developers to add more data to their silverlight based
web sites.

No Comments so far

Jump into a conversation

No Comments Yet!

You can be the one to start a conversation.

<