Advertisment

Accessing Web Services Using Silverlight

author-image
PCQ Bureau
New Update

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.

Advertisment

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;

Advertisment

namespace SilverlightApplication4.Web



{





AspNetCompatibilityRequirementsMode.Allowed)>


public class PcquestService


{





public int CountUsers()


{


return 2;


}





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.
Advertisment





public class User


{





public bool IsMember { get; set; }





public string Name { get; set; }





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;

Advertisment

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(proxy_CountUsersCompleted);


proxy.CountUsersAsync();


proxy.GetUserCompleted += new EventHandler(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':

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"



xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"


Width="400" Height="300">

































Grid.Row="2"/>
















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.

Advertisment