sams silverlight 4 unleashed

736

Upload: hoang-ngoc-hung

Post on 11-Feb-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/23/2019 Sams Silverlight 4 Unleashed

    1/734

  • 7/23/2019 Sams Silverlight 4 Unleashed

    2/734

    Silverlight 4

    UNLEASHED

    800 East 96th Street, Indianapolis, Indiana 46240 USA

    Laurent Bugnion

  • 7/23/2019 Sams Silverlight 4 Unleashed

    3/734

    Silverlight 4 UnleashedCopyright 2011 by Pearson Education

    All rights reserved. No part of this book shall be reproduced, stored in a retrieval

    system, or transmitted by any means, electronic, mechanical, photocopying, recording,

    or otherwise, without written permission from the publisher. No patent liability isassumed with respect to the use of the information contained herein. Although every

    precaution has been taken in the preparation of this book, the publisher and author

    assume no responsibility for errors or omissions. Nor is any liability assumed for

    damages resulting from the use of the information contained herein.

    ISBN-13: 978-0-672-33336-8

    ISBN-10: 0-672-33336-1

    Library of Congress Cataloging-in-Publication Data

    Bugnion, Laurent.

    Silverlight 4 unleashed / Laurent Bugnion.

    p. cm.

    Includes index.

    ISBN 978-0-672-33336-1

    1. Silverlight (Electronic resource) 2. Multimedia systems. 3. Application software

    Development. 4. Web site development. 5. Internet programming. 6. User interfaces

    (Computer systems) I. Title.

    QA76.575.B839 2011

    006.76dc22

    2010040175

    Printed in the United States on America

    First Printing October 2010

    TrademarksAll 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 ofthis information. Use of a term in this book should not be regarded as affecting the

    validity of any trademark or service mark.

    Warning and DisclaimerEvery effort has been made to make this book as complete and as accurate as possi-

    ble, 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 or from the use of the programs accompanying it.

    Bulk SalesSams 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

    Kristy Hart

    Project Editor

    Andy Beaster

    Copy Editor

    Keith Cline

    IndexerBrad Herriman

    Proofreader

    Jennifer Gallant

    Technical Editor

    Peter Bromberg

    Publishing

    Coordinator

    Cindy Teeters

    Book DesignerGary Adair

    Composition

    Gloria Schurick

  • 7/23/2019 Sams Silverlight 4 Unleashed

    4/734

    Contents at a Glance

    Foreword ....................................................................................................xxiii

    Introduction....................................................................................................1

    1 Three Years of Silverlight ................................................................................7

    2 Setting Up and Discovering Your Environment .........................................27

    3 Extending Your Application with Controls .................................................49

    4 Investigating Existing Controls . .................................................................75

    5 Understanding Dependency Properties .....................................................103

    6 Working with Data: Binding, Grouping, Sorting, and Filtering ...............129

    7 Understanding the Model-View-ViewModel Pattern ................................157

    8 Using Data Controls ..................................................................................187

    9 Connecting to the Web .............................................................................215

    10 Creating Resources, Styles, and Templates . ..............................................247

    11 Mastering Expression Blend ......................................................................273

    12 Sketching User Experience .........................................................................301

    13 Creating Line-of-Business Applications .....................................................329

    14 Enhancing Line-of-Business Applications and

    Running Out of the Browser .....................................................................365

    15 Developing Navigation Applications and Silverlight for

    Windows Phone 7 ......................................................................................401

    16 Using Effects and Recording Media ...........................................................435

    17 New Transforms, Right Click, HTML Browser, WebBrowserBrush, and

    Isolated Storage ...........................................................................................467

    18 Drag and Drop, Full Screen, Clipboard, COM Interop, Duplex Polling,

    Notification Windows, and Splash Screens................................................503

    19 Authentication, Event to Command Binding, Random Animations,

    Multitouch, Local Communication, and Bing Maps Control ...................539

    20 Building Extensible and Maintainable Applications .................................573

    21 Optimizing Performance ...........................................................................609

    22 Advanced Development Techniques . ........................................................641

    Conclusion ..................................................................................................675

    Index ...........................................................................................................677

  • 7/23/2019 Sams Silverlight 4 Unleashed

    5/734

    Table of Contents

    Foreword xxiii

    Introduction 1

    1 Three Years of Silverlight 7

    Discovering Silverlight 4. ...............................................................................7

    Learning Silverlight Is Betting on the Future .......................................8

    How Can They Be So Fast?. ..................................................................9

    How About Compatibility with Older Versions?..................................9

    Cross-Browser and Cross-Platform Compatibility. ......................................10

    Windows and Macintosh ....................................................................11

    Linux. ..................................................................................................12

    Alternatives to Silverlight . ...........................................................................12

    In the Web Browser .............................................................................12

    Out of the Browser . ............................................................................13

    Legacy Technologies . ..........................................................................14

    A Short History of Silverlight . .....................................................................15Silverlight 1.0.......................................................................................16

    Silverlight 2. ........................................................................................16

    Silverlight 3. ........................................................................................16

    And Silverlight 4 ..............................................................................17

    Previewing the Future of Silverlight.............................................................17

    Installing Silverlight 4 as a User ...................................................................18

    Opening a Silverlight 4 Application ...................................................19

    What to Do If Silverlight Is Not Installed? .........................................19

    Exploring Silverlight 4 Demos. ....................................................................19Deep Zooming the Matterhorn...........................................................19

    Getting Involved Socially with Sobees................................................20

    Navigating with Bing Maps Streetside and PhotoSynth.....................21

    Visualizing Information with the Pivot Viewer..................................23

    Drawing on the Web with Fantasia.....................................................25

    How Can You Get Involved? ........................................................................25

    Summary . .....................................................................................................26

  • 7/23/2019 Sams Silverlight 4 Unleashed

    6/734

    2 Setting Up and Discovering Your Environment 27

    Installing Visual Studio. ...............................................................................27

    Visual Studio 2010...............................................................................27

    Visual Web Developer Express ............................................................28Installing the Silverlight Tools for Visual Studio ................................28

    Verifying the Installation ....................................................................29

    Inspecting the Application..................................................................31

    Unpacking an XAP File........................................................................32

    Using the Visual Studio Designer........................................................32

    Implementing Hello Silverlight. ..................................................................33

    Checking the Properties Editor ...........................................................34

    Adding Some Text. ..............................................................................36

    Using Design Time Width and Height................................................39Saving the Application . ......................................................................40

    Installing Expression Blend . ........................................................................40

    Creating a New Silverlight Application ..............................................40

    Opening Hello Silverlight. ..................................................................41

    Adding an Effect . ................................................................................42

    Creating a Pulse Animation . ..............................................................44

    Triggering the Storyboard. ..................................................................45

    Testing the Application . .....................................................................46

    Summary .......................................................................................................47

    3 Extending Your Application with Controls 49

    Extending XAML. .........................................................................................49

    Mapping a Prefix to a CLR Namespace...............................................49

    Why Is a Prefix Not Always Needed?. ................................................52

    Adding a Namespace to Any Element. ...............................................52

    Defining Your Own URI and Mapping CLR Namespaces...................52

    Whats a Control? . .......................................................................................53

    User Controls.......................................................................................53

    Custom Controls .................................................................................63

    Summary .......................................................................................................73

    4 Investigating Existing Controls 75

    Reviewing the Basics.....................................................................................75

    Show Me Some Code! ...................................................................................76

    Changes in Existing Controls.......................................................................77

    Mouse Wheel Support .........................................................................77

    Localizing for Right-to-Left Languages ...............................................77

    Getting a Control Templates Current State .......................................78

    Contents v

  • 7/23/2019 Sams Silverlight 4 Unleashed

    7/734

    Silverlight 4 Unleashedvi

    Adding SelectedValue and SelectedValuePath . ..............................79

    Adding Command and CommandParameter . ...........................................79

    Presenting and Editing Text with the RichTextBox .....................................84

    Zooming with the Viewbox. .........................................................................85Opening a ChildWindow . ..............................................................................87

    Finding More Information. ..........................................................................90

    Where to Find Additional Controls?. ..........................................................90

    Do You Really Need a Control?...........................................................90

    The Silverlight Toolkit . .......................................................................91

    Installing the Silverlight Toolkit . .......................................................92

    Third-Party Providers. .......................................................................101

    Summary .....................................................................................................102

    5 Understanding Dependency Properties 103

    Inheriting DependencyObject .....................................................................104

    Threading...........................................................................................104

    Accessing a Dependency Propertys Value ........................................105

    Using a DependencyObject as Data Item...........................................105

    Registering Dependency Properties . ..........................................................108

    Defining Metadata.............................................................................109

    Initializing Dependency Objects.......................................................111

    Understanding Attached Properties. ..........................................................114

    Using Attached Properties for Values................................................114

    Registering an Attached Property. ....................................................115

    Using Custom Attached Properties in XAML ...................................118

    Implementing an Attached Behavior................................................118

    Building on Attached Behaviors with Blend Behaviors....................122

    Adding a New Property with Snippets . .....................................................123

    Installing the Snippets for Silverlight ...............................................123

    Using the Snippets. ...........................................................................124

    Calculating a Dependency Propertys Value . ............................................124

    Getting the Propertys Base Value .....................................................126

    Reading the Local Value . ..................................................................126

    Summary .....................................................................................................127

    6 Working with Data: Binding, Grouping, Sorting, and Filtering 129

    Diving into Data Bindings. ........................................................................130

    Understanding a Bindings Elements ................................................130

    Understanding the Namescope . .......................................................132

    Setting the Source. ............................................................................133

    Refining the Path. .............................................................................136

  • 7/23/2019 Sams Silverlight 4 Unleashed

    8/734

    Contents vii

    Flowing in Two Directions ................................................................138

    Converting the Values.......................................................................138

    Changing the Format . ......................................................................139

    Handling Special Cases. ....................................................................141Property Trigger . ...............................................................................142

    Validating Input. ...............................................................................142

    Using the Visual Studio Binding Dialog.....................................................146

    Using the Expression Blend Binding Dialog ..............................................148

    Debugging Data Bindings . .........................................................................149

    Checking the Output Tab..................................................................149

    Creating a Test Converter. ................................................................150

    Grouping, Filtering, and Sorting Data. ......................................................151

    Working with theCollectionViewSource

    ........................................151 Using a PagedCollectionView . .........................................................154

    Binding Directly to the Source. ........................................................154

    Summary .....................................................................................................155

    7 Understanding the Model-View-ViewModel Pattern 157

    About Design Patterns ................................................................................157

    Separating the Concerns.............................................................................158

    Why Is Separation Good?. ................................................................158

    Classic Separation Patterns. ..............................................................158

    History of MVVM. ......................................................................................159

    Developing Expression Blend. ..........................................................160

    Presentation Model for WPF and Silverlight ....................................160

    Architecture of MVVM. ..............................................................................160

    Translating to Silverlight . .................................................................161

    Two Kinds of View-models................................................................162

    Binding the View to the View-model. .......................................................163

    Understanding the Data Context. ....................................................163

    Inheriting the Data Context . ...........................................................164

    Binding to the View...........................................................................164

    Building a Sample Application . .................................................................168

    The Models Interface ........................................................................168

    Building a CustomerViewModel . ........................................................170

    Calling the Service in the MainViewModel.........................................172

    Binding to Results. ............................................................................174

    Testing the Application .....................................................................177

    Bridging the Separation ..............................................................................178

    Implementing a ViewModelBase Class ..............................................178

    Using Commands . ............................................................................180Sending Messages . ............................................................................183

  • 7/23/2019 Sams Silverlight 4 Unleashed

    9/734

    Silverlight 4 Unleashedviii

    Using an MVVM Framework ......................................................................184

    What Could Be Better? . .............................................................................184

    Summary . ...................................................................................................184

    8 Using Data Controls 187

    Filtering and Paging with the PagedCollectionView . ..............................188

    Preparing the Sample.........................................................................188

    Building the PagedCollectionView ...................................................190

    Filtering Data . ...................................................................................192

    Paging Through Data.........................................................................194

    Optimizing Data Handling................................................................195

    Implementing Custom Sorting .........................................................195

    Adding a DataPager Control ......................................................................196Customizing the Display ...................................................................197

    Validating Data Input . ...............................................................................197

    Using Interface-Based Validation ......................................................198

    Validating with Data Annotations ....................................................201

    Validating Before or After the Data Is Set .........................................203

    Validating on the Client and on the Server......................................203

    Reviewing the DataGrid. ............................................................................204

    Using the DataGrid with Automatic Columns .................................204

    Choosing Between DataGrid and ListBox . .....................................208

    Editing Data in the DataForm . ...................................................................208

    Adding a Description.........................................................................210

    Validating the Input ..........................................................................211

    Committing Changes Manually........................................................211

    Defining Fields Manually ..................................................................212

    Getting More Information ................................................................213

    Making a Simple Property Editor ......................................................213

    Summary .....................................................................................................214

    9 Connecting to the Web 215

    Getting Information from Cross-Domain Servers. ....................................216

    Checking Whether a Policy File Exists..............................................216

    Working Around Cross-Domain Restrictions....................................217

    Placing Simple Calls. ..................................................................................218

    Informing the User ............................................................................218

    Learning with a Sample.....................................................................219

    Downloading Strings .........................................................................219

    Detecting Errors, Checking the Result ..............................................223

    Opening a Resource for Reading .......................................................224

    Uploading a String. ...........................................................................225

  • 7/23/2019 Sams Silverlight 4 Unleashed

    10/734

    Contents ix

    Opening a Resource for Writing........................................................227

    Accessing Headers. ............................................................................231

    Sending Complex Messages. ......................................................................231

    Posting a File to the Server with HttpWebRequest ............................231Discovering the New Networking Stack. ...................................................234

    Using the Client HTTP Stack. ...........................................................235

    Using Other HTTP Methods..............................................................236

    Using the CookieContainer. .............................................................236

    Handling Responses....................................................................................237

    Handling XML Responses..................................................................238

    Handling JSON Responses. ...............................................................238

    Communicating with WCF ........................................................................239

    Setting Up a Service...........................................................................239Connecting the Client Application...................................................241

    Updating the Code on the Server .....................................................244

    Publishing the Service .......................................................................244

    Summary .....................................................................................................245

    10 Creating Resources, Styles, and Templates 247

    Working with Resources in XAML . ...........................................................248

    Using Local Resources........................................................................248

    Merging Dictionaries . .......................................................................249

    From the Same Assembly ..................................................................250

    From a Different Assembly................................................................251

    Resolving Resources. .........................................................................254

    Working with Resources in Blend . ............................................................256

    Merging a Resource Dictionary .........................................................256

    Creating New Resources . ..................................................................257

    Selecting a Resource for a Property ...................................................257

    Using the Resources Panel.................................................................257

    Cleaning Up Unused Resources. ................................................................259

    Using the Pistachio Tool....................................................................259

    Styling a Control. .......................................................................................260

    Using Implicit Styles..........................................................................261

    Creating a Hierarchy of Styles...........................................................263

    Creating a New Style in Blend ..........................................................264

    Templating a Control..................................................................................265

    Copying a Template in Blend............................................................265

    Creating a Custom Easing Function .................................................269

    Making a Control in Blend . .............................................................270

    Applying a Theme.......................................................................................271Summary . ...................................................................................................272

  • 7/23/2019 Sams Silverlight 4 Unleashed

    11/734

    Silverlight 4 Unleashedx

    11 Mastering Expression Blend 273

    What Is Blend, Exactly?. ............................................................................274

    Working as a Tool for Integrators......................................................274

    Editing XAML Markup . ....................................................................274When Should You Use User Controls?..............................................274

    Making an Application Blend. ...................................................................275

    Why Is Some Code Not Executed?....................................................275

    Why Does Some Code Fail? . ............................................................275

    Detecting the Cause of an Exception................................................276

    Isolating Code in Design Mode. .......................................................278

    Creating Design Time Data in Blend . ..............................................280

    Understanding the Design-Time Data Context ................................288

    Using Blend Behaviors. ..............................................................................289Behavior, Trigger, or Action? .............................................................292

    Adding a Blend Behavior in Code.....................................................293

    Creating a New Blend Behavior ........................................................293

    Finding More Information..........................................................................300

    Summary . ...................................................................................................300

    12 Sketching User Experience 301

    Sketching as a Discovery Process. ..............................................................301

    Using Sketching and Wireframing Tools ..........................................302Other Kinds of Sketching . ................................................................303

    Discovering SketchFlow. ............................................................................304

    Creating a New SketchFlow Application...........................................305

    Checking the Panels . ........................................................................305

    Creating and Connecting Screens. ...................................................305

    Building the UI . .........................................................................................308

    Creating a Component Screen ..........................................................309

    Using Sketch Controls . .....................................................................310

    Exploring the Sketch Controls . ........................................................313

    Creating States and Transitions. .......................................................318

    Building an Animation. ....................................................................321

    Deploying the SketchFlow Application......................................................323

    Running the Prototype . .............................................................................323

    Giving Feedback ................................................................................324

    Importing and Managing User Feedback ...................................................325

    Importing and Exporting. ..........................................................................325

    Importing from Photoshop and Illustrator.......................................326

    Importing from PowerPoint . ............................................................326

    Exporting to Word. ...........................................................................326

  • 7/23/2019 Sams Silverlight 4 Unleashed

    12/734

    Contents xi

    Integrating and Collaborating. ..................................................................327

    Integrating into SharePoint...............................................................327

    Integrating into Team Foundation Server.........................................327

    Summary .....................................................................................................328

    13 Creating Line-of-Business Applications 329

    Preparing the Server-Side............................................................................331

    Prerequisites .......................................................................................332

    Preparing the Server-Side Application...............................................332

    Creating the Silverlight Client....................................................................333

    Bringing the Client and the Server Together .............................................334

    Adding a Domain Service..................................................................334

    Inspecting the Domain Service Class................................................335Inspecting the Metadata....................................................................336

    Creating a New Server-Side Query ....................................................336

    Working with the Visual Designer . ...........................................................338

    Understanding the DomainDataSource ............................................339

    Calling a Query with Parameter. ......................................................339

    Sorting the Data. ...............................................................................341

    Adding a Pager. .................................................................................341

    Refactoring the Application to MVVM . ....................................................342

    Adding a View-model ........................................................................342

    Adapting the XAML Markup.............................................................345

    Customizing the Columns ................................................................346

    Localizing the User Interface.............................................................347

    Adding a RelayCommand Class ........................................................348

    Executing the CRUD Operations in Code ........................................348

    Displaying Messages from the View-model ......................................351

    Deleting an Order. ............................................................................354

    Validating the Values.........................................................................357

    Filtering the Data. .............................................................................360

    Showing Feedback While Processing ................................................362

    Sharing Code . ...................................................................................363

    Summary .....................................................................................................363

    14 Enhancing Line-of-Business Applications and

    Running Out of the Browser 365

    Enhancing LOB Applications . ...................................................................365

    Adding Paging....................................................................................365

    Showing Errors...................................................................................369

    Reconciling Data................................................................................371Copying and Pasting Rows................................................................373

    Printing . ............................................................................................373

  • 7/23/2019 Sams Silverlight 4 Unleashed

    13/734

    Silverlight 4 Unleashedxii

    Taking Silverlight Out of the Browser . ......................................................382

    Setting Up the Application................................................................383

    Uninstalling the Application. ...........................................................384

    Debugging the OOB Application ......................................................385Looking Under the Hood . ................................................................386

    Changing the Settings .......................................................................387

    Updating the Application. ................................................................391

    Installing from the Code . .................................................................393

    Saving Files . ......................................................................................395

    Working Offline. ...............................................................................398

    Summary .....................................................................................................399

    15 Developing Navigation Applications and Silverlight for

    Windows Phone 7 401

    Navigating with Silverlight. .......................................................................401

    Should You Always Use a Navigation Application?..........................404

    Creating a New Navigation Application . .........................................404

    Accessing Navigation Information. ..................................................412

    Providing Custom Navigation. .........................................................413

    Adding Navigation to a Non-Navigation Application. ....................414

    Developing with Silverlight for Windows Phone 7 . .................................415

    Getting Hardware ..............................................................................416

    Targeting a Specific Audience............................................................416

    Developing for Windows Phone 7 ....................................................416

    Developing for a Uniform Hardware Platform .................................417

    Designing for the Phone ...................................................................418

    Installing the Tools ............................................................................419

    Selling Your Applications ..................................................................420

    Building Compatible Applications for the Desktop

    and the Phone .................................................................................420

    Continuing the Exploration..............................................................432

    Summary .....................................................................................................432

    16 Using Effects and Recording Media 435

    Creating Effects with Pixel Shaders . ..........................................................435

    Writing, Finding, and Compiling Shader Files .................................436

    Creating and Modifying Shaders with Shazzam...............................437

    Integrating Shaders in the Application. ...........................................438

    Adding Properties and Animating Shaders . .....................................440

    Using Shaders for Transitions in the VSM ........................................443

  • 7/23/2019 Sams Silverlight 4 Unleashed

    14/734

    Contents xiii

    Accessing the Webcam and the Microphone. ...........................................443

    Getting the List of Devices ................................................................444

    Enabling Access. ................................................................................448

    Displaying the Video Output ............................................................448Detecting Whether Other Applications Use the Device...................449

    Capturing Audio .........................................................................................450

    Converting to a WAV File..................................................................450

    Creating a Sink . ................................................................................450

    Using the SaveFileDialog . .................................................................452

    Using the Sink and Adding Commands ...........................................454

    Wiring the Commands......................................................................456

    Testing Audio Recording . .................................................................457

    Writing to a Bitmap ....................................................................................457Saving the Picture to a PNG File .......................................................459

    Manipulating Pixels. .........................................................................460

    Extending WriteableBitmap........................................................................462

    Using the Open File Dialog ........................................................................464

    Learning About News in Media..................................................................465

    Summary . ...................................................................................................466

    17 New Transforms, Right Click, HTML Browser, WebBrowserBrush,

    and Isolated Storage 467

    Transforming Elements in a Projection. ....................................................467

    Setting Additional Properties.............................................................469

    Using a Matrix3DProjection..............................................................470

    Animating the PlaneProjection .........................................................470

    Composing Transforms...............................................................................472

    Handling the Right-Click Event .................................................................473

    Handling a Routed Event ..................................................................473

    Displaying a Context Menu ..............................................................476

    Hosting an HTML Browser (Out-of-the-Browser Only) . ...........................478

    Understanding the Limitations.........................................................479

    Building a Simple Web Browser ........................................................480

    Loading HTML Content from Memory ............................................484

    Invoking JavaScript. ..........................................................................485

    Writing and Reading in the Isolated Storage . ...........................................485

    Saving to the Isolated Storage ...........................................................485

    Reading from the Isolated Storage ....................................................492

    Deleting Files . ...................................................................................495

    Using the IsolatedStorageSettings .....................................................496

    Trusting the Isolated Storage or Not .................................................499Painting with HTML ...................................................................................499

    Summary . ...................................................................................................501

  • 7/23/2019 Sams Silverlight 4 Unleashed

    15/734

    Silverlight 4 Unleashedxiv

    18 Drag and Drop, Full Screen, Clipboard, COM Interop, Duplex Polling,

    Notification Windows, and Splash Screens 503

    Dragging and Dropping. ............................................................................503

    Dragging Files on the Silverlight Application...................................504Drag-and-Drop Restrictions. .............................................................505

    Working in Full Screen . .............................................................................507

    Getting Keyboard Support in Full-Screen Mode

    (Elevated Permissions).....................................................................507

    Using Full Screen on a Monitor While Working on Another ..........509

    Copying to and from the Clipboard . ........................................................510

    Working with COM (Elevated Permissions). .............................................512

    Understanding the Restrictions.........................................................512

    Communicating with Microsoft Office.............................................512Communicating over Duplex Polling . ......................................................519

    Implementing the Server-Side Service...............................................519

    Unregistering a Client . .....................................................................524

    Configuring the Service. ...................................................................524

    Implementing the Client. .................................................................525

    Unsubscribing and Resubscribing . ...................................................528

    Testing the Application . ...................................................................529

    Displaying Notification Windows . ............................................................530

    Understanding the Restrictions.........................................................530

    Adding a Notification Window.........................................................531

    Queuing Notification Windows ........................................................533

    Interacting with the Main Window ..................................................533

    Creating a Custom Splash Screen...............................................................534

    Summary . ...................................................................................................537

    19 Authentication, Event to Command Binding, Random Animations,

    Multitouch, Local Communication, and Bing Maps Control 539

    Logging In with Authentication. ...............................................................539

    Creating a New Website ....................................................................540

    Adding and Managing Users .............................................................541

    Configuring the Authentication Web Service...................................542

    Checking the Access . ........................................................................544

    Adding References to the Services.....................................................544

    Implementing the Client...................................................................545

    Binding an Event to a Command . ............................................................547

    Executing a Command When a TextBox Loses Focus......................548

    Building Random Animations . ..................................................................554

    Creating the Base Animation in Blend .............................................554

    Randomizing the Animation. ...........................................................555

  • 7/23/2019 Sams Silverlight 4 Unleashed

    16/734

    Contents xv

    Implementing Multitouch in Silverlight. ..................................................557

    Getting the Right Computer .............................................................558

    Investigating Existing Elements ........................................................559

    Using Multitouch Libraries. ..............................................................560Scaling, Rotating, and Translating . ..................................................560

    Implementing a Multitouch Application..........................................561

    Using Multitouch in Windows Phone 7 Applications......................563

    Finding More Information . ..............................................................563

    Enabling Local Communication . ..............................................................563

    Understanding the Restrictions.........................................................564

    Building a Receiver . ..........................................................................564

    Building a Sender. .............................................................................565

    Testing the Application . ...................................................................567Mapping with the Bing Maps Control . .....................................................567

    Adding the Map.................................................................................568

    Getting Location Information and Marking It .................................569

    Getting More Information ................................................................571

    Summary .....................................................................................................571

    20 Building Extensible and Maintainable Applications 573

    Inverting Dependencies with Unity. .........................................................573

    Refactoring to Smaller and Simpler Classes ......................................575

    Setting Up the Services . ....................................................................578

    Calling the Setup Method and Wiring Up .......................................582

    Discovering More About Unity . .......................................................583

    Composing an Application with MEF. ......................................................583

    Exporting and Importing ..................................................................584

    Downloading on Demand.................................................................594

    What About Prism? . .........................................................................603

    Using an MVVM Framework . ....................................................................604

    Discovering the Components ...........................................................604

    Sending Messages . ............................................................................604

    Summary .....................................................................................................607

    21 Optimizing Performance 609

    Improving the XAP Download Time. ........................................................609

    Loading Content on Demand ...........................................................611

    Caching Common Assemblies ..........................................................615

    Virtualizing the User Interface . .................................................................616

    Virtualizing the ItemsControl ..........................................................617

    Unvirtualizing the ListBox ................................................................619

    Simplifying the DataTemplate...........................................................619

  • 7/23/2019 Sams Silverlight 4 Unleashed

    17/734

    Silverlight 4 Unleashedxvi

    Creating Items in Batches. .........................................................................620

    Working in Threads ...........................................................................621

    Accelerating the User Interface. .................................................................624

    Enabling Hardware Acceleration in the Browser ..............................624Enabling Hardware Acceleration Out of the Browser.......................628

    Accelerating with Care . ....................................................................629

    Accelerating in the Windows Phone 7..............................................630

    Using a Code Profiler..................................................................................630

    Avoiding Memory Leaks .............................................................................631

    Saving an Object on the Stack or the Heap......................................631

    Collecting Garbage and Leaking Memory . ......................................632

    Living a Shorter Life . ........................................................................635

    Unregistering Event Handlers . .........................................................635Disposing Objects . ............................................................................637

    Using Weak References. ....................................................................637

    Finding a Leak . .................................................................................638

    Summary .....................................................................................................639

    22 Advanced Development Techniques 641

    Using New C# and .NET Features. .............................................................641

    Using Modern Programming Syntax.................................................641

    Creating Extension Methods. ...........................................................645

    Consuming Dynamic Objects . .........................................................646

    Using Named/Optional Parameters. .................................................646

    Localizing Applications. .............................................................................647

    Adding a Resource File.......................................................................647

    Making an Application Localizable...................................................648

    Using Tools . ......................................................................................651

    Downloading Resource Applications on Demand............................652

    Encrypting and Decrypting . ......................................................................652

    Understanding the Encryption/Decryption Mechanism..................652

    Multithreading. ..........................................................................................653

    What Is a Thread?..............................................................................653

    Using the ThreadPool........................................................................654

    Dispatching Back to the UI Thread...................................................657

    Creating and Using a BackgroundWorker ..........................................660

    Locking Critical Resources.................................................................663

    Enhancing Multithreaded Code........................................................666

    Unit Testing the Application ......................................................................667

    Installing a Unit Test Framework ......................................................668

    Adding Functionality with TDD .......................................................668

  • 7/23/2019 Sams Silverlight 4 Unleashed

    18/734

    Contents xvii

    Using Code Coverage ........................................................................673

    Unit Testing Windows Phone 7 Applications...................................673

    Summary .....................................................................................................674

    Conclusion 675

    Index 677

  • 7/23/2019 Sams Silverlight 4 Unleashed

    19/734

    About the Author

    Laurent Bugnion works as a senior user-experience integrator for IdentityMine, one of

    the leading companies committed to redefining the user experience and a Microsoft Gold

    Partner dedicated to easing the adoption and optimal use of Microsoft presentation tech-

    nologies, including Windows Presentation Foundation (WPF), Silverlight, Windows Phone

    7, Surface, and Windows 7.

    Originally an electronics engineer, Laurent achieved postgrad credentials in software engi-

    neering in 1999. Before IdentityMine, he worked for Siemens for 13 years, introducing

    WPF and other .NET 3.5 technologies worldwide. His responsibilities involved developing

    with the previously mentioned technologies, training and coaching his colleagues, coordi-nating and integrating the graphic-design work, and fostering relationships with

    Microsoft. Before that, he wrote embedded C/C++, and then moved to desktop computers

    in Java, JavaScript, and eventually .NET (desktop and ASP.NET).

    Privately, he codes in Silverlight, WPF, and ASP.NET. He blogs onhttp://blog.galasoft.ch

    and writes on http://www.galasoft.ch, where he publishes articles, prototypes, and demos

    related to the previously mentioned technologies. In 2008, he earned an MCTS for WPF.

    (In October of that same year, his book Silverlight 2 Unleashedwas published.) This year,

    2010, is his fourth year as a Microsoft MVP (Silverlight), and he was selected this year as

    Silverlight MVP of the year.

    Laurent is based in Zurich, Switzerland, where he lives with his wife, Chi Meei, and his

    two daughters, Alise and Laeticia.

    http://blog.galasoft.ch/http://blog.galasoft.ch/http://www.galasoft.ch/http://www.galasoft.ch/http://blog.galasoft.ch/
  • 7/23/2019 Sams Silverlight 4 Unleashed

    20/734

  • 7/23/2019 Sams Silverlight 4 Unleashed

    21/734

    Acknowledgments

    Thanking everyone who helped me complete this book would probably take another 700

    pages. So, to keep these acknowledgments concise, I want to generally thank everyone

    who helped in any way, while specifically calling out a few without whom I couldnt have

    completed this work.

    The Silverlight community has been nothing short of fantastic. I received wonderful

    motivation every time I was about to throw in the towel (usually around 2 a.m.). I found

    documentation about the most cryptic topics in amazingly rich and detailed blog posts,

    and I had the best reviewers in the world, who did all that work with just the promise of

    a thank you and a beer next time I meet them. It is a wonderful time to develop soft-ware.

    I especially want thank the following (in no particular order) and apologize to those I

    might have forgotten:

    At IdentityMine: Nathan Dunlap, Josh Wagoner, Josh Smith, Andrew Whidett, and

    Jonathan Russ for teaching me all I know (or so it feels); Lu Silverstein, Mark Brown,

    Chad Brown, and Craig Jaris for encouraging me to write this book and dealing with the

    disturbance.

    The designer dream team: Jonah Sterling, Javier Roca Garcia, Jamey Baumgardt, Stuart

    Mayhew, Lydia Bagwell, and more who help me to think differently. And all the others

    for making me part of the family. It is a privilege to work with you.

    My dream team of reviewers: Corrado Cavalli, Laurent Kemp, David Gardner, Peter

    Bromberg, David Anson, Josh Smith, Shawn Wildermuth, Christian Schormann, Colin

    Blair, Tim Heuer, Rene Schulte, Walt Ritscher, and Glenn Block. Thank you so much.

    A very special extra thank you to Laurent Kemp and Corrado Cavalli for jumping in at

    the last minute to review additional chapters.

    At Microsoft: For building these fantastic frameworks and tools, and for answering my

    frequent pleas for help: Scott Guthrie, Ian Ellison-Taylor, Tim Sneath, Nikhil Kothari, JohnGossman, Jaime Rodriguez, Laurence Moroney, Jesse Liberty, John Papa, Rob Relyea, Ted

    Hu, Stefano Malle, Ronnie Saurenmann, Sascha Corti, Pete Brown, Jeff Wilcox, David

    Anson, Christian Schormann, Pete Blois, Unni Ravindranathan, Kirupa Chinnathambi,

    Joanna Mason, David Teitlebaum, Tim Heuer, Glenn Block, Karen Corby, Mike Harsh, Joe

    Stegman, Rochelle Benavides, Grant Hinkson, Katrien de Graeve, Lisa Feigenbaum, Mark

    Boulter, Chad Royal, Chris Koenig, and all the others at the DevDiv.

    The source of eternal inspiration and support: Dave Campbell, Adam Kinney, Robby

    Ingebretsen, Kevin Moore, Charles Petzold, Marlon Grech and all the WPF disciples,

    Shawn Wildermuth, Walt Ritscher, Justin Angel, Davide Zordan, David Yack, Don Burnett,

  • 7/23/2019 Sams Silverlight 4 Unleashed

    22/734

    Erik Mork, Brian Noyes, Ward Bell, Rob Eisenberg, Dan Wahlin, Chad Campbell, John

    Stockton, Jonas Follesoe, Seema Ramchandani, Brian Henderson, Ian Smith, Scott Barnes,

    Jeremy Likness, Page Brooks, Rick Barraza, Cigdem Patlak, Michael Sync, Victor Gaudioso,

    David Kelley, Anand Iyer, all the Silverlight MVPs, and the whole vibrant and amazing

    Silverlight community.

    The great team at Sams: And especially Neil Rowe (my editor, mentor, and friend since

    2007), Andy Beaster, and Mark Renfrow.

  • 7/23/2019 Sams Silverlight 4 Unleashed

    23/734

  • 7/23/2019 Sams Silverlight 4 Unleashed

    24/734

    Foreword

    The growth of Silverlight has been perhaps faster than any of us involved in its inception

    would have predicted. In less than three years, Microsoft has released four desktop

    releases, each packing a payload of hundreds of features in response to customer feedback.

    Silverlight is now deployed on somewhere approaching two-thirds of all Internet-

    connected PCs,1 and its the primary platform for general-purpose development on the

    new Windows Phone 7. Silverlight powers all manner of mainstream applications: from

    high-end media experiences like Netflix, NBC Sports, and Sky Player to the web version of

    Office. Its in use at top consumer websites like eBay and for mission-critical applications

    inside the firewall of numerous Fortune 500 companies.

    In one sense, Silverlight is, of course, just an evolution of the .NET Framework that has

    been central to Microsofts developer strategy for the past ten years. It stands on the

    shoulders of giants like Windows Presentation Foundation (WPF,) the big-sister technol-

    ogy that preceded it and laid the groundworkwith an architecture and XAML format

    that had already proved itself in real-world implementations.

    When we started building Silverlight, one of the greatest constraints was size. We knew

    we needed something that was lightweight and easy to deploy without requiring a big

    download or dependencies on other prerequisites. At the same time, we wanted to ship a

    high-quality product as quickly as possible. There was a lot of debate internally about

    whether we should start with the existing .NET codebase and take away code orwhether we should build up by starting with a clean slate and gradually adding features

    until we had an attractive product. In the end, we went with the latter approach, and I

    think it shows in the final product: Silverlight contains the key things that a developer

    needs while bringing little cruft along for the ride. For me, this is one key reason why

    Silverlight offers a unique sweet spot of power, flexibility, and easy deployment that suits

    it well for both consumer and business usage.

    But a framework alone isnt sufficient for most pragmatic developers, who are less inter-

    ested in history lessons or arcane details of internal architecture and more concerned with

    what they themselves can create quickly and efficiently. Over the last year or two sincethe last Silverlight Unleashedbook was published, its true that Silverlight has been

    expanded and enhanced; but even more important, the palette of tools available to a

    Silverlight developer has grown tremendously. In particular, the release of Visual Studio

    2010 brought true WYSIWYG in-place editing to Silverlight, along with WCF RIA Services,

    a set of classes and design-time tools that offer major productivity gains to business appli-

    cation authors.

    Beyond the core elements of Silverlight, a burgeoning community has sprung up over the

    past couple of years both inside and outside of Microsoft. The engineering team them-

    selves have released a plethora of open source controls, components, and themes along

    with rich frameworks for media, extensibility, and analytics. Others have contributed

    libraries and components for everything from PDF creation to physics engines and full 3D

  • 7/23/2019 Sams Silverlight 4 Unleashed

    25/734

    support: CodePlex alone shows nearly 500 projects that are based on Silverlight. And of

    course, there is an endless supply of great content targeted at Silverlight developers,

    including the weekly Silverlight TV show at http://silverlight.tv.

    What of the future of Silverlight? Some have argued that the rapid rise of HTML5 presentsa new competitive threat to Silverlight. Its certainly true that the browser wars of old are

    back, with vendors duking it out to deliver the most advanced hardware-accelerated

    graphics platform for developers while delivering a stable and secure browser for a broader

    audience. Its also true that HTML in general has the most pervasive reach of any client

    platform. Indeed, the momentum behind Internet Explorer 9 shows that we at Microsoft

    are also putting a lot of energy into providing first-class support for standards-based

    web development.

    A favorite business read among Microsoft executives isBuilt to Lastby Jim Collins and

    Jerry Porras, which highlights how easy it is to be trapped by a false dichotomy (thetyranny of the OR). The authors note how many strategic decisions are framed incor-

    rectly as a choice between A or B (but notboth). Yet often the correct answer is an and

    rather than an or.

    In this vein, there need be no fork in the road between HTML5 and Silverlight. Both serve

    key needs that developers have, and both have powerful strengths. Even more important,

    many so-called Silverlight applications are in fact hybrid solutions that combine both

    technologies. Silverlight contains many useful bridging features to enable developers of

    both hues to access code and UIs written in the opposite framework. Silverlight develop-

    ers should therefore feel confident that their skills have value for the indefinite future and

    that Silverlight itself has a rosy future.

    I want to close this foreword by noting my delight to see this update to Laurents popular

    predecessor title, Silverlight 2 Unleashed. Ive had the privilege of knowing Laurent for

    some years now, and I can tell you that few in the Silverlight community command the

    respect that he does. He combines a passion for writing quality client software with a

    deep, practical, real-world knowledge of the tools and framework. He has had an insiders

    view of each release of Silverlight as it has been developed, and his feedback has shaped

    the product for the better. Laurents own experience developing complex, large-scale

    Silverlight applications shines through, particularly in the more advanced topics toward

    the end of the book.I heartily commend this book, both to newcomers to Silverlight as well as to those who

    already have experience with early releases of Silverlight and want to upgrade their

    knowledge with the latest advances.

    Tim Sneath

    Senior Director, Client Platform Evangelism

    Microsoft Corp.

    1

    As attested by our internal data and sites like riastats.com, which measure deployments of plug-insbased on millions of real-world users.

    Silverlight 4 Unleashedxxiv

    http://silverlight.tv/http://silverlight.tv/
  • 7/23/2019 Sams Silverlight 4 Unleashed

    26/734

  • 7/23/2019 Sams Silverlight 4 Unleashed

    27/734

    . Chapter 2, Understanding XAML, is still valid. You can learn a lot about the

    fundamentals of XAML by reading this chapter.

    . Chapter 3, Playing with XAML Transforms and Animations, is still valid. All the

    transforms and animations present in Silverlight 2 work unchanged in Silverlight 4.

    . Chapter 4, Expression Blend, refers to Expression Blend 2. Many basic features are

    still valid, but we will cover Expression Blend 4 in this book.

    . Chapter 5, Using Media, is still valid and describes colors, vector graphics, and

    basic image and video handling.

    . Chapter 6, Blending a Little More, is still an interesting read, and provides an

    overview of functionalities that are still available in Expression Blend 4 (transforms,

    opacity masks, paths, clipping paths, grouping controls, and making user controls).

    . Chapter 7, Deploying to a Web Page, is still valid with minor changes. It showsyou how to select a provider for your website and how to deploy your Silverlight

    application to that site.

    . Chapter 8, Programming Silverlight with JavaScript, is less relevant to Silverlight 4

    than it was to Silverlight 2. However, JavaScript is an important skill to have for

    anyone who is involved into creating web applications.

    . Chapter 9, Understanding .NET, and Chapter 10, Progressing with .NET, provide

    a tutorial from scratch about the most important constructs of the C# programming

    language and of the .NET framework. It is a good read for people who come to

    Silverlight from Flash, for instance, and have never worked in .NET before.

    . Chapter 11, Progressing with Animations is still valid and will teach you how to

    create animations in Blend, how to start and stop animations in code, and other

    special kinds of animations. Silverlight 4 and especially Blend 4 build on this and

    offer additional features that you will discover in the present book.

    . Chapter 12, Encoding Videos with Expression Encoder, and Chapter 13,

    Progressing with Videos, are based on Expression Encoder 2. The current version

    of this software (Expression Encoder 4) available today offers much of the same

    functionalities, with added features and a slightly different look and feel. Note,

    however, that the Microsoft Silverlight Streaming servers are unfortunately not

    available anymore.

    . Chapter 14, Letting Silverlight and JavaScript Talk, is less relevant to Silverlight 4,

    although most of the techniques will still work.

    . Chapter 15, Digging into Silverlight Elements, and Chapter 16, Digging Deeper

    into Silverlight Elements, are still very much current. In fact, it is almost a must-

    read before starting to work in Silverlight.

    . Chapter 17, Using Resources, Styling, and Templating, is still valid; however, it is

    possible to store resources in external resource dictionaries in Silverlight 4, whichwas not the case in Silverlight 2.

    Silverlight 4 Unleashed2

  • 7/23/2019 Sams Silverlight 4 Unleashed

    28/734

    . Chapter 18, Data Binding and Using Data Controls, will be developed deeper in

    Silverlight 4 Unleashed. The section about the DataGrid is still an interesting read if

    you are working with this control. Note, however, that the DataGrid is now part of

    the core Silverlight framework.. Chapter 19, Creating User Controls and Custom Controls, overlaps in part with

    the present books content. Controls are a very important part of the Silverlight

    framework, and it is important to understand how they are built and how they

    work.

    . Chapter 20, Taking Silverlight 2 One Step Further, and Chapter 21, Taking

    Silverlight 2 Even Further, lists various topics, some of them overlapping with the

    present books content.

    . Chapter 22, Connecting to the Web, overlaps in part with the present books

    content, but also has some interesting techniques to download files and access theircontent.

    . Chapter 23, Placing Cross-Domain Requests and Handling Exceptions, contains

    information about the topic of cross-domain communication that is still current in

    Silverlight 4, as well as a tutorial about exceptions and how to handle them.

    . Chapter 24, Silverlight: Continuing the Journey, contains various information

    that can be interesting for Silverlight developers.

    About Code in This BookWe tried to keep formatting as consistent as possible throughout this book and to make

    the code look like it does in Visual Studio. The source code is color-coded to help you to

    work faster and so that you can recognize key concepts in Visual Studio and in Expression

    Blend. Note that depending on the context where a keyword is used (XAML or C#, Visual

    Studio, or Expression Blend), the color code might differ.

    The source code lines are numbered only where relevant (for example, when the text

    makes explicit reference to a line number).

    The whole source code for this book is available online athttp://www.galasoft.ch/SL4U/code. A translation of the C# code into VB.NET is being

    prepared at the time of this writing.

    Adding a Reference to a Namespace

    In some listings, classes from other namespaces/assemblies are added to the code. In some

    occasions, doing so might cause a compilation error with the following message:

    The type or namespace name MyClass could not be found (are you missing a using directive or

    an assembly reference?).

    Introduction 3

    http://www.galasoft.ch/SL4U/codehttp://www.galasoft.ch/SL4U/code
  • 7/23/2019 Sams Silverlight 4 Unleashed

    29/734

    To correct this, make sure that the assembly in which MyClass is defined is added to the

    References folder in the Visual Studio Solution Explorer. If that is not the case, right-click

    this folder and select Add Reference from the context menu. In the Add Reference dialog,

    browse to the missing assembly and add it to the project.If the error persists, you must add a reference to the namespace in which MyClass is

    placed in the source code file. You can do so by adding an entry at the top the current

    page, as follows (where SilverlightApplication1.AnotherNamespace is the namespace in

    which MyClass lives):

    using SilverlightApplication1.AnotherNamespace;

    In Visual Studio, this step can be automated by placing the cursor inside the name

    MyClass and pressing Ctrl+. (Ctrl and a dot) to open the context menu. Then, select the

    first entry of the menu to add a using directive.

    Setting the Right Project as Startup

    When an existing solution is opened, and this solution contains a web project hosting

    the Silverlight application (in the ClientBin folder), the web project should be set as

    Startup. This means that when Ctrl+F5 is pressed in Visual Studio, the Silverlight applica-

    tion will be executed in http: context, and not in the file: context that has more

    restrictions. To ensure that the web project is set as Startup, follow these steps:

    1. Check in the Solution Explorer whether the web project is represented in bold. If

    that is the case, skip to Step 3.2. If that is not the case, right-click the web projects name and select Set as StartUp

    Project from the context menu.

    3. Right-click the HTML test page name (usually named

    [YourSilverlightApplication]TestPage.html or index.html) and select Set as Start Page

    from the context menu.

    Using the var Keyword

    Since Silverlight 3, it has been possible to use the var keyword to implicitly type a localvariable. For example, in the following code, both expressions are exactly similar after the

    code is compiled:

    var myVariable1 = new Button();

    Button myVariable2 = new Button();

    There is a lot of discussion in the .NET community about the usage of the var keyword.

    Choosing to use the keyword or not is very much a matter of personal preference, and

    there is unfortunately no way to please everyone in this matter. In this book, the var

    keyword is used consistently as shown here.

    Silverlight 4 Unleashed4

  • 7/23/2019 Sams Silverlight 4 Unleashed

    30/734

    Happy Coding!Now its time to start! I wish you a successful journey in this book, and I am anxious to

    hear from you on Twitter (@LBugnion). I cannot promise to reply to every message, but I

    will definitely do my best, and I am very open to criticism (as long as it is constructive)

    and questions. Enjoy the trip, and happy coding!

    Laurent

    Stfa, Switzerland, September 2010

    Introduction 5

  • 7/23/2019 Sams Silverlight 4 Unleashed

    31/734

    This page intentionally left blank

  • 7/23/2019 Sams Silverlight 4 Unleashed

    32/734

  • 7/23/2019 Sams Silverlight 4 Unleashed

    33/734

    The very first public glimpse of Silverlight 4 beta was offered at

    the Professional Developer Conference 2009, when Scott

    Guthrie (Corporate Vice President, .NET Developer Platform,

    Microsoft) gave one of the exciting talks full of demos forwhich he is famous. Although still in beta stage, we were

    already able to clearly see the direction that the technology

    was taking. Even more important, we were told often that

    Silverlight is the future of client applications at Microsoft!

    With this new release, the border between web applications

    and desktop applications is becoming much thinner. For

    example, Silverlight 4 can now install applications out of the

    browser, with a shortcut in the Start menu or on the desktop.

    Although these applications have fewer

    privileges and features than full-blowndesktop applications, they have the

    huge advantage to be cross-platform

    (you can run them on Apple computers,

    too) and provide a very elegant way to

    offer rich functionality in online and

    also offline mode. We talk a lot more

    about out-of-the-browser applications in

    this book.

    A lot of other features, which we discusslater too, help the developers to build

    so-called line-of-business (LOB) applications (for example, rich data applications for busi-

    nesses, catalogs for products, data visualization screens, and many more). Silverlight is

    often mistaken for yet another media framework, when it is in fact much more than this.

    This new release makes the point very clear, and should help to put Silverlight in the

    focus of enterprise applications developers while continuing to build on the success it

    already has for multimedia applications.

    Learning Silverlight Is Betting on the Future

    With all this in mind, it is quite clear that learning Silverlight is a perfect way to advance

    in the future of client application development:

    . For web developers, it adds important skills to your arsenal that will help enrich

    your web pages. Silverlight is not replacing classic web technologies such as

    Hypertext Markup Language (HTML), Cascading Style Sheets (CSS), and JavaScript,

    but it enhances them and plays an important role in the way that websites are

    evolving always more from document presentation to rich interactive applications.

    CHAPTER 1 Three Years of Silverlight8

    FIGURE 1.1

    Silverlight logo.

    T I PWhat About Windows PresentationFoundation?

    The richer (but running on Windows only) big

    sister of Silverlight called Windows

    Presentation Foundation (WPF) is still actively

    developed and extended by Microsoft,

    although in a maybe less-glamorous way. See

    the section Alternatives to Silverlight, later

    in this chapter.

  • 7/23/2019 Sams Silverlight 4 Unleashed

    34/734

    . For classic desktop developers in the Windows world (with technologies such as

    Microsoft Foundation Classes [MFC] or Windows Forms), it teaches you a modern

    and exciting framework with revolutionary features such as the fantastic data

    binding system, rich animations and graphics, media integration, and so on.. For WPF developers, you leverage a lot from what you already know and gain cross-

    platform compatibility for your applications, easy web deployment, and exposure to

    a wider audience.

    One important thing to keep in mind is that Silverlight is not a replacement for HTML

    web pages, and will absolutely not kill HTML. Silverlight is here to enhance your web

    pages with richer content, and with the out-of-the-browser feature, to create lightweight

    applications that can function online or offline. Learning Silverlight does not mean that

    you should avoid writing HTML code, or that you should stop investing in technologies

    such as ASP.NET. But it means that you can now realize applications that were impossible

    (or very difficult) to do in HTML/CSS/JavaScript, and that you can use the same languages

    (and in some cases reuse code) on the server and on the client.

    How Can They Be So Fast?

    There are a few aspects that explain how new versions of Silverlight can hit the market so

    fast, and yet be so stable:

    . Silverlight is developed in an agile manner. With short iterations and early releases,

    the team is able to react quickly when problems are found in the code or new

    features are suggested. This explains why we had three releases in less than three

    years.

    . Silverlight is taking advantage of the experience gathered by the Windows

    Presentation Foundation team. Many features are similar, and some code can even

    be reused. Other features are re-implemented in a different way based on customer

    feedback. The teams are communi-

    cating to leverage the experience

    gained since WPF was released.

    . The community is involved in an

    interactive manner. Your input

    counts! We will talk about ways to

    get involved in this chapter.

    How About Compatibility with Older Versions?

    An agile team at work for Silverlight provides a great basis for a rich feature set evolving

    very fast. With version 4, we can say that Silverlight is reaching maturity. There will, of

    course, be additional versions in the future, but it is obvious that versions 3 and 4 were

    Discovering Silverlight 4 9

    T I P

    The Community Counts!

    Did you know that approximately 70% of thefeatures requested by the Silverlight commu-

    nity have been implemented in Silverlight 4!

  • 7/23/2019 Sams Silverlight 4 Unleashed

    35/734

    major steps for this platform, which explains Microsofts enthusiasm at the conferences

    where early versions were shown. Note, however, that a lot of effort has been put into

    backward compatibility:

    . If you open a Silverlight 2 (or 3) project in the Silverlight 4 development environ-ment, a lot of your code will work as is. Some of it will need to be updated, but the

    changes are, in general, painless ones. Note that the project files (*.CSPROJ) will be

    updated to the new environment, though.

    . If you run a Silverlight 2 (or 3) application on a PC with Silverlight 4 installed, it

    will run without glitches, because the runtime environment is fully backward

    compatible.

    In fact, your Silverlight 2 (or 3) applications should run even better in a Silverlight 4

    runtime environment, because of the improvements brought to the core and to the plug-in. This history of backward compatibility is most certainly going to continue with future

    versions, so what you learn now is going to be a major skill for your future as a developer.

    Cross-Browser and Cross-Platform CompatibilityThe version of Silverlight developed by Microsoft is available on a wide variety of plat-

    forms, both on the Windows and Macintosh operating systems. This plug-in will run on

    all these platforms with the same feature set (with one exception that we will discuss in

    Chapter 18, Drag and Drop, Full Screen, Clipboard, COM Interop, Duplex Polling,

    Notification Windows, and Splash Screens, namely the COM integration that is of courseavailable only on Windows operating systems).

    In addition, Novell is working on a version named Moonlight, available for certain distri-

    butions of Linux. The effort by Novell is encouraged by Microsoft but is conducted inde-

    pendently. This is why the version releases are not necessarily coordinated, and there

    might be some discrepancies in the feature set, too. However, a great effort is being

    expended to create a plug-in that is largely compatible with the one developed by

    Microsoft.

    Finally, we will also take a look in Chapter 15, Developing Navigation Applications and

    Silverlight for Windows Phone 7 at Silverlight for the mobile platform. After announcingthat they wanted to support the mobile platform, Microsoft did not communicate much

    and encountered a few technical difficulties that took longer than expected to solve. This

    year, however, we finally heard much more about support for the mobile platform, and

    we will take a first look at what will be available in the near future.

    In short, Silverlight is your best bet if you want to run .NET-based code on a large number

    of platforms!

    CHAPTER 1 Three Years of Silverlight10

  • 7/23/2019 Sams Silverlight 4 Unleashed

    36/734

  • 7/23/2019 Sams Silverlight 4 Unleashed

    37/734

  • 7/23/2019 Sams Silverlight 4 Unleashed

    38/734

    The advantage of these frameworks is

    that they standardize the JavaScript

    functions by providing a layer on top of

    the various implementations available indifferent web browsers on different plat-

    forms. jQuery can be extended by plug-

    ins that are available for the user

    experience itself (for example, to create

    smoother animations), or at a lower

    level to enhance the communication with the web server, and so on. Also, they do not

    require an additional component in the web browser to run.

    However, programming in JavaScript is not an easy task. The dynamic nature of the

    language makes it more difficult to offer advanced development tools (such as IntelliSense

    in Visual Studio) and to find and correct bugs. Also, the HTML platform is limited:Advanced and smooth animations with high frame rates are impossible to realize, it is

    impossible to create certain transformations for graphic elements, and so forth.

    Note, however, that using Silverlight on a web page doesnt prevent you from using

    jQuery or another JavaScript-based frameworkon the contrary. Here, too, these tech-

    nologies complement each other.

    HTML5

    This new revision of HTML intends to provide a wide range of rich functionality, allowing

    developers to reduce the use of third-party plug-ins. In this matter, it positions itself as aconcurrent of Adobe Flash and Microsoft Silverlight.