Chapter 10
Designing Silverlight Applications

Key Skills & Concepts

image Start a New Silverlight Project

image Work with the Silverlight Designer

image Add Controls to an Application

image Play Silverlight Videos

image Deploy Silverlight Applications

Silverlight is a Web technology that allows you to add a rich user experience to Web applications. It uses XAML, just like WPF applications, but runs in a Web page supported by ASP.NET.

Other parts of this book prepare you for working with Silverlight. Since Silverlight uses XAML, you can review Appendixes A and B to get up-to-speed on XAML essentials. Silverlight also has many features in common with WPF. Therefore, it would be useful to review Chapter 8 before reading this chapter. What you’ll learn in this chapter is how VS helps you create a Silverlight project, how to add controls to the Silverlight designer, and how to deploy Silverlight applications.

Starting a Silverlight Project

As when starting other projects, you can select File | New | Project or press CTRL-SHIFT-N; you then select a Silverlight application in the New Project window. After you set up the project with a name and folder, VS will display another window for configuring the Silverlight application, shown in Figure 10-1.

Silverlight gives you the option to create a Web site at the same time as you create the Silverlight application. You can opt not to create the Web site, but ultimately, you’ll need to host your Silverlight application on a Web page. There is an alternate Web technology based on ASP.NET Web forms, but this book concentrates on the ASP.NET MVC Web development model, discussed in Chapter 9, which is why you see the New Web project type set to ASP.NET MVC Web Project. Click OK to create the Silverlight application, shown in Figure 10-2. You’ll also see a screen asking if you want to create a unit test project, which is the same window discussed in Chapter 9. Click OK to continue.

image

Figure 10-1 Creating a new Silverlight application

image

Figure 10-2 A new Silverlight project

Similar to WPF applications, Silverlight applications start with a MainPage.xaml file and an App.xaml file, where App.xaml runs to initialize the application and MainPage.xaml contains the display page. The Web site is a typical ASP.NET MVC application, except that it does have a test page that hosts the Silverlight application, SilverlightDemo CSTestPage.aspx (SilverlightDemoVBTestPage.aspx for VB). There’s also a Silverlight DemoCSTestPage.html (SilverlightDemoVBTestPage.html for VB), which performs the same function as the SilverlightDemoCSTestPage.aspx (SilverlightDemoVBTestPage.aspx for VB) hosting Silverlight, except that the *.html version uses JavaScript and the HTML object tag to host Silverlight. Listing 10-1 shows the contents of the test page and how it hosts the Silverlight application. There is no C# or VB version of Listing 10-1 because the code is XAML, which works exactly the same with either language.

Listing 10-1 Hosting a Silverlight application on a Web page

<%@ Page Language="C#" AutoEventWireup="true" %>

<!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>SilverlightDemoCS</title>
    <style type="text/css">
    // css styles omitted
    </style>
    <script type="text/javascript" src="Silverlight.js"></script>
    <script type="text/javascript">
        function onSilverlightError(sender, args) {
            // error handling code omitted
        }
    </script>
</head>
<body>
<form id="form1" runat="server" style="height:100%">
<div id="silverlightControlHost">
    <object data="data:application/x-silverlight-2,"
            type="application/x-silverlight-2"
            width="100%" height="100%">
        <param name="source"
               value="ClientBin/SilverlightDemoCS.xap"/>
        <param name="onError" value="onSilverlightError" />
        <param name="background" value="white" />
        <param name="minRuntimeVersion" value="3.0.40818.0" />
        <param name="autoUpgrade" value="true" />
        <a
href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40818.0"
style="text-decoration:none">
          <img src="http://go.microsoft.com/fwlink/?LinkId=161376"
               alt="Get Microsoft Silverlight"
               style="border-style:none"/>
        </a>
     </object>
    <iframe id="_sl_historyFrame"
            style="visibility:hidden;height:0px;width:0px;border:0px">
    </iframe>
</div>
</form>
</body>
</html>

Listing 10-1 contains an object tag that hosts the Silverlight application. This object tag has various parameters, which are described in Table 10-1.

You can run the application and view the Web page, but there isn’t much to see yet. The next section starts you in the direction of making something useful happen with Silverlight by reviewing the Designer.

image

Table 10-1 Object Tag Parameters for Silverlight

Navigating the Silverlight Designer

The underlying technology for displaying the UI is XML Application Markup Language (XAML), pronounced “Zamel.” Appendix A contains an introduction to XML, and Appendix B contains an introduction to XAML if you need to obtain a basic understanding of these two technologies. It would really be helpful for you to review Chapter 8 because you’ll find many of the same controls for layout and display in both Silverlight and WPF.

The Silverlight Designer is very similar to the WPF Designer in how you work with controls. Drag and drop from the Toolbox, configure Grids, interact with XAML, and set properties in exactly the same way with Silverlight as with WPF. Since there are so many similarities, I won’t repeat the material covered in Chapter 8 but will build upon previous material, showing you what is special about Silverlight.

Using Silverlight Controls

Silverlight has strong multimedia support through streaming audio and video. In fact, the Toolbox has controls that make it easy to host your own videos and control the user experience for playing videos. The following steps show how to design a screen that shows a video, as shown in Figure 10-3.

1. Your project starts out with a page named MainPage.xaml, which you should open so the designer is showing. If the XAML editor is showing, click on the Design tab at the bottom of the designer window.

2. You’ll have a default Grid, which you can work with in exactly the same way as the designer for WPF, discussed in Chapter 8. You need to ensure the Grid has two rows, with the top row being large enough to fit the MediaElement and the bottom large enough to fit a single button. Hover over the left margin of the window until you see a grid line appear on the window. Move the grid line vertically until you’ve created two rows, where the bottom row is large enough to hold a button, as shown in Figure 10-3. Click on the window margin when you have the grid line positioned where you want.

3. Find the MediaElement in the Toolbox and drag it onto the top row of the Window in the designer. If you find that you haven’t made the top row large enough, grab the grid line arrow in the left margin and drag it down some more.

4. Set the Name property of the MediaElement control to VideoPlayer.

5. The MediaElement control has a Source property that you can set with the URL of a movie. Set the Source property of the MediaElement control to http://mschnlnine .vo.llnwd.net/d1/ch9/8/3/7/0/7/4/OfficeVS10SC1_2MB_ch9.wmv, which is a video that introduces VS 2010.

6. Drag a Button from the Toolbox to the bottom row of the Window in the designer.

7. Set the Name property of the Button to StartStopButton and set the Content property of the Button to Start.

In Figure 10-3, you can see a Grid with two rows. The top row holds a MediaElement control and the bottom row holds a button. The name of the Video control is VideoPlayer and the name of the button is StartStopButton.

image

Figure 10-3 Playing Silverlight videos

Double-clicking the StartStopButton control will generate this Click event handler in the code-behind at MainPage.xaml.cs, shown in Listing 10-2.

Listing 10-2 Playing and stopping a video

C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightDemoCS
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            VideoPlayer.AutoPlay = false;
        }

        private bool m_isPlaying = false;

        private void StartStopButton_Click(
            object sender, RoutedEventArgs e)
        {
            if (m_isPlaying)
            {
                VideoPlayer.Stop();
                StartStopButton.Content = "Start";
                m_isPlaying = false;
            }
            else
            {
                VideoPlayer.Play();
                StartStopButton.Content = "Stop";
                m_isPlaying = true;
            }
        }
    }
}

VB:

Partial Public Class MainPage
    Inherits UserControl

    Public Sub New()
        InitializeComponent()
        VideoPlayer.AutoPlay = False
    End Sub

    Dim m_isPlaying As Boolean = False

    Private Sub StartStopButton_Click(
        ByVal sender As System.Object,
        ByVal e As System.Windows.RoutedEventArgs)
        If (m_isPlaying) Then
            VideoPlayer.Stop()
            StartStopButton.Content = "Start"
            m_isPlaying = False
        Else
            VideoPlayer.Play()
            StartStopButton.Content = "Stop"
            m_isPlaying = True
        End If
    End Sub
End Class

By default, the MediaElement starts playing the Source video as soon as the application loads, so I set AutoPlay to false in the code-behind constructor. The m_isPlaying field keeps track of whether the MediaElement is playing or not. The Click event handler uses m_isPlaying to toggle between playing and stopped.

This is a quick demo of how to work with the MediaElement control, but there’s much more you can do, such as pausing, tracking buffering, checking video position, and more. All you need to do is either capture events of the MediaElement control or use controls like buttons and sliders to interact with MediaElement, as the example shows in Listing 10-2. It would be good practice for you to take what you’ve learned here and add more functionality to the MediaElement control.

Running Silverlight Out-of-Browser (OOB)

A new capability of Silverlight 3 is running out-of-browser, meaning that users can load your application onto their desktop without needing to visit the hosting site. To implement OOB, open the Silverlight application properties by double-clicking the Properties folder in Solution Explorer. You’ll see a window similar to Figure 10-4.

Most of the properties in Figure 10-4 have been covered in previous chapters. What’s different is the section on Silverlight build options, which allows you to set the version and check the box to reduce the size of the *.xap file through caching. However, leave the option to reduce the *.xap file size unchecked if running OOB because it’s not compatible

image

Figure 10-4 Silverlight properties

image

Figure 10-5 Out-of-browser settings

with OOB. The Manifest file describes the contents of the *.xap file. To enable OOB, check the box “Enable running application out of the browser.” Then click the Out-Of-Browser Settings button to display the window shown in Figure 10-5.

The OOB settings in Figure 10-5 allow you to set information for the application, the size it will take when running, and variously sized icons that Windows will display. Setting GPU acceleration allows the application to take advantage of the local hardware to optimize graphics.

After you save OOB settings and run the application, the user can right-click the application running in the browser and select Install SilverlightDemoCSApplication Onto This Computer, as shown in Figure 10-6.

image

Figure 10-6 Choosing OOB

The next window you’ll see gives options for adding the application to the Start menu and an icon on the desktop. Figure 10-7 shows that both options are checked.

When you click OK, Silverlight creates a Start menu item and adds the application to the desktop, as shown in Figure 10-8. When you start the application, it will run in a window rather than the browser.

image

Figure 10-7 Choosing OOB deployment options

image

Figure 10-8 Executing an OOB application

Deploying Silverlight Applications

You can deploy a Silverlight application to a Web site, as you would an ASP.NET MVC application. However, you’ll need to ensure the MIME type and policy is in place to ensure the application will run outside of your development environment.

If you’re running IIS 7, Silverlight will already be set up. However, if you’re deploying to an IIS 6 server, you must set the MIME type for *.xap files to application/x-silverlight-app as described in the following steps:

1. Open Administrative Tools | Internet Information Services (IIS) Manager.

2. Under Web Sites, in IIS, right-click on the Web site for your Silverlight application and select Properties.

3. Click the HTTP Headers tab, click MIME Types, and click New.

4. Type .xap as the Extension and application/x-silverlight-app as the MIME type.

Click OK three times to close all windows and close IIS.

Additionally, you must have a policy file in the root folder of your Web site. There are two types of policy files you can use: crossdomain.xml or clientaccesspolicy.xml.

The crossdomain.xml policy was created for Adobe Flash applications and can be used with Silverlight applications too. Here’s an example:

<!DOCTYPE cross-domain-policy
  SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <allow-access-from domain="*" />
  <allow-http-request-headers-from domain="*" headers="*" />
</cross-domain-policy>

When designing Silverlight, Microsoft recognized that the crossdomain.xml file wasn’t flexible enough and added support for another type of policy called clientaccesspolicy.xml. Here’s an example:

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-methods="*">"
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

This clientaccesspolicy.xml listing allows all domains to access all site content that isn’t already secured by other means. You can restrict access by replacing the * in the domain uri with an allowable domain. Further, you can replace the resource path with a path on the site to restrict access to specific folders. Add more policy elements to this file to add more domains and paths.

Summary

This chapter explains how to run a Silverlight application. You learned how to use the MediaElement control and how to build UIs using the same techniques as in WPF. The OOB functionality allows you to run Silverlight from your desktop. A section describes deploying the Silverlight application to a Web server.

We’ve discussed a couple Web technologies already: ASP.NET MVC in Chapter 9 and Silverlight in this chapter. The next chapter shows you another Web technology: WCF Web services.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.80.211.101