Silverlight 2 Unleashed

Laurent Bugnion

SAMS
800 East 96th Street, Indianapolis, Indiana 46290.

Silverlight 2 Unleashed

Trademarks

All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

Warning and Disclaimer

Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book.

Bulk Sales

Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact

U.S. Corporate and Government Sales
1-800-382-3419
[email protected]

For sales outside of the U.S., please contact

International Sales
[email protected]

Editor-in-Chief
Karen Gettman

Executive Editor
Neil Rowe

Development Editor
Mark Renfrow

Managing Editor
Patrick Kanouse

Project Editor
Mandie Frank

Copy Editor
Geneil Breeze

Indexers
Tim Wright
Brad Herriman

Proofreader
Deborah Williams

Technical Editors
J. Boyd Nolan
Martha Rotter

Publishing Coordinator
Cindy Teeters

Designer
Gary Adair

Compositor
Bronkella Publishing, LLC

Contents at a Glance

Introduction

  1    Introducing Silverlight

  2    Understanding XAML

  3    Playing with XAML Transforms and Animations

  4    Expression Blend

  5    Using Media

  6    Blending a Little More

  7    Deploying to a Web Page

  8    Programming Silverlight with JavaScript

  9    Understanding .NET

10    Progressing with .NET

11    Progressing with Animations

12    Encoding Videos with Expression Encoder

13    Progressing with Videos

14    Letting .NET and JavaScript Talk

15    Digging into Silverlight Elements

16    Digging Deeper Into Silverlight Elements

17    Using Resources, Styling, and Templating

18    Data Binding and Using Data Controls

19    Creating User Controls and Custom Controls

20    Taking Silverlight 2 One Step Further

21    Taking Silverlight 2 Even Further

22    Connecting to the Web

23    Placing Cross-domain Requests and Handling Exceptions

24    Silverlight: Continuing the Journey

Index

Table of Contents

Introduction

About Code in This Book

One Year Older

  1    Introducing Silverlight

Where Does Silverlight Come From?

Automating Web Pages with JavaScript

Cascading Style Sheets

Progressing to DHTML

Communicating in a Richer Way with AJAX

Using Third-Party Plug-Ins

Using Java Applets

Using ActiveX Controls

Using Flash Applications

Running on Multiple Platforms

Making the Web Application Secure

Introducing Silverlight.net

What Do You Need to Run Silverlight?

Updating Your Runtime—Automatically

Trying Silverlight Demos

Playing Chess Against Silverlight

Planning Your Trips with the Airline Application

DeepZooming into the Hard Rock Café

Finding More Demos

What Do You Need to Develop Silverlight?

Expression Studio

Visual Studio 2008

Reading the Documentation

Browsing the Online Reference

Finding More Documentation

Learning with Tutorials

Looking into Silverlight’s Future

Is ASP.NET/HTML/JavaScript Dead?

Summary

  2    Understanding XAML

Using XML for Data

Using XML for User Interfaces

Understanding XML Namespaces

Defining Additional Namespaces

Creating a Canvas with Children

Attaching Properties: Canvas.LeftandCanvas.Top

Documenting Your Markup with XML Comments

Testing XAML Markup

Using SilverlightPad

Using KaXaml

Setting Properties in XAML

Changing Brushes

Composing Scenes in XAML

Saving Typing, Saving Space

Summary

  3    Playing with XAML Transforms and Animations

Transforming Visuals

Types of Transforms

RotateTransform

TranslateTransform

ScaleTransform

SkewTransform

MatrixTransform

Composing Transforms

Creating a Basic Animation

Understanding the Animation’s Elements

Adding a Scale Animation

Using Other Types of Animations

Navigating the Property Path

Deploying the Scene to a Web Page

Summary

  4    Expression Blend

The Expression Studio in Short

Installing Expression Blend

Starting Expression Blend

Setting Options

Creating a New Project

Understanding the Panels

Looking at the Files

Executing in the Web Browser

Working with Shapes

Using the Properties Panel

Using the Color Picker

Creating a LinearGradientBrush

Changing the Gradient Vector

Creating a RadialGradientBrush

Creating a 3D Border Effect Using RadialGradientBrush

Resetting Properties to Their Default Value

Composing the Elements Hierarchy

Summary

  5    Using Media

Mixing Colors

Why FF?

Seeing Through the Transparency Channel

Seeing Through the Opacity

Using Vector Graphics

Adding Media to Your Scenes

Laying Out the Application

Adding Pictures

Adding Video

Testing the Result Quickly in a Web Browser

Refining the Layout

Adding Yet Another Image

Controlling Sound and Video

Switching Auto-Play Off

Creating an Endless Loop

Pausing and Playing the Video

Setting a “Hand” Cursor

Checking the Other Properties

Filling the Space

Hiding the Media from Mouse Input

Using Media to Write

Writing with Video

Writing with Images

Transforming Media

Using Web-Based Media

Summary

  6    Blending a Little More

Creating Transforms

Creating an OpacityMask

Using Paths

Creating a Path from Scratch

Using Splines to Modify a Path

Combining Shapes

Clipping Path

Paths in XAML

Grouping Controls

Grouping Elements

Trying Other Panels

Scrolling the Thumbnails

Making a User Control

Creating a User Control

Using the User Control

Working on the Thumbnails Gallery

Adding a Display Frame

Adding a Reflection under the Thumbnails

Reflecting Video

Just One Last Thing

Summary

  7    Deploying to a Web Page

Creating a Test Page

Understanding the object Tag

Attributes

Parameters

Modifying the Attributes and Parameters

Deploying with JavaScript

Detecting Silverlight

Integrating Silverlight in an Existing Web Page

Understanding the Original Code

Getting the XAP file

Modifying the Markup

Testing the Result

Referencing a XAP on Another Web Server

Getting Web Space

Web Server Requirements

Finding a Provider

Getting Started with FTP

Setting Up an FTP Client

Connecting to Your Server

Copying Your Silverlight Application

Testing Your Work

Summary

  8    Programming Silverlight with JavaScript

Learning the Basics

Comments

Semicolons

Case Sensitivity

Variables

Functions

Prototype, this, new

Types

Built-In Objects and Libraries

alert

undefined

null

Handling Events

Understanding the Concept of Objects

Interfacing with Other Instances

Storing Stuff Globally

Using the Literal Notation JSON

Creating Objects with JSON

Static Members

Loading Scripts in a Web Page

Understanding the Context

Integrating Silverlight in an Existing Web Page Using JavaScript

Finding Silverlight.js

Using Silverlight.js

Detecting Silverlight Versions

Detecting JavaScript

Modifying the Web Page During Runtime

Debugging

Summary

  9    Understanding .NET

History of .NET

Versions, Versions, Versions

Managed Versus Unmanaged

Downloading and Installing Visual Studio 2008

Creating a Silverlight 2 Application in Visual Studio 2008

Building and Running the Application

Finding Compilation Errors

Exploring the Files

Running the (Empty) Application

Intellisense

Programming C# with Basic Constructs

Types

Type Conversion

if then else

for

foreach

while

do…while

switch…case

Operators

Summary

10    Progressing with .NET

Programming with Objects in C#

Breaking Your Problem into Smaller Ones

Namespaces and the using Directive

Visibility

Properties

Inheritance

Adding Interactivity to the Thumbnails Application

Adding Event Handlers in Code

Displaying the Expanded Media

Overloading Methods

Raising Events and Using Delegates

Creating an EventArgs

Declaring the Event

Subscribing to the Event

Storing Data on the Client

Understanding the Isolated Storage Security Restrictions

Creating Objects

Reading from the Isolated Storage

Writing to the Isolated Storage

Updating the User Interface

Multibrowser Compatibility

Summary

11    Progressing with Animations

Animating Elements in Blend

Testing the Application

Editing the Animation’s Properties

Easing In and Out

Synchronizing Animations

Understanding the Animation Elements

Reversing a Storyboard

PointAnimation

Starting and Stopping the Animation

Working on the Thumbnails Gallery

Making a Scenario

Setting the Stage

Making the Draft Animation

Easing the Translate Animation

Triggering the Animation in Code

Creating the “Fading” Animation in Code

Summary

12    Encoding Videos with Expression Encoder

Before We Start…

Introducing Expression Encoder

Setting Options

Understanding the Panels

Importing a Video

Saving your Changes

Specifying the Output Type

Editing the Video Size and Aspect

Advanced Processing and Codec Settings

Adding a Leader and Trailer Video

Testing Before Encoding

Setting Metadata

Adding Your Own Metainformation

Creating Chapters

Creating Captions

Encoding the Video for Silverlight

Checking the Result

Playing the Video in Full Screen

Advanced Parameters

Summary

13    Progressing with Videos

Why Streaming?

Publishing on Your Own Website

Copying the Files

Adding an Overlay

Adding an Icon or a Video

Setting Advanced Properties

Adding an XAML Overlay

Letting Your Users Choose the Player

Copying the Files

Modifying the Files

Creating the Video

How Does It Work?

Publishing on Microsoft Silverlight Streaming Servers

Signing Up

Installing, Setting Up the Plug-in, Publishing

Testing the Output

Adding the Application in an Existing Web Page

Using an iframe

Using JavaScript and a Live Control

Firing Script Commands (and Catching Them)

Modifying the Player Template in Blend

Adding a Full Screen Button

Handling the Event in Script

Testing the Result

Summary

14    Letting .NET and JavaScript Talk

Making .NET Available to JavaScript

Using the ScriptableMember Attribute

Registering the Object

Handling .NET Events in JavaScript

Preparing the scriptable Class

Raising the Event

Subscribing to the Event on the JavaScript Side

Testing the Code

Calling JavaScript Methods from .NET

Calling .NET Methods from JavaScript

Adding a “Login” Dialog to the Thumbnails Application

Extending the User Object

Handling Multiple Users

Modifying the Page Class

Adding a “Login” Label

Adding a Web Project

Checking the Media Files’ Build Action

Adding the HTML Login Dialog

Blending the Silverlight Application with HTML

Catching the .NET Event

Wiring Up the Scripts

Handling the HTML Events

Summary

15    Digging into Silverlight Elements

Exploring the Class Hierarchy

Exploring the Object

Exploring the DependencyObject

Exploring the UIElement

Exploring the FrameworkElement

Choosing XAML or Code-Behind

Packing and Laying out with Panels

Composing Elements

Discovering the Canvas

Using a Canvas to Drag an Element

Stacking Elements in a StackPanel

Using a StackPanel for “Flow Layout”

Using a Grid to Align Elements

Setting Up a Minimum and Maximum Size

Adding Elements to a Grid

Adding Elements to a Grid in Code-Behind

Scrolling and Bordering

Using a ScrollViewer to Scroll Big Areas

Surrounding an Element with a Border

Using Pop-Ups

Drawing Shapes

The Data Property

Summary

16    Digging Deeper into Silverlight Elements

Understanding the Control Class

Enabling and Disabling Controls

Styling and Templating Controls

About Fonts

Discovering Basic Controls

Presenting and Inputting Text

Discovering the ButtonBase

Scrolling and Dragging

Presenting Media

Picking Dates with Calendar and DatePicker

Using the Calendar

Using the DatePicker

Catching Errors

Writing with Ink

Making a Simple Drawing Application

Preparing the Scene

Handling the Events

Running the Application

Presenting Data with ItemsControls

Using the TabControl

Deep Zooming Your Image Collection

How Does It Work?

Creating a DeepZoom Image Pyramid

The MultiScaleImage Control

Summary

17    Using Resources, Styling, and Templating

Storing Items in Collections

Implementing Interfaces

Using ResourceDictionaries in Silverlight

Storing Resources

Using Resources in Code-Behind

What’s the Point Anyway?

Using Resources in XAML

Storing Resources in App.xaml

Styling a Control

Creating a Style

Using a Style

Priority of Property Setters

Creating a Style in Blend

Editing a Style in Blend

Styling the Thumbnails Application

Styling the TextBlocks

Styling the Thumbnails

Moving Resources in Blend

Embedding Fonts in the Application

Embedding a Font in Blend

Embedding a Font in Visual Studio

Templating the Lookless Control

But the Control Has a Look!

Editing the Template

Modifying the States

Binding the Template to the Control

Presenting Content

Summary

18    Data Binding and Using Data Controls

Understanding Data Binding

Creating a Data Object

Creating the Data Object in Resources

Writing to the Data Object with a Binding

Getting Notified, Finding Binding Errors

Converting Values in Bindings

Digging in the Binding Class

Setting the DataContext

Using Data Controls

Using a ListBox

Using the DataGrid

Using XML Data Sources

Summary

19    Creating User Controls and Custom Controls

Creating a Thumbnails Viewer User Control

Creating the Data Objects

Packing the ThumbnailsViewerControl

Communicating with the Outside World

Creating the Items and Designing a DataTemplate

Creating the Media Instances in XAML

Designing a DataTemplate

Removing the Test Data Source

Moving the Media Files

Connecting the ThumbnailsViewer to the Real Data

Raising and Handling the SelectionChanged Event

Creating a MediaInfoDisplay Custom Control

Making a Blueprint

Creating the “Shell”

Handling the States

Handling the Part

Applying the Template

Summary

20    Taking Silverlight 2 One Step Further

Creating a Default Template for the MediaInfoDisplay Control

Using the MediaInfoDisplay Control

Adding Test Data

Adding the Control to the Scene

Creating a Template

Making Transitions

Removing the Test Data

Wiring Up

Digging Deeper

Scrolling the Items

Creating a New RepeatButton Template

Creating the Template

Changing the Transitions

Binding the Template

Testing the New Button

Styling the RepeatButton

Styling the Other Button

Exporting Classes to an External Assembly and Refactoring

Creating a Silverlight Class Library

Using an External Class Library

Talking About the Application Object

Using Generics

Summary

21    Taking Silverlight 2 Even Further

Registering Multiple JavaScript Event Handlers

Finding Silverlight Elements in JavaScript

Accessing the HTML Page From .NET

Exchanging Data Between .NET and JavaScript

Attempting Conversion

Passing Standard Formats

Converting the ScriptObject Class

Passing Initialization Parameters

Setting Initialization Parameters

Retrieving Initialization Parameters

Attaching .NET Events to HTML Elements

Using the HtmlEventArgs Class

Publishing Directly from Visual Studio

Debugging Your Silverlight Application

Comparing Debug Version and Release Version

Creating the Release Version

Stepping Through the Code

Inspecting and Modifying Variables

Debugging in a Web Site Project

Debugging JavaScript

Debugging Running Applications

Debugging Silverlight Running on a Macintosh

Summary

22    Connecting to the Web

Creating and Loading an XML File

Removing the Media Information from the Application

Showing and Hiding a Startup Screen

Loading the XML Media Information File

Sending the Request

Getting a Response

Reading an XML File with LINQ

Parsing Enums

Triggering the Request

Handling the Results

Testing the Application

Loading a Zip File and Showing Progress

Creating the Zip File

Extending the MediaEx Class to Store the Stream

Loading the Zip File

Reading the Zipped Files

Updating the UI

Making Requests to WCF Services

Moving the User and DataFile Classes to the Server

Changing the DataFile to Run on the Server

Creating the WCF Service

Implementing the Service

Updating the Client Application

More Connectivity

Summary

23    Placing Cross-domain Requests and Handling Exceptions

Placing Cross-domain Requests

Using the Flash Cross-domain Policy File

Using the Silverlight Cross-domain Policy File

Understanding the Restrictions

Communicating with Third-Party Services

Accepting the Flickr Terms of Services

Getting a Flickr API Key

Preparing and Sending the Request

Handling the Response

Updating the UI

Placing POST Requests

Throwing and Catching Exceptions

Bubbling Exceptions

Understanding an Exception’s Properties

Catching Unhandled Exceptions

Creating Custom Exceptions

Handling Silverlight Errors in JavaScript

Summary

24    Silverlight: Continuing the Journey

Updating a Service Reference

Killing a Process

Killing the Process in Debug Mode

About Protecting Your Work

Protecting Your Work Anyway

Binding in Special Configurations

Setting a Binding in Blend

Handling Validation Errors

Binding Through a Converter, ConverterParameter, ConverterCulture

Binding to an Object Rather Than a Property

Using the ASP.NET Controls Silverlight and MediaPlayer

Using the Silverlight ASP.NET Control

Using the MediaPlayer ASP.NET Control

Creating Unit Tests for Silverlight

Installing the Silverlight Unit Test Framework

Creating a New Silverlight Test Application

Creating the TryFindResource Extension Method

Making the Test Pass

Implementing Recursion

Learning More About Unit Test

Reusing Microsoft Unit Tests

Making or Buying XAML Resources

Using Expression Design

Finding XAML Resources Online

Converting Files to XAML

Using Third-Party Controls and Libraries

Reading Silverlight-Related Blogs

Summary

Index

Foreword

There are two undeniable trends in the software development world. The first is toward web style deployment of applications. The web is quickly maturing as an application delivery platform, and increasingly, web applications are seen as the right solution for many styles of applications. The second is toward richness of applications. User experience is becoming increasingly important; consumer-facing applications attracting and retaining users has never been harder and even small usability improvements often make the difference. In business applications, CIOs are realizing that if they can save even a few seconds on every transaction by making employees more effective they can save millions of dollars.

Not surprisingly, Silverlight 2 sits squarely in this sweetspot.

Silverlight 2 is a web application technology. The Silverlight runtime itself is smaller than the average Britney Spears song and is seamless to install on any browser (Internet Explorer, Firefox, Safari, and so on) and on any platform (Windows, Mac, Linux). Silverlight applications are small and fast to deploy and have zero impact on the client machine. There is no install or uninstall step for Silverlight applications, and all these applications run in a sandbox that ensure they cannot harm user machines or other applications.

Silverlight 2 enables building great user experiences. Through the power of the convergence around video, vector graphics and a powerful developer framework, Silverlight is the ideal platform for UX. Developers have full expressiveness with the power of the CLR under the hood in Silverlight. The C# and VB languages allow developers to be productive today without learning new languages and development tools. The XAML markup allows designers to use Expression and other design tools to build great transitions and animations so that applications look and feel great. All of this together enables Silverlight applications to deliver more productive experiences to end users helping them get their jobs done faster.

This book unleashes Silverlight for you. Laurent not only has a deep understanding of Silverlight, where it is now and where it is going, but he also deeply understands real world programming concerns. This book will make learning Silverlight fun.

I can’t wait to see what you build with it.

Brad Abrams
Product Unit Manager
Microsoft Corporation
http://blogs.msdn.com/brada

September 2008

About the Author

Laurent Bugnion works as a senior software developer and architect in Switzerland, where he lives with his wife, Chi Meei, and his two daughters, Alise (2001) and Laeticia (2004). Originally an electronics engineer from the Engineering School of Yverdon (Switzerland), his interests quickly moved to software, and he achieved a post-graduate degree in software engineering in 1999 in the Engineering School of Rapperswil (Switzerland).

Currently, his interests are very much set on WPF, Silverlight, and other .NET 3.5 technologies, which he helped introduce, teach, and coach at Siemens for the past three years. Prior to that, he first wrote embedded C/C++, and then moved to desktop computers in Java, JavaScript, and eventually .NET (WinForms and ASP.NET). After more than 12 years spent developing various software products at Siemens, Laurent is employed since December 2008 by IdentityMine, one of the world’s leading firms in WPF and Silverlight development and design.

Privately, Laurent has also been active, developing websites and web applications in HTML, JavaScript, CSS, ASP, and currently ASP.NET. He has done his best to contribute to various developers communities, first in the JavaScript newsgroups, and then in Microsoft’s forums related to ASP.NET, C#, WPF, and Silverlight. He blogs regularly on http://blog.galasoft.ch and publishes articles, prototypes, and demos related to the mentioned technologies.

Laurent became a Microsoft Most Valuable Professional (MVP) in 2007 for ASP.NET and then in 2008 for Client Application Development. In 2008, he also earned an MCTS for Windows Presentation Foundation.

Dedication

How to write this book without your never-ending, ever patient
support
, Chi Meei… This was once again a crazy project, and I
couldn’t have done it without your approval and your help
. By your
constant support and the energy and dedication you put into shielding
me from the small worries of life
, you made this book possible.
I love you.

To Alise and Laeticia, my two princesses. Before you appeared in my
life
, I thought I was happy. Now I know something big was missing.
I love you both so much
.

Un jour sans danser est un jour perdu
Maurice Béjart

Je ne sais pas ce qui est beau, mais je sais ce que j’aime
et je trouve Ça amplement suffisant
.
Boris Vian

Le Poète est semblable au prince des nuées
Qui hante la tempête et se rit de l’archer;
Exilé sur le sol au milieu des huées,
Ses ailes de géant l’empêchent de marcher
.
Baudelaire – L’Albatros

Acknowledgments

A book about a to-be-released technology cannot be written without strong support from the community, both within Microsoft and outside it. Making a complete list of all the people who encouraged me and helped me in this daunting task is impossible, but I want to mention and thank some people (and for some of them, friends) explicitly (and in no particular order):

Image At Microsoft: Scott Guthrie, Tim Sneath, Ian Ellison-Taylor, Brad Abrams, Rob Relyea, Tim Heuer, Adam Kinney, Peter Blois, Unni Ravindranathan, Joe Stegman, Mike Harsh, Karen Corby, Kathy Kam, Corrina Barber, Beatriz Costa, James Clarke, John Gossmann, Karsten Januszewski, Adam Nathan, Christian Schormann, Mark Feinholz, Ted Hu, Jeff Wilcox, Justin Angel, and many others from the Dev Div, for building the stuff my dreams are made of (and for writing about it!). I’ve seen the “new Microsoft” at work, and I like it!

Image In the Silverlight and WPF community: Josh Smith, Jonathan Russ, Brennon Williams, Karl Shifflett, Marlon Grech, Corrado Cavalli, Grant Hinkson, Nathan Dunlap, Josh Wagoner, Robby Ingebretsen, Kevin Moore, Shawn Wildermuth, Dave Campbell, Jon Galloway, Grant Hinkson, John Papa, and all the WPF Disciples for teaching me all I know (or so it feels).

Image The team at Sams and especially Neil Rowe, Mark Renfrow, Mandie Frank, and Geneil Breeze for their patience and support for this first-time author.

Image The whole MVP community and especially the Client Application Development members, for welcoming me and making me feel worth it.

Image All my friends, online and offline, who had to bear with me being either working on the book or talking about the book or thinking about the book or, you know, sleeping (and probably dreaming about the book).

A very special thanks to Brennon Williams who gave me such invaluable comments and advice; to J. Boyd Nolan for reviewing and editing, and for converting this book’s examples from C# in VB.NET; to Adam Nathan who advised me about the book’s outline before I even started writing it; to Shawn Wildermuth for pulling me out of many a technical hole; to Peter Blois for listening patiently to my bug reports and proposing solutions; to Tim Heuer and Adam Kinney, for clearly showing that Silverlight is more than just a job to them; to all the Silverlight Insiders for the always interesting and often life-saving discussions.

Software engineering is a passion. To all of you whom I learn from everyday, and to whom I try to teach a little through my blog, my site, or in conferences, thank you for making this more than a job: a way of life.

We Want to Hear from You!

As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way.

You can email or write me directly to let me know what you did or didn’t like about this book—as well as what we can do to make our books stronger.

Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message.

When you write, please be sure to include this book’s title and author as well as your name and phone or email address. I will carefully review your comments and share them with the author and editors who worked on the book.

E-mail: [email protected]

Mail:     Neil Rowe
            Executive Editor
            Sams Publishing
            800 East 96th Street
            Indianapolis, IN 46240 USA

Reader Services

Visit our website and register this book at www.informit.com/title/9789780768685824 for convenient access to any updates, downloads, or errata that might be available for this book.

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

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