MANNING
Pete Brown
Revised Edition of
Silverlight 4 in Action
IN ACTION
Silverlight 5 in Action
PETE BROWN
MANNING
S
HELTER
I
SLAND
For online information and ordering of this and other Manning books, please visit
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: [email protected]
©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
4
■
Working with HTML and browsers 73
5
■
Out-of-browser applications 95
6
■
The security model and elevated trust 114
P
ART
2 C
REATING
THE
USER
INTERFACE
125
7
■
Rendering, layout, and transforming 127
8
■
Panels 160
9
■
Human input 180
10
■
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
■
PART 1 CORE SILVERLIGHT 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
Features for business and client applications 8
■
Media and
graphics enhancements 10
■
User interaction 11
■
Text 11
1.3 Getting started with Silverlight development 12
Setting up your development environment 13
■
Helpful sites 13
1.4 Building your first Silverlight web application 14
Project setup 15
■
User interface 16
■
Calling Twitter
search 18
■
Parsing the results and binding the ListBox 19
■
XAP 50
■
The application
manifest file 51
■
The Silverlight application object 52
Application dependencies 55
■
Assembly caching 56
3.2 Creating the Silverlight plug-in 58
Using the object tag 59
■
Using 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 64
■
Handling plug-in
events 68
■
Sending initialization parameters 70
3.4 Summary 71
4
Working with HTML and browsers 73
4.1 Silverlight and the HTML DOM 74
4.2 Working with the web page from managed code 75
Navigating web page contents 76
■
5.2 The end-user experience 98
5.3 Creating out-of-browser applications 100
The out-of-browser settings file 100
■
Controlling the
experience 102
■
Customizing icons 105
■
Updating 105
5.4 Alerting the user with notification toast 106
5.5 Controlling the host window 107
Basic window properties 108
■
Changing window
chrome 109
■
Minimizing, maximizing, restoring, and
closing 110
■
Moving a window 111
■
Resizing 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 120
■
ScaleTransform 150
SkewTransform 150
■
TranslateTransform 151
TransformGroup 151
■
CompositeTransform 152
MatrixTransform 153
7.5 3D projection transforms 155
PlaneProjection 155
■
Matrix3dProjection 157
7.6 Summary 159
8
Panels 160
8.1 Canvas 161
Setting the offsets 162
■
Setting the stack order 163
8.2 The StackPanel 165
8.3 The WrapPanel 166
Vertical wrapping 167
■
Horizontal wrapping 168
8.4 The Grid 169
Arranging Grid content 170
■
Positioning Grid content 172
Spanning cells 172
ix
10
Text fundamentals 199
10.1 The text system 200
Subpixel text rendering 200
■
Text hinting 201
■
Text
formatting 202
■
Text rendering 203
10.2 Displaying text 204
Font properties 204
■
Flow control 208
■
Text
properties 209
■
Spacing 212
10.3 OpenType font support 215
Ligatures 216
■
Stylistic sets 217
■
Font capitals 219
Fractions and numbers 220
■
Variants, superscript, and
12.2 ContentControl 251
The ContentPresenter 252
12.3 Button controls 253
The Button 254
■
The HyperlinkButton 255
The RadioButton 255
■
The CheckBox 257
CONTENTS
x
12.4 ItemsControls 258
The ListBox 259
■
The ComboBox 262
■
The
TabControl 262
12.5 Creating UserControls 265
Defining the appearance 266
■
Defining behavior of a
control 267
■
Calling the control 270
12.6 Summary 271
13
Animation and behaviors 272
13.1 Animating a value over time 273
■
Creating your own
behavior 305
13.8 Summary 306
14
Resources, styles, and control templates 307
14.1 Being resourceful 308
Declarative resources 308
■
Accessing loose resources 314
Bundled resources 315
14.2 Giving your elements style 317
Defining the look 319
■
Explicitly keyed style definitions 321
Implicit style definitions 322
CONTENTS
xi
14.3 Creating templates 323
Building a control template 323
■
Creating reusable
templates 328
14.4 Dealing with visual states 329
Understanding the components 329
■
Leveraging the
VisualStateManager 331
14.5 Sharing your visual states 335
Visual states 360
■
Visual states in template 361
15.5 Summary 363
PART 3 WORKING WITH DATA AND SERVICES 365
16
Binding 367
16.1 Binding basics 368
Mastering the binding syntax 369
■
Choosing a binding
mode 371
16.2 Understanding your binding source 373
Binding to a property 374
■
Binding to an object 376
Binding to a UI element 378
■
Binding to an indexed
element 381
■
Binding to a keyed (string indexed)
element 382
■
Binding to an entire collection 383
Deciding when to update binding 385
CONTENTS
xii
16.3 Binding to dynamic properties 386
Customizing display 424
■
Customizing edit, add, and display
templates 425
■
Finer control over editing and committing
data 427
17.3 Annotating for display 428
The Display attribute 429
■
The Editable attribute 430
17.4 Summary 431
18
Input validation 433
18.1 The validation example source and UI 434
18.2 Exception-based property validation 438
Handling exception validation errors 438
■
Custom
validation code 439
■
Validation error display 440
18.3 Synchronous validation with IDataErrorInfo 441
The IDataErrorInfo interface 441
■
Simple validation with
IDataErrorInfo 442
■
Cross-field validation with IData-
ErrorInfo 443
19.1 The web request/response pattern 461
WebRequest and HttpWebRequest 462
■
WebResponse and
HttpWebResponse 463
19.2 Simplifying the request/response pattern with WebClient 465
String operations 465
■
Stream operations 468
19.3 Asynchronous communication 469
When async methods attack 470
■
Saving your sanity
with Rx 471
■
Simplifying with tasks 474
19.4 Trust and cross-domain network access 476
Structuring the cross-domain file 477
■
Other cross-domain
policy files 479
■
Locating your cross-domain policy 480
19.5 The browser HTTP stack 481
Connection count limit 481
■
Cookies 482
■
Caching 482
19.6 The client HTTP stack 483
■
Sharing
type definitions 505
■
Adding 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 513
■
Exposing exception information
for debugging 515
■
Error handling with WCF SOAP
faults 516
20.5 Summary 518
21
RESTful services with the ASP.NET Web API 520
21.1 Creating a RESTful service using the ASP.NET Web API 522
Solution setup 523
■
Creating the services 525
■
Testing the
service using the browser 530
■
Adding the Silverlight
project 531
21.2 Consuming REST services 539
REST service GET operations 540
■
Creating the service logic 582
■
Managing
client subscriptions 584
■
Using the duplex service 585
CONTENTS
xv
23.2 Connecting to sockets 589
Serving the policy file 590
■
Opening the connection 591
Handling the response 591
23.3 Multicast sockets 593
Any-Source Multicast/Internet Standard Multicast 593
Source-Specific Multicast 594
23.4 Connecting to other local Silverlight applications 595
Creating the receiver 596
■
Creating the sender 597
Putting it all together 597
23.5 Summary 599
PART 4 2D AND 3D GRAPHICS 601
24
Graphics and effects 603
24.1 Shapes 604
Lines 605
■
Creating from UI
elements 634
■
A Mandelbrot fractal generator 636
25.3 Deep Zoom 638
Showing an image 639
■
Zooming in and out 639
Managing the viewport 641
■
Deploying multiscale
images 643
CONTENTS
xvi
25.4 Dealing with dead space 643
Filling the space 644
■
Uniform sizing 645
■
Fill the
area 646
■
UniformToFill 647
25.5 Summary 647
26
Introduction to 3D 649
26.1 3D—a natural way of interacting with information 650
26.2 The Silverlight/XNA 3D API 652
Rendering pipeline 652
Sphere normal vectors 682
Indexed vertices 684
27.2 Applying a texture 687
The ContentManager 687
■
Texturing 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
CONTENTS
xvii
PART 5 MAKING 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 713
■
Displaying a dialog box with the
ChildWindow control 713
28.2 Creating native windows 717
Creating a normal window 718
■
Customizing window
chrome 723
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 763
■
Saving files with the
SaveFileDialog 767
30.2 Working with directories 770
Getting directory timestamps 772
■
Checking for directory
existence 774
■
Getting the directory root 774
■
Creating
and deleting directories 775
■
Listing directory contents 777
Accessing special folders 778
CONTENTS
xviii
30.3 Working with individual files 780
Creating a file 784
■
Writing to a file 785
■
Reading from a
Prerequisites 816
■
Printing line items 820
■
Adding
multipage support 825
■
Adding a header and footer 827
31.4 Summary 830
32
COM, Native Extensions, and p-invoke 832
32.1 COM automation 833
Detecting COM automation availability 834
■
Using COM
automation to make Silverlight talk 835
■
Accessing GPS data
using COM automation 836
■
Automating Excel 837
32.2 Native Extensions for Silverlight 839
Accessing an accelerometer 840
■
Integrating with the
Windows taskbar 849
■
Runtime automation server
installation 855
32.3 P-invoke for API calls 857
behavior 896
■
View-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 910
■
Testing asynchronous
operations 911
33.6 Summary 912
34
Debugging your application 913
34.1 Debugging basics 914
Using the Debug class 914
■
IDE breakpoints 916
The good old MessageBox 918
34.2 Binding debugging 920
Viewing binding errors in the output window 921
■
Debugging
with custom value converters 922
■
Using XAML
breakpoints 922
34.3 Troubleshooting network operations 923
Installing Fiddler 924
■
Monitoring and logging traffic 924
Coding on the client is fun. I started on the Commodore 64 in seventh grade in the
1980s; 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 tap
into the power of the local machine. I want to be able to hear the individual bits moving
across 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 Micro
Framework 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 Silverlight
has 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 uptake
among business application developers, and those same developers helped drive the
features that made it into Silverlight 5. These developers are writing the types of
bread-and-butter applications that leverage Silverlight for its simple deployment and
great 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.
PREFACE
xxii
General adoption of Silverlight is up too, as you can see in figure 1. These unofficial
third-party charts, reformatted for print from http://riastats.com data obtained in
PREFACE
xxiii
more productive in. Two key points rise above any trendy discourse and well into the
realm of GSD (Getting Stuff Done):
■
Know your audience —Develop in what your users can use (behind the firewall
has more choice and control than the public web).
■
Know your skills and requirements —Develop in what you can be most productive
in—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 easy
for 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 more
compelling as a platform.
As a developer, or manager of developers, you must choose technology based not
only on the longevity of that technology, but also on what makes it possible for you to
deliver 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 for
Silverlight and WPF, Microsoft is using XAML in Windows 8 Metro and on the Windows
Phone. I believe in XAML strongly enough to have written this book (around 1,200
pages 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 XAML
development 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.