1. Trang chủ
  2. » Công Nghệ Thông Tin

Silverlight 5 in action

1K 233 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1.002
Dung lượng 37,13 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

1 1 Introducing Silverlight 3 1.1 A Silverlight primer 4 Silverlight and the web 5 ■ Silverlight and WPF 6 Types of Silverlight applications 6 1.2 A brief history of Silverlight 8 Featur

Trang 1

Pete Brown

Revised Edition of

Silverlight 4 in Action

IN ACTION

Trang 2

Silverlight 5 in Action

PETE BROWN

M A N N I N G

SHELTER ISLAND

Trang 3

www.manning.com The publisher offers discounts on this book when ordered in quantity For more information, please contact

Special Sales Department

Manning Publications Co

20 Baldwin Road

PO Box 261

Shelter Island, NY 11964

Email: orders@manning.com

©2012 by Manning Publications Co All rights reserved

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in the book, and Manning

Publications was aware of a trademark claim, the designations have been printed in initial caps

or all caps

Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without elemental chlorine

Development editor: Jeff BleielManning Publications Co Technical proofreader: Thomas MacKearney

Cover designer: Marija Tudor

ISBN: 9781617290312

Printed in the United States of America

1 2 3 4 5 6 7 8 9 10 – MAL – 18 17 16 15 14 13 12

Trang 4

brief contents

PART 1 CORE SILVERLIGHT 1

1 ■ Introducing Silverlight 3

2 ■ XAML and the property system 26

3 ■ The application model and the plug-in 47

4 ■ Working with HTML and browsers 73

5 ■ Out-of-browser applications 95

6 ■ The security model and elevated trust 114

PART 2 CREATING THE USER INTERFACE 125

7 ■ Rendering, layout, and transforming 127

8 ■ Panels 160

9 ■ Human input 180

10 ■ Text fundamentals 199

11 ■ Editing plain and rich text 225

12 ■ Control basics and UserControls 247

13 ■ Animation and behaviors 272

Trang 5

14 ■ Resources, styles, and control templates 307

15 ■ Extensions, converters, custom controls, and panels 337

PART 3 WORKING WITH DATA AND SERVICES 365

16 ■ Binding 367

17 ■ Data controls: DataGrid and DataForm 410

18 ■ Input validation 433

19 ■ Networking basics 460

20 ■ Working with SOAP services 491

21 ■ RESTful services with the ASP.NET Web API 520

22 ■ Working with XML, JSON, RSS, and Atom 549

23 ■ Duplex, sockets, and local connections 575

PART 4 2D AND 3D GRAPHICS 601

24 ■ Graphics and effects 603

25 ■ Working with images 630

26 ■ Introduction to 3D 649

27 ■ 3D lighting, texturing, and animation 679

PART 5 MAKING THE MOST OF THE PLATFORM 709

28 ■ Pop-ups, windows, and full-screen applications 711

29 ■ Navigation 734

30 ■ Working with files and directories 761

31 ■ Printing 798

32 ■ COM, Native Extensions, and p-invoke 832

PART 6 BEST PRACTICES 867

33 ■ Structuring and testing with the MVVM pattern 869

34 ■ Debugging your application 913

35 ■ The install experience and preloaders 929

Trang 6

contents

preface xxi acknowledgments xxiv about this book xxvi about the cover illustration xxxi

P ART 1 C ORE S ILVERLIGHT 1

1 Introducing Silverlight 3

1.1 A Silverlight primer 4

Silverlight and the web 5Silverlight and WPF 6 Types of Silverlight applications 6

1.2 A brief history of Silverlight 8

Features for business and client applications 8Media and graphics enhancements 10User interaction 11Text 11

1.3 Getting started with Silverlight development 12

Setting up your development environment 13Helpful sites 13

1.4 Building your first Silverlight web application 14

Project setup 15User interface 16Calling Twitter search 18Parsing the results and binding the ListBox 19 Making the ListBox contents more meaningful 23

1.5 Summary 25

Trang 7

2 XAML and the property system 26

2.1 XAML basics 27

Objects 28Namespaces 29Properties 32 Dependency properties 33Attached properties 35 Events 36Commands 38

2.2 Object trees and namescope 39

Object trees 39Namescope 42

2.3 XAML type converters 43 2.4 Loading XAML at runtime 44 2.5 Summary 46

3 The application model and the plug-in 47

3.1 The Silverlight application model 48

Application startup process 49XAP 50The application manifest file 51The Silverlight application object 52 Application dependencies 55Assembly caching 56

3.2 Creating the Silverlight plug-in 58

Using the object tag 59Using the Silverlight.js utility file 60 Creating an instance of the Silverlight plug-in 61

3.3 Integrating the Silverlight plug-in 62

Relating the Silverlight application to the HTML DOM 62 Clarifying the initial experience 64Handling plug-in events 68Sending initialization parameters 70

3.4 Summary 71

4.1 Silverlight and the HTML DOM 74 4.2 Working with the web page from managed code 75

Navigating web page contents 76Working with element properties 77Handling CSS information 78

Accessing the query string 78

4.3 Working with the hosting browser window 79

Prompting the user 79Navigating the browser window 81 Discovering the browser properties 81

4.4 Bridging the scripting and managed code worlds 82

Calling managed code from JavaScript 82Using JavaScript from managed code 85

Trang 8

Process and hosting 97Capabilities and restrictions 98

5.2 The end-user experience 98 5.3 Creating out-of-browser applications 100

The out-of-browser settings file 100Controlling the experience 102Customizing icons 105Updating 105

5.4 Alerting the user with notification toast 106 5.5 Controlling the host window 107

Basic window properties 108Changing window chrome 109Minimizing, maximizing, restoring, and closing 110Moving a window 111Resizing 111

5.6 Summary 112

6 The security model and elevated trust 114

6.1 Code classifications and the transparency model 115 6.2 User initiation and consent 117

6.3 Elevated trust 119

Creating elevated trust applications 120Enabling in-browser elevated trust applications 122Detecting elevated trust mode 124

6.4 Summary 124

7 Rendering, layout, and transforming 127

7.1 The UIElement and FrameworkElement 128

Properties 128Methods 134

7.2 The rendering process 135

Clock tick 137Per-frame rendering callback 137 Rasterization 138

Trang 9

7.3 The layout system 144

Multipass layout—measuring and arranging 144 The LayoutInformation class 146Performance considerations 147

7.4 Render transforms 148

RotateTransform 149ScaleTransform 150 SkewTransform 150TranslateTransform 151 TransformGroup 151CompositeTransform 152 MatrixTransform 153

Vertical wrapping 167Horizontal wrapping 168

8.4 The Grid 169

Arranging Grid content 170Positioning Grid content 172 Spanning cells 172Sizing it up 173Working with the grid programmatically 176Customizing cell

boundaries 177

8.5 Summary 179

9.1 Capturing the keyboard 181

Understanding focus 181Handling keyboard events 182 Dealing with modifier keys 184

9.2 Mouse input 185

Mouse movement events 186Mouse button events 188 Using the mouse wheel 191

9.3 Using multitouch 193 9.4 Collecting ink drawings 194

Creating the InkPresenter 195Collecting ink 195 Styling the ink 197

9.5 Summary 198

Trang 10

10 Text fundamentals 199

10.1 The text system 200

Subpixel text rendering 200Text hinting 201Text formatting 202Text rendering 203

10.2 Displaying text 204

Font properties 204Flow control 208Text properties 209Spacing 212

10.3 OpenType font support 215

Ligatures 216Stylistic sets 217Font capitals 219 Fractions and numbers 220Variants, superscript, and subscript 221

10.4 Embedding fonts 223

10.5 Summary 224

11.1 Handling basic text input 226

Enabling multiline text support 227Mastering text selection 228

11.2 Understanding input method editors 228

11.3 Copying text with the Clipboard API 231

11.4 Collecting sensitive data 232

11.5 Entering and displaying rich text 233

Formatting and inline elements 233Working with selected text 237

11.6 Multicolumn and free-form linked text 241

Multicolumn text 241Free-form text layout 242

Trang 11

13.1 Animating a value over time 273 13.2 Mastering the timeline 275

What type of property are you animating? 275Where are you starting from and where are you going? 277How long should the animation run? 280

13.3 Storyboards 283

Understanding the storyboard 283Storyboard target 284 Controlling the Storyboard 287Resources 289

13.4 Keyframing 291 13.5 Interpolation 293

Linear interpolation 294Spline interpolation 294 Discrete interpolation 296KeyTime 296

13.6 Easing functions 297

Using easing functions 298Creating a custom easing function 301

13.7 Behaviors, triggers, and actions 302

Using existing behaviors 303Creating your own behavior 305

14.2 Giving your elements style 317

Defining the look 319Explicitly keyed style definitions 321 Implicit style definitions 322

Trang 12

14.3 Creating templates 323

Building a control template 323Creating reusable templates 328

14.4 Dealing with visual states 329

Understanding the components 329Leveraging the VisualStateManager 331

14.5 Sharing your visual states 335 14.6 Summary 335

15 Extensions, converters, custom controls, and panels 337

15.1 Markup extensions 338

Creating a simple custom markup extension 339Creating a parameterized markup extension 340

15.2 Custom type converters 342

Creating the converter 342Using the converter 343

15.3 Creating a custom panel 345

Project setup 346The OrbitPanel class 346 Properties 347Custom layout 350Enhancements 354

15.4 Creating a custom control 355

Choosing the base type 355Properties 356The control template contract 357The default template 359

Visual states 360Visual states in template 361

16.2 Understanding your binding source 373

Binding to a property 374Binding to an object 376 Binding to a UI element 378Binding to an indexed element 381Binding to a keyed (string indexed) element 382Binding to an entire collection 383 Deciding when to update binding 385

Trang 13

16.3 Binding to dynamic properties 386

ICustomTypeProvider overview 387Creating the helper classes 387Using the helper class 390

16.4 Customizing the display 395

Formatting values 395Converting values during binding 395Providing default fallback values 399 Handling null values 399

16.5 Creating explicit data templates 400

Using a DataTemplate with a ContentControl 400 Rendering an ItemsControl with a DataTemplate 402

16.6 Creating implicit data templates 403 16.7 Summary 409

17.3 Annotating for display 428

The Display attribute 429The Editable attribute 430

18.3 Synchronous validation with IDataErrorInfo 441

The IDataErrorInfo interface 441Simple validation with IDataErrorInfo 442Cross-field validation with IData- ErrorInfo 443Combining exceptions and IDataErrorInfo 445

18.4 Asynchronous validation with INotifyDataErrorInfo 446

The INotifyDataErrorInfo interface 446Implementing the interface 447Binding support 448Building the WCF

Trang 14

web service 448Adding the client service code 449 Property modifications 450

18.5 Annotating for validation 451

Validation attributes 452Annotating your entity 453 Calling external validation functions 454Creating custom validators 456

18.6 Comparison of validation approaches 457

18.7 Summary 458

19.1 The web request/response pattern 461

WebRequest and HttpWebRequest 462WebResponse and HttpWebResponse 463

19.2 Simplifying the request/response pattern with WebClient 465

String operations 465Stream operations 468

19.3 Asynchronous communication 469

When async methods attack 470Saving your sanity with Rx 471Simplifying with tasks 474

19.4 Trust and cross-domain network access 476

Structuring the cross-domain file 477Other cross-domain policy files 479Locating your cross-domain policy 480

19.5 The browser HTTP stack 481

Connection count limit 481Cookies 482Caching 482

19.6 The client HTTP stack 483

Manually creating the client stack 483Automatically using the client stack 484Automatically setting the HTTP Referer and other headers 484Authentication credentials 485 Managing cookies with the CookieContainer 486When to use the client stack 488

19.7 Checking the network state 489

19.8 Summary 490

20.1 Introducing ASP.NET SOAP services using ASP.NET 492

Silverlight-compatible SOAP services 492Service references 495Receiving data with the proxy 495 Sending data using the proxy 499

Trang 15

20.2 Using WCF services and complex data types 500

Creating the Silverlight-enabled WCF service 501Sharing type definitions 505Adding the service reference 508 Using the service 509

20.3 Using the configuration file 511 20.4 Error handling with WCF 513

Using an out parameter 513Exposing exception information for debugging 515Error handling with WCF SOAP faults 516

20.5 Summary 518

21.1 Creating a RESTful service using the ASP.NET Web API 522

Solution setup 523Creating the services 525Testing the service using the browser 530Adding the Silverlight project 531

21.2 Consuming REST services 539

REST service GET operations 540Updating resources by POSTing to the service 544Removing resources using DELETE 546

21.3 Summary 548

22.1 Parsing plain old XML 550

LINQ to XML 550XmlSerializer 554

22.2 Working with JSON 558

JsonObject and JsonArray 559DataContractJsonSerializer 562

22.3 Working with RSS and Atom 566

Reading syndication feeds 566Working with feed items 569

22.4 Summary 573

23 Duplex, sockets, and local connections 575

23.1 WCF polling duplex services 576

Creating the project and callback contract 577Creating the service 579Creating the service logic 582Managing client subscriptions 584Using the duplex service 585

Trang 16

23.4 Connecting to other local Silverlight applications 595

Creating the receiver 596Creating the sender 597 Putting it all together 597

23.5 Summary 599

P ART 4 2D AND 3D GRAPHICS 601

Creating from existing images 633Creating from UI elements 634A Mandelbrot fractal generator 636

25.3 Deep Zoom 638

Showing an image 639Zooming in and out 639 Managing the viewport 641Deploying multiscale images 643

Trang 17

25.4 Dealing with dead space 643

Filling the space 644Uniform sizing 645Fill the area 646UniformToFill 647

25.5 Summary 647

26.1 3D—a natural way of interacting with information 650 26.2 The Silverlight/XNA 3D API 652

Rendering pipeline 652Project templates 653

26.3 Detecting capabilities with the GraphicsDeviceManager 654 26.4 Using the DrawingSurface 658

26.5 Project structure: the scene and objects 659

The scene 660Renderable scene objects 663 The camera 665

26.8 Summary 678

27 3D lighting, texturing, and animation 679

27.1 Lighting and normal vectors 680

Lighting the scene 681Sphere normal vectors 682 Indexed vertices 684

27.2 Applying a texture 687

The ContentManager 687Texturing the sphere 688 Adding and texturing a background 691

27.3 Coordinate spaces and matrices 695

The three coordinate space conversion matrices 696 The Matrix class 697

27.4 Keyframe animation 698

The KeyFrame and KeyframeAnimation classes 698 Using animation 703

27.5 Summary 706

Trang 18

P ART 5 M AKING THE MOST OF THE PLATFORM 709

28 Pop-ups, windows, and full-screen applications 711

28.1 Showing pop-ups and child windows 712

The Popup control 713Displaying a dialog box with the ChildWindow control 713

28.2 Creating native windows 717

Creating a normal window 718Customizing window chrome 723

28.3 Running in full screen 730

Normal full-screen mode 731Elevated trust full-screen mode 732

28.4 Summary 733

29.1 Browser navigation background 735

Browser journals 735Anchor hashtags 736 Back and forth 737

29.2 The Navigation Application template 738

Creating a navigation application 738Adding a new page 740Changing the application theme 742

29.3 Navigating to pages 744

The Page class 744The NavigationService class 746 Frames and URIs 748Caching pages 751

Navigating to pages in other assemblies 753

29.4 Navigation out of the browser 755

Providing custom navigation controls 756

29.5 Summary 759

30 Working with files and directories 761

30.1 Using the file open and save dialogs 762

Working with the OpenFileDialog 763Saving files with the SaveFileDialog 767

30.2 Working with directories 770

Getting directory timestamps 772Checking for directory existence 774Getting the directory root 774Creating and deleting directories 775Listing directory contents 777 Accessing special folders 778

Trang 19

30.3 Working with individual files 780

Creating a file 784Writing to a file 785Reading from a file 787Getting and setting file metadata 789

File utility functions 790

30.4 Storing data in isolated storage 791

IsolatedStorageFile: the virtual filesystem 792Reading and writing files: the isolated storage way 795

30.5 Summary 797

31.1 How Silverlight printing works 799

The PrintDocument class 801The PrintPage Event 804 Converting to PostScript 807Rasterization 807 Forcing bitmap printing 808Forcing vector printing 809

31.2 Printing onscreen information 810

Printing the content as is 810Reparenting the elements

to fit 812Scaling content to fit 814

31.3 Multipage printing dedicated trees 816

Prerequisites 816Printing line items 820Adding multipage support 825Adding a header and footer 827

32.2 Native Extensions for Silverlight 839

Accessing an accelerometer 840Integrating with the Windows taskbar 849Runtime automation server installation 855

32.3 P-invoke for API calls 857

Setting up the printer application 857The Win32 API interface 860

32.4 Summary 865

Trang 20

P ART 6 B EST PRACTICES 867

33 Structuring and testing with the MVVM pattern 869

33.1 Project setup and traditional code-behind approach 870

Project and service setup 871A typical code-behind solution 875

33.2 Model-View-ViewModel basics 878

Myths about MVVM Model-View-ViewModel 881Keep it simple: a basic ViewModel implementation 882

33.3 Factoring out reusable code 887

Business rules and logic 888Data access and service calls 890

33.4 Better separation from the UI 892

Using commands 892Using the CallMethodAction behavior 896View-specific entities and ViewModels 898 Interfaces, IoC, and ViewModel locators 903

33.5 Testing MVVM applications 906

Introduction to the Silverlight Unit Testing Framework 906 Testing the ViewModel 910Testing asynchronous operations 911

34.3 Troubleshooting network operations 923

Installing Fiddler 924Monitoring and logging traffic 924 Inspecting individual requests 926

34.4 Summary 928

Trang 21

35 The install experience and preloaders 929

35.1 Handling the ‘Silverlight not installed’ scenarios 930

Creating your own install experience 931

35.2 Using a custom preloader 933

Creating the appearance 934Integrating the custom splash screen 936Monitoring the load progress 936

35.3 Summary 937

online appendixes

Online appendixes available as a free download from

www.manning.com/Silverlight5inAction

Trang 22

preface

Coding on the client is fun I started on the Commodore 64 in seventh grade in the1980s; later moved to DOS with dBASE, QuickBasic, and C++; and eventually began Win-dows programming using C++, Borland Delphi 1.0, PowerBuilder, Visual Basic 3-6, and.NET I like the ozone smell of making my CPU work for a living I like being able to tapinto the power of the local machine I want to be able to hear the individual bits movingacross the bus

I like client application development, and I really like XAML I like Silverlight, WPF,and Windows 8 XAML I even like working in the WPF subset on the NET MicroFramework and Gadgeteer boards I own Sometimes, when I’m feeling especially dan-gerous I’ll write some C++, or C, or even a little assembly It’s all about the power

A year and a half ago, Manning published Silverlight 4 in Action As proud as I am of

that book, I’m even more excited to bring you this updated version Not only because

of the work involved in bringing you this edition, but because of how far Silverlighthas come in that time With Silverlight 5, Silverlight has the power.1

What a difference a year and a half makes! Silverlight 4 saw significant uptakeamong business application developers, and those same developers helped drive thefeatures that made it into Silverlight 5 These developers are writing the types ofbread-and-butter applications that leverage Silverlight for its simple deployment andgreat validation and data binding capabilities

1 And now, you have C&C Music Factory’s “I Got the Power” looping in your head You can thank me later.

Trang 23

General adoption of Silverlight is up too, as you can see in figure 1 These unofficialthird-party charts, reformatted for print from http://riastats.com data obtained inearly 2012, show Silverlight and Adobe Flash adoption taken from a large segment ofthe general internet population They reveal overall Silverlight adoption at a hair over

75 percent with version 4 at a bit over 67 percent and overall flash adoption around 96percent, with Flash 11 at a hair over 70 percent

I’m not a marketing person; I’m a developer Although such a blunt numbers parison between the two competing products may look dire at first glance, adoptionnumbers like these aren’t at all bad, considering Silverlight was a far more recentintroduction and didn’t benefit from either the late 1990s boom in website intro apps

com-or bundling with Internet Explcom-orer 6 You can do a lot with 75 percent of the PCs outthere It’s my goal to help you do it

2011 was also a rocky year for Silverlight and Flash developers, with confusion overwhat Silverlight is to be used for and where it fits into the development strategy atMicrosoft and in the web as a whole The Apple position on Flash didn’t help Flash orplug-ins in general Flash definitely had a reputation for websites, whereas Silverlightevolved to more of a browser-delivered client technology There were as many, if notmore, out-of-browser apps as in-browser apps written in Silverlight

With HTML5 (and JavaScript and CSS3, all of which I’ll lump into “HTML5” just asthe media tends to) having picked up serious speed, especially on the media andcasual games front on the public web, I think it’s a sure bet to become the way forwardfor broad-reach, public-facing website content There’s so much momentum behindHTML5 that to fight it would simply land you behind others HTML5 will suit you justfine, especially for run-of-the-mill, non-digital rights management (DRM), non-smooth-streaming media like what you see on YouTube

But for many, HTML5 isn’t a realistic choice Either you can’t count on browsersupport for key features, or you have a behind-the-firewall (or other controlled net-work) application scenario that makes it easier for you to use technologies you’ll be

Figure 1 Adoption of Adobe Flash vs Microsoft Silverlight in 2012

Trang 24

more productive in Two key points rise above any trendy discourse and well into therealm of GSD (Getting Stuff Done):

Know your audience—Develop in what your users can use (behind the firewallhas more choice and control than the public web)

Know your skills and requirements—Develop in what you can be most productivein—what will meet the project requirements with the least amount of fudging.Without a doubt, most NET developers are more productive in Silverlight when build-ing business applications There’s so much there, right in the box, that makes it easyfor you to quickly create stunning, feature-rich apps Not only that, but the added sys-tem integration features of Silverlight 5 (like COM and p-invoke) make it even morecompelling as a platform

As a developer, or manager of developers, you must choose technology based notonly on the longevity of that technology, but also on what makes it possible for you todeliver the best possible application for the most reasonable cost

Regardless of where Silverlight goes in the long term, you already know that XAML,C#, and Visual Basic are all here to stay In addition to continued desktop support forSilverlight and WPF, Microsoft is using XAML in Windows 8 Metro and on the WindowsPhone I believe in XAML strongly enough to have written this book (around 1,200pages if you include the downloadable content) while working at Microsoft, as well as

a book dedicated to XAML on Windows 8 Given the resources dedicated to XAMLdevelopment and tools at Microsoft, I’m glad to see they believe in it too

Ultimately, it’s good to have a choice I choose XAML I choose Silverlight

Trang 25

acknowledgments

A book of this size and complexity takes a large number of people to write (and tolift) Though my name is on the cover, there’s no way I could’ve completed this with-out the support and hard work of many others I’d like to thank:

■ Chad Campbell and John Stockton for creating such an excellent first edition.Without their hard work covering Silverlight 2, I’d never have thought to create

a Silverlight 4 edition or this Silverlight 5 edition

■ The Silverlight product team for their continued help in digging into thedetails of the runtime There were too many helpful people to list here

■ My stalwart tech reviewer Tom McKearney I appreciate most that he didn’t justdie on the spot when he was told the 800 pages he had to review were actually inthe 1,200 neighborhood

■ I’d like to thank my friends at Manning People like Mary Piergies, Liz Welch,Elizabeth Martin, and others worked tirelessly to get this book published intime Michael Stephens, Maureen Spencer, and of course, Marjan Bace allworked with me to help ensure that you, the reader, get all the text I wrote,without them having to print a multivolume set I thank them and the rest ofthe folks at Manning

■ Unique in this thanks is my development editor, Jeff Bleiel A good editor canmake the difference between a horrible authoring experience and a good one,and for the second time, Jeff definitely made that difference He was my inter-face with Manning and my continued mentor as an author Jeff made a positivecontribution to this book and to my writing in general

Trang 26

■ Thanks to the following reviewers who read the manuscript at various stages ofits development; your insight and feedback made this a better book: DaveCampbell, Mark Monster, “Anil” Radhakrishna, Darren Neimke, MichaelCrump, Dave Davis, Joe Suchy, and Rich Dudley.

■ I’d like to thank my mum for making sure I knew the difference between

“you’re” and “your” and that spelling always counts Hi, Mum!

■ Most importantly, I’d like to thank my wife Melissa and my children Ben andAbby for sticking by me as I spent day after day basking in the cool glow of mytwin 30-inch displays staring at a mosaic of Microsoft Word, Visual Studio, andAdobe Illustrator Writing a book involves the whole family, regardless of whosename goes on the cover

■ A special thanks to my son Ben, who is now learning to read, and is superexcited that his old man “makes robots and writes HUGE books!” for a living

■ Finally, I’d like to thank you, my readers Thank you again for making this ble I’ll make it worth the trip

Trang 27

about this book

The goal of this book is to take you, the developer who’s at least a little familiar withC# and NET, and help you become an awesome Silverlight developer If you’re already

an awesome Silverlight developer, I’ve included deep topics to help you learn moreabout the platform and how things work under the covers

After you’ve read this book, you should be able to confidently design, develop, anddeliver Silverlight applications that meet your application requirements To facilitatethe learning process, I’ve structured the book to get you developing as soon as possi-ble, while providing quality, in-depth content

Within each chapter, I’ve included a collection of devices to help you build a firmunderstanding of Silverlight The following list explains how each device helps alongthe journey:

Figures—Visual depictions that summarize data and help with the connection of

complex concepts Silverlight is highly visual

Code snippets—Small, concise pieces of code primarily used for showing

syntacti-cal formats You’re usually not expected to type these in and compile, becausethey’re incomplete

Code listings—Code that you can type into your project in Visual Studio In many

cases, it will take multiple code listings to build a working example

Tables—Easy-to-read summaries.

In addition to these learning devices, my site http://10rem.net hosts some imageassets and contains links to the code samples used in this book

Trang 28

This book assumes you have at least a passing familiarity with common web dards such as HTML, CSS, XML, and JavaScript This content comes up primarily inintegrating with the browser, but also to help draw parallels with other approaches

In addition, and more importantly, this book assumes you have a backgroundusing the NET Framework and Microsoft Visual Studio Although I’ll be using C# asthe primary development language, I won’t be reviewing the C# language or explain-ing basic programming constructs such as classes, methods, and variables

Experience with previous versions of Silverlight isn’t required for this book

The bits: what you need

This book provides ample opportunity for hands-on learning But it also provides agreat deal of flexibility by allowing you to learn the material without using the hands-

on content or optional tools You’ll find it equally valuable to read this book at thecomputer, on the train, or wherever else you happen to be

If you want to get the greatest value out of this book and use the hands-on nities, the following tools are recommended:

opportu-■ Visual Studio 2010 Pro or higher, or Visual Studio Web Developer 2010 (free)

■ You can also use Microsoft Visual Studio 11

■ Silverlight 5 tools for Visual Studio 2010, including the Silverlight 5 SDK andWCF RIA Services

■ The Silverlight toolkit

■ Microsoft Expression for Silverlight 5 (optional)

■ Microsoft Expression Blend SDK for Silverlight 5 (installed with Blend) for ating and using behaviors

cre-You’ll find links to all of these tools at http://silverlight.net/GetStarted

Roadmap

Developing for Silverlight is a large topic I’ve endeavored to cover a bit of everythinghere, with special emphasis on topics useful to professional developers To aid yourjourney through this book, I’ve broken it up into six parts and a set of appendixes

Part 1 Core Silverlight

Part 1 covers the most important concepts to understand when learning Silverlight Itbegins with a brief introduction to Silverlight and a step-by-step “Hello World!” exam-

Trang 29

ple The remaining chapters in part 1 cover XAML, the application model, the ins, HTML and browsers, out-of-browser applications, and the security model and ele-vated trust mode.

plug-Part 2 Creating the user interface

Part 2 covers the visible parts of Silverlight applications In this part you’ll learn aboutrendering, layout, panels, transformations, mouse and keyboard input, text displayand editing, controls, animation, UI styles, and custom controls and panels

Part 3 Working with data and services

Most applications need to access data, whether it’s on the local machine or hidingbehind a service on a remote server Part 3 covers everything you need to know towork with all sorts of data in Silverlight, starting with binding, data controls, and inputvalidation and finishing with SOAP services, RESTful services, XML, JSON, RSS, andWCF Duplex services

Part 4 2D and 3D graphics

Most visual elements in Silverlight are composed of graphics primitives Part 4 startsoff with working with graphics like lines and circles, and show you how to augmentthem using effects like blurs and drop shadows You’ll even learn how to create yourown effects and shaders To round out the 2D content, part 4 also includes great infor-mation on working with bitmap graphics The last two chapters in this part cover 3Dgraphics from the basics of points, meshes, lighting, and shading, all the way to creat-ing your own frame-based animation system

Part 5 Making the most of the platform

Silverlight is a client-side technology Because of that, it makes sense to want to grate more deeply with the computer and tap some of its capabilities Part 5 coverscross-platform integration features like full-screen applications, windows, pop-ups,navigation, file access, and printing, as well as Windows-only features such as p-invokeand COM automation

inte-Part 6 Best practices

This book wraps up with a number of best practices you’ll want to apply once you getthe basics under your belt Specifically, you’ll learn about the MVVM (Model-View-ViewModel) pattern as well as customizing the installation and loading experience.Information on techniques for debugging applications rounds out this part

Appendixes

There are six appendixes in the book One is included in the print book; the othersare available as a free download from the publisher's website at www.manning.com/Silverlight5inAction These appendixes were originally written to be included as part

of the print book, so they’re of the same quality as the rest of the book Because of

Trang 30

their relative niche appeal, they’ve been pulled out and made into downloadablechapters.

■ Appendix A is included in the print book It covers setup of the database andservices used in some of the examples

■ Appendix B covers the basics of media, including media advances in Silverlight 5

■ Appendix C builds on this to describe how to generate media on the fly andcapture media from the webcam and microphone

■ Appendixes D, E, and F cover WCF RIA Services Appendix D introduces WCFRIA Services and sets up the example project Appendix E covers security, busi-ness logic, and techniques for partitioning your application Appendix F takesall this information and applies the MVVM information from chapter 33, as well

as advances in the latest version of WCF RIA Services, to provide the best possiblestructure for your WCF RIA Services application

Code conventions and downloads

All the code used in this book is presented in a monospaced font like this Thiscode can be in one of a variety of languages; the language used is indicated at thebeginning of the code block For longer lines of code, a wrapping character may beused to be technically correct while forming to the limitations of a printed page.Annotations accompany many of the code listings and numbered cueballs are used iflonger explanations are needed

Longer listings of code examples appear under clear listing headers; shorter ings appear between lines of text

The source code for all of the examples in the book is available for download fromthe publisher’s website at www.manning.com/Silverlight5inAction and from theauthor’s website at http://10rem.net

Author Online

The purchase of Silverlight 5 in Action includes free access to a private forum run by

Manning Publications where you can make comments about the book, ask technicalquestions, and receive help from the author and other users You can access and sub-scribe to the forum at www.manning.com/Silverlight5inAction This page providesinformation on how to get on the forum once you’re registered, what kind of help isavailable, and the rules of conduct in the forum

Manning’s commitment to our readers is to provide a venue where a meaningfuldialogue between individual readers and between readers and the author can takeplace It isn’t a commitment to any specific amount of participation on the part of theauthor, whose contributions to the book’s forum remains voluntary (and unpaid) Wesuggest you try asking the author some challenging questions, lest his interest stray! The Author Online forum and the archives of previous discussions will be accessi-ble from the publisher’s web site as long as the book is in print

Trang 31

In addition to the Author Online forum available on Manning’s website, you mayalso contact us regarding this book, or anything else, through one of the followingavenues:

Pete’s site and blog—http://10rem.net

Pete’s Twitter account—http://twitter.com/pete_brown

About the author

Pete Brown currently works for Microsoft helping to educate developers on all thingsXAML, as well as the NET Micro Framework and programmable devices Prior to joiningMicrosoft in 2009, Pete was an architect, engagement manager, and user experiencedesigner at a consulting company in the Washington, DC, area, where he focused onSilverlight and WPF development During that time he was also an International NETAssociation (INETA) speaker, a Microsoft WPF MVP, and a Microsoft Silverlight MVP Pete enjoys writing, woodworking, electronics, programming, making things with

no practical use, acquiring huge monitors, cooking processors, and spending timewith his wife and two children at their home in Maryland

Pete’s man cave…er…home office looks like a cross between a Commodoremuseum, a radio station, and Dexter’s lab (the one with Dee Dee as a sister, not theserial killer, honestly)!

Pete’s site and blog is at http://10rem.net Drop him a line

About the title

By combining introductions, overviews, and how-to examples, the In Action books are

designed to help learning and remembering According to research in cognitive ence, the things people remember are things they discover during self-motivatedexploration

Although no one at Manning is a cognitive scientist, we are convinced that forlearning to become permanent it must pass through stages of exploration, play, and,interestingly, retelling of what is being learned People understand and remembernew things, which is to say they master them, only after actively exploring them

Humans learn in action An essential part of an In Action book is that it’s example

driven It encourages the reader to try things out, to play with new code, and explorenew ideas

There is another, more mundane, reason for the title of this book: our readers arebusy They use books to do a job or solve a problem They need books that allow them

to jump in and jump out easily and learn just what they want just when they want it

They need books that aid them in action The books in this series are designed for

such readers

Trang 32

illus-be surprised to find their art gracing the front cover of a computer programmingbook two hundred years later.

The collection was purchased by a Manning editor at an antiquarian flea market inthe “Garage” on West 26th Street in Manhattan The seller was an American based inAnkara, Turkey, and the transaction took place just as he was packing up his stand forthe day The Manning editor did not have on his person the substantial amount ofcash that was required for the purchase and a credit card and check were both politelyturned down With the seller flying back to Ankara that evening the situation was get-ting hopeless What was the solution? It turned out to be nothing more than an old-fashioned verbal agreement sealed with a handshake The seller simply proposed thatthe money be transferred to him by wire and the editor walked out with the bankinformation on a piece of paper and the portfolio of images under his arm Needless

to say, we transferred the funds the next day, and we remain grateful and impressed bythis unknown person’s trust in one of us It recalls something that might have hap-pened a long time ago

Trang 33

The pictures from the Ottoman collection, like the other illustrations that appear

on our covers, bring to life the richness and variety of dress customs of two centuriesago They recall the sense of isolation and distance of that period—and of every otherhistoric period except our own hyperkinetic present Dress codes have changed sincethen and the diversity by region, so rich at the time, has faded away It is now oftenhard to tell the inhabitant of one continent from another Perhaps, trying to view itoptimistically, we have traded a cultural and visual diversity for a more varied personallife Or a more varied and interesting intellectual and technical life

We at Manning celebrate the inventiveness, the initiative, and, yes, the fun of thecomputer business with book covers based on the rich diversity of regional life of twocenturies ago‚ brought back to life by the pictures from this collection

Trang 34

Part 1 Core Silverlight

When you’re learning a new technology, it’s always a good idea to start atthe core: the core concepts, the core features, the core technologies, and thecore skills Taking that as a given, the first six chapters of this book will get youthe grounding you need to learn about Silverlight and make good decisionsabout how you write your applications

In the first chapter, you’ll learn what Silverlight is and how it fits into thedeveloper platforms offered by Microsoft You’ll spend the remainder of thechapter building your very first Silverlight application Believe me, it won’t be aboring old “Hello World!”

XAML is the XML-based approach to defining the UI for Silverlight, WPF,Windows Phone, and Windows 8 XAML applications These chapters take a deeplook into XAML so that you’ll understand how it works, how to handlenamespaces, how to map objects into XAML, and much more

Silverlight differs substantially from other client and web technologies when

it comes to its application model and how the plug-in integrates with the system.It’s essential and interesting to learn how all the pieces fit together, so I’ll coverthat next

Building on what you learned about the app model and web page plug-in, I’llshow you how Silverlight can integrate with web applications Silverlight hasdeep integration with the browser and HTML while running on a web page.You’ll learn how Silverlight can interact with the web page on which it resides,even to the point of manipulating the page’s DOM from within Silverlight From there, I’ll turn to an increasingly popular model for Silverlight: the out-of-browser application Application developers, especially those developing

Trang 35

install from the web but otherwise look and behave like any other native application.It’s the best of both worlds.

Part 1 wraps up with a look at the security model used by Silverlight, including how

it determines whether code is safe to run and how to get elevated permissions toescape from the sandbox

First, you’ll explore the basics of Silverlight and build your first Silverlight tion Come with me—I think you’ll enjoy the ride

Trang 36

Introducing Silverlight

First, let me thank you for starting at chapter 1 I’m one of those people who tend

to read magazines back to front and skim technology books, so I appreciate it whensomeone reads a book’s chapters in order Then again, maybe you read this bookbackward as well In that case, you’ll find the “Hello World!” walkthrough in thischapter to be a refreshingly simple take on building Silverlight applications unen-cumbered with patterns such as Model View ViewModel (MVVM), words such asDependencyProperty, and technologies such as Windows Communication Founda-tion (WCF) Rich Internet Application (RIA) Services For the rest of you, don’t

This chapter covers

■ Silverlight, the web, and WPF

■ The best applications for Silverlight

■ Getting started with Silverlight

■ Changes in Silverlight since the previous

edition of this book

■ Building your first Silverlight “Hello World!”

application

Trang 37

worry—we’ll cover each of those throughout the rest of the book, steadily buildingour Silverlight skills as we go.

Because you’ve picked up a Silverlight book, you’d probably like to know what verlight is Luckily, I’m horrible at marketing, so I’ll put it simply: Silverlight is a cross-platform NET runtime, a cross-browser plug-in, and a set of Windows-based developertools for building RIAs At its heart, Silverlight is an implementation of the conceptsand standards from Windows Presentation Foundation (WPF) such as binding, theproperty system, and Extensible Application Markup Language (XAML) in a cross-platform version of the NET Common Language Runtime (CLR) and libraries There I think that paragraph managed to get all of the acronyms defined for therest of the book Then again, this is a Microsoft technology, so expect more acronymsbefore we’re through

Silverlight runs on Windows and Mac through Microsoft-supplied plug-ins as well

as on Linux through the Moonlight project It’s the primary development platformfor Windows Phone You’ve likely seen demos of it running on set-top boxes con-nected to TVs and serving up ads and content on the Xbox Put simply, short ofASP.NET, Silverlight is the broadest reaching technology ever produced by Microsoft Silverlight applications work on the web as well as on the client You can create vir-tually any type of application in Silverlight, from web content, to widgets, to mediaplayers, to full-blown client applications

By the end of this chapter, you’ll have created your first functional Silverlight cation, a Twitter search client with nice visualization of the tweets You’ll be intro-duced to XAML, binding, networking, controls, and much more—even a little LINQ toXML These are all topics I’ll dive deeply into in the rest of the book First, you’ll learn

appli-a bit appli-about where Silverlight fits into the developer ecosystem This is appli-a big questionfor many and needs to be resolved up front I’ll follow that up with a look at the types

of applications for which Silverlight is well suited After that, I’ll explore the featuresand capabilities that have been added since the first edition of this book

1.1 A Silverlight primer

Silverlight’s place in the world has evolved since its original inception Market forcesand customer preferences have both led to Silverlight moving more toward privateweb and line-of-business applications as opposed to broad-reach public websites andapplications Clearly both Microsoft’s customers and partners have moved to a stan-dards-based public web Nevertheless, there are great ways and reasons to use Silver-light on the public web, especially while the HTML standards are still catching up towhat plug-ins like Silverlight can accomplish Of course, on the desktop and in theenterprise, Silverlight is as viable as ever

In this section, I’ll introduce Silverlight in context, looking at how it fits into thedeveloper stack both on the web and on the desktop I’ll then look at some of thetypes of applications for which Silverlight is well suited

Silverlight got its start as a web page plug-in, so that’s where we’ll start as well

Trang 38

1.1.1 Silverlight and the web

Silverlight sits in that interesting place between desktop applications and browserapplications In many ways, when in the browser it’s like a little traditional desktopapplication embedded in HTML Of course, the same can be said of many JavaScriptapplications, themselves modeled on the code-on-the-client desktop applicationparadigm

Great frameworks such as jQuery and the oft-confused HTML5 and CSS3 furthermuddy the waters Where’s Silverlight’s place on the web? Why should you use Silver-light instead of these other technologies?

I’ll give you a few reasons:

■ Silverlight has top-tier media support, including digital rights management(DRM), far more advanced than the proposed HTML5 standards It’ll be a whilebefore HTML5 catches up across all browsers

■ Silverlight is a no-brainer if you’re already a NET developer looking to expand

to other platforms It’s simply easier to develop with and in

■ Silverlight has best-of-class development and debugging tools

Don’t get me wrong; I think HTML5 and CSS3 and even JavaScript are a great thing forthe web—exciting and capable Having said that, I contend that Silverlight has moreadvanced authoring tools, faster execution, and more capabilities than HTML5 cur-rently has HTML5 will continue to raise the floor, driving up the quality and experi-ence across the spectrum of platforms and developer tools On the public web, HTML5will eventually catch up to the capabilities of Silverlight for the majority of typical webscenarios and plug-ins won’t be needed For many public sites and applications, we’vealready reached that point due to the proliferation of plug-in–hostile tablets

I don’t think that the code-on-the-client application development approach isgoing to completely disappear Though doom has been forecast for many major devel-opment approaches over the years, few have declined when another rose in popular-ity Silverlight and HTML5 will provide more options for how to implement thesolution you need in the most optimal way, using the tools you’re comfortable withand the skills you already have The balance of what code you put in each technologywill be the real point of debate for development teams In addition, the skills youlearn as a Silverlight developer will port quite nicely to Windows 8 XAML, once youdecide to adopt that operating system

Remember that HTML/CSS/JavaScript and Silverlight aren’t mutually exclusive.Silverlight applications can happily coexist on a page with JavaScript applications,each complementing the other with features that play to their strengths

Silverlight is far more than a web technology Though it can live on a web page, it’salso common to have out-of-browser Silverlight applications, either connected to ser-vices or simply using resources on the client In those instances, you may wonderwhen to use WPF and when to use Silverlight

Trang 39

1.1.2 Silverlight and WPF

Silverlight and WPF were born of the same ideas WPF came first and broke the groundrequired to make XAML a UI-friendly markup language WPF also introduced you todependency properties and binding, storyboard-based animation, and subpixel-ren-dered vector UIs WPF was, and continues to be, an amazingly rich platform for devel-oping both traditional Windows and natural user interface (NUI) applications But WPF is large and complex It’s also deeply rooted in Windows, with no goodway to substitute alternate stacks for those it relies on WPF also relies on the ratheroutdated and web-unfriendly code access security model for application security So,when Microsoft decided to enter the RIA space with a CLR-based vector UI technology,

it took the concepts and some of the code from WPF and reimplemented them in asmaller, tighter, and more platform-independent way

Silverlight primarily is a subset of WPF

and NET 4 with significant additions Some

of the additions, such as the Visual State

Manager, have been migrated back from

Silverlight into WPF Others, such as Deep

Zoom, Media Stream Source, and the

web-cam and microphone APIs, are

Silverlight-only features, unlikely to be ported to WPF

Others like XNA sound and 3D APIs are

from entirely different technologies

Ignor-ing alternative solutions to the same

prob-lems, figure 1.1 shows this relationship

using our friend, the Venn diagram

I recommend that developers new to both technologies learn Silverlight beforelearning WPF In general, you’ll find it easier to learn Silverlight first and scale up toWPF, should your needs dictate Silverlight is smaller, typically having a singleapproach to solving a given problem, whereas WPF may have several solutions for thesame task Though Silverlight doesn’t have everything WPF has, Silverlight is an excel-lent, capable development platform and can cover many types of applications youwould’ve previously written in Windows Forms, WPF, or even HTML

1.1.3 Types of Silverlight applications

You can build just about anything you’d like using Silverlight Of course, Silverlight isbetter suited for some types of applications over others For example, though possible,you wouldn’t necessarily want to build an entire website using Silverlight; there arebetter tools for the job The most common types of applications where Silverlight is agood fit are media, business, and games

Media: Silverlight excels at media When Silverlight 1.0 was first introduced, one of

the few capabilities it had was an excellent media stack Silverlight through version 5has built on that to include new media capabilities such as smooth streaming,

Figure 1.1 Silverlight is primarily a subset of WPF with extras added Ignoring alternative solutions to the same problems, the places where WPF differs most are in the integration with the Windows OS and the access to the full NET framework.

Trang 40

enhanced navigation with trick play (media playback rate changes without pitchchanges), pluggable codecs using the Media Stream Source API, support for remotecontrols and media keys, and even the DRM technologies required for the large con-tent producers to adopt Silverlight.

Silverlight’s early focus on media was both helpful and hurtful Video on the web is

a great way to gain product adoption, especially when you have a capable high-defvideo technology

Business: Early on, many potential Silverlight developers failed to see past the media

roots and missed the rich business capabilities Silverlight provides Starting with sions 3 and 4, Silverlight gained serious business capabilities From simple things such

ver-as sync and ver-async validation, to patterns such ver-as MVVM and Prism, and entire tier frameworks such as WCF RIA Services, Silverlight showed itself to be a mature plat-form, able to absorb the best practices from other areas and build on them

middle-Games: Though business and media applications certainly are great staples,

another fun application type is games HTML5 will likely turn out to be a more lar broad-reach gaming platform, but Silverlight has good support for casual games,including the ability to generate bitmaps on the fly, create sound from bits, loop audio

popu-in the background, play real-time sound effects, manipulate and render 3D scenes,and more The community has successfully ported over physics and gaming engines toSilverlight, making it even easier to create complex casual games

There are many other types of Silverlight applications, ranging from ads, to photoviewers, to social media clients, to analogs for virtually every type of major desktop andweb application Some, such as desktop applications, weren’t possible with Silverlight

2, the version used in the first edition of this book Let’s take a high-level view of whathas changed in that time For readers of the Silverlight 4 edition, I’ll mention somekey new features in Silverlight 5 as well

How this book is organized

When I turned in the first complete version of this book, it came in at over 1,200 pages

I can’t remember the last time I owned a 1,200-page printed book, but I’m pretty surethat’s an awful lot of paper and shelf space

Rather than open the publisher up to lawsuits for all the back injuries this was likely

to cause, and also end up paying for all the damage caused by broken bookshelvessitting above your prized first-edition 1977 fine china Star Wars collector plates, I de-cided to break up the book, with all material included in the purchase price of thebook (Some reviewers suggested breaking up this book into a series of volumes, so

perhaps I could sell Encyclopedia Silverlightica door to door.) Material that isn’t

nec-essarily core to the book, or not really new to Silverlight 5, has been moved into a set

of appendices Specifically:

■ Media Basics and Raw Media, Webcam and Microphone, which didn’t havesubstantial product updates for Silverlight 5

Ngày đăng: 27/03/2019, 10:18

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w