Publish Article
Go Freelance

How to use ASP.Net web services in Silverlight


If you are seeing this section and do not see download links, this means that you are not logged into our site. If you already are a member, click on the login link and login into site and come back to this page for downloading the control files. If you are not a member, click on registration link to become a Winista member and download the control for free.

How to use ASP.Net web services in Silverlight

For 2-3 days i have been playing around with Silverlight 2 to figure out if I can use this slick piece of new technology into our existing web application. As a proof of concept i needed to create a prototype that would be able to use data from our exiting ASP.Net and Java web services and display it in cool way. Well, it did not turn out to be a bad expereince at all and after few road blocks or learning curves i was able to do what i wanted to accomplish. This artcile is my expereince with creation of Silverlight control that consumes an ASP.Net web service and calls it periodically using a timer. Yes timer, i had to throw in some fun stuff for me as well.

Silverlight Tools

To get started with Silverlight 2 development you are going to need to install the following development tools on your machine.

  • Visual Studio 2008 (prefered) but you can use Visual Studio 2005 as well.
  • Silverlight 2 Development tools. If you have already installed Silverlight 2 runtime and SDK installed on your machine, you will have to uninstall it otherwise VS2008 and other tools with not install. The installation with keep promptin you to remove those first.
  • Expression Blend. You do not need this for starters. But if you are interested in doing some cool graphics and generate XAML for you, then this will be tool of choice.

Get Started With Application

After you have installed Silverlight plugin for visual studio, you will see new project types added into your user interface when you for creating new project. Select "Silverlight Application" project and you will have the boiler plate projects, pages and code files created for you.

Silverlight plugin for Visual Studio 2008

You will see 2 projects have been created for you in the solution tree. One will test web application and other will be project that contains Silverlight control that you are going to build.


Control user interface layout is done using XAML. Current Beta 1 version of add-in does not allow you to drag and drop Silverlight controls into design area. But you can do that in XAML view. In my control i needed to display an item's name, description and price in a vertical stacked form. So my XAML layout for the control looks like following.

<UserControl x:Class="SilverSpice.Page"
    Width="240" Height="320">
    <Grid x:Name="LayoutRoot">
		<StackPanel Orientation="Vertical">
			<Border Background="Blue" CornerRadius="10">
				<TextBlock x:Name="ItemName" Foreground="White" 
				Text="Item Name" FontWeight="Bold" 
				HorizontalAlignment="Center" />
			<TextBlock x:Name="ItemDescription" Foreground="Black"
			 Text="Description" TextWrapping="Wrap" />
			<Border Background="BlanchedAlmond"  CornerRadius="10">
				<TextBlock x:Name="ItemPrice" Foreground="Red" 
				Text="Price" FontWeight="Bold" 
				HorizontalAlignment="Right" />

Referencing Web Service

Right click on "Reference" node in project's tree view and select "Add Service Reference" option. In the wizard specify location of ASMX file of your web service. Reference to web services will get added to your project.

Calling Web Service

Calling web service in Silverlight is slightly different. First all web service requests are asynchronous, so that means you will have register an event to handle completion of the request. Second, the call to web service are made throgh SOAP client. You do not have to worry about all the details of constructing bindings etc. When you added reference to ASMX file using wizard, Reference.cs file was created for you which has the ncessary code to make simple request to your web service. Following code snippet shows what I did in my control to call web service.

private KitchenNetMenuService.KitchenNetMenuSoapClient _wsClient = 
	new SilverSpice.KitchenNetMenuService.KitchenNetMenuSoapClient();
private void CreateMenuService()
	// Add event handler for ws call completion.
	this._wsClient.GetMenuItemsCompleted += 
		new EventHandler<KitchenNetMenuService.GetMenuItemsCompletedEventArgs>

protected void GetMenuItemsCompleted
	(object sender, KitchenNetMenuService.GetMenuItemsCompletedEventArgs e)
 	 _menuItems = (SilverSpice.KitchenNetMenuService.MenuItem[]) e.Result;
	 if (null == _wsCallTimer)
	catch(Exception ex)
	 this._errorMessage += ex.Message;
	 this._errorMessage += ex.StackTrace;

Creating Timer In Silverlight

Next thing i want to add to my control is ability to rotate display of menu items at specified interval. Create a System.Windows.Threading.DispatchTimer object and set the interval at which timer will tick and call the tick event handler. In the following code I have set the timer to tick every 5 seconds.

private void CreateTimer()
	_wsCallTimer = new System.Windows.Threading.DispatcherTimer();
	_wsCallTimer.Interval = new TimeSpan(0, 0, 0, 0, 5000);
	_wsCallTimer.Tick += new EventHandler(GetNewMenuItem);

Compile and Deploy

When you compile a Silverlight application, it generates .xap file that gets streamed down to client browser. To test the control i started an ASP.Net web application from scratch. Add reference to System.Web.Silverlight assembly in your application. And then on the page register tag to use Silverlight control.

<%@ Register Assembly="System.Web.Silverlight" 
	Namespace="System.Web.UI.SilverlightControls" TagPrefix="asp" %>

Now you can put the control on the page as shown below.

<asp:ScriptManager ID="ctlScriptManager" runat="server"></asp:ScriptManager>
<asp:Silverlight ID="ctlSilverSpiceMenu" runat="server" Source="~/SLControls/SilverSpice.xap" Version="2.0" Width="100%" Height="500" />

You will have to include ScriptManage control on your page because it is required for asp:Silverlight control to work. If you do not include ScriptManager control on the page, you will end up with following run time exception.

The control with ID 'ctlSilverSpiceMenu' requires a ScriptManager on the page. 
The ScriptManager must appear before any controls that need it. 							

Now copy .xap file created from your Silverlight application under your web application. And speicfy the location of that file in Source attribute of Silverlight control. Tada! You are done!


Like any other new technologies in Beta stage, Silverlight also has some quirks that you need to be aware of. Following is list of some URLs that you should view to get some details on these issues.

Go Freelance
Home     About us     Contact us    Copyright    Privacy Policy    Return Policy    Advertisers
Copyright © Netomatix