Integrating Silverlight with ASP.NET AJAX
- About the controls that Microsoft provided for integrating Silverlight with ASP.NET
- How to utilize Silverlight from an ASP.NET AJAX page
- About the various Web service transport protocols and how to consume a Web service from a Silverlight application
- How to consume a WCF service from a Silverlight application
This lesson will introduce some of the new ASP.NET Futures controls that Microsoft has released for integrating and extending ASP.NET, ASP.NET AJAX, and Silverlight.
Silverlight ASP.NET AJAX Controls
ASP.NET was released to developers approximately 8 years ago and it has been heavily adopted in the industry. In addition to proliferating the market, ASP.NET has had plenty of time to become a very stable product. There is a plethora of ASP.NET applications in production on the Web that would benefit from upgrading to Silverlight. However, bear in mind that ASP.NET is processed on the server. ASP.NET AJAX is also processed on the server through the ASP.NET page event life cycle although through the use of AJAX more processing occurs on the client's machine as to forego anymore postbacks occurring than is necessary.
A Silverlight application is hosted on a Web server so that a user can make a request for it over the Web. However, once a request is made for a Silverlight application, the entire contents of the application are sent to the client's machine and processed there. Once a Silverlight application is executing on a client's machine, calls can be made to the server or to a Web service but, by default, no postbacks occur to the server; the application is executing in an isolated and independent environment.
There are times when an application will benefit from merging the server-side and client-side worlds so that postbacks do occur to the server. For instance, a Silverlight application that must continually be updated from server-side content many benefit from postbacks. Additionally, completely redesigning a Web application around a new technology is a time-consuming and considerable task. Many ASP.NET and ASP.NET AJAX applications that are already developed, deployed, and stable may benefit from integrating Silverlight without being fully redesigned. Microsoft realized the need to merge the two worlds of Web computing and released some controls to do so in the ASP.NET Futures extensions.
The Microsoft ASP.NET Futures extensions include new features and functionality that are being considered for integration into ASP.NET, ASP.NET AJAX, and Silverlight and are made available for developers to begin experimenting with and adopting. Components that are released in ASP.NET Futures are normally somewhat stable and are generally included in the next release of ASP.NET, ASP.NET AJAX, and Silverlight.
The asp:Xaml Control
The Silverlight framework provides a generic class, or type, for working with XAML, the Sys.Preview.UI.Xaml.Control. The asp:Xaml control is used to insert XAML into an ASP.NET AJAX page in a very generic manner. The asp:Xaml control is typically extended through JavaScript, managed code, or dynamic code to provide a specialized implementation of the control. The most commonly used attribute of the asp:Xaml control is the XamlUrl attribute. The XamlUrl attribute identifies the XAML file to include in the page. The asp:Xaml control only exposes three minimal events with one of those fired upon an error and one fired upon the XAML loading.
An example of including XAML in an ASP.NET AJAX page by using the asp:Xaml control is shown in the code listing below.
Code Sample: IntegratingSilverlightWithASPNETAJAX/Demos/aspXamlSimple/Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register assembly="Microsoft.Web.Preview" namespace="Microsoft.Web.Preview.UI.Controls" tagprefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>My Simple XAML Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
</div>
<asp:Xaml ID="Xaml1" runat="server" Height="300px" Width="300px"
XamlUrl="~/Scene.xaml" />
</form>
</body>
</html>
The asp:Media Control
The asp:Media control is included in the ASP.NET Futures release and is used to easily integrate audio and video into an ASP.NET or ASP.NET AJAX application. The asp:Media control is designed to integrate Silverlight audio and video. The benefit of using the asp:Media control is that it integrates Silverlight audio and video without the developer being required to have knowledge of XAML or JavaScript. The asp:Media control allows for quick Silverlight integration into an ASP.NET or ASP.NET AJAX application while giving a developer time to get up to speed on the new technologies.
Silverlight supports Windows Video (WMV), Windows Media Audio (WMA), and MP3 media formats.
Properties, Events, and Methods
The asp:Media control includes a number of properties and methods. The asp:Media control inherits from the System.Web.UI.Controls.WebControl.XamlControl and, as such, also includes all of the properties, events, and methods included in the XamlControl.
The most commonly used properties supported by the asp:Media control are the MediaUrl and the MediaSkin properties. As their names imply, the MediaUrl property is used to identify the URL, or location, of the media file that is to be played by the asp:Media control and the MediaSkin property is used to identify the skin that the asp:Media control should display while playing the media file. The asp:Media control supports several predefined skins that can easily be selected as well as custom skins.
The asp:Media control also supports a number of built-in events including the onClientMediaOpened event and the onClientChapterStarted event.
The asp:Media control is incredibly easy to use right out of the box. Once the ASP.NET Futures extensions are installed, the asp:Media control can be added to ASP.NET pages declaratively or by dragging and dropping the control from the ASP.NET Futures tab in the Toolbox. By simply dragging and dropping the asp:Media control onto a new ASP.NET page and assigning the MediaUrl property a valid value, the page is media enabled. However, the ASP.NET Futures controls, including the asp:Media control requires use of the ASP.NET AJAX script library, hence any page that utilizes the asp:Media control must have an asp:ScriptManager control on the page as well. The markup shown below is the result of dropping the asp:Media control on a new ASP.NET page and assigning a value to the MediaUrl property.
Code Sample: IntegratingSilverlightWithASPNETAJAX/Demos/aspMediaSimple/Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="Microsoft.Web.Preview" Namespace="Microsoft.Web.Preview.UI.Controls"
TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>My Cardinals Videos</title>
<script type="text/JavaScript">
function onChapterStarted(sender, chapterEventArgs) {
var chapters = sender.get_chapters();
var ci = chapterEventArgs.get_chapterIndex();
var chapter = chapters[ci];
Sys.Debug.trace("Chapter Info" + chapter.imageUrl + " " + chapter.title);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="smCardinalVideos" runat="server">
</asp:ScriptManager>
<div>
<asp:Media ID="myCardVideo" AutoPlay="true" runat="server" Height="388px" MediaUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn.wmv"
Width="512px" XamlUrl="~/CustomProfessional.xaml" OnClientChapterStarted="onChapterStarted">
<Chapters>
<asp:MediaChapter Title="Start" TimeIndex="0.0" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.00.jpg" />
<asp:MediaChapter Title="Reception" TimeIndex="6.6253847" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.06.6253847.jpg" />
<asp:MediaChapter Title="Broken Tackle" TimeIndex="10.5280086" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.10.5280086.jpg" />
<asp:MediaChapter Title="End Zone" TimeIndex="13.1600108" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.13.1600108.jpg" />
<asp:MediaChapter Title="Replay" TimeIndex="17.3349108" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.17.3349108.jpg" />
<asp:MediaChapter Title="Celebration" TimeIndex="55.1768291" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.55.1768291.jpg" />
<asp:MediaChapter Title="End" TimeIndex="71.2455760" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.01.11.2455760.jpg" />
</Chapters>
</asp:Media>
</div>
</form>
</body>
</html>
The same page displayed in Design view shows the Silverlight media player as shown in the figure below.
When run, the ASP.NET page plays the media file targeted by the asp:Media control as shown below.
Chapters
Audio and video, and the combination thereof, are generically referred to as media. Media may exist in various formats. Most media vendors, such as Microsoft, Apple, and Real, distribute and save media in proprietary formats. Most media players will play media in multiple formats. There are also industry standard media formats that most players also support. Media may be stored in a particular format when it is saved after being recorded or may be converted from one format to another using a converter tool.
When media is prepared for playback in a particular format, the process is referred to as media encoding. During the encoding process, the stream of media bits may also be manipulated and modified. For instance, by using a media encoder, a media (video / audio) stream may be played to a certain point and then another media source may be interjected. Television production studios perform this type of encoding action to interject a commercial into a live or recorded media stream (television show) that is being broadcast.
Microsoft released the Expression Media Encoder (EME) with the Expression Suite of designer tools. By using EME, you can define markers, similar to bookmarks, in a media stream. The asp:Media control detects these markers in the media stream and can respond to them. By using the Silverlight player, a user can jump in the media playback from one marker to another. Furthermore, events can automatically be fired when a new marker is encountered. Markers are generally referred to as chapters. EME with imported media with markers defined is shown in the following figure.
When media is prepared and encoded by using EME, including markers, the output in Visual Studio 2008 appears as shown in the figure below.
The asp:Media control includes functionality for navigating defined markers, or chapters, in encoded media. The asp:Media control includes a child element named <Chapters> that is used to define the chapters in encoded media. The <Chapters> element, in turn, contains a series of <asp:MediaChapter> elements that correlate to each chapter in the media. Each <asp:MediaChapter> element may contain three attributes:
- Title: this attribute defines the title of a chapter and is displayed by the media player to identify the chapter
- TimeIndex: this attribute is defines location in the encoded media where the chapter begins
- ImageUrl: this attribute identifies an image that is displayed by the media player to visually identify the chapter
The easiest method of providing values for each of the attributes is by using the marker definitions in EME. However, the TimeIndex attribute should be represented in a value that can be converted to a double numeric value, hence some conversion of values from EME to asp:Media might be necessary. For instance, in the example shown here, the marker at the end of the media is shown at 1.11.2455760 in EME whereas it must be converted to the actual number of minutes in the TimeIndex attribute as 71.2455760. The resulting asp:Media element definition is shown in the markup snippet below.
<asp:Media ID="myCardVideo" AutoPlay="true" runat="server" Height="240px"
MediaSkin="Professional" MediaUrl="SteveBreastonCardinalsPuntReturn.wmv"
Width="320px">
<Chapters>
<asp:MediaChapter Title="Start" TimeIndex="0.0"
ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.00.jpg" />
<asp:MediaChapter Title="Reception" TimeIndex="6.6253847"
ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.06.6253847.jpg" />
<asp:MediaChapter Title="Broken Tackle" TimeIndex="10.5280086"
ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.10.5280086.jpg" />
<asp:MediaChapter Title="End Zone" TimeIndex="13.1600108"
ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.13.1600108.jpg" />
<asp:MediaChapter Title="Replay" TimeIndex="17.3349108"
ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.17.3349108.jpg" />
<asp:MediaChapter Title="Celebration" TimeIndex="55.1768291"
ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.55.1768291.jpg" />
<asp:MediaChapter Title="End" TimeIndex="71.2455760"
ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.01.11.2455760.jpg" />
</Chapters>
</asp:Media>
The Silverlight media player is capable of navigating the chapters in the encoded media once the chapters are defined. In order to navigate the chapters, hover the mouse over the bottom of the player and the chapter images will be displayed. By clicking one of the chapter images, the media jumps to that chapter. The resulting player is shown in the following image.
Skins
The asp:Media control includes several built-in skins that are used to change the appearance of the media player. The built-in skin can easily be changed using Visual Studio 2008 either declaratively in the markup through intellisense or visually in the designer. A custom skin can also be provided for the media player by creating a custom XAML file and referencing the XAML file through the XamlUrl attribute of the asp:Media control.
An easier method of creating a custom player skin is to export an existing skin and modify it. To export and modify a skin by using Visual Studio 2008, use the asp:Media control smart tag menu in design view and select Configure Skin. The Configure Player Skin offers options to select a built-in skin, export a built-in skin, and select a custom skin. Select the skin to be exported and then click the Export button. Modify the skin XAML and then select the modified XAML as a custom skin. For example, in the figure below, the Professional skin was exported, modified to add some orange highlights, and then selected as the active skin.
Handling Media Player Events
The Microsoft Silverlight plug-in includes a framework of namespaces, classes, and functionality that are used to interact with the media player and create applications. The Sys.Preview.UI.Xaml.Media.Player class is used to directly control the Silverlight media player. Classes in the Silverlight documentation are referred to as client types. This makes sense as a class, in object oriented terminology, is defined as representing a particular type of entity.
The Player type is tightly coupled to the media player. The media player and its active skin are defined by using XAML. As such, the XAML used to define the player skin must adhere to a specific XML grammar so that the Player type can assume that particular elements exist within the player skin XAML. If the player skin XAML includes the correct elements, identifying functions to handle player events by using the asp:Media control is a simple process. Function handlers can easily be identified either declaratively or through the designer by using Visual Studio 2008. The full markup of the page with the OnClientChapterStarted function handler defined is shown in the markup listing below.
Code Sample: IntegratingSilverlightWithASPNETAJAX/Demos/aspMediaSimple/Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="Microsoft.Web.Preview" Namespace="Microsoft.Web.Preview.UI.Controls"
TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>My Cardinals Videos</title>
<script type="text/JavaScript">
function onChapterStarted(sender, chapterEventArgs) {
var chapters = sender.get_chapters();
var ci = chapterEventArgs.get_chapterIndex();
var chapter = chapters[ci];
Sys.Debug.trace("Chapter Info" + chapter.imageUrl + " " + chapter.title);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="smCardinalVideos" runat="server">
</asp:ScriptManager>
<div>
<asp:Media ID="myCardVideo" AutoPlay="true" runat="server" Height="388px" MediaUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn.wmv"
Width="512px" XamlUrl="~/CustomProfessional.xaml" OnClientChapterStarted="onChapterStarted">
<Chapters>
<asp:MediaChapter Title="Start" TimeIndex="0.0" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.00.jpg" />
<asp:MediaChapter Title="Reception" TimeIndex="6.6253847" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.06.6253847.jpg" />
<asp:MediaChapter Title="Broken Tackle" TimeIndex="10.5280086" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.10.5280086.jpg" />
<asp:MediaChapter Title="End Zone" TimeIndex="13.1600108" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.13.1600108.jpg" />
<asp:MediaChapter Title="Replay" TimeIndex="17.3349108" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.17.3349108.jpg" />
<asp:MediaChapter Title="Celebration" TimeIndex="55.1768291" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.00.55.1768291.jpg" />
<asp:MediaChapter Title="End" TimeIndex="71.2455760" ImageUrl="~/EMEOutput/SteveBreastonCardinalsPuntReturn_MarkerThumb 00.01.11.2455760.jpg" />
</Chapters>
</asp:Media>
</div>
</form>
</body>
</html>
The resulting Visual Studio 2008 Output window is shown in the figure below.
Consuming Web Services
A primary function of an ASP.NET application is the ability to interact with a Web server. In a standard ASP.NET application, each page refresh causes a postback to occur to the server and, thus, interaction occurs. In an ASP.NET AJAX application, interaction with the server is minimized but postbacks to the server still occur. In either scenario, interaction with a Web server can be optimized by making calls to a Web service. In a Silverlight application, once the application has been downloaded to the client's machine, interaction with the server does not occur unless a call is initiated at the client. The most common method of interacting with a Web server from a Silverlight application is to make a call to a Web service.
A Web service is a component, similar to a procedure file or an object with methods, that is callable over the Web by using Web protocols. Just as a procedure file or object with methods is called from code to provide a service or benefit to the calling code, a Web service functions in the same way. Code with access to the Web service calls the Web service in order to provide some type of additional functionality. Web services use HTTP as a communication protocol, by default, and an XML grammar called the Simple Object Access Protocol (SOAP), to transport data, again, by default. Just as any client with a Web browser can view a Web page, due to the use of the Web standards, a Web service can be called by any programming language that is capable of working with open Web standards. Additionally, due to the use of HTTP as a communication protocol, Web services are generally accessible through firewalls.
As with most popular Web technologies, Web services include many additional technologies that enhance and extend the basic functionality of a Web service. Furthermore, the technologies surrounding Web services have been evolving at an astronomical rate and its been tough for development environments to keep up with the supported technologies. Supporting technologies include enhancements to security, the ability to manage messages being sent to and from a Web service and ensure reliability, and the functionality for working with messages in transactions.
It's fairly straightforward to consume a Web service from a Silverlight application. However, Web services reside on a Web server, whereas Silverlight applications reside on a client workstation. Hence, it can be a little tricky to test communications between a Silverlight application and a Web service on a single machine. This module illustrates both consuming a Web service and testing Silverlight and Web service communications.
Consuming a Web Service From Silverlight
When a client application calls a method of a Web service, the client application is said to "consume" the Web service. The first thing that should be noted is that there are some limitations to consuming Web services from the current version of Silverlight. The current version of Silverlight, Silverlight 2.0, only supports consuming a Web service that is hosted on the same Web server as the Silverlight application that is consuming it. Consuming a Web service that is not hosted on the same Web server requires making a call to a different domain or making a cross-domain call. Silverlight 2.0 does not support cross-domain calls due to security concerns. However, cross-domain calls may be supported by a future version of Silverlight.
Web services can be consumed by a Silverlight 2.0 application in multiple ways:
- By programmatically configuring a call to a Web service method and passing standard, well-formed, XML that does not adhere to the SOAP schema by including a SOAP envelope or wrapper. XML passed to a Web service in this manner is referred to as Plain Old XML (POX). The System.Net.BrowserHttpWebRequest class is used to place a call to a Web method and the System.Net.HttpWebResponse class is used to capture the response. Calling a Web method by using POX is fairly easy to do and the call can be made either synchronously or asynchronously. However, programmatically calling a Web method in this manner is difficult to test by using the built-in Web server in Visual Studio 2008.
- By calling a Web service by passing data formatted in JavaScript Object Notation (JSON). JSON is an industry-standard data exchange format that is compact and ideal for ASP.NET AJAX applications and Silverlight applications. As mentioned, by default, ASP.NET Web services transport data by using SOAP, an extended XML grammar. However, it's very easy to direct an ASP.NET Web service to transport data using JSON. The ASP.NET AJAX extensions, now incorporated into the .NET Framework, provide a new attribute, the System.Web.Script.Services.ScriptServiceAttribute attribute, that can be applied to a Web service class to direct the ASP.NET Web service to transport data by using JSON. Any ASP.NET Web service that must be called from JavaScript in an ASP.NET AJAX or code in a Silverlight application must be marked up by using the ScriptService attribute. This module illustrates configuring an ASP.NET Web service to be called by a Silverlight application and tested.
Configuring Visual Studio 2008
The ASP.NET Futures extensions provide several additions for use in ASP.NET AJAX and Silverlight. One addition provided is the ability to create an ASP.NET Futures Web Site in Visual Studio 2008. The ASP.NET Futures Web Site is ideal for testing ASP.NET Web service calls from a Silverlight application.
Create the Web Service
The first step in the process of configuring a Web service for calls from a Silverlight application and testing those calls is to create an ASP.NET Futures Web Site. The New Web Site dialog is shown in the figure below.
When a new ASP.NET Futures Web site is created, a Default.aspx page is created that includes a <ScriptManager> element ready to work with AJAX. The next step of the process is to add a new ASP.NET Web service to the Futures project. The Add New Item dialog is shown in the figure below.
When a new Web service is created by using ASP.NET 2.0 or greater, the code behind file for the Web service is placed in the App_Code folder in the solution. To direct the new Web service to transport data by using JSON, uncomment the [System.Web.Script.Services.ScriptService] attribute at the top of the Web service code behind file. Next, create one or more methods in the Web service class that can be called. The following snippet illustrates a simple greeting Web method.
[WebMethod]
public string Greet(string name) {
return "Hey, " + name + ", how's it going?";
}
Test the Web service to ensure that it is functioning as intended.
Create the Silverlight Application
Now that the Web service is functioning correctly, it is ready to be called by a Silverlight application. The next step is to create the Silverlight application. The application created to test the Web method above is shown in the figure below.
Code Sample: IntegratingSilverlightWithASPNETAJAX/Demos/Greeter/Greeter/Page.xaml
<Canvas
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c1="clr-namespace:C1.Silverlight;assembly=ClientBin/C1.Silverlight.dll"
x:Name="parentCanvas"
Loaded="Page_Loaded"
x:Class="Greeter.Page;assembly=ClientBin/Greeter.dll"
Width="800"
Height="800"
>
<Canvas.Background>
<LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5" SpreadMethod="Pad">
<GradientStop Color="#FFD2CBD2" Offset="0"/>
<GradientStop Color="#FF4D1E4C" Offset="1"/>
</LinearGradientBrush>
</Canvas.Background>
<TextBlock Width="142" Height="20" Canvas.Left="10" Canvas.Top="26">
<Run FontFamily="Segoe UI" FontSize="12" Foreground="#FF1E2576" Text="Enter Name:"/>
</TextBlock>
<c1:TextBox Canvas.Top="25" Canvas.Left="90" Width="200" x:Name="txtName" />
<c1:Button AutoWidth="False" Width="100" Canvas.Top="25" Canvas.Left="292" Text="Greet Me" Click="GetGreeting"/>
<TextBlock x:Name="tbGreeting" Width="506" Height="68" Canvas.Left="10" Canvas.Top="50" TextWrapping="Wrap">
<Run Text="" FontFamily="Segoe UI" FontSize="12" Foreground="#FF330909"/>
</TextBlock>
</Canvas>
To consume a Web service from the Silverlight application, right-click the Silverlight project in the Solution Explorer and select Add Web Reference. Due to the Web service residing in the same solution as the Silverlight application, Visual Studio 2008 makes it easy to locate the Web service; simply select the option to locate Web services in the current solution. The Add Web Reference dialog is shown in the following figure.
Once the Web reference is added to the Silverlight project, the methods of the Web service can be called from the Silverlight application. The event handler for the button in the Silverlight application is located in the code behind for the XAML file and is shown in the snippet below.
public void GetGreeting(object o, EventArgs e) {
// Due to a bug in the early alpha of the controls, we'll hard code the input value here.
// Create an instance of the service class.
Greeter.localhost.GreetService svc = new Greeter.localhost.GreetService();
// Call the method and set the textblock value.
tbGreeting.Text = svc.Greet("Shannon");
}
In a traditional ASP.NET application, this code would run without error. However, due to Silverlight now allowing cross-domain calls, when you attempt to run this code in Visual Studio 2008, you receive the following warning.
If you select Yes when prompted with this dialog, the Silverlight application should display but the call to the Web service will not execute successfully. When testing a Silverlight application making calls to a Web service, Visual Studio is simulating an isolated client application communicating with a Web server. In order to configure the Visual Studio environment to simulate this scenario successfully, some additional configuration is required. In this scenario, testing occurs from the Web service project instead of the Silverlight project.
To remedy the situation, right-click the Web service project and select Add Silverlight Link. The Add Silverlight Link dialog box is shown below.
When prompted to enable Silverlight debugging, select Yes.
You'll notice that a ClientBin folder that contains the Silverlight application assemblies and project debug files as well as any XAML files contained in the Silverlight application now appear in the Web service project. The Silverlight link added to the Web service project will now keep the Web service project in sync with the Silverlight application so that the Silverlight application can now be tested locally to the Web service.
In order to test the XAML from the Silverlight application, open the Default.aspx page and add an asp:Xaml control to the page. Set the XamlUrl attribute to the XAML file to be tested and run the Default.aspx page. The page containing the XAML selected should be displayed in the browser and testing can being. The resulting XAML page used in this example is shown in the figure below.
Integration with WCF
Windows Communication Foundation (WCF) is Microsoft's new SOA technology that encompasses ASP.NET Web services, .NET remoting, and the various WS-technologies and extends upon each. Currently, calling a WCF service is configured and tested in the same manner as an ASP.NET Web service within Visual Studio 2008.
Lab: Integrating with ASP.NET AJAX
In this lab, you will work with the ASP.NET Futures controls as well as configure a Silverlight application to test calls to a Web service.
Integrating Silverlight with ASP.NET AJAX Conclusion
In this lesson of the Silverlight tutorial, you
- Learned about the new ASP.NET Futures controls for integrating Silverlight with ASP.NET AJAX
- Utilized Silverlight from an ASP.NET AJAX page
- Reviewed Web service transport protocols and consumed a Web service from Silverlight
- Consumed a WCF service by using Silverlight
