Silverlight and ASP.NET



February 06, 2008
URL:http://www.drdobbs.com/web-development/silverlight-and-aspnet/206105457

Matthew MacDonald and Mario Szpuszta are the authors of Pro ASP.NET 3.5 in C# 2008, Second Edition, from which this article is adapted. Copyright Apress All rights reserved.


The Silverlight examples you've seen so far can be used in a basic, stand-alone website or in an ASP.NET web application. If you want to use them in an ASP.NET website, you simply need to add the Silverlight files to your website folder or web project. You copy the same files that you copy when deploying a Silverlight application_everything except the source code files.

Unfortunately, the ASP.NET development process and the Silverlight development process aren't yet integrated in Visual Studio. As a result, you'll need to compile your Silverlight project separately and copy the compiled assembly by hand. (You can't simply add a reference to the compiled assembly, because Visual Studio will place the referenced assembly in the Bin folder, so it's accessible to your ASP.NET server-side code, which isn't what you want. Instead, you need to place it in the ClientBin folder, which is where your HTML entry page expects to find it.)

This approach allows you to place Silverlight and ASP.NET pages side-by-side on the same website; but they aren't in any way integrated. You can navigate from one page to another (for example, use a link to send a user from an ASP.NET web form to a Silverlight entry page), but there's no interaction between the server-side and client-side code. In many situations, this design is completely reasonable, because the Silverlight application represents a distinct "applet" that's available in your website. In other scenarios, you might want to share part of your data model, or integrate server-side processing and client-side processing as part of a single task.

ASP.NET Futures

The ASP.NET Futures release includes two ASP.NET web controls that render Silverlight content: Xaml and Media (which are described in the following sections). Both of these controls are placed in an assembly named Microsoft.Web.Preview.dll, which you can find in a directory with a name like

c:\Program Files\Microsoft ASP.NET\ASP.NET Futures July 2007\v1.2.61025\3.5.

In order to use the Xaml and Media controls, you need a reference to the Microsoft.Web.Preview.dll assembly. You also need to register a control tag prefix for the Microsoft.Web.Preview.UI.Controls namespace (which is where the Xaml control is located). Here's the Register directive that you can add to a web page (just after the Page directive) to use the familiar asp tag prefix with the new ASP.NET Futures controls:

<%@ Register Assembly="Microsoft.Web.Preview"
Namespace="Microsoft.Web.Preview.UI.Controls" TagPrefix="asp" %>

Alternatively, you can register the control prefix in your web.config file so that it automatically applies to all pages:

<?xml version="1.0"?>
<configuration>
 ...
<system.web>
<pages>
<controls>
<add tagPrefix="asp" namespace="Microsoft.Web.Preview.UI.Controls"
assembly="Microsoft.Web.Preview" />
 ...
</controls>
</pages>
 ...
</system.web>
 ...
</configuration>

Rather than adding the assembly reference and editing the web.config file by hand, you can use a Visual Studio website template. Choose File -> New -> Web Site and select ASP.NET Futures Web Site.

When you take this approach, you'll end up with many more new settings in the web.config file, which are added to enable other ASP.NET Futures features that aren't related to Silverlight. Once you've finished these configuration steps, you're ready to place the Xaml and Media controls in a web page. You'll need to type the markup for these controls by hand, as they won't appear in the Toolbox. (You could add them to the Toolbox, but it's probably not worth the effort considering that there are likely to be newer builds of ASP.NET Futures in the near future.)

The Xaml Control

As you learned earlier, the HTML entry page creates a Silverlight content region using a <div> placeholder and a small snippet of JavaScript code. There's no reason you can't duplicate the same approach to place a Silverlight content region in an ASP.NET web form. However, there's a shortcut that you can use. Rather than creating the <div≫ tag and adding the JavaScript code by hand, you can use the Xaml control.

The Xaml control uses essentially the same technique as the HTML entry page you saw earlier. It renders a <div> tag and adds the JavaScript (using an instance of the ScriptManager control. The advantage is that you specify the XAML page you want to use (and configure a few additional details) using properties on the server side. That gives you a slightly simpler model to work with, and an easy way to vary these details dynamically (for example, choose a different XAML page based on server-side information, like the identity of the current user).

Here's the ASP.NET markup you'd use to show a XAML file named Page.xaml:

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Xaml XamlUrl="~/Page.xaml" runat="server"></asp:Xaml>
</form>

You can set a number of properties on the Xaml control to configure how the Silverlight content region will be created, including Height, Width, MinimumSilverlightVersion, SilverlightBackColor, and EnableHtmlAccess. You can also attach the Xaml control to two JavaScript functions. Set OnClientXamlError with the name of a JavaScript function that will be triggered if the Silverlight XAML can't be loaded, and set OnClientXamlLoaded with the name of the JavaScript function that will be triggered if the Silverlight content region is created successfully.

You also need to add the XAML page to your website. Unfortunately, the current build of ASP.NET Futures doesn't include a XAML template for Silverlight 1.1 content. Instead, it includes a XAML template for Silverlight 1.0 content, complete with a JavaScript code-behind file. (This choice was made for compatibility with Silverlight 1.0, which doesn't support client-side C# and the scaled-down CLR.) The easiest way to use Silverlight 1.1 content with the Xaml control is to create your XAML pages in a dedicated Silverlight project. You can then copy the XAML files and the ClientBin folder to your ASP.NET website. This extra work isn't the result of a technical limitation -- it's simply a limitation of pre-release software.

The Media Control

The Media web control gives you a server-side abstraction over the MediaElement class from Silverlight. The obvious question is, "When should you use the MediaElement, and when should you prefer the server-side Media web control?" They both amount to the same thing -- after all, the server-side Media web control renders a MediaElement,s although it requires slightly more work on the server to do so. The primary advantage to using the Media web control is that you have the chance to set some of its properties using server-side code. For example, you could set the media URL based on information from a database and even extract it through data binding.

Here's an example of how you might define the Media control:

<asp:Media runat="server" ID="Media1"
AutoPlay="true" MediaUrl="MyVideoFile.wmv"
SilverlightBackColor="blue" MediaSkin="Professional"
Height="240" Width="320" />

This creates a Silverlight control with a media player in it, as shown in Figure 1.

[Click image to view at full size]
Figure 1: The Silverlight media player

The media player attempts to access the MyViewFile.wmv file, and begins playing it immediately. In order to streamline the video playback experience, the media player downloads and buffers small chunks of video data as it plays. Best of all, the Silverlight media player works without requiring Windows Media Player. It's more lightweight and performant, and the user interface (playback buttons, skin, and so on) is more customizable.

To get the most out of Silverlight's media playing ability, you need to take a closer look at the properties provided by the Media control. Table 1 lists some of the most important.

MediaUrl Identifies the location of the media file. You can use .wma, .wmv, .mp3 and .asx file types. You can specify a relative path for a file on your web server, or you can supply a full URL that points to another location.
AutoPlay Sets whether playback starts immediately when the page is initialized. The default is false, which means the user will need to use the playback controls to initiate playback.
AutoScale Sets whether the XAML should be resized to fit the player size. The default is true.
LoopCount Sets the number of times to loop (repeat) the media file. Use a value of 0 to loop the media file continuously.
MediaSkin Specifies the "skin" that determines the appearance of the media player. The media player includes several built-in skins that include different graphics, colors, and animated effects. Each skin is defined in a XAML resource that's embedded in the Silverlight assemblies. Skins are defined by the MediaSkin enumeration and include AudioGray, Basic, Blitz, Classic, Expression, Game, Professional, and Simple. PlaceholderImageUrl Specifies a URL to a placeholder image that will be shown while the media file is being opened. Once the media file is opened, this image is replaced with the first frame of your video.
Volume Sets the volume as a value between 0 (silent) and 1 (the maximum volume).
Muted Determines whether the audio should be muted initially. The default is false.
StartTime Specifies a location in the media file (as an offset in seconds) where playback should start. By default, playback starts at the beginning of the file.
Duration Sets the number of seconds that media should play before stopping. By default, the entire media file is played.
Table 1: Properties of the Media Web Control

There are several more features of the Media control that aren't covered here:

You can also set various OnXxx properties (like OnClientMediaEnded and OnClientMediaFailed) to trigger a JavaScript function when a specific event happens in the media player. For information about these more advanced tasks, refer to http://quickstarts.asp.net/Futures/Silverlight/media.aspx.

Communicating Between Silverlight and ASP.NET

If your website includes ASP.NET code and Silverlight content, you may want to pass some information from one side to another. There are several ways that you can allow this sort of interaction. Here are two simple approaches:

Both of these techniques allow you to send information as you switch from the client side to the server side, and vice versa. For example, if your Silverlight control calls HtmlPage.Submit(), the entire page is posted back, the Silverlight application ends, and the ASP.NET objects are created. If you want the user to perform another action with your Silverlight application, you need to return a new page with the Silverlight content. Then, the Silverlight control needs to be created and initialized all over again.

Another option is to allow a long-running Silverlight application to trigger some server-side code without actually posting back the page. That way, the application continues running. The easiest way to do this is to have your Silverlight application call an ASP.NET web service, just as you would with an ASP.NET AJAX page. The development model is quite convenient -- when you add a web reference to your web service in the Silverlight project, Visual Studio generates the proxy class you need to call the web service. You simply need to instantiate the proxy class and call its methods, just as you would in a full-fledged .NET application that calls a web service.

Terms of Service | Privacy Statement | Copyright © 2024 UBM Tech, All rights reserved.