Silverlight 2 Unleashed1st Edition Laurent
Bugnion download
https://ebookbell.com/product/silverlight-2-unleashed-1st-
edition-laurent-bugnion-2176608
Explore and download more ebooks at ebookbell.com
2.
Here are somerecommended products that we believe you will be
interested in. You can click the link to download.
Silverlight 4 Unleashed 1st Edition Laurent Bugnion
https://ebookbell.com/product/silverlight-4-unleashed-1st-edition-
laurent-bugnion-2104258
Silverlight 10 Unleashed 1st Edition Adam Nathan
https://ebookbell.com/product/silverlight-10-unleashed-1st-edition-
adam-nathan-980298
Silverlight 20 For Aspnet Developers Swift Jonathanalvarez
https://ebookbell.com/product/silverlight-20-for-aspnet-developers-
swift-jonathanalvarez-22123486
Silverlight 2 Visual Essentials 1st Edition Matthew Macdonald
https://ebookbell.com/product/silverlight-2-visual-essentials-1st-
edition-matthew-macdonald-42992032
3.
Silverlight 2 RecipesA Problemsolution Approach 1st Edition Jit Ghosh
https://ebookbell.com/product/silverlight-2-recipes-a-problemsolution-
approach-1st-edition-jit-ghosh-4491144
Silverlight 2 Bible Brad Dayley Lisa Danae Dayley
https://ebookbell.com/product/silverlight-2-bible-brad-dayley-lisa-
danae-dayley-1426516
Silverlight 2 In Action 1st Edition Chad A Campbell John Stockton
https://ebookbell.com/product/silverlight-2-in-action-1st-edition-
chad-a-campbell-john-stockton-1380724
Silverlight 2 In Action 1st Edition Chad A Campbell John Stockton
https://ebookbell.com/product/silverlight-2-in-action-1st-edition-
chad-a-campbell-john-stockton-59800590
Pro Silverlight 2 In C 2008 1st Edition Matthew Macdonald Auth
https://ebookbell.com/product/pro-silverlight-2-in-c-2008-1st-edition-
matthew-macdonald-auth-4201368
6.
Table of Contents
Copyright.....................................................................................................1
Foreword.................................................................................................... 4
About the Author......................................................................................... 5
Acknowledgments....................................................................................... 6
We Want to Hear from You!........................................................................ 7
Introduction............................................................................................... 9
About Code in This Book................................................................................................................................................................ 9
One Year Older.............................................................................................................................................................................. 10
Chapter 1. Introducing Silverlight.............................................................. 11
Where Does Silverlight Come From?............................................................................................................................................ 12
Using Third-Party Plug-Ins........................................................................................................................................................... 15
Running on Multiple Platforms..................................................................................................................................................... 17
Making the Web Application Secure............................................................................................................................................. 18
Introducing Silverlight.net............................................................................................................................................................ 19
What Do You Need to Run Silverlight?......................................................................................................................................... 19
Updating Your Runtime—Automatically..................................................................................................................................... 20
Trying Silverlight Demos.............................................................................................................................................................. 20
What Do You Need to Develop Silverlight?.................................................................................................................................. 24
Reading the Documentation......................................................................................................................................................... 25
Looking into Silverlight’s Future.................................................................................................................................................. 27
Summary....................................................................................................................................................................................... 28
Chapter 2. Understanding XAML.............................................................. 29
Using XML for Data...................................................................................................................................................................... 29
Using XML for User Interfaces..................................................................................................................................................... 31
Understanding XML Namespaces................................................................................................................................................ 31
Defining Additional Namespaces................................................................................................................................................. 32
Creating a Canvas with Children.................................................................................................................................................. 33
Attaching Properties: Canvas.Left and Canvas.Top..................................................................................................................... 34
Documenting Your Markup with XML Comments...................................................................................................................... 35
Testing XAML Markup................................................................................................................................................................. 35
Setting Properties in XAML.......................................................................................................................................................... 38
Changing Brushes......................................................................................................................................................................... 40
Composing Scenes in XAML........................................................................................................................................................ 40
Saving Typing, Saving Space......................................................................................................................................................... 42
Summary....................................................................................................................................................................................... 43
Chapter 3. Playing with XAML Transforms and Animations..................... 45
Transforming Visuals.................................................................................................................................................................... 45
Types of Transforms...................................................................................................................................................................... 47
Composing Transforms................................................................................................................................................................. 52
Creating a Basic Animation.......................................................................................................................................................... 54
Understanding the Animation’s Elements................................................................................................................................... 55
Adding a Scale Animation............................................................................................................................................................. 57
Using Other Types of Animations................................................................................................................................................ 58
Deploying the Scene to a Web Page.............................................................................................................................................. 60
Summary....................................................................................................................................................................................... 60
Chapter 4. Expression Blend..................................................................... 61
The Expression Studio in Short.................................................................................................................................................... 61
Installing Expression Blend.......................................................................................................................................................... 62
Starting Expression Blend............................................................................................................................................................ 62
Setting Options.............................................................................................................................................................................. 63
Creating a New Project................................................................................................................................................................. 64
Understanding the Panels............................................................................................................................................................. 65
Looking at the Files....................................................................................................................................................................... 66
Silverlight 2 Unleashed
7.
Executing in theWeb Browser...................................................................................................................................................... 67
Working with Shapes.................................................................................................................................................................... 67
Using the Properties Panel........................................................................................................................................................... 68
Using the Color Picker.................................................................................................................................................................. 69
Creating a 3D Border Effect Using RadialGradientBrush............................................................................................................ 71
Resetting Properties to Their Default Value................................................................................................................................. 72
Composing the Elements Hierarchy............................................................................................................................................. 72
Summary....................................................................................................................................................................................... 73
Chapter 5. Using Media............................................................................. 75
Mixing Colors................................................................................................................................................................................ 75
Seeing Through the Transparency Channel.................................................................................................................................. 77
Seeing Through the Opacity.......................................................................................................................................................... 79
Using Vector Graphics.................................................................................................................................................................. 80
Adding Media to Your Scenes....................................................................................................................................................... 82
Controlling Sound and Video....................................................................................................................................................... 88
Checking the Other Properties...................................................................................................................................................... 91
Using Media to Write.................................................................................................................................................................... 92
Transforming Media..................................................................................................................................................................... 94
Using Web-Based Media............................................................................................................................................................... 94
Summary....................................................................................................................................................................................... 95
Chapter 6. Blending a Little More.............................................................. 97
Creating Transforms..................................................................................................................................................................... 97
Creating an OpacityMask.............................................................................................................................................................. 98
Using Paths................................................................................................................................................................................. 100
Clipping Path............................................................................................................................................................................... 102
Grouping Controls....................................................................................................................................................................... 103
Making a User Control................................................................................................................................................................ 106
Working on the Thumbnails Gallery.......................................................................................................................................... 109
Summary...................................................................................................................................................................................... 113
Chapter 7. Deploying to a Web Page......................................................... 115
Creating a Test Page..................................................................................................................................................................... 115
Understanding the object Tag...................................................................................................................................................... 117
Detecting Silverlight.................................................................................................................................................................... 122
Integrating Silverlight in an Existing Web Page......................................................................................................................... 123
Getting Web Space...................................................................................................................................................................... 128
Getting Started with FTP............................................................................................................................................................ 130
Copying Your Silverlight Application.......................................................................................................................................... 132
Summary...................................................................................................................................................................................... 134
Chapter 8. Programming Silverlight with JavaScript............................... 137
Learning the Basics..................................................................................................................................................................... 138
Understanding the Concept of Objects....................................................................................................................................... 144
Using the Literal Notation JSON................................................................................................................................................ 146
Static Members............................................................................................................................................................................ 148
Loading Scripts in a Web Page.................................................................................................................................................... 149
Understanding the Context......................................................................................................................................................... 150
Integrating Silverlight in an Existing Web Page Using JavaScript............................................................................................. 151
Debugging.................................................................................................................................................................................... 158
Summary...................................................................................................................................................................................... 159
Chapter 9. Understanding .NET............................................................... 161
History of .NET............................................................................................................................................................................ 161
Downloading and Installing Visual Studio 2008....................................................................................................................... 164
Creating a Silverlight 2 Application in Visual Studio 2008....................................................................................................... 164
Intellisense................................................................................................................................................................................... 170
Programming C# with Basic Constructs..................................................................................................................................... 171
Summary..................................................................................................................................................................................... 182
Chapter 10. Progressing with .NET.......................................................... 183
Programming with Objects in C#............................................................................................................................................... 183
Adding Interactivity to the Thumbnails Application.................................................................................................................. 189
Silverlight 2 Unleashed
8.
Overloading Methods.................................................................................................................................................................. 193
RaisingEvents and Using Delegates........................................................................................................................................... 194
Storing Data on the Client........................................................................................................................................................... 198
Summary..................................................................................................................................................................................... 205
Chapter 11. Progressing with Animations................................................ 207
Animating Elements in Blend..................................................................................................................................................... 207
Synchronizing Animations.......................................................................................................................................................... 212
Reversing a Storyboard............................................................................................................................................................... 214
PointAnimation........................................................................................................................................................................... 214
Starting and Stopping the Animation......................................................................................................................................... 216
Working on the Thumbnails Gallery........................................................................................................................................... 218
Summary..................................................................................................................................................................................... 229
Chapter 12. Encoding Videos with Expression Encoder........................... 231
Before We Start............................................................................................................................................................................ 231
Introducing Expression Encoder................................................................................................................................................ 232
Setting Options............................................................................................................................................................................ 232
Understanding the Panels........................................................................................................................................................... 233
Importing a Video....................................................................................................................................................................... 234
Saving your Changes................................................................................................................................................................... 235
Specifying the Output Type......................................................................................................................................................... 235
Testing Before Encoding............................................................................................................................................................. 239
Setting Metadata......................................................................................................................................................................... 240
Encoding the Video for Silverlight.............................................................................................................................................. 243
Checking the Result.................................................................................................................................................................... 244
Advanced Parameters................................................................................................................................................................. 245
Summary..................................................................................................................................................................................... 246
Chapter 13. Progressing with Videos....................................................... 247
Why Streaming?.......................................................................................................................................................................... 247
Publishing on Your Own Website............................................................................................................................................... 248
Adding an Overlay....................................................................................................................................................................... 249
Letting Your Users Choose the Player........................................................................................................................................ 253
Publishing on Microsoft Silverlight Streaming Servers............................................................................................................. 258
Adding the Application in an Existing Web Page...................................................................................................................... 260
Firing Script Commands (and Catching Them)......................................................................................................................... 262
Modifying the Player Template in Blend.................................................................................................................................... 264
Summary..................................................................................................................................................................................... 267
Chapter 14. Letting .NET and JavaScript Talk.......................................... 269
Making .NET Available to JavaScript......................................................................................................................................... 269
Handling .NET Events in JavaScript.......................................................................................................................................... 271
Calling JavaScript Methods from .NET...................................................................................................................................... 275
Calling .NET Methods from JavaScript...................................................................................................................................... 277
Adding a “Login” Dialog to the Thumbnails Application........................................................................................................... 278
Summary..................................................................................................................................................................................... 297
Chapter 15. Digging into Silverlight Elements......................................... 299
Exploring the Class Hierarchy.................................................................................................................................................... 299
Choosing XAML or Code-Behind................................................................................................................................................ 301
Packing and Laying out with Panels........................................................................................................................................... 304
Scrolling and Bordering............................................................................................................................................................... 315
Using Pop-Ups............................................................................................................................................................................. 318
Drawing Shapes........................................................................................................................................................................... 319
Summary...................................................................................................................................................................................... 321
Chapter 16. Digging Deeper into Silverlight Elements............................. 323
Understanding the Control Class................................................................................................................................................ 323
Discovering Basic Controls......................................................................................................................................................... 325
Picking Dates with Calendar and DatePicker............................................................................................................................. 333
Writing with Ink.......................................................................................................................................................................... 335
Making a Simple Drawing Application....................................................................................................................................... 336
Presenting Data with ItemsControls.......................................................................................................................................... 343
Silverlight 2 Unleashed
9.
Deep Zooming YourImage Collection........................................................................................................................................ 345
Summary..................................................................................................................................................................................... 348
Chapter 17. Using Resources, Styling, and Templating............................ 349
Storing Items in Collections....................................................................................................................................................... 350
Using ResourceDictionaries in Silverlight.................................................................................................................................. 351
Styling a Control.......................................................................................................................................................................... 356
Styling the Thumbnails Application........................................................................................................................................... 360
Embedding Fonts in the Application.......................................................................................................................................... 362
Templating the Lookless Control................................................................................................................................................ 364
Summary..................................................................................................................................................................................... 369
Chapter 18. Data Binding and Using Data Controls.................................. 371
Understanding Data Binding...................................................................................................................................................... 371
Digging in the Binding Class....................................................................................................................................................... 377
Setting the DataContext.............................................................................................................................................................. 378
Using Data Controls.................................................................................................................................................................... 380
Using XML Data Sources............................................................................................................................................................ 394
Summary..................................................................................................................................................................................... 394
Chapter 19. Creating User Controls and Custom Controls....................... 395
Creating a Thumbnails Viewer User Control............................................................................................................................. 395
Creating the Items and Designing a DataTemplate................................................................................................................... 405
Creating a MediaInfoDisplay Custom Control........................................................................................................................... 413
Summary..................................................................................................................................................................................... 422
Chapter 20. Taking Silverlight 2 One Step Further.................................. 423
Creating a Default Template for the MediaInfoDisplay Control............................................................................................... 423
Using the MediaInfoDisplay Control.......................................................................................................................................... 425
Scrolling the Items...................................................................................................................................................................... 430
Creating a New RepeatButton Template.................................................................................................................................... 433
Exporting Classes to an External Assembly and Refactoring.................................................................................................... 437
Talking About the Application Object........................................................................................................................................ 442
Using Generics............................................................................................................................................................................ 444
Summary..................................................................................................................................................................................... 445
Chapter 21. Taking Silverlight 2 Even Further......................................... 447
Registering Multiple JavaScript Event Handlers....................................................................................................................... 448
Finding Silverlight Elements in JavaScript................................................................................................................................ 449
Accessing the HTML Page From .NET....................................................................................................................................... 451
Exchanging Data Between .NET and JavaScript........................................................................................................................ 453
Passing Initialization Parameters............................................................................................................................................... 461
Attaching .NET Events to HTML Elements............................................................................................................................... 462
Publishing Directly from Visual Studio...................................................................................................................................... 465
Debugging Your Silverlight Application..................................................................................................................................... 466
Summary..................................................................................................................................................................................... 473
Chapter 22. Connecting to the Web.......................................................... 475
Creating and Loading an XML File............................................................................................................................................. 475
Loading a Zip File and Showing Progress.................................................................................................................................. 488
Making Requests to WCF Services............................................................................................................................................. 496
More Connectivity....................................................................................................................................................................... 505
Summary..................................................................................................................................................................................... 506
Chapter 23. Placing Cross-domain Requests and Handling Exceptions...
507
Placing Cross-domain Requests................................................................................................................................................. 507
Communicating with Third-Party Services................................................................................................................................. 511
Placing POST Requests............................................................................................................................................................... 524
Throwing and Catching Exceptions............................................................................................................................................ 525
Summary..................................................................................................................................................................................... 533
Chapter 24. Silverlight: Continuing the Journey...................................... 535
Updating a Service Reference..................................................................................................................................................... 535
Killing a Process.......................................................................................................................................................................... 536
Silverlight 2 Unleashed
10.
About Protecting YourWork...................................................................................................................................................... 538
Binding in Special Configurations.............................................................................................................................................. 539
Using the ASP.NET Controls Silverlight and MediaPlayer........................................................................................................ 544
Creating Unit Tests for Silverlight.............................................................................................................................................. 549
Making or Buying XAML Resources........................................................................................................................................... 557
Using Third-Party Controls and Libraries................................................................................................................................. 560
Reading Silverlight-Related Blogs.............................................................................................................................................. 561
Summary...................................................................................................................................................................................... 561
Silverlight 2 Unleashed
11.
Silverlight
UNLEASHED
800 East 96thStreet, Indianapolis, Indiana 46240 USA
Laurent Bugnion
Silverlight 2 Unleashed Page 1 Return to Table of Contents
Dedication
How to writethis book without your never-ending, ever patient
support, Chi Meei… This was once again a crazy project, and I
couldn’t have done it without your approval and your help. By your
constant support and the energy and dedication you put into shield-
ing me from the small worries of life, you made this book possible. I
love you.
To Alise and Laeticia, my two princesses. Before you appeared in my
life, I thought I was happy. Now I know something big was missing.
I love you both so much.
Un jour sans danser est un jour perdu
Maurice Béjart
Je ne sais pas ce qui est beau, mais je sais ce que j’aime
et je trouve ça amplement suffisant.
Boris Vian
Le Poète est semblable au prince des nuées
Qui hante la tempête et se rit de l’archer;
Exilé sur le sol au milieu des huées,
Ses ailes de géant l’empêchent de marcher.
Baudelaire – L’Albatros
Silverlight 2 Unleashed Page 3 Return to Table of Contents
14.
Foreword
There are twoundeniable trends in the software development world. The first is toward
web style deployment of applications. The web is quickly maturing as an application
delivery platform, and increasingly, web applications are seen as the right solution for
many styles of applications. The second is toward richness of applications. User experi-
ence is becoming increasingly important; consumer-facing applications attracting and
retaining users has never been harder and even small usability improvements often make
the difference. In business applications, CIOs are realizing that if they can save even a few
seconds on every transaction by making employees more effective they can save millions
of dollars.
Not surprisingly, Silverlight 2 sits squarely in this sweetspot.
Silverlight 2 is a web application technology. The Silverlight runtime itself is smaller than
the average Britney Spears song and is seamless to install on any browser (Internet
Explorer, Firefox, Safari, and so on) and on any platform (Windows, Mac, Linux).
Silverlight applications are small and fast to deploy and have zero impact on the client
machine. There is no install or uninstall step for Silverlight applications, and all these
applications run in a sandbox that ensure they cannot harm user machines or other
applications.
Silverlight 2 enables building great user experiences. Through the power of the conver-
gence around video, vector graphics and a powerful developer framework, Silverlight is
the ideal platform for UX. Developers have full expressiveness with the power of the CLR
under the hood in Silverlight. The C# and VB languages allow developers to be productive
today without learning new languages and development tools. The XAML markup allows
designers to use Expression and other design tools to build great transitions and anima-
tions so that applications look and feel great. All of this together enables Silverlight appli-
cations to deliver more productive experiences to end users helping them get their jobs
done faster.
This book unleashes Silverlight for you. Laurent not only has a deep understanding of
Silverlight, where it is now and where it is going, but he also deeply understands real
world programming concerns. This book will make learning Silverlight fun.
I can’t wait to see what you build with it.
Brad Abrams
Product Unit Manager
Microsoft Corporation
http://blogs.msdn.com/brada
September 2008
Silverlight 2 Unleashed Page 4 Return to Table of Contents
15.
About the Author
LaurentBugnion works as a senior software developer and architect in Switzerland, where
he lives with his wife, Chi Meei, and his two daughters, Alise (2001) and Laeticia (2004).
Originally an electronics engineer from the Engineering School of Yverdon (Switzerland),
his interests quickly moved to software, and he achieved a post-graduate degree in soft-
ware engineering in 1999 in the Engineering School of Rapperswil (Switzerland).
Currently, his interests are very much set on WPF, Silverlight, and other .NET 3.5 tech-
nologies, which he helped introduce, teach, and coach at Siemens for the past three years.
Prior to that, he first wrote embedded C/C++, and then moved to desktop computers in
Java, JavaScript, and eventually .NET (WinForms and ASP.NET). After more than 12 years
spent developing various software products at Siemens, Laurent is employed since
December 2008 by IdentityMine, one of the world’s leading firms in WPF and Silverlight
development and design.
Privately, Laurent has also been active, developing websites and web applications in
HTML, JavaScript, CSS, ASP, and currently ASP.NET. He has done his best to contribute to
various developers communities, first in the JavaScript newsgroups, and then in
Microsoft’s forums related to ASP.NET, C#, WPF, and Silverlight. He blogs regularly on
http://blog.galasoft.ch and publishes articles, prototypes, and demos related to the
mentioned technologies.
Laurent became a Microsoft Most Valuable Professional (MVP) in 2007 for ASP.NET and
then in 2008 for Client Application Development. In 2008, he also earned an MCTS for
Windows Presentation Foundation.
Silverlight 2 Unleashed Page 5 Return to Table of Contents
16.
Acknowledgments
A book abouta to-be-released technology cannot be written without strong support from
the community, both within Microsoft and outside it. Making a complete list of all the
people who encouraged me and helped me in this daunting task is impossible, but I want
to mention and thank some people (and for some of them, friends) explicitly (and in no
particular order):
. At Microsoft: Scott Guthrie, Tim Sneath, Ian Ellison-Taylor, Brad Abrams, Rob
Relyea, Tim Heuer, Adam Kinney, Peter Blois, Unni Ravindranathan, Joe Stegman,
Mike Harsh, Karen Corby, Kathy Kam, Corrina Barber, Beatriz Costa, James Clarke,
John Gossmann, Karsten Januszewski, Adam Nathan, Christian Schormann, Mark
Feinholz, Ted Hu, Jeff Wilcox, Justin Angel, and many others from the Dev Div, for
building the stuff my dreams are made of (and for writing about it!). I’ve seen the
“new Microsoft” at work, and I like it!
. In the Silverlight and WPF community: Josh Smith, Jonathan Russ, Brennon
Williams, Karl Shifflett, Marlon Grech, Corrado Cavalli, Grant Hinkson, Nathan
Dunlap, Josh Wagoner, Robby Ingebretsen, Kevin Moore, Shawn Wildermuth, Dave
Campbell, Jon Galloway, Grant Hinkson, John Papa, and all the WPF Disciples for
teaching me all I know (or so it feels).
. The team at Sams and especially Neil Rowe, Mark Renfrow, Mandie Frank, and
Geneil Breeze for their patience and support for this first-time author.
. The whole MVP community and especially the Client Application Development
members, for welcoming me and making me feel worth it.
. All my friends, online and offline, who had to bear with me being either working
on the book or talking about the book or thinking about the book or, you know,
sleeping (and probably dreaming about the book).
A very special thanks to Brennon Williams who gave me such invaluable comments and
advice; to J. Boyd Nolan for reviewing and editing, and for converting this book’s exam-
ples from C# in VB.NET; to Adam Nathan who advised me about the book’s outline
before I even started writing it; to Shawn Wildermuth for pulling me out of many a tech-
nical hole; to Peter Blois for listening patiently to my bug reports and proposing solu-
tions; to Tim Heuer and Adam Kinney, for clearly showing that Silverlight is more than
just a job to them; to all the Silverlight Insiders for the always interesting and often life-
saving discussions.
Software engineering is a passion. To all of you whom I learn from everyday, and to
whom I try to teach a little through my blog, my site, or in conferences, thank you for
making this more than a job: a way of life.
Silverlight 2 Unleashed Page 6 Return to Table of Contents
17.
We Want toHear from You!
As the reader of this book, you are our most important critic and commentator. We value
your opinion and want to know what we’re doing right, what we could do better, what
areas you’d like to see us publish in, and any other words of wisdom you’re willing to
pass our way.
You can email or write me directly to let me know what you did or didn’t like about this
book—as well as what we can do to make our books stronger.
Please note that I cannot help you with technical problems related to the topic of this book, and
that due to the high volume of mail I receive, I might not be able to reply to every message.
When you write, please be sure to include this book’s title and author as well as your
name and phone or email address. I will carefully review your comments and share them
with the author and editors who worked on the book.
E-mail: webdev@samspublishing.com
Mail: Neil Rowe
Executive Editor
Sams Publishing
800 East 96th Street
Indianapolis, IN 46240 USA
Reader Services
Visit our website and register this book at www.informit.com/title/9780672330148 for
convenient access to any updates, downloads, or errata that might be available for this
book.
Silverlight 2 Unleashed Page 7 Return to Table of Contents
Introduction
With the releaseof Windows Presentation Foundation (a new graphical user interface
framework for Windows desktop applications) in 2006 and of Silverlight in 2008, client
application development took a turn for the best. Microsoft boldly decided to abandon
some concepts and technologies that had been used since the first release of Windows
and to do something new and better. While it sometimes seems difficult to keep up with
the pace of change imposed on software developers, this one is really worth it. Microsoft’s
bet on Silverlight and WPF is huge, and it cannot fail. These technologies represent the
future of client application development.
Because it runs on multiple platforms in a web browser plug-in that will soon be available
on most of the rich clients accessing the Internet, because it can be deployed as easily as
any web content and be served from any web server without additional infrastructure,
and because of the rich graphic interfaces it allows to be built and the amazingly easy
connectivity to remote services that it offers, Silverlight will be a major player in the
world of rich interactive applications (RIA). Silverlight is also a gateway to Windows
Presentation Foundation, the client application technology that represents the future of
Microsoft Windows programming for desktop computers.
In a World Wide Web where Adobe Flash currently has a leading edge, Silverlight repre-
sents much more than just an alternative: It is the .NET way! Every .NET programmer will
feel at home with Silverlight, because the libraries, the programming languages (C#,
VB.NET, Ruby, Python), and the development environment (Visual Studio, Expression
Studio) are the same. In addition, new concepts developed and refined in Windows
Presentation Foundation are made available to Silverlight programmers, such as data
binding, separation of behavior and looks, lookless controls that can be styled and
templated at will in powerful design tools such as Expression Blend, a rich animation
system, media integration, and so on. XAML, the new XML-based Application Markup
Language developed by Microsoft, can be leveraged as a bridge between developers and
designers to enable new workflows.
This book is not and was never intended to be a complete reference of the Silverlight plat-
form. Honestly, I am not even sure that you need a book for this: The Internet is at your
disposal and has a better, more complete, and more actual reference base than any book
can ever offer. No, this book is here to help you discover why programming is fun and
why Silverlight is even more fun, and to contaminate you with the Silverlight virus.
Complex concepts are explained in simple terms, with many hands-on demos and figures
so that beginners as well as advanced developers quickly will feel at home.
About Code in This Book
We tried to keep formatting as consistent as possible throughout the book and to make
the code look like it does in Visual Studio. The code is color coded to help you work faster
Silverlight 2 Unleashed Page 9 Return to Table of Contents
20.
and recognize keyconcepts in XAML, C#, JavaScript, and HTML in Studio and in
Expression Blend.
The source code lines are only numbered where it is relevant, for example, when the text
makes explicit reference to a line number.
The whole source code for this book is available online at www.galasoft.ch/SL2U/Code.
For C# code, a translation in VB.NET is also available, courtesy of this book’s technical
editor, J. Boyd Nolan.
One Year Older
I started working on this book in September 2007, and I am now exactly one year older.
Professionally speaking, it has been the most interesting year of my life. Since I started
working as a developer in 1996, I have worked with many client technologies and
programming languages, including C, VB, Java, HTML, CSS, JavaScript, ASP.NET, Windows
Forms and finally Windows Presentation Foundation and Silverlight. In all these years, I
have never been as excited about a new programming platform. Writing a book is hard,
and it’s a lot of work. But it was also fun and so interesting that I always felt right doing
it. If I had to do it again, I would sign without hesitation. And now that it’s going to be
published, I can’t wait to see what you, the reader, will create in Silverlight. Software has
much to do with art, and Silverlight is the richest palette you can imagine. So grab the
book and your computer, start coding and designing, and show the world what you can
do. I will be waiting.
Happy coding!
Laurent
Introduction
2
Silverlight 2 Unleashed Page 10 Return to Table of Contents
21.
CHAPTER 1
Introducing Silverlight
Itall started when Microsoft presented its revolutionary
user interface (UI) framework, Windows Presentation
Foundation, to an enthusiastic crowd of graphics designers,
software developers, and businessmen in March 2006 at the
new MIX conference in Las Vegas. Microsoft also added
one session about a lesser-known technology with the
rather barbarian name Windows Presentation Foundation
Everywhere, or WPF/E. There was nothing much to see yet,
but the abstract was enticing: “With WPF/E you’ll be able
to build rich, interactive experiences that run in major Web
browsers on major platforms as well as on mobile devices.”
A little more than a year later, at the second edition of the
same MIX conference, Scott Guthrie (general manager at
Microsoft, responsible for most of the .NET teams) climbed
on stage and gave the crowd an amazing software demon-
stration. The barbarian WPF/E was gone; in its place was
Silverlight (see Figure 1.1).
A bright new logo revolved on the screens. Gradients and
animations were all over the place. Planes flew over the
web browser’s window, connecting US cities while Scott
was planning his next trips; a chess application let the
browser’s JavaScript engine play against .NET, demonstrat-
ing without any doubt the superior power of the compiled
.NET application over JavaScript’s interpreted code. Yes, the
browser was running .NET!—not only in Internet Explorer
but also on Firefox! And yes, even on a Macintosh
computer.
IN THIS CHAPTER
. Where Does Silverlight Come
From?
. Using Third-Party Plug-Ins
. Running on Multiple Platforms
. Making the Web Application
Secure
. Introducing Silverlight.net
. What Do You Need to Run
Silverlight?
. Updating Your Runtime—
Automatically
. Trying Silverlight Demos
. What Do You Need to Develop
Silverlight?
. Reading the Documentation
. Looking into Silverlight’s
Future
Silverlight 2 Unleashed Page 11 Return to Table of Contents
22.
It was anintense hour! Later that day,
more demos of the new Expression
Encoder were presented, which allows
users to produce movies and run them
in the web browser, after having copied
them to a streaming (or to a nonstream-
ing) web server. Even better, with the
Expression Encoder you can now change
the look and feel of the video player
completely, basing your work on prede-
fined templates, but also changing
everything from colors to shapes in
Expression Blend.
These first demos were only the start of an amazing three days packed with Silverlight
content. In a little less than a year, Silverlight had made it from little-known side attrac-
tion to major technology with a huge potential.
Where Does Silverlight Come From?
A little history can be interesting to understand where Silverlight came from, and how it
is positioned among the many UI technologies available today. Depending on your past
experience, you may be well aware of the facts presented in the next sections. In that
case, feel free to skip ahead (the next interesting section for you will probably be
“Running on Multiple Platforms”). If you don’t want to skip ahead, or if you feel like
refreshing your memory, keep reading as this section and the next few sections fast
forward from the antiquity of the World Wide Web to the magic of today.
Web pages have been around for a long time. In fact, HTML was presented to the world as
early as 1992. (You know the old line about dog years being equal to seven human years?
Well, 1992 in computer years is, like, Middle Age for humans!) Of course, HTML was
limited in the beginning. Web pages were simple, composed mostly of text and hypertext
(the most revolutionary idea of HTML, and the origin of the name Hypertext Markup
Language).
Very quickly, however, the inventors of HTML saw the need for richer content to be made
available in web pages. The first step in that direction was the invention of the IMG tag,
allowing images to be placed inline. The basis for richer content was there, and the first
popular web browser, Mosaic, displayed these pages.
Automating Web Pages with JavaScript
The next big step forward in the quest for rich content was the addition of a JavaScript
engine running in the web browser.
CHAPTER 1 Introducing Silverlight
4
FIGURE 1.1 Microsoft Silverlight logo
N O T E
All the sessions presented at MIX 2006,
2007 and 2008 can be viewed online at
http://sessions.visitmix.com.
Silverlight 2 Unleashed Page 12 Return to Table of Contents
23.
This programming language(added in
1995 to the Netscape web browser, and
then in 1996 in Microsoft Internet
Explorer) enabled a much richer interac-
tion with the user. Earlier, the only
possible user action was through a post-
back to the web server, meaning that
any data entered by the user had to be
sent back to the server for handling, and
the result was returned as a response.
Obviously, this model was slow, espe-
cially at the time of dial-up connections.
With JavaScript, it was possible to
provide a basic treatment of data on the
client directly, without postback. A first
obvious use for this client-side technology was a prevalidation of data, making sure that
the user was not sending useless information to the server, wasting bandwidth and valu-
able server time. With JavaScript enabled, errors could be caught early, and faulty data
would never leave the client. Of course, as soon as a web server interaction was needed,
for example, to retrieve data, for complex calculations, to authenticate users, and so on, a
postback was needed. This model still prevails in many websites even today.
Cascading Style Sheets
Another big step forward in the creation of rich web content has been the creation of
Cascading Style Sheets (CSS). Finally a separation of content and layout was made possible.
The look and feel of a web page could be extracted from the page itself and governed by
the use of rules placed in external files. This model has many advantages:
. The responsibilities can easily be shared by various teams, depending on their skills.
Graphics designers can be in charge of the look, developers of the functionality,
while marketing is in charge of the content.
. In smaller projects, the developer can concentrate on the page’s structure and func-
tionality first, and create the look later, after the content is fully known. This way of
working is much more efficient than doing everything at the same time.
. The page’s look can be changed easily without touching the page itself.
. Same styles can be reused over and over again without having to rewrite the code.
Classes can be located in a central location and referenced anywhere. In fact, it’s even
possible to have styles on a central server and be used on other web servers, related
or not.
As CSS became more and more sophisticated, the pages became more and more beautiful,
to a point where the aspect of the pages, in some cases, becomes as important as the
Where Does Silverlight Come From? 5
1
N O T E
There are many names for this scripting
language, from Netscape’s JavaScript to
Microsoft’s JScript to the standard
ECMAScript. In this book, the term
“JavaScript” will be used without distinction.
WA R N I N G
Client-side validation can easily be side
tracked, and it is always necessary to vali-
date data on the server too!
Silverlight 2 Unleashed Page 13 Return to Table of Contents
24.
content itself. Onecan argue endlessly
whether that’s a good thing (after all,
content is what users are really looking
for, isn’t it?), but if you can choose
between boring content and beautiful
content, surely the beauty will make the
experience more pleasurable.
Progressing to DHTML
As the JavaScript and CSS engines became more advanced, some interaction was made
possible between them. DHTML (Dynamic HTML) was born. Actually, DHTML is not a
technology; it’s a combination of JavaScript and CSS used in the context of HTML.
Using JavaScript as a programming language, it is possible to access elements of the page
itself (content and style), and to modify them. Since this is client-side technology, no
interaction with the server is required for this kind of effect.
Because CSS allows the setting of an element’s opacity, it is possible to create fade-in/
fade-out effects. With the possibility to set an element’s position in an absolute manner,
JavaScript allows you to move an element across the screen. In addition to “just” adding
some kind of intelligence and good looks to the web pages, the interaction between CSS
and JavaScript enabled the creation of richer, smoother web pages.
Although this all sounds nice, DHTML is rather limited:
. Opacity is not supported in all browsers, and the ones that support it don’t use a
standard syntax, making it kind of a maintenance nightmare.
. Moving elements across the screen can only be done at limited speed and is not as
smooth as you would want.
. It is impossible to rotate elements. If you want to show a rotated button, you need
to simulate this using multiple images, and the effect will not be smooth.
. Text (such as a title, in a logo, etc…) can only be rotated by using images. In that
case, the localization becomes a nightmare, because you need to translate each
image in each language you want to support.
. The “hit test area” for any element is always square. In other words, even if you
have an image of a round button with a transparent background, you may activate
the action even if you click outside the round area. The mouse cursor will turn to a
hand even though the mouse is still on the transparent area.
Thankfully, Silverlight corrects all these shortcomings, and since it can be “blended”
among HTML elements, it offers a real possibility to graphically enrich a web page.
CHAPTER 1 Introducing Silverlight
6
WA R N I N G
Although CSS allows creating beautiful
pages, it also allows creating ugly looks.
Unfortunately, the technology has no taste;
only the developer/designer has some (or
hasn’t any). That’s true for Silverlight (and
any UI technology) as well.
Silverlight 2 Unleashed Page 14 Return to Table of Contents
25.
Communicating in aRicher Way with AJAX
In addition to enabling DHTML,
JavaScript brought a huge improvement
to client-server communication, and to
creating a smoother user experience:
Asynchronous JavaScript And XML (AJAX),
a cumbersome name for a great technol-
ogy. In short, AJAX allows JavaScript to
send a request to the web server, and to
get the response without the web page being refreshed. Instead of using the normal post-
back mechanism, the whole communication occurs in the background, and the user
doesn’t notice it.
With this technology, the user can get additional information from the server without
losing the context he is working in. The user experience is also much smoother, because
new information gets loaded without the “traumatic” reloading of the page and the
temporary white screen caused by it.
Using Third-Party Plug-Ins
With the limitations of DHTML, various
third-party additions to the web browser
have been created with the explicit
intent to enhance the user experience.
The most notorious technologies are
probably Java applets, ActiveX controls,
and Flash applications. This section
reviews the advantages and shortcom-
ings of these technologies to understand
better how Silverlight compares.
Using Java Applets
Java applets were extraordinarily
popular for a short time and then
became unpopular. While some web pages still use the Java technology, their number is
decreasing. The main problem with Java is that the runtime is very slow to start. When
you load a page with a Java applet on it, the initial loading time makes it a painful experi-
ence.
On the plus side, Java is a great programming language. It paved the way for .NET, and
many of the best features of C# are greatly inspired by the Java language. It also enables
advanced graphical effects, such as the famous ripple effect.
Limited Java-to-JavaScript and JavaScript-to-Java communication is possible. However, the
interface used for this communication is not supported by all the web browsers that Java
runs into. Also, the syntax is not easy to learn, and communication is awkward.
Using Third-Party Plug-Ins 7
1
T I P
AJAX is not very easy to program. Like you
will see later, Silverlight 2 offers a great deal
of improvement in this area too and makes
background communication much easier.
N O T E
An annoying shortcoming of all the technolo-
gies described in this section is that it is
impossible to place HTML content in front of
a third-party plug-in. The Java applet, ActiveX
control, or Flash application will always be in
the top level. Silverlight corrects this
problem and makes it possible to have HTML
content blending with Silverlight content.
Also, the HTML–JavaScript–Silverlight interac-
tion is better than with any of these older
technologies. The boundaries are thinner
than ever.
Silverlight 2 Unleashed Page 15 Return to Table of Contents
26.
Java makes itpossible to open alterna-
tive communication ways to the web
server. For example, it enables the server
to “talk” directly to the client, which is
impossible with classic web communica-
tion. While this can be a huge techno-
logical advantage in certain scenarios, it
can also, under certain circumstances, represent a security threat. Because of this, the
acceptance of Java applets by big, security-sensitive corporations has been slow and has
pretty much “killed” Java in the web browser.
Using ActiveX Controls
When Microsoft introduced the COM technology in 1993, it also made it possible to
create so-called ActiveX controls, “packing” pieces of software and communicating with
the external world using the COM interfaces. With this, it is possible to develop controls
using classic Windows technology (including fast C++ code), and to place it in a web
browser. It is even possible to have some limited interaction with JavaScript and through
this to the web page.
The major shortcoming of ActiveX is that it uses an obsolete, almost 15-year-old technol-
ogy. Also, ActiveX controls can only be used in Internet Explorer on Windows.
Using Flash Applications
Adobe Flash is probably the most
popular third-party plug-in currently
available. On the plus side, it allows
advanced graphical effects, and it’s not
rare to find websites programmed
entirely in Flash. While Flash content is
often called “Flash movies,” it’s probably
fairer to call them “applications.”
Flash’s major shortcoming is that it is
difficult to program. A (commercial)
editor is needed to create the front-end
user interface. Additionally, the code-
behind can only be programmed in a
language called ActionScript, which is a
subset of JavaScript. The fact that Flash
has been created primarily for graphics
designers makes it difficult for software
developers to use the tools and to create
compelling content and functionality.
CHAPTER 1 Introducing Silverlight
8
N O T E
Every book about web technology should
make one thing clear: Java and JavaScript
have strictly no relationship. When you
program JavaScript, you do not program Java.
WA R N I N G
Programming a website entirely in Flash (or
in Silverlight) is not a good idea. Many plat-
forms (especially mobile phones, PDAs, and
so on) do not allow accessing such sites (or
only in a limited manner). This type of tech-
nology should only be used to enhance the
content of a website, not to replace it
completely.
N O T E
Microsoft doesn’t advertise Silverlight as a
Flash “killer.” This strategy would probably be
doomed anyway, considering how many Flash
designers there are, and how much Flash
content is available online. Since both tech-
nologies can run safely side-by-side, there is
really no need to start a religion war about
which is the best!
Silverlight 2 Unleashed Page 16 Return to Table of Contents
27.
A limited interactionbetween the Flash application and the containing HTML page is
possible through JavaScript. Some interaction between the Flash application and the
containing HTML page is possible through JavaScript.
Running on Multiple Platforms
One important factor when you develop a third-party web technology is to run it on as
many platforms as possible. The Web is, by definition, ubiquitous, and it is not rare to
find Internet-enabled devices of every shape and power. Adobe Flash is a good example of
this: The plug-in is available for a great number of browsers on a great number of operat-
ing systems. This makes Flash a powerful platform, and Microsoft understands the need
for Silverlight to run in multiple browsers too.
As said earlier, at the time of this
writing, the Silverlight runtime is avail-
able for Internet Explorer and Firefox on
Windows, and for Firefox and Safari on
Macintosh. A version for Linux is in
preparation. The real challenge is to
offer consistent interfaces on all the
platforms on which Silverlight runs. So far, this goal has been very successful, and is a
great achievement in the quest for a unified web environment.
Some prototypes of Silverlight for smartphones have also been presented, but not much is
known about what will be supported on these limited devices. A first version of Silverlight
for mobile phone (running on Windows Mobile and also on Nokia mobile phones)
should be released by the end of 2008. This should support Silverlight 1 applications,
including video.
Because Silverlight runs on so many platforms, some limitations in the functionality
(compared to the full .NET platform) are unavoidable. Many factors must be considered:
. The goal is to keep the runtime small, so that it can easily be installed over Internet
connections. The goal in the foreseeable future is to keep it under (or equal to) 5MB.
When you compare to the size of the full .NET runtime (and even if you remove all
the server-side bits), it’s obvious that not everything can be implemented.
. Features requiring a lot of hard-
ware acceleration (especially 3D
animations) will probably be too
hard to implement consistently on
multiple platforms (not even
mentioning small limited mobile
devices).
. Various platforms use various
underlying graphic technologies,
and some of these technologies
Running on Multiple Platforms 9
1
N O T E
In order to run Silverlight on many platforms
in a consistent way, Microsoft is also collabo-
rating with Novell and the makers of the
open source .NET framework “Mono.”
T I P
Hardware acceleration is the process through
which some of the complex calculations are
executed by hardware processors specializ-
ing in graphics (as opposed to software).
Hardware graphic processors are much
faster than anything that software can calcu-
late.
Silverlight 2 Unleashed Page 17 Return to Table of Contents
28.
may not allowall the desired effects. It’s already pretty amazing to see how consis-
tent the implementation is on both Windows and Macintosh. For Silverlight to be
viable, it is imperative that it remain totally compatible on all supported platforms
and browsers.
All these reasons create a lot of intense discussions to decide what will make it to
Silverlight and what won’t. It will be interesting to observe the development of the plat-
form!
CHAPTER 1 Introducing Silverlight
10
T I P
Microsoft is listening to you! Don’t hesitate to contact evangelists and other Silverlight devel-
opers, either through the Silverlight forums (http://silverlight.net/forums), or through their
blogs (check the section titled “Reading Silverlight-related blogs” in Chapter 24, “Silverlight:
Continuing the Journey”). Let them know what you do with the technology, and what your
expectations are. Just like third-party developers influenced the way WPF is growing, the
same process is true for Silverlight! Let them hear your voice!
Making the Web Application Secure
Security in web applications is a huge challenge. Even though Microsoft has more often
than any other company been the target of virulent criticisms because some of their
applications or operating systems were not secure enough, it’s fair to say that any popular
web technology is exposed and has had security issues (Java, Firefox, the Linux operating
system, the new Google Chrome web browser and many others have all been the target of
attacks).
Microsoft is taking the security of Silverlight-based applications very seriously. Silverlight
applications run in a “sandbox” that limits the functionality of the application and
protects the computer it runs on against attacks. Every time a feature is allowed by the
sandbox, it is carefully tested to make sure that the change doesn’t present a hole for a
potential attack.
If humanity was intrinsically good, programming would be easier, but of course, security
is not just a matter of attackers, it also has a lot to do with bad code, memory corrup-
tions, and so on. Thankfully, the .NET programming platform (the so-called “managed
code”) is a secure way of programming. Unlike older unmanaged C++ code, many bugs
are eliminated already at the source by the much safer managed programming languages.
Memory corruption is almost impossible; memory is automatically freed by the Garbage
collector when it is not used anymore, making memory leaks much more infrequent.
Obviously it would be naive to believe that Silverlight will never be attacked, or that
Silverlight applications will never crash. However, thanks to the experience gathered
by the .NET teams, thanks to the managed programming languages, and thanks to the
Silverlight 2 Unleashed Page 18 Return to Table of Contents
29.
extra attention investedby Microsoft into that matter, Silverlight should provide a very
safe environment.
Introducing Silverlight.net
The community website http://silverlight.net contains a collection of valuable informa-
tion about Silverlight, including quickstarts, samples, tutorials, and so on. Maybe the
most interesting section is the gallery, available at http://silverlight.net/community/
communitygallery.aspx.
Here you will find a lot of samples, made by Microsoft and third-party developers. This is
a good starting point to get an idea of what Silverlight is capable of. Currently, the gallery
is divided into two subsections: Silverlight 1.0 (with JavaScript) and Silverlight 2 (with
.NET). However, if you install Silverlight 2 (as we recommend), you can still execute older
applications.
What Do You Need to Run Silverlight?
Silverlight is an add-on to the web browser. It gets installed separately and adds function-
ality to your web pages. It is currently available for Internet Explorer and Firefox on the
Windows XP and Vista operating systems; it is also available for Firefox and Safari on the
Macintosh. At the time of this writing, a version for Linux is in preparation, following a
historical agreement between Microsoft and Novell.
To run Silverlight applications, you need
a compatible web browser. When you
point a Silverlight-capable web browser
to a web page with Silverlight content,
you get a small Install Microsoft
Silverlight icon, as shown in Figure 1.2,
instead of the Silverlight content.
. Click on the icon to be taken to a Microsoft web page where you can download and
install the Silverlight runtime on your PC.
. After installing Silverlight in Internet Explorer, you don’t even need to restart your
web browser. In Firefox, you might have to, but it’s not that big a deal.
Alternatively, you can install Silverlight 2 from http://silverlight.net/GetStarted.
What Do You Need to Run Silverlight? 11
1
FIGURE 1.2 The Install Microsoft Silverlight
icon
WA R N I N G
If you worked with Silverlight before and you already installed a version older than the one
required by the current application, you will also see the “Install Microsoft Silverlight” button.
You can check the Silverlight version by right-clicking on any Silverlight application, choosing
the Silverlight Configuration menu, and selecting the About tab.
Silverlight 2 Unleashed Page 19 Return to Table of Contents
30.
Updating Your Runtime—Automatically
Oncethe runtime is installed, the
Silverlight content will automatically be
started. Also, a version check will
happen when Silverlight is started; if a
newer version is available, you can
choose to install it automatically. This
can be set up in the Silverlight configu-
ration dialog by following these steps:
1. Navigate to http://silverlight.net/
samples/1.0/Page-Turn/default.
html. This starts one of the earlier
Silverlight demos created by
Microsoft: The PageTurn sample
application.
2. Right-click on the Silverlight appli-
cation and choose Silverlight
Configuration.
3. Click on the Updates tab.
4. Choose the options you want (see Figure 1.3).
CHAPTER 1 Introducing Silverlight
12
T I P
You can turn pages by clicking and dragging
your mouse on the bottom-right corner of the
photo album. If you click on the small open
book icon on the bottom right, you see a list
of thumbnails.
FIGURE 1.3 Silverlight configuration
Trying Silverlight Demos
The cool thing with Silverlight is that it’s so easy to deploy: Simply put the files on a web
server, and anyone in the world with a Silverlight-capable browser can see the applica-
tions.
N O T E
Silverlight gets installed only once, and then
runs in Firefox or IE (on the Mac, on Safari
and Firefox) with the same runtime. If you
change the options in Firefox, it will be valid
in the other browser installed on the same
PC too!
Silverlight 2 Unleashed Page 20 Return to Table of Contents
31.
The applications developedby Microsoft for demo purposes are also available online.
Additionally, third-party developers can also publish their own sample applications to the
Silverlight.net website. As mentioned previously Microsoft used two demo applications
when they first introduced Silverlight to the public: the Chess application and the
Silverlight Airline sample.
Playing Chess Against Silverlight
At the time of writing, the Chess demo (see Figure 1.4) is not available yet for Silverlight
2. You can, however, see a video illustrating this application at http://on10.net/blog/tina/
Microsoft-Silverlight-Chess. Also, keep checking the Silverlight.net gallery where the
demo and its source code should be posted soon.
Trying Silverlight Demos 13
1
FIGURE 1.4 Chess application
In this application, you get a chance to play against the machine: The Human button is
selected on the bottom. On the top, you can choose to play against another human
(booooring), against JavaScript (remember, JScript is Microsoft’s name for its implementa-
tion of the technology) or against .NET.
The implementation for the chess engine is exactly the same in JavaScript and in .NET. So
the most interesting thing to do in that application is to let JavaScript play against .NET:
1. On top, make sure that the .NET button is selected.
2. On the bottom, select the JScript button.
3. Observe how both engines are playing against each other. The most interesting data
is the number of nodes per second calculated by each engine. This is an indication
of how fast each engine can process data. Typically, .NET calculates approximately
1,000 times faster than JavaScript!
Silverlight 2 Unleashed Page 21 Return to Table of Contents
32.
Running this applicationalways leads to the same result: .NET wins over JavaScript,
because it is just so much faster. This is a good proof (if it was needed) of some of the
advantages we will encounter when we use .NET for advanced calculations instead of the
JavaScript engine.
Planning Your Trips with the Airline Application
The airline application shown in Figure 1.5 was also shown on stage at MIX07 and
presents what could be an airline reservation system in the (near) future. Here too, the
demo is not yet available for Silverlight 2 at the time of writing but should be updated
soon in the Silverlight.net gallery. A video showing this application is available at
http://on10.net/blogs/tina/Microsoft-Silverlight-Airlines.
CHAPTER 1 Introducing Silverlight
14
FIGURE 1.5 Airline application
1. Click and hold the departure city. Then, still holding down the button, move the
cursor to the target city. You can release the mouse now.
2. Select a date for your trip in the Calendar on the right.
3. The system calculates a number of possible itineraries for your trip. They are shown
under the map. Pass your mouse cursor over one itinerary to see it drawn on the
screen, and to see a small plane fly from city to city.
This example is interesting, because
strictly speaking, Silverlight doesn’t offer
new functionality here. Online reserva-
tion systems are already available today.
However, the user interface is better
with Silverlight and makes the user
experience better and more attractive.
N O T E
Thanks to the goodness of vector-based
graphics, you can also resize the window and
note how the whole user interface gets
resized to fit the screen.
Silverlight 2 Unleashed Page 22 Return to Table of Contents
33.
DeepZooming into theHard Rock Café
At MIX08, probably the most exciting demo was given by the Hard Rock Café and its
memorabilia collection of rock souvenirs: How would you like to be able to see high reso-
lution pictures of all the souvenirs normally exposed in various Hard Rock Cafés around
the globe (see Figure 1.6)? Even better, how would you like to be able to select them by
artist, year, type, and so on? And the most awesome feature of all: Zoom smoothly into
the pictures until you are able to see every detail, like small scratches or a handwritten
dedication on a guitar! Navigate to http://memorabilia.hardrock.com to try it yourself.
Trying Silverlight Demos 15
1
FIGURE 1.6 Hard Rock Memorabilia
This application is enabled by a feature introduced in Silverlight 2, named DeepZoom. A
very high resolution picture is prepared by a tool and divided in multiple, lower-resolu-
tion pictures. A Silverlight control is loading these images dynamically (according to the
level of zoom chosen) and displays them. Additionally, you can pan the image simply by
clicking and dragging the mouse, with a lifelike movement. All these seemingly very
complex features are made rather easy thanks to Silverlight 2 (though one should not
underestimate the value of the developers and designers having created this application!).
Finding More Demos
Many more samples and demos are available online. Make sure to browse through the
Silverlight.net gallery and play with demos to see what Silverlight can do at
http://silverlight.net/community/communitygallery.aspx.
Silverlight 2 Unleashed Page 23 Return to Table of Contents
34.
What Do YouNeed to Develop Silverlight?
The term “Silverlight” also qualifies the programming platform, which is developed in
parallel to .NET 3.5. Since Silverlight is in development now, not all the .NET classes are
available yet. In fact, some of them will never make it to Silverlight, as mentioned earlier.
However, because the .NET basis is stable now, we can expect to see big improvements in
Silverlight in the coming months as Microsoft releases new versions.
We are not going to create standalone applications here. We will only create applications
embedded in a web page and unable to run on their own. The nice thing with this way of
programming is that distributing (deploying) your application is as easy as copying some
files to your web server. If you are adding Silverlight content to an existing web page, you
probably already have a web server. If you don’t, you will need to get web server space
eventually to publish your application.
During development, however, you will
be able to use the web server IIS built in
the Windows operating system. Even
better, if you use Expression Blend or
Visual Studio 2008, starting a web appli-
cation is as easy as pressing F5! You
learn more about deploying web appli-
cations in Chapter 7, “Deploying to a
Web Page.”
Developing Silverlight can be done with just a text editor. Notepad (or its Mac equivalent)
is an option, seriously. You can write your XAML markup (a new programming language
we will introduce later) in there, and then run it in the web browser to see the result.
However, developing this way can be painful. Fortunately, we now have the support of
great tools to make that experience a real pleasure. The best place to start and install the
development environment for Silverlight is from http://silverlight.net/GetStarted.
Expression Studio
When Microsoft announced WPF, it also
gave us a new suite of tools named the
Expression Studio. Included are three
important tools for the Silverlight devel-
oper: Expression Design, Expression
Blend, and Expression Encoder.
This book uses these tools to create Silverlight content. Expression Blend is studied more
in detail in Chapters 4, “Expressing Yourself with Expression Blend,” and 6, “Blending a
Little More” (and throughout the book). This great tool is located at the border between
designers and developers and is used by both professions. It is an almost unavoidable tool
when you create WPF and/or Silverlight content. Unfortunately, at the time of writing
there is no free edition of Expression Blend. A fully functional demo version can be
downloaded from the Microsoft Expression website at www.microsoft.com/expression.
CHAPTER 1 Introducing Silverlight
16
WA R N I N G
Even though the Silverlight runtime is avail-
able for multiple platforms, the development
environment described in this book (program-
ming, designing, compiling, debugging) is
available only for the Windows operating
system. There is also a development environ-
ment for Linux (Moonlight).
N O T E
Expression Studio also contains Expression
Web (used to develop web pages) and Ex-
pression Media, a tool used to manage media
collections (pictures, videos, and so on).
Silverlight 2 Unleashed Page 24 Return to Table of Contents
35.
In addition toExpression Blend, we will
be using Expression Encoder in this
book. This application can also be
downloaded from the Microsoft
Expression website.
Expression Design can be used to create
XAML-based “assets” (pieces of design). Later, you can import these elements in your
Silverlight application. We will talk about this in Chapter 24.
Visual Studio 2008
Additionally, we will enjoy a better programming tool than Notepad: The powerful
Integrated Development Environment (IDE) Visual Studio 2008 is the tool of choice to
program Silverlight applications. In this book, we will use mostly Visual Studio 2008 and
Expression Blend to program Silverlight applications. A fully functional 90-day demo
version can be downloaded at http://msdn.microsoft.com/en-us/vs2008/products/
cc268305.aspx.
In addition to Visual Studio, you must also install the Silverlight tools available from the
“Get Started” page at http://silverlight.net/GetStarted/.
You learn more about Visual Studio 2008 in Chapters 9, “Understanding .NET” and 10,
“Progressing with .NET” about .NET, and
in following chapters, where we will use
these tools to create C# code-behind.
Microsoft released so-called Express
editions of Visual Studio. Each Express
edition presents a limited set of features
targeted at a specific type of software
development (for example, web applica-
tions, C#, VB.NET, and so on). These
limited editions are free to download
and install. According to Microsoft, you
will be able to use these Express editions
to program Silverlight. At the time of
writing, however, an exact release date
was not public.
Reading the Documentation
This book does not contain a full reference documentation about Silverlight but will give
you a great head start in this technology. In addition, you will use the Silverlight docu-
mentation, available in various forms.
Reading the Documentation 17
1
T I P
If you are a MSDN subscriber, Expression
Blend is included in the premium edition of
MSDN, so you don’t need to purchase it.
N O T E
Even though Silverlight supports VB.NET and
other managed languages, the examples in
this book are written in C#. I want to person-
ally apologize for this to all the VB.NET devel-
opers interested in Silverlight. A translated
version of the source code is available on
the book’s website at www.galasoft.ch/
SL2U/Code.
In addition to C# and VB.NET, Silverlight
supports the so-called dynamic languages
IronRuby and IronPython.
Silverlight 2 Unleashed Page 25 Return to Table of Contents
36.
Browsing the OnlineReference
The official Silverlight reference is found on MSDN (Microsoft Developer Network) online.
You can start at http://msdn.microsoft.com/en-us/library/bb404710(VS.95).aspx (for
Silverlight 1.0) and http://msdn.microsoft.com/en-us/library/bb404700(VS.95).aspx (for
Silverlight 2).
Finding More Documentation
With the number of classes available in the .NET framework (and even in the Silverlight
subset), and with the number of members that each class contains, a comprehensive
documentation is a key factor when you program against this framework. Microsoft
released a Silverlight 2 Software Development Kit (SDK). It contains technical documenta-
tion, libraries and tools to help you in your Silverlight experience.
1. Navigate to the Get Started page at http://silverlight.net/GetStarted
2. Scroll down until you see the link to Microsoft Silverlight 2 SDK. Follow this link
and download the SDK setup file.
3. Execute the file “silverlight_sdk.exe” you just downloaded. This will extract the
content to C:Program FilesMicrosoft SDKsSilverlightv2.0
4. For more information about the SDK, technical documentation, links to external
resources, etc., check the “Welcome” page. You find it in your Start menu, under
“All Programs / Microsoft Silverlight 2 SDK”.
The Silverlight documentation is also available as a compiled HTML file that can be
installed locally (see Figure 1.7). The download link is on the SDK welcome page.
CHAPTER 1 Introducing Silverlight
18
FIGURE 1.7 Silverlight documentation
The Search tab allows you easy access to a specific topic. The documentation contains
many interesting topics, and it is absolutely worth browsing through it.
Learning with Tutorials
Many tutorial websites are available for WPF, Silverlight, and Blend. The community
website Silverlight.net has already been mentioned. Another exciting and innovative site
is the Nibbles Tutorials website at www.nibblestutorials.net.
Silverlight 2 Unleashed Page 26 Return to Table of Contents
37.
This website doesan amazing job of
presenting and teaching the technology.
Using small, bite-sized tutorials, the
Nibbles website allows you to test some
of the knowledge acquired in this book.
Additionally, the website’s author, Celso
Gomes, is a talented graphics designer
working for Microsoft, and his tutorials
give you the designer’s point of view on
Silverlight (while this book gives you the
developer’s point of view).
Looking into Silverlight’s Future
Web technologies are evolving fast, and any attempt to look into the future and predict
where they are heading in the long term will result in mortifying failure for the
psychic…Silverlight is no exception. It’s almost impossible to predict where the technol-
ogy will be five or ten years from now.
One thing is sure, though: Microsoft is putting a lot of effort in Silverlight and porting
the .NET framework to multiple platforms. Mobile Silverlight will “hit us” in the very
close future. And because so many developers are already active on the .NET platform, we
will see more and more Silverlight content soon.
It is also safe to write that Silverlight
and WPF will become always more
compatible with each other. Silverlight 2
is already delivering a great number of
WPF-compatible classes. Learning either
WPF or Silverlight will offer an easy
passage to the other.
Is ASP.NET/HTML/JavaScript Dead?
With the advent of Rich Interactive Applications (RIAs) made with Silverlight or Flash,
one can wonder if classic ASP.NET will still be available in the future. One thing is sure:
ASP.NET is a very strong and important pillar of Microsoft’s client application strategy. In
fact, Microsoft also released updates to the ASP.NET framework with its .NET framework
3.5 this year.
With “classic” ASP.NET (HTML/CSS/JavaScript) for “thin clients,” Silverlight for RIAs and
WPF for desktop applications, you cover the whole range of client applications. And since
all these platforms run .NET, you can use the same programming language of your choice
(amongst C#, VB.NET and many others) to create your libraries.
So in short: No, ASP.NET is definitely not dead, and HTML-based web pages will continue
to entertain and inform us on the Internet for many years to come.
Looking into Silverlight’s Future 19
1
WA R N I N G
The “Nibbles” website doesn’t display any
content if Silverlight is not installed. Install
Silverlight before you navigate to this site!
Like we mentioned before in this chapter,
Silverlight-only websites are not recom-
mended because they are only visible on
Silverlight-compatible web browsers which
speaks against the principles of the World
Wide Web.
N O T E
At MIX08, in March 2008, Nokia announced
a partnership with Microsoft to deliver the
Silverlight mobile platform on the Nokia
mobile phones.
Silverlight 2 Unleashed Page 27 Return to Table of Contents
38.
Summary
In this chapter,we took a preliminary look at Silverlight and understood where it comes
from and what technologies are its “ancestors.” We also started playing with demo appli-
cations and installed the development environment.
Now it is time to start getting our hands dirty, and to write code. The next chapters intro-
duce you to the new programming language XAML and give you the occasion to write
markup and to see your creations running. Gradually, we will build knowledge and help
you create more elaborate code. Eventually, we will build applications together, bringing
your knowledge of Silverlight to a productive level.
CHAPTER 1 Introducing Silverlight
20
Silverlight 2 Unleashed Page 28 Return to Table of Contents
39.
CHAPTER 2
Understanding XAML
Whatwould software development be without
acronyms? Let’s meet XAML, also known as eXtensible
Application Markup Language (and pronounced “Zammel”).
Located at the border between graphics designers and soft-
ware developers, this language enables new workflows and
allows the designers to implement markup instead of
working on static screenshots. Optimized for tools like
Expression Blend, but still readable (and writable) by
humans (with the help of Visual Studio), XAML is a really
fascinating new language that admittedly comes with a
learning curve. Don’t be afraid, though, soon you will have
fun mastering this markup language!
Using XML for Data
XAML is based on XML, the eXtensible Markup Language.
Sometimes we say that XAML is an XML dialect. What does
it mean?
Data used to be stored in databases, a special type of file
handled by a database system or application. Databases are
efficient when it comes to storing and retrieving data. They
are fast. But they are complex. Managing a database is so
complex that there are engineers who dedicate their job to
doing just this. Even the simplest database applications
(such as Microsoft Access) are complex, and accessing the
stored data from an application can be difficult.
XML, on the other hand, is simple to handle: It’s just a text
file. If you open an XML file in a text editor, you will see
something like the markup shown in Listing 2.1. In fact, a
IN THIS CHAPTER
. Using XML for Data
. Using XML for User Interfaces
. Understanding XML
Namespaces
. Defining Additional
Namespaces
. Creating a Canvas with
Children
. Attaching Properties:
Canvas.Left and Canvas.Top
. Documenting Your Markup
with XML Comments
. Testing XAML Markup
. Setting Properties in XAML
. Changing Brushes
. Composing Scenes in XAML
. Saving Typing, Saving Space
Silverlight 2 Unleashed Page 29 Return to Table of Contents
40.
standard text editorwill not color-code the XML file. More advanced XML editors like the one
integrated into Visual Studio use color with XML tags, attributes, strings to make it easier to
read. The samples in this book follow this practice and all the XML and XAML samples are
color coded for clarity.
LISTING 2.1 XML File for Data Storage
<!--MyLibrary.xml - All my books-->
<MyLibrary>
<Authors>
<Author Name=”Zola”
FirstName=”Emile”>
<Books>
<Book ReleaseYear=”1883”>
<Title>Au bonheur des dames</Title>
</Book>
<Book ReleaseYear=”1885”>
<Title>Germinal</Title>
</Book>
</Books>
</Author>
<Author Name=”Balzac”>
<Books>
<Book ReleaseYear=”1831”>
<Title>La Peau de chagrin</Title>
</Book>
</Books>
</Author>
<Author Name=”Flaubert” />
</Authors>
</MyLibrary>
Let’s review the main characteristics of an XML document:
. XML is a hierarchic language, where nodes contain children nodes. Every node has a
parent, except the top one, called the root node.
. In addition to containing 0 or more children, each node can also have attributes. For
example, the ReleaseYear is an attribute of the Book node.
. A node may be empty; for example the author “Flaubert” is defined, but the library
doesn’t contain any of his books. Instead of writing an opening tag <Author> and a
closing tag </Author>, which would have been possible and allowed, the node is
“self-closed” to make the markup more readable and shorter.
. Similarly, not all attributes are compulsory. In Listing 2.1, the attribute FirstName is
defined only in one of the Nodes. It is an optional attribute.
CHAPTER 2 Understanding XAML
22
Silverlight 2 Unleashed Page 30 Return to Table of Contents
41.
When you havedata in an XML file, you must parse the file to retrieve the data. Parsing a
file is a long and error-prone process. Thankfully, many programming platforms (includ-
ing JavaScript and .NET) offer built-in ways to handle XML files in a much easier way. If
you pass a valid XML file to an XML parser, you can get an object, containing all the
nodes, organized in collections just like they are defined in the XML file. XML files can be
used as lightweight databases, containing information without the heavy infrastructure of
a database system.
Using XML for User Interfaces
Another use for XML is to describe a user interface (UI). The idea of using a markup
language for this purpose is not new. The most famous UI markup language is without a
doubt HTML (Hypertext Markup Language), but there are other XML-based UI languages,
for example, SVG (Scalable Vector Graphics), XUL (XML User Interface Language, a
Mozilla project), and so on.
However, HTML is not fully compliant with XML. Trying to load an HTML file with an
XML parser will most probably result in errors. But HTML proved that a hierarchic
markup language is good at describing complex user interfaces.
XAML obeys stricter rules than HTML. This is a good thing, really. Like XML, XAML must
be parsed, and as mentioned already, parsing is a long and error-prone process. If you
apply loose rules, the parser must accept many different text strings, and sometimes try to
imagine what the programmer actually meant. This is why it is so difficult to write web
pages that work the same in different web browsers: The rules of HTML allow too many
variations, so the parser implementations use different interpretations, and the same
markup can mean different things, depending on which browser loads it.
Understanding XML Namespaces
In XAML as in XML, the rules are defined in namespaces. You may have heard this term in
relation to .NET, but this is not the same, so don’t be confused. .NET namespaces are
discussed later in this book. Take a look at the simplest Silverlight file in Listing 2.2:
LISTING 2.2 Simplest Silverlight File Ever
<Canvas xmlns=”http://schemas.microsoft.com/client/2007” />
The Canvas element in this (too simple)
XAML file uses one XML namespace.
Note that the address used here does not
correspond to a website. If you enter it
in a web browser, you will get a “File
Not Found” error (go on, try it!). It is
only a URI (Unique Resource Identifier)
used to designate a uniquely named
Understanding XML Namespaces 23
2
WA R N I N G
If you already took a look at a WPF XAML
file, you’ll notice that the default namespace
is not the same! This is because Silverlight-
XAML is a subset of WPF-XAML; different
rules must be used for WPF than for
Silverlight.
Silverlight 2 Unleashed Page 31 Return to Table of Contents
42.
resource, in thiscase the schema in which the XAML structure is defined. The schema is
used by the XML parser to validate the file (to make sure that the file complies with the
rules). Later, we will see that the schema is also used by XML editors to offer assistance to
the user when she is typing XML (and XAML) to make this task easier and to reduce the
number of errors.
When a XAML file is loaded into the Silverlight engine, the schema is loaded and checked
to see whether a Canvas element is defined. If that is the case, the element is read and
used to instantiate (create) a Canvas object.
Defining Additional Namespaces
The “X” in XML and in XAML stands for “eXtensible.” One XML document can refer to
multiple XML namespaces, making it possible to mix multiple schemas and to extend the
document with elements coming from other sources.
There can be, however, only one default namespace. Additional namespaces must define a
prefix. For example, XAML typically uses an additional namespace as shown in Listing 2.3:
LISTING 2.3 Additional Namespace
<Canvas xmlns=”http://schemas.microsoft.com/client/2007”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” />
The second namespace is assigned to the x prefix (that’s just a convention; the prefix can
be any word as long as it is a valid XML identifier according to XML rules for naming
elements that can be found online at www.w3.org/TR/REC-xml). If you want to use
elements defined in this second namespace, you must prefix the element’s name with x.
For example, the x namespace in Silverlight defines general purpose attributes:
. Name—Gives a name to the element, used to identify it in the code associated to this
markup.
. Key—When an element is defined in a resource dictionary (a collection of objects), it
is identified by a key. This allows retrieving the object later to use it in the code.
. Class—Used to link a XAML file with a .NET code file. See Chapter 9.
. Other attributes—These are discussed in the next chapters when needed.
Knowing this, it is easy to assign a name to the root Canvas, allowing this object to be
referenced in the code later, as shown in Listing 2.4:
LISTING 2.4 Naming the Canvas
<Canvas xmlns=”http://schemas.microsoft.com/client/2007”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
x:Name=”MyCanvas” />
CHAPTER 2 Understanding XAML
24
Silverlight 2 Unleashed Page 32 Return to Table of Contents
43.
This syntax allowsadding many more namespaces, and these are used later when we
create user controls (reusable XAML structures), or when we want to use our own .NET
classes in the XAML markup. This is where the XML namespaces meet the .NET name-
spaces: WPF and Silverlight make it possible to use your code-behind classes in XAML
files, like in Listing 2.5! However, we will not use this particular feature before we start
using .NET to program Silverlight.
LISTING 2.5 Referencing external assemblies
<Canvas
xmlns=”http://schemas.microsoft.com/client/2007”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
x:Name=”MyCanvas”
xmlns:src=”clr-namespace:MyOwnClrNamespace”
xmlns:external=”clr-namespace:MyOtherClrNamespace;assembly=MyAssembly” />
Creating a Canvas with Children
An empty Canvas is not very useful, however, so Listing 2.6 presents a more complete
example.
LISTING 2.6 Canvas with Children
<!--SimpleExampleWithChildren.xaml - a simple Canvas with children-->
<Canvas xmlns=”http://schemas.microsoft.com/client/2007”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Background=”Red”
Width=”500”
Height=”300”>
<Ellipse Width=”400”
Height=”200”
Fill=”Yellow”
Stroke=”Orange”
StrokeThickness=”4”
Canvas.Left=”50”
Canvas.Top=”50”/>
<TextBlock Text=”Hello world”
FontSize=”36”
Foreground=”Blue”
Canvas.Left=”150.763”
Canvas.Top=”122.34”/>
</Canvas>
Creating a Canvas with Children 25
2
Silverlight 2 Unleashed Page 33 Return to Table of Contents
44.
This Canvas hasthree attributes:
. Background is a brush; in that case, we use a plain red color to “paint” the back-
ground of the Canvas. We will see later that there are various types of brushes.
. Width and Height define the dimension of the Canvas.
The Canvas also has two children:
. An Ellipse, also with the following attributes:
. Width and Height—Define the Ellipse’s dimensions.
. Fill—Like the Canvas’s background, it is also a brush; in that case we use a
plain yellow color to paint the Ellipse’s insides.
. Stroke—This is again a brush, used to draw the outside border of the Ellipse.
In this case, we use a plain orange.
. StrokeThickness—Defines the thickness of the outside border of the Ellipse.
. Canvas.Left and Canvas.Top—These are special, and are discussed later in the
chapter.
Another element has been placed in the Canvas: a TextBlock. Because it appears after the
Ellipse, the TextBlock will be drawn on top of it. The TextBlock also defines a few
attributes:
. Text—The string that will be written when the TextBlock is rendered.
. FontSize—This element is self-explanatory.
. Foreground—This is (again) a brush, in this case a plain blue, used to draw the text.
Attaching Properties: Canvas.Left and Canvas.Top
The Ellipse element doesn’t define a Left or Top attribute. These attributes are specified
in the Canvas element and “attached” to the Ellipse (and later to the TextBlock). That’s
why these properties are called attached properties in WPF and in Silverlight. These two
specify the location of the Ellipse on the Canvas, relative to the top-left corner, with the
X axis pointing to the right and the Y axis pointing down (as is usual in UI development).
There are multiple benefits to using attached properties: Instead of defining a Left and a
Top in the Ellipse object, and another Left and another Top inside the TextBlock object,
they are implemented only on the Canvas object. Because a Canvas can contain a lot of
various elements, defining these properties on the Canvas and attaching them to the
target element are easier. Also, Left and Top make sense for a Canvas, a simple type of
panel. But Silverlight supports other types of panels (for example, Grid, StackPanel, and
CHAPTER 2 Understanding XAML
26
Silverlight 2 Unleashed Page 34 Return to Table of Contents
45.
so on). Forthese panels, Left and Top don’t make sense, so why define these two proper-
ties on the children elements? It makes more sense to define them only on the Canvas
panel and to attach them when we add children to it.
Documenting Your Markup with XML Comments
XML allows entering comments in the markup. The comments will be parsed, but they do
not have any effect on the resulting objects. Commenting your markup (and also your
source code as we will see later) is important and is a good programming practice,
because:
. You will sometimes read markup written by other people, and their way of thinking
isn’t always the same as yours (yes, yours is better, but still…).
. You will sometimes read your own code years later and need to remember what the
heck you were trying to do.
Writing comments in the XAML markup
will help you a lot when you are
confronted with these scenarios. XML
comments use the following syntax:
<!--This is a comment-->
Testing XAML Markup
That was a lot of theory; now we can put this in practice and experiment with XAML.
There are many ways to execute XAML markup. Of course, you can create a Silverlight
application (for example, with Expression Blend like we will do later), but that’s a bit
heavy if you just want to test a few simple (or even not so simple!) XAML constructs.
Thankfully, we have other tools at our disposal.
Using SilverlightPad
Point your browser to the following URL to start the SilverlightPad application, shown in
Figure 2.1: http://silverlight.net/samples/1.0/Silverlight-Pad/default.html.
SilverlightPad is a Silverlight sample application, available on the community website
Silverlight.net. It can either run online (if you are connected to the Internet) or can be
installed locally, with the following steps:
1. Navigate to the Silverlight 1.0 gallery website at http://silverlight.net/community/
communitygallery.aspx.
2. Click on View All 1.0 Samples.
3. Locate the SilverlightPad application (see Figure 2.2).
Testing XAML Markup 27
2
T I P
In XML editors, XML comments are usually
rendered in green. This makes them easy to
recognize.
Silverlight 2 Unleashed Page 35 Return to Table of Contents
46.
FIGURE 2.1 SilverlightPad
CHAPTER2 Understanding XAML
28
FIGURE 2.2 View or Download SilverlightPad
4. Click on Download It. This triggers the download of a Zip file. Open the file or save
it to your hard disk.
5. Extract the Zip file content to a folder on your disk.
6. Navigate to this folder and start index.html in your favorite browser.
If you run SilverlightPad online, you can see sample XAML files on the left, useful to
learn complex constructs. In the bottom, you can see (and type) XAML markup. There is
also a JavaScript tab, used to attach JavaScript code to the XAML elements. The XAML
markup you type is parsed when you click on the Parse button on the bottom right, and
the corresponding UI is rendered in the Scene pane. Note also the Zoom controls on the
top-right corner. This allows testing the “zoomability” of vector graphics (we’ll talk more
about that in Chapter 5, “Using Media”).
Silverlight 2 Unleashed Page 36 Return to Table of Contents
47.
SilverlightPad also allowsrunning animations; for example, if you click on the Blocks
XAML file (available if you run SilverlightPad from the Silverlight.net website), you’ll see
that the blocks are moving. We will program XAML animations in Chapter 3, “XAML
Transforms and Animations.”
Using KaXaml
SilverlightPad is a great application to
train your XAML skills, but it is limited
to Silverlight 1. To dig deeper in
Silverlight 2 and its XAML markup, you
can use the excellent KaXaml created by
Robby Ingebretsen.
1. Navigate to the website http://kaxaml.com.
2. Click on the “Download” button and run the installer file.
3. After the installation is complete, run KaXaml from your Start menu. KaXaml
appears like in Figure 2.3.
Testing XAML Markup 29
2
WA R N I N G
SilverlightPad can be run in any web browser
supporting Silverlight 1. However, KaXaml is
a Windows application, and can only run on
Windows systems.
FIGURE 2.3 KaXaml
4. On the right hand side, KaXaml has a XAML markup pane (in the bottom), in
which you can type or paste Silverlight markup.
5. On the right hand side, top, the visual rendering of the XAML markup will be
displayed.
6. In addition, utilities are available on the left hand side:
. A collection of “snippets,” small pieces of XAML markup that can be dragged
to the XAML markup pane.
Silverlight 2 Unleashed Page 37 Return to Table of Contents
48.
. A “Find”dialog handy to look for information in big XAML files.
. A Color picker including a Color palette.
. A Snapshot utility, copying the current visual to a PNG image file.
. A XAML “Scrubber,” a utility cleaning up the XAML markup according to user-
defined settings.
KaXaml is a very useful tool to learn XAML, and a very fast way to visualize the results of
your XAML experiments.
Setting Properties in XAML
Most properties can be set using the XML attribute syntax, but sometimes it is not
enough. That’s why there is also an expanded syntax in XAML. For example, copy Listing
2.7 in SilverlightPad. Then don’t forget to click the Parse button to trigger SilverlightPad
to render your markup.
LISTING 2.7 Red Canvas
<Canvas xmlns=”http://schemas.microsoft.com/client/2007”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Background=”Red”
Width=”500”
Height=”300”>
</Canvas>
This creates an empty, red rectangle. It’s red because you set the Background property
using the string “Red”. Now, modify the markup to look like Listing 2.8:
LISTING 2.8 Another Red Canvas
<Canvas xmlns=”http://schemas.microsoft.com/client/2007”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Width=”500”
Height=”300”>
<Canvas.Background>
<SolidColorBrush Color=”Red”/>
</Canvas.Background>
</Canvas>
The result is exactly the same. How is that possible? In the first case, using the attribute
syntax (also called simple property syntax), when the XAML markup is parsed and objects
are created, the string “Red” will be converted into an object (of type SolidColorBrush),
and assigned to the Background property. Converters in XAML are powerful. They do their
CHAPTER 2 Understanding XAML
30
Silverlight 2 Unleashed Page 38 Return to Table of Contents
49.
best to understandthe programmer’s intentions and to create the object best suited to
reflect the markup.
In the second case, the one with the expanded property syntax, the markup is straightfor-
ward. We tell the parser exactly what we want to happen: Create a SolidColorBrush object
and assign it to the Background property of the Canvas. Note that one converter is still
involved: The one converting the string “Red” in a Color object, so that this object can be
assigned to the Color property of the SolidColorBrush.
Sometimes, you have to use the expanded property syntax, because it is not possible to
define complex objects in just one string so that the converters can create the correspond-
ing objects, as shown in Listing 2.9 and in Figure 2.4.
LISTING 2.9 LinearGradientBrush
<!--RainbowBrush.xaml - a simple LinearGradientBrush-->
<Canvas xmlns=”http://schemas.microsoft.com/client/2007”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Width=”500”
Height=”300”>
<Canvas.Background>
<LinearGradientBrush StartPoint=”0,0”
EndPoint=”1,0”>
<GradientStop Color=”Red” Offset=”0”/>
<GradientStop Color=”Orange” Offset=”0.25”/>
<GradientStop Color=”Yellow” Offset=”0.5”/>
<GradientStop Color=”Green” Offset=”0.75”/>
<GradientStop Color=”Blue” Offset=”1”/>
</LinearGradientBrush>
</Canvas.Background>
<TextBlock Text=”Start” TextWrapping=”Wrap”
Canvas.Top=”8” Canvas.Left=”8”/>
<TextBlock Text=”End” TextWrapping=”Wrap”
Canvas.Top=”8” Canvas.Left=”465.717”/>
</Canvas>
This markup creates another type of brush, a LinearGradientBrush. It produces a gradient,
starting in the top-left corner (x=0, y=0) and ending in the top-right corner (x=1, y=0).
The expanded syntax may seem complicated at first, but once you get used to it, you’ll
notice that it is in fact very logical and well structured.
Setting Properties in XAML 31
2
Silverlight 2 Unleashed Page 39 Return to Table of Contents
50.
FIGURE 2.4 LinearGradientBrush
ChangingBrushes
How can you assign an object of type SolidColorBrush to the Background property, and
later change that to an object of type LinearColorBrush? When we check the documenta-
tion online, we see that the Background property of a Canvas object is of type Brush:
http://msdn2.microsoft.com/en-us/library/bb738074.aspx (Canvas.Background)
http://msdn.microsoft.com/en-us/library/bb188310.aspx (Brush)
In fact, the Brush class is abstract, meaning that you cannot directly create an object of
this type. But there are derived types, for example SolidColorBrush. Since SolidColorBrush
and LinearColorBrush both inherit the Brush class, you can say that the SolidColorBrush
is a Brush, and the LinearColorBrush is also a Brush. This concept is important when you
do so-called Object Oriented Programming (OOP), and is called polymorphism.
Composing Scenes in XAML
XAML being XML, it is based on the composition of objects. This means that every object
has a parent (except the topmost one), and a parent may have 0 or more children, as
shown in Listing 2.10 and Figure 2.5.
LISTING 2.10 Composing a Scene
<!--ComposedScene.xaml - Hierarchical scene-->
<Canvas xmlns=”http://schemas.microsoft.com/client/2007”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Background=”Red”
Width=”500” Height=”400”>
<Rectangle Width=”240” Height=”150”
Fill=”Yellow” Margin=”40”/>
<Grid Width=”330” Height=”250”
CHAPTER 2 Understanding XAML
32
Silverlight 2 Unleashed Page 40 Return to Table of Contents
51.
LISTING 2.10 Continued
Canvas.Left=”120”Canvas.Top=”110”
Background=”#CCFFFFFF”>
<Ellipse Width=”200” Height=”140”
Fill=”Orange”
HorizontalAlignment=”Right”
VerticalAlignment=”Bottom”
Margin=”20” />
</Grid>
</Canvas>
Composing Scenes in XAML 33
2
FIGURE 2.5 Composing a scene
In Figure 2.5, the yellow Rectangle is one of the children of the red Canvas. There is also
a white Grid, defined as another child of the red Canvas. You might wonder why you can
see through this white Grid: The Background is set to #CCFFFFFF, which creates an 80%
transparent white color. You learn more about transparency in Chapter 5, which deals
with media in general and colors in particular.
T I P
Grid and Canvas are two Panels, with different functionalities. The various panels available
will be reviewed in detail in Chapter 15, “Digging into Silverlight Elements.”
. A Grid is a Panel in which you can define rows and columns, a little like a table (or a
grid, for that matter).
. A Canvas is another Panel, like a piece of paper, on which you can draw objects with
Top and Left coordinates.
Silverlight 2 Unleashed Page 41 Return to Table of Contents
52.
The red Canvashas two children, one of them a Rectangle and the other one a Grid. The
half white Grid has a child, the orange Ellipse. So the XAML markup can be represented
as a tree:
. Red Canvas
. Yellow Rectangle
. Half white Grid
. Orange Ellipse
This tree is called the logical tree and plays an important role in Silverlight.
Another important thing is that the children of a Grid or a Canvas appear on top of each
other, depending on the order in which they appear in the tree. In Figure 2.5, the yellow
Rectangle appears under its sibling, the half-white Grid. The first child in the tree has a
lower ZIndex than the second one, which in turn has a lower ZIndex than the third one,
and so on. You can also change the ZIndex in the markup, changing the superposition
effect. Change the Rectangle markup as in Listing 2.11:
LISTING 2.11 Changed ZIndex
<Rectangle Width=”246”
Height=”152”
Fill=”Yellow”
Canvas.ZIndex=”2”/>
This causes the Rectangle to appear on top of the half-white Grid, as shown in Figure 2.6,
(because the ZIndex of the Rectangle is set to 2, which is higher than the default value of
0 assigned to the half-white Grid). Note also that ZIndex, like Left and Top, is an attached
property of the Canvas class, thus the syntax Canvas.ZIndex.
CHAPTER 2 Understanding XAML
34
FIGURE 2.6 Rectangle in front
Saving Typing, Saving Space
As you already found out, typing XAML can take some time. In fact, XAML was not
created for humans. It was created for computer tools (like Expression Blend or Visual
Studio), to be used as a storage medium, and then later optimized so that humans can
Silverlight 2 Unleashed Page 42 Return to Table of Contents
53.
type it anywaywithout too much pain. In further chapters, we will see how a good editor
can help you save time, using a technology called Intellisense, automatic tag completion,
and so on.
One such improvement is that for each class, one of the properties can be defined as the
default property. In Silverlight, we talk about the Content Property. It doesn’t need to be
explicitly mentioned when you type XAML markup, to save typing and space. For each
object in Silverlight, the most used property may be marked as the Content Property by
the developer. For example, the Children property of each Panel is the Content Property,
so you can add elements in a Canvas without having to use the Canvas.Children syntax
like in Listing 2.12.
LISTING 2.12 Setting the Canvas.Children Explicitly
<!--Children.xaml-->
<Canvas
xmlns=”http://schemas.microsoft.com/client/2007”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Width=”640”
Height=”480”>
<Canvas.Children>
<Ellipse Width=”400”
Height=”200”
Fill=”Yellow”
Stroke=”Orange”
StrokeThickness=”4”
Canvas.Left=”50”
Canvas.Top=”50”/>
<TextBlock Text=”Hello world”
FontSize=”36”
Foreground=”Blue”
Canvas.Left=”150.763”
Canvas.Top=”122.34”/>
</Canvas.Children>
</Canvas>
Summary
This chapter gave you a first contact with XAML and some important features of this new
language. XAML comes with a learning curve, especially for developers or designers not
used to XML. This learning curve can be a little frightening sometimes, but as time goes
by, you will learn how to master this language and be productive with it.
Summary 35
2
Silverlight 2 Unleashed Page 43 Return to Table of Contents
54.
In the nextchapter, we continue to work with XAML and learn more complex constructs,
adding movement to our applications without writing one line of C# or JavaScript. Later,
we introduce Expression Blend, a tool that allows you to visually edit the XAML markup.
This is where XAML gives us the best of both worlds: a great visual designer and the
possibility to act on markup level if we prefer.
CHAPTER 2 Understanding XAML
36
Silverlight 2 Unleashed Page 44 Return to Table of Contents
Britain they foundin it two races of men physically very distinct, one
of them the aborigines, who had made their way to the island as its
first population after the close of the mammoth age, the others
apparently a later intrusion. They are known to English antiquaries
from their modes of burial as the men of the long and the round
barrows or funeral mounds. The first of these are beyond doubt the
kinsmen of our little men of the Trou de Frontal, in Belgium. They
are thus described by Greenwell and Taylor [29]:
[29] Greenwell, British Barrows; Taylor, Origin of the Aryans.
They were of feeble build, short stature, dark complexion, and
somewhat long skull. They buried their dead in long barrows or
mounds with interior chambers and passages; some of these are as
much as 400 feet in length, and resemble artificial caves; and there
can be no doubt that, as in Belgium, they buried their dead in caves
when these were accessible; and the laborious construction of the
long barrows when caves failed is an indication of the great
importance they attached to the secure and decent sepulture of the
dead. No trace of metal is found in their barrows, and but little
pottery, but it is believed that they had at a very early time
domesticated sheep and cattle and practised agriculture. These
people are now identified with the people of the south and west of
England, called by the Romans Silures. They were the builders of the
cromlechs, dolmens, and other megalithic structures so common in
various parts of the old continent. Their type survives to this day in
the small dark people of parts of Wales and the south and west of
Ireland, and in parts of the Hebrides. Their physical characters
connect them with the primitive populations of the hills of Central
France, with the Basques of the Pyrenees, the Corsicans, the
Berbers of Africa, and the Guanches of the Canary Islands, and the
term Iberian has been applied to the whole group. Their language
was originally not Aryan, but Turanian. They represent not merely a
new race still surviving, but a distinct advance in practical civilisation
over that of the peoples of the palanthropic age, in Europe at least.
57.
At the timeof the Roman conquest this primitive race had been
replaced in the east of England and south of Scotland by a wholly
different people, supposed to be identical with the Celtæ of the
Romans. They were tall, muscular, with broader and shorter heads,
fair complexion, and light-coloured hair. They buried their dead in
round barrows or mounds, and seem at a very early period to have
possessed bronze, and so to have introduced what has been termed
the bronze age into Britain. At the time of the Roman invasion,
however, they already possessed iron weapons. These people were
Aryan in speech, allied to the Gauls and Belgæ, and the ancestors of
the so-called Celtic populations of the British Islands.
CROMLECH AT FONTANACCIA, CORSICA (after De Mortillet)
CHAPTER VIII
58.
THE PALANTHROPIC AGEIN THE LIGHT OF
HISTORY
The time was when the earlier books of the Hebrew Scriptures
stood almost alone in their notices of the creation and antediluvian
times, and when critics could quietly take for granted that they were
altogether mythical. This state of things has now passed away from
the minds of the better informed, and it may be profitable before
proceeding farther to glance for a moment at some of the recent
corroborations, if they may be so called, of the Bible history from
altogether unexpected quarters.
In the first place, there can now be no doubt that the order of
creation, as revealed to the author of the first chapter of Genesis,
corresponds with the results of astronomical and geological research
in a manner which cannot be accidental. [30] This old document thus
stands in the position of a prophecy which has been fulfilled in its
details. Besides this, the discovery of the similar though not identical
Chaldean creation tablets throws a remarkable and interesting side-
light on the whole question. The Chaldean tablets are
unquestionably very ancient, and borrowed from still older
documents from which they are alleged to have been copied. But
they and the Genesis narrative are independent of each other.
Neither can have been copied from the other. Thus there must have
been a still more ancient common source of the narrative, and, as I
have elsewhere urged, [31] the greater simplicity and monotheistic
character of the Hebrew document entitle it to the palm of the
higher antiquity.
[30] For evidence of this I may be permitted to refer to my work,
The Origin of the World.
[31] Modern Science in Bible Lands.
With reference to the antediluvian age and the Deluge, while the
Bible is here only in accord with almost universal tradition, and this
in reference to an event which if it occurred at all must have fixed
59.
itself in thememory of the survivors, it is in remarkable accordance
with very ancient Chaldean writings commemorative of the same
event. Some principal points of this accordance are the following.
The Chaldean account implies that the anger of the gods, or some of
them, against an evil race of men was the cause of the catastrophe.
It gives it a universal character, so far as the sphere of observation
extended. It represents the survivors as saved in a ship or ark. It
represents Hasisadra, its Noah, as sending out birds to ascertain the
subsidence of the waters. In all these points and many others the
Chaldean account agrees with the Biblical in representing
antediluvian men, or some of them, as civilised, possessing domestic
animals, and competent to construct large ships.
When we leave the Deluge and come to the postdiluvian or
neanthropic period, similar coincidences occur. The foundation of a
primitive Cushite or Akkadian kingdom in the Euphratean valley, the
dispersion of men according to their families and their languages,
the early kingdoms contemporary with Abraham, mentioned in the
narrative of his campaign to recover the captives taken from the
cities of the plain, the extremely early use of the arrow-headed
characters in Asia, of the hieroglyphic writing in Egypt, and of a
proto-Phœnician or early Hebrew alphabet among the Mineans of
ancient Arabia, tend at once to vindicate the Bible history, and to
show how at a very early period this history may have been
rendered permanent in written documents. On all these grounds
scientific archæologists are beginning to attach more value than
formerly to the Hebrew annals, and to recognise them as true
historical accounts of the times to which they relate.
It may seem rash to make such a statement at a time when it is
well known that many divines of repute avow themselves as
believers in the theory that the earlier Biblical books are of
comparatively late composition. But Science will have her way in a
matter of this kind, whatever literature or criticism may say, and she
is beginning strongly to lift her voice against the destructive criticism
of the Pentateuch. In a recent article, Professor Sayce, one of the
60.
best-informed experts inthese subjects, uses the following
language:
'Naturally, the "higher criticism" is disinclined to see its
assumptions swept away along with the conclusions which are based
upon them, and to sit humbly at the feet of the newer science. At
first, the results of Egyptian or Assyrian research were ignored; then
they were reluctantly admitted, so far as they did not clash with the
preconceived opinions of the "higher" critics. It was urged,
unfortunately with too much justice, that the decipherers were not,
as a rule, trained critics, and that in the enthusiasm of research they
often announced discoveries which proved to be false or only
partially correct. But it must be remembered, on the other side, that
this charge applies with equal force to all progressive studies, not
excluding the "higher criticism" itself.
'The time is now come for confronting the conclusions of the
"higher criticism," so far as it applies to the books of the Old
Testament, with the ascertained results of modern Oriental research.
The amount of certain knowledge now possessed by the
Egyptologist and Assyriologist would be surprising to those who are
not specialists in these branches of study, while the discovery of the
Tel-el-Amarna tablets has poured a flood of light upon the ancient
world, which is at once startling and revolutionary. As in the case of
Greek history, so too in that of Israelitish history, the period of
critical demolition is at an end, and it is time for the archæologist to
reconstruct the fallen edifice.
'But the very word "reconstruct" implies that what is built again
will not be exactly that which existed before. It implies that the work
of the "higher criticism" has not been in vain; on the contrary, the
work it has performed has been a very needful and important one,
and in its own sphere has helped us to the discovery of the truth.
Egyptian or Assyrian research has not corroborated every historical
statement which we find in the Old Testament, any more than
classical archæology has corroborated every statement which we
find in the Greek writers; what it has done has been to show that
61.
the extreme scepticismof modern criticism is not justified, that the
materials on which the history of Israel has been based may, and
probably do, go back to an early date, and that much which the
"higher" critics have declared to be mythical and impossible was
really possible and true.'
In point of fact a much stronger position might be held in favour
of Genesis, and we shall find in comparing it with the monuments of
the palanthropic and early neanthropic ages that its statements
vindicate themselves as derived from original contemporary
documents, which were under no obligations to the literature or
philosophy of those later times, to which they have been relegated
by some of the critics.
Let us inquire a little more in detail into the general features of
these early historic notices.
For the purposes of this inquiry we may content ourselves with
the consideration of the ancient Hebrew documents incorporated in
the Book of Genesis, and the remains which have been preserved of
the old Chaldean literature. Both of these represent an antediluvian
period of long duration. [32] Both refer the primitive seats of
population to the Euphratean region of Western Asia. Both terminate
the antediluvian age with a great diluvial catastrophe. These are
sufficient points of general agreement to make it probable that both
originated in one fundamental history, or at least were based on
attempts to describe the same events. Otherwise there are great
differences. The Chaldean accounts have a prolix iteration, which
makes it probable that they were prepared for popular and liturgic
use, and may not fairly represent the original documents in
possession of the priestly class. They also naturally introduce all the
personnel of the Chaldean pantheon, and as this must have been a
thing of gradual growth it gives them an air of recency, though we
know that they are very old. The Hebrew version, on the other hand,
is monotheistic, and has an aspect of severe simplicity in striking
contrast to the florid and popular Chaldean version.
62.
[32] Hommel hasproved (Journal of the Society of Biblical
Archæology, 1893), what has always been suspected, that the ten
patriarchs of Berosus are the same with those of the Sethite line
in Genesis.
We may first notice what history can tell of the palanthropic age,
supposing this to be the same with that historically known as
antediluvian. The account of creation in the first chapter of Genesis
is altogether general, and has no local colouring. It evidently refers
to the whole history of the making of the earth. The second chapter,
on the other hand, begins at verse 4 the special history of man, and
opens with a picture which is not, as some have rashly supposed, a
repetition of the previous general account of creation, and still less
contradictory to it, but a statement that immediately before the
introduction of man the earth had been in a desolate and
comparatively untenanted state, that state to which we know it had
been reduced by the glacial cold and submergence.
Thus the two accounts of the creation of man, that in which he
appears in his chronological position in the general development,
and that in which he takes a first place, as introductory to his special
history, are not contradictory, but complementary to each other; and
the latter refers wholly to man and the creatures contemporary with
him in the palanthropic age. It is in accordance with this, and no
doubt intended by the editor to mark this distinction, that the name
Elohim is used in the general narrative, and Jehovah Elohim in the
special one. The failure of so many critics to notice this distinction,
which must have been so plain to the primitive historian himself, is a
marked illustration of the blindness of certain nineteenth-century
savants, so full of their own special knowledge, yet so careless of
science and common sense.
It would even seem that this distinction appeared in the
Chaldean Genesis as well; for fragments of what has been called a
second Chaldean Genesis have been found which seem to
correspond with the statements of the second chapter of Genesis.
63.
The following isan extract from this second Chaldean or
Akkadian Genesis as translated by Pinches: [33]
1 The glorious house, the house of the gods, in a glorious
place had not been made;
2 A plant had not been brought forth, a tree had not been
created;
3 A brick had not been laid, a beam had not been shaped;
4 A house had not been built, a city had not been
constructed;
5 A city had not been made, a foundation had not been
made glorious;
6 Niffer had not been built, Ê-kura had not been
constructed;
7 Erech had not been built, Ê-ana had not been constructed;
8 The Abyss had not been made, Ê-ridu had not been
constructed;
9 (As for) the glorious house, the house of the gods, its seat
had not been made—
10 The whole of the lands were sea.
This may be supposed to correspond with the Hebrew verses
following:
And no plant of the field was yet in the earth.
And no herb of the field had yet sprung up.
For Jahveh Elohim had not caused it to rain on the earth.
And there was not a man to till (irrigate) the ground.
64.
And there wentup a vapour from the earth, and watered the
surface of the ground.
[33] Expository Times, December 1892
This is the Hebrew idea of the condition of the great
Mesopotamian plain after the pleistocene submergence, and before
the appearance of man. The Chaldean version refers to the same
region, but is more elaborate and artificial, and brings in the historic
cities of a later time. This difference alone would induce us to
suppose that the Hebrew record may be a better guide for our
present comparison.
The Hebrew writer in the first place gives us to understand that a
period of comparative desolation preceded the appearance of man, a
great winter of destruction preparatory to a returning spring. He
then proceeds to localise primeval man by placing him in Eden, the
Idinu of the Chaldean accounts, which we also recognise by the
geographical indications of the Euphrates and Tigris as its rivers,
with two companion streams which can scarcely be other than the
Karun and the Kerkhat. Thus the Bible and the Chaldean account
agree in their locality for the advent of man, for Idinu was the
ancient name of the plain of Babylonia. It has been objected to this
locality that much of this region is low and swampy, and has only
recently become land by the encroachment of the rivers on the head
of the Persian Gulf. But if our Biblical authority really refers to
palanthropic man, we must bear in mind that in the post-glacial
period the continents were higher than now, and the Babylonian
plain must have been a dry and elevated district, in all probability
forest-clad. We must also bear in mind that Eden was a region of
country, and that the 'garden' or selected spot 'eastward in Eden'
may have been some rich wooded island surrounded by the river
streams, and producing all fruits pleasant to the taste and good for
food. In any case the modern objections to the site are based on
entire ignorance of its geological history, and only serve to show how
65.
much better informedthe ancient writer was as to antediluvian
geography than his modern critics. [34]
[34] See, for full discussion of this, Modern Science in Bible
Lands, by the author.
It is scarcely necessary to say that this Biblical environment of
primitive man corresponds with the requirements of the case. In a
genial climate and sheltered position, and supplied with abundance
of food, the first men would have the conditions necessary for
comfortable existence and for multiplying in numbers.
We have also in the description of one of the rivers of Eden a
hint as to a few of the wants of early man beyond mere food and
shelter. We are told that the district traversed by this river produced
gold, bedolach, and the shoham stone. I have elsewhere shown that
this river must be the Karun, draining the Luristan mountains, and
that the productions indicated must have been 'native gold and
silver, wampum beads, and jade and similar stones suitable for
implements.' [35] Thus we have here a picture which may well
represent the origin and early condition of our palæocosmic men.
But the parallel does not end here.
[35] Modern Science in Bible Lands.
According to the history, man falls, and is expelled from Eden, is
clothed with skins, and becomes an eater of animal food. Next we
find murderous violence, and a consequent separation of the
primitive people into two tribes, one of which migrates to a distance
from the other and adopts different modes of life. Finally, we have a
mixture of the two races, leading to a powerful and terrible race of
half-breeds, or metis, who filled the earth with violence. [36]
[36] Genesis vi. 1-6.
66.
MAP SHOWING THEGEOGRAPHICAL AND GEOLOGICAL
RELATIONS OF THE SITE OF EDEN AS DESCRIBED IN GENESIS
In one point only have we reason to doubt whether this old
history fairly represents the palanthropic age. It notes the invention
of musical instruments, the use of metals, the domestication of
animals as already existing in the antediluvian period. Of these we
have little or no archæological evidence. The only musical
instrument of this period known is a whistle made of one of the
bones of a deer's foot, and capable of sounding a tetrachord or four
67.
notes, and wehave no certain evidence of metals or domesticated
animals. We must bear in mind that there may have been more
civilised races than those of the Cro-magnon type, and that the
latter evince an artistic skill which if it had any scope for
development may have led to great results. The native metals must
have been known to man from the first, though they must have
been rare or only locally common; and many semi-barbarous nations
of later times show us that it is only a short step from the knowledge
of native metals to the art of metallurgy, in so far as it consists in
treating those ores that in weight and metallic lustre most resemble
the metals themselves. It is also deserving of notice that no other
hypothesis than that of antediluvian civilisation can account for the
fact that in the dawn of postdiluvian history we find the dwellers by
the Euphrates and the Nile already practising so many of the arts of
civilised life. In connection with this we may place the early dawn of
literature. Without insisting on the documents which the Chaldean
Noah, Hasisadra, is said to have hid at Sippara before the Deluge,
we have the known fact that in the earliest dawn of postdiluvian
history the art of writing was known in Chaldea and in Egypt. This at
once testifies to antediluvian culture, and shows that the means
existed to record important events.
There is, perhaps, no one of the vagaries now current under the
much abused name of evolution more opposed to facts, whether
physical or historical than the notion that, because 3000 years B.C.
we have evidence of an advanced civilisation in Chaldea and in
Egypt, this must have been preceded by a long and uninterrupted
progress through many thousands of years from a savage state. Two
facts alone are sufficient to show the folly of such a supposition.
First, the intervention of that great physical catastrophe which
separates the palanthropic and neanthropic periods; and secondly,
the testimony of history in favour of the arts of civilisation originating
with great inventors, and not by any slow and gradual process of
evolution. According to all history, sacred and profane, many such
inventors existed even in the palanthropic and early neanthropic
ages, and transmitted their arts in an advanced state to later times.
68.
The Book ofGenesis testifies to this in its notices of Tubal Cain and
Jubal; and the monuments of Chaldea and Egypt show that
metallurgy, sculpture, and architecture were as far advanced at the
very dawn of history as in any later period. It is true that Genesis
represents its early inventors as mere men, albeit 'sons of God,'
while they often appear as gods or demi-gods in the early history of
the heathen nations; but the fact remains that then, as now, the
rare appearance of God-given inventive genius is the sole cause of
the greater advances in art and civilisation. Spontaneous
development may produce socialistic trades' unions or Chinese
stagnation, but great gifts, whether of prophecy, of song, of
scientific insight, or of inventive power, are the inspiration of the
Almighty.
We have in the closing part of the Bible story of the antediluvian
age even an intimation of the deterioration of climate and means of
subsistence towards the end of the period. Lamech, we are told,
named his son Noah—rest or comfort—in the hope that by his
means he should be comforted, because of the ground which the
Lord had cursed. That curse provoked by the sons of man he may
have recognised as fulfilled in the gradual deterioration of the
climate toward the close of the palanthropic age. There are here
surely some curious coincidences which might be followed farther,
did space permit.
We now come to the close of the whole in the Deluge; and as
this has been made in our own time the subject of much discussion,
and as it contains within itself the whole kernel of the subject, it
merits a separate treatment.
CHAPTER IX
THE DELUGE OF NOAH
69.
To the oldermen of this generation, who have followed the
changes of scientific and historical opinion, the story of the Deluge,
old though it is, has passed through a variety of phases like the
changes of a kaleidoscope, and which may afford an instructive
illustration of the modifications of belief in other, and some of them
to us more important, matters, whether of history or of religion,
which have presented themselves in like varied aspects, and may be
variously viewed in the future.
As children we listened with awe and wonder to the story of the
wicked antediluvians, and of their terrible fate and the salvation of
righteous Noah, and received a deep and abiding impression of the
enormity of moral evil and of the just retribution of the Great Ruler
of the Universe. A little later, though the idea that all the fossil
remains imbedded in the rocks are memorials of the Deluge had
passed away from the minds of the better informed, we read with
interest the wonderful revelations of the bone-caves described by
Buckland, and felt that the antediluvian age had become a scientific
reality. But later still all this seemed to pass away like a dream.
Under the guidance of Lyell we learned that even the caves and
gravels must be of greater age than the historical Deluge, and that
the remains of men and animals contained in them must have
belonged to far-off æons, antedating perhaps even the Biblical
creation of man, while the historical Deluge, if it ever occurred, must
have been an affair so small and local that it had left no traces on
the rocks of the earth. At the same time Biblical critics were busy
with the narrative itself, showing that it could be decomposed into
different documents, that it bore traces of a very recent origin, that
it was unhistorical, and to be relegated to the same category with
the fairy-tales of our infancy. Again, however, the kaleidoscope turns,
and the later researches of geology into the physical and human
history of the more recent deposits of the earth's crust, the
discoveries of ancient Assyrian or Chaldean records of the Deluge,
and the comparison of these with the ancient history of other
nations, rehabilitate the old story; and as we study the new facts
respecting the so-called palæolithic and neolithic men, the clay
70.
tablets recovered fromthe libraries of Nineveh by George Smith, the
calculations of Prestwich and others respecting the recency of the
glacial period, and the historical gatherings of Lenormant, we find
ourselves drifting back to the faith of our childhood, or may
congratulate ourselves on having adhered to it all along, even when
the current of opinion tended strongly to turn us away.
In illustration of the present aspects of the question I make two
extracts, one from Lenormant's Beginnings of History, another from
a recent work of my own.
'We are,' says Lenormant, 'in a position to affirm that the account
of the Deluge is a universal tradition in all branches of the human
family, with the sole exception of the black race, and a tradition
everywhere so exact and so concordant cannot possibly be referred
to an imaginary myth. No religious or cosmogonic myth possesses
this character of universality. It must necessarily be the reminiscence
of an actual and terrible event, which made so powerful an
impression upon the imaginations of the first parents of our species
that their descendants could never forget it. This cataclysm took
place near the primitive cradle of mankind, and previous to the
separation of the families from whom the principal races were to
descend, for it would be altogether contrary to probability and to the
laws of sound criticism to admit that local phenomena exactly similar
in character could have been reproduced at so many different points
on the globe as would enable one to explain these universal
traditions, or that these traditions should always have assumed an
identical form, combined with circumstances which need not
necessarily have suggested themselves to the mind in such a
connection.' [37]
[37] Les Origines de l'Histoire. Brown's translation.
On the geological side, the following may be accepted as a
summary of facts: [38]
71.
[38] Modern Sciencein Bible Lands, 1888, pp. 244, 245, 251,
252.
'If the earliest men were those of the river gravels and caves,
men of the mammoth age or of the palæolithic or palæocosmic
period, we can form some definite ideas as to their possible
antiquity. They colonised the continents immediately after the
elevation of the land from the great subsidence which closed the
pleistocene or glacial period, or in what has been called the
"continental" period of the post-glacial age, because the new lands
then raised out of the sea exceeded in extent those which we now
have. We have some measures of the date of this great continental
elevation. Many years ago, Sir Charles Lyell used the recession of the
Falls of Niagara as a chronometer, estimating their cutting power as
equal to one foot per annum. He calculated the beginning of the
process, which dates from the post-glacial elevation, to be about
thirty thousand years ago. More recent surveys have shown that the
rate is three times as great as that estimated by Lyell, and also that
a considerable part of the gorge was merely cleaned out by the river
since the pleistocene age. In this way the age of the Niagara gorge
becomes reduced to perhaps seven or eight thousand years. Other
indications of similar bearing are found both in Europe and America,
and lead to the belief that it is physically impossible that man could
have colonised the northern hemisphere at an earlier date. These
facts render necessary an entire revision of the calculations based on
the growth of stalagmite in caves, and other uncertain data which
have been held to indicate a greater lapse of time.
'If we identify the antediluvians of Genesis with the oldest men
known to geological and archæological science, the parallelism is
somewhat marked in physical characteristics and habits of life, and
also in their apparently sudden and tragical disappearance from
Europe and Western Asia, along with several of the large mammalia
which were their contemporaries. If the Deluge is to be accepted as
historical, and if a similar great break interrupts the geological
history of man, separating extinct races from those which still
survive, why may we not correlate the two? If the Deluge was
72.
misused in theearly history of geology, by employing it to account
for changes which took place long before the advent of man, this
should not cause us to neglect its legitimate uses, with reference to
the early human period. It is evident that if this correlation be
accepted as probable, it must modify many views now held as to the
antiquity of man. In that case the modern gravels and silts, spread
over the plateaus between the river valleys, will be accounted for,
not by any greater overflow of the existing streams, but by the
abnormal action of currents of water diluvial in their character.
Further, since the historical Deluge must have been of very limited
duration, the physical changes separating the deposits containing
the remains of palæocosmic men from those of later date would in
like manner be accounted for, not by the slow processes imagined by
extreme uniformitarians, but by causes of a more abrupt and
cataclysmic character.' [39]
[39] See also Howorth, The Mammoth and the Flood, and papers
by Professor Prestwich in Journal Geol. Society and Trans. Royal
Society and by Andrews, Winchell, and others in America.
We may proceed to inquire as to whether the position which we
have now reached is likely to be permanent, or may represent
merely one shifting phase of opinion. For this purpose we may
formulate these conclusions in a few general statements, merely
referring to the evidence on which they are based, as any complete
discussion of this would necessarily be impossible within the limits of
this work. We may first summarise the present position of the matter
as indicated by historical and scientific research, altogether
independently of the Bible. [40]
[40] See articles by the author in The Contemporary Review,
December 1889, and in The Magazine of Christian Literature,
October 1890.
1. The recent discovery of the Chaldean deluge tablets has again
directed attention to the statements of Berosus respecting the
Babylonian tradition of a great flood, and these statements are
found to be borne out in the main by the contents of the tablets.
73.
There is thusa twofold testimony as to the occurrence of a deluge in
that Babylonian plain which the Old Testament history represents as
the earliest seat of antediluvian man. As Lenormant has well shown,
the tradition exists in the ancient literature of India, Persia,
Phœnicia, Phrygia, and Greece, and can be recognised in the
traditions of Northern and Western Europe and of America, while the
Egyptians had a similar account of the destruction of men, but
apparently not by water, though their idea of a submerged continent
of Atlantis probably had reference to the antediluvian world. Thus
we find this story widely spread over the earth, and possessed by
members of all the leading divisions of mankind. This does not
necessarily prove the universality of the Deluge, though every
distinct people naturally refers it to its own country. It shows,
however, the existence of some very early common source of the
tradition, and the variations are not more than were to have been
expected in the different channels of transmission.
2. Parallel with this historical evidence lies the result of geological
and archæological research, which has revealed to us the remains
and works of prehistoric men, racially distinct from those of modern
times, and who inhabited the earth at a period when its animal
population was to a great extent distinct from that at present
existing, and when its physical condition was also in many respects
different. Thus in Europe and Asia, and to some extent also in
America, we have evidence that the present races of men were
preceded by others which have passed away, and this at the same
time with many important species of land animals, once the
contemporaries of man, but now known only as fossils. These
ancient men are those called by geologists later pleistocene, or post-
glacial, or the men of the cave and gravel deposits, or of the age of
the mammoth, and who have been designated by archæologists
palæolithic men, or, more properly, palæocosmic men, since the
character of their stone implements is only one not very important
feature of their history, and implements of the palæolithic type have
been used in all periods, and indeed are still used in some places.
74.
3. The prevalenceamong geologists of an exaggerated and
unreasonable uniformitarianism, which refused to allow sufficient
prominence to sudden cataclysms arising from the slow
accumulation of natural forces, and which was a natural reaction
from the convulsive geology of an earlier period, has caused the idea
to be generally entertained that the age of palæocosmic men was of
vast duration, and passed only by slow gradations and a gradual
transition into the new conditions of the modern period. This view
long was, and still is, an obstacle to any rational correlation of the
geological and traditional history of man. Recently, however, new
views have been forced on geologists, and have led many of the
most sagacious observers and reasoners to see that the palanthropic
period is much nearer to us than we had imagined. The arguments
for this I have referred to in previous pages, and need not reiterate
them, here. A few leading points may, however, be noted. One of
these is the small amount of physical or organic change which has
occurred since the close of the palanthropic period. Another is the
more rapid rate of erosion and deposition by rivers in the modern
period than had previously been supposed. Another is the striking
fact that a large number of mammals, like the mammoth and woolly
rhinoceros, seem to have perished simultaneously with the
palæocosmic men, and this by some sudden catastrophe. [41] It has
also been shown by Pictet and Dawkins that all the extant mammals
of Europe already existed in the post-glacial age, but along with
many others now altogether or locally extinct. Thus there seems to
have been the removal over the whole northern hemisphere of a
number of the largest mammals, while a selected number survived
and no additions were made. Again, while at one time it was
supposed that the remains of palæocosmic man and his
contemporaries were confined to caverns and river alluvia, it is now
known that they occur also on high plateaus and water-sheds, in
beds of gravel and silt which must have been deposited there under
conditions of submergence and somewhat active current drift,
perhaps in some cases aided by floating ice. [42] Lastly, while, as
must naturally be the case, in some places the remains of ancient
75.
and more modernmen are mixed, or seem to pass into each other,
in others, as in the Swiss, Belgian and Lebanon caves and in the
superficial deposits, there is a distinct separation, implying an
interval accompanied by physical change between the time of the
earlier and later men.
[41] Howorth, The Mammoth and the Flood.
[42] Prestwich on deposits at Ightham, Kent, Journal Geological
Society, May 1889.
Such considerations as these, the force of which is most strongly
felt by those best acquainted with the methods of investigation
employed by geologists and archæologists, are forcing us to
conclude: (1) That there are indicated in the latest geological
formations two distinct human periods, an earlier and a later,
characterised by differences of faunæ and of physical conditions, as
well as by distinct races of men. (2) That these two periods are
separated by a somewhat rapid physical change of the nature of
submergence, or by a series of changes locally sudden and generally
not long-continued. (3) That it is not improbable that this greatest of
all revolutions in human affairs may be the same that has so
impressed itself on the memory of the survivors as to form the basis
of all the traditions and historical accounts of the Deluge.
This being the state of the case, it becomes expedient to review
our ideas of the ancient Hebrew records, from which our early, and
perhaps crude, impressions of this event were derived, and to
ascertain how much of our notions of the Deluge of Genesis may be
fairly deduced from the record itself, and how much may be due to
more or less correct interpretations, or to our own fancy. In
connection with this we may also be able to obtain some guidance
as to the value to be attached to the Hebrew document as a
veritable and primitive record of the great catastrophe.
The key to the understanding of the early human history of
Genesis lies in the story of the fall of man, and its sequel in the
murder of Abel by his brother Cain, the beginning of that reign of
76.
violence which endureseven to this day. From this arose the first
division of the human race into hostile clans or tribes, the races of
Cain and Seth, on which hinges the history, characteristics and fate
of antediluvian man; and, as we shall see in the sequel, from this
arose profound differences in religious beliefs, which have tinged the
theology and superstitions of all subsequent times. Of course, in
making this statement I refer to the history given in Genesis, without
special reference to its intrinsic truth or credibility, but merely in
relation to its interpretation in harmony with its own statements.
It is further evident that this tragic event must have occurred in
that Tigro-Euphratean region which was the Biblical site of Eden [43]
and that while the Sethite race presumably occupied the original
home of Adam, and adhered to that form of religion which is
expressed in the worship of Jahveh, the coming Redeemer and the
expected 'Seed of the Woman,' the other race spread itself more
widely, probably attained to a higher civilisation, in so far as art is
concerned, in some of its divisions, and sank to a deeper barbarism
in others, while it retained the original worship of God the Creator
(Elohim). Hence the Sethite race is designated as the sons of Adam
(Beni ha Adam), the true and legitimate children of the first man,
and the Cainites as Beni Elohim, or sons of God. [44] The mixture of
these races produced the godless, heaven-defying Nephelim, the
Titans of the Old Testament, whose wickedness brought on the
diluvial catastrophe. These half-breeds of the antediluvian time were
in all probability the best developed, physically and perhaps
mentally, of the men of their period; and but for the Deluge they
might have become masters of the world.
[43] Modern Science in Bible Lands, chap. iv.
[44] That this is the true meaning of the expressions in Genesis
vi. I cannot doubt. See discussion of the subject in the work cited
in previous note.
This question of different races and religions before the Flood is,
however, deserving of a little farther elucidation. The names Elohim
77.
and Jahveh areused conjointly throughout the Book of Genesis
except in its first chapter, and their mode of occurrence cannot be
explained merely on the theory of two documents pieced together
by an editor. It has a deeper significance than this, and one which
indicates a radical diversity between Elohists and Jahvists even in
this early period. In the earliest part of the human history, as
distinguished from the general record of creation, the two names are
united in the compound Jahveh-Elohim, but immediately after the
fall Eve is represented as attributing to, or identifying with, Jahveh
alone the birth of her eldest son—'I have produced a man, the
Jahveh,' and which may mean that she supposed Cain to be the
promised manifestation of God as the Redeemer. Accordingly Cain
and Abel are represented as offering sacrifice to Jahveh, and yet it is
said in a verse which must be a part of the same document, that it
was not till the time of Enos, a grandson of Adam, that men began
to invoke the name of Jahveh. It would seem also that this
invocation of Jahveh was peculiar to the Sethites, and that the
Cainites were still worshippers of Elohim, the God of nature and
creation, a fact which perhaps has relation to the so-called physical
religion of some ancient peoples. Hence their title of Beni ha Elohim.
Thus the division between the Cainite and Sethite races early
became accentuated by a sectarian distinction as well. We may
imagine that the Cainites, worshipping God as Creator, and ignoring
that doctrine of a Redeemer which seemed confined to the rival race
of Seth, were the deists of their time, and held a position which
might, according to culture and circumstances, degenerate into a
polytheistic nature-worship, or harden into an absolute materialism.
On the other hand, the Sethites, recognised by the author of Genesis
as the orthodox descendants of Adam, and invoking Jahveh, held to
the promise of a coming Saviour, and to a deliverance from the
effects of the Fall to be achieved by His means.
It is clear that, from the point of view of the author of Genesis,
the chosen seed of Seth should have maintained their separation
from a wicked world. Their failure to do this involves them in the
wrath of Jahveh and renders the destruction of mankind necessary,
78.
and in thisthe whole Godhead under its combined aspects of Elohim
and Jahveh takes a part. A similar view has caused the Chaldean
narrator to invoke the aid of all the gods in his pantheon to effect
the destruction of man.
These considerations farther throw light on the double character
of the Deluge narrative in Genesis, which has induced those
ingenious scholars who occupy themselves with analysis or
disintegration of the Pentateuch to affirm two narratives, one Elohist
and one Jahvist. [45] Whatever value may attach to this hypothesis,
it is evident that if the history is thus made up of two documents it
gains in value, since this would imply that the editor had at his
disposal two chronicles embodying the observations of two
narrators, possibly of different sects, if these differences were
perpetuated in the postdiluvian world; and farther, that he is enabled
to affirm that the catastrophe affected both the great races of men.
It farther would imply that these early documents were used by the
writer to produce his combined narrative almost without change of
diction, so that they remain in their original form of the alleged
testimony of eye-witnesses, a peculiarity which attaches also to the
Chaldean version, as this purports to be in the form given by
Hasisadra, the Chaldean Noah, himself. [46]
[45] See, for a very clear statement of these views, Professor
Green in Hebraica, January 1889, along with Dr. Harper's résumé
of the Pentateuchal criticism in the previous number.
[46] Translation of G. Smith and others. With reference to the
preservation of this and the Hebrew narrative in writing, we
should bear in mind that writing was an art well known in Chaldea
and Egypt immediately after the Deluge, or at least between 2000
and 3000 B.C., and that the Chaldean narrator speaks of
documents hidden by Noah at Sippara before the Deluge.
Let us now inquire into the physical aspects of the Deluge, as
they are said to have presented themselves to the ancient witness or
witnesses to whom we owe the Biblical account of the catastrophe,
and endeavour to ascertain if they have any agreement with the
79.
conditions of thegreat post-glacial Deluge of geology. Let it be
observed here that we are dealing not with prehistoric events but
with a written history, supposed by some to have been compiled
from two contemporary documents, and corroborated by the
testimony of the ancient Chaldean tablets copied by the scribes of
Assurbanipal, apparently from different originals, preserved in very
ancient Chaldean temples.
The preparation of an ark or ship, and the accommodation
therein, not only of Noah and his family, but of a certain number of
animals, is a feature in which most Deluge narratives agree. This
implies a considerable advance in the arts of construction and
navigation, but not more than we have a right to infer from the
perfection of these arts in early postdiluvian times, when it can
scarcely be supposed that the new communities of men had fully
regained the position of their ancestors before the destruction
caused by the great Flood. Lenormant, however, remarks here:
'The Biblical narrative bears the stamp of an inland nation,
ignorant of things appertaining to navigation. In Genesis the name
of the ark, Têbâh, signifies "chest," and not "vessel"; and there is
nothing said about launching the ark on the water; no mention
either of the sea, or of navigation, or any pilot. In the Epopee of
Uruk, on the other hand, everything indicates that it was composed
among a maritime people; each circumstance reflects the manners
and customs of the dwellers on the shores of the Persian Gulf.
Hasisadra goes on board a vessel, distinctly alluded to by its
appropriate appellation; this ship is launched, and makes a trial-trip
to test it: all its chinks are calked with bitumen, and it is placed
under the charge of a pilot.'
This remark, which I find made by other commentators as well,
suggests, it seems to me, somewhat different conclusions. The
Hebrews when settled, either in Egypt or in Canaan, were near to
the sea-coast, and familiar with boats and with the ships of the
Phœnicians. If, therefore, they persisted in calling Noah's ark a
'chest,' it must have been from unwillingness to change an old
80.
history derived fromtheir Chaldean or Mesopotamian ancestors, or
because they continued to regard the ark as rather a great box than
a ship properly so called. On the other hand, it is likely that the
particulars in the Chaldean account came from later manipulation of
the narrative, after commerce and navigation on the Euphrates and
Persian Gulf had become familiar to the Chaldeans. Thus in this as in
other respects the Hebrew narrative is the more primitive of the two,
and is consistent with the necessity of Divine instructions to Noah,
which, if he had been familiar with navigation, would not have been
necessary. [47]
[47] See also the evidence of an inland position of the writers in
the record of creation in Genesis i., as stated in my work cited in
previous note.
As in the Chaldean version, the Biblical history begins with the
specification of the ark. On this (Elohist) portion it is only necessary
to say that the dimensions of the ark are large and well adapted to
stowage rather than to speed, and that within it was strengthened
by three decks and by a number of bulkheads, or partitions,
separating the rooms or berths into which it was divided. Without, it
was protected and rendered tight by coats of resinous or asphaltic
varnish (copher), and it was built of the lightest and most durable
kind of wood (gopher or cypress). Only two openings are mentioned,
a hatch or window above, and a port or door in the side. There is no
mention of any masts, rigging, or other means of propulsion or
steerage. The Chaldean history differs in introducing a steersman,
thus implying the means of propulsion as in an actual ship.
Noah is instructed, in addition to his own family, to provide for
animals, two of every kind; but these very general terms are
afterwards limited by the words uph, bemah, and remesh, which
define birds, cattle, and small quadrupeds as those specially
intended. Noah's ark was not a menagerie, but rather like a cattle-
ship, capable perhaps of accommodating as many animals as one of
those steamers which now transfer to England the animal produce of
Western fields and prairies. The animals portrayed on the ancient
81.
monuments of Egyptand Assyria, however, inform us that, in early
post-diluvial times, and therefore probably also in the time of Noah,
a greater variety of animals were under the control of man than is
the case in any one country at present. [48] In the passage referring
to the embarkation, only the cattle and fowls are mentioned, but
seven pairs are to be taken of the clean species which could be used
as food. [49] The embarkation having been completed on the very
day when the Deluge commenced, we have next the narrative of the
Flood itself. Here it is noteworthy that God (Elohim) makes the
arrangements, and Jahveh shuts the voyagers in.
[48] Houghton, Natural History of the Ancients, and Transactions
of the Society of Biblical Archæology; also representations of
tame antelopes, &c., on Egyptian monuments.
[49] This has been considered a later addition; but the practice of
all primitive peoples has sanctioned the distinction of clean and
unclean beasts, which is merely defined in the Mosaic law, not
instituted for the first time.
The first note that our witness enters in his 'log' relates to his
impressions of the causes of the catastrophe, which was not effected
supernaturally, but by natural causes. These are the 'breaking up of
the fountains of the great deep' and the 'opening of the windows of
heaven.' These expressions must be interpreted in accordance with
the use of similar terms in the account of creation in Genesis i., the
more so that this statement is a portion regarded by the composite
theory as Elohistic. On this principle of interpretation, the great deep
is that universal ocean which prevailed before the elevation of the
dry land, and the breaking up of its fountains is the removal of that
restriction placed upon it when its waters were gathered together
into one place. In other words, the meaning is the invasion of the
land by the ocean. In like manner, the windows of heaven, the
cloudy reservoirs of the atmospheric expanse, or possibly
waterspouts, or even volcanic eruptions, and not necessarily
identical with the great rain extending for forty days, as stated in the
following clause. The Chaldean record adds the phenomena of
thunder and tempest, but omits the great deep; an indication that it
82.
is an independentaccount, and by a less informed or less intelligent
narrator. It is worthy of note that our narrator has no idea of any
river inundation in the case.
At this stage we are brought into the presence of the question: Is
the Deluge represented as a miraculous or a merely natural
phenomenon? Yet, from a scientific point of view, this question has
not the significance usually attributed to it. True miracles are not,
and cannot be, contraventions or violations of God's natural laws.
They are merely unusual operations of natural powers under their
proper laws, but employed by the Almighty for effecting spiritual
ends. Thus, naturally, they are under the laws of the material world,
but, spiritually, they belong to a higher sphere. In the present case,
according to the narrative in Genesis, the Flood was physically as
much a natural phenomenon as the earthquakes at Ischia, or the
eruption of Krakatoa. It was a miraculous or spiritual intervention
only in so far as it was related to the destruction of an ungodly race,
and as it was announced beforehand by a prophet. Had the
approaching eruption of Krakatoa been intended as a judgment on
the wicked, and had it been revealed to anyone who had taken pains
to warn his countrymen and then to provide for his own safety, this
would have given to that eruption as much of a miraculous character
as the Bible attaches to the Deluge. In the New Testament, where
we have more definite information as to miracles, they are usually
called 'powers' and 'signs,' less prominence being given to the mere
wonder which is implied in the term 'miracle.' Under the aspect of
powers, they imply that the Creator can do many things beyond our
power and comprehension, just as in a lesser way a civilised man,
from his greater knowledge of natural laws and command over
natural energies, can do much that is incomprehensible to a savage;
and in this direction science teaches us that, given an omnipotent
God, the field of miracle is infinite. As signs, on the other hand, such
displays of power connect themselves with the moral and spiritual
world, and become teachers of higher truths and proofs of Divine
interference. The true position of miracles as signs is remarkably
brought out in that argument of Christ, in which He says, 'If ye
83.
believe not Mywords, believe Me for the works' sake.' It is as if a
civilised visitor to some barbarous land, who had been describing to
an incredulous audience the wonders of his own country, were to
exhibit to them a watch or a microscope, and then to appeal to them
that these were things just as mysterious and incredible as those of
which he had been speaking.
Returning to the Deluge, we may observe that such an invasion
of the great deep is paralleled by many of which geology presents to
us the evidence, and that our knowledge of nature enables us to
conceive of the possibility of greater miracles of physical change
than any on record, such as, for instance, the explosion of the earth
itself into an infinity of particles, the final extinction of the solar heat,
or the accession to this heat of such additional fierceness as to burn
up the attendant planets. All this might take place without any
interference with God's laws, but merely by correlations and
adjustments of them, as much within His power as the turning on or
stopping of a machine is in the power of a human engineer. Further,
such acts of Divine power may be related to moral and spiritual
things, just as easily as any outward action resulting from our own
will may be determined by moral considerations. The time is past
when any rational objection can be made on the part of science to
the so-called miracles of the Bible.
To return to the passengers in the ark. This must have been built
on high ground, or the progress of the Deluge must have been slow,
for forty days elapsed before the waters reached the ship and
floated it. It is not unlikely that the ark was built on rising ground,
for here supplies of timber would be nearer. It has puzzled some
simple antiquarians to find dug-out canoes of prehistoric date on the
tops of hills; but they did not reflect that the maker of a canoe
would construct his vessel where the suitable wood could be found,
since it would be much easier to carry the finished canoe to the
shore than to drag thither the solid log out of which it was to be
fashioned. So Noah would naturally build his ark where the wood he
required could be procured most easily. The Chaldean narrator
84.
seems to haveoverlooked this simple consideration, for he mentions
a launching and trial-trip of the ship, a sure mark that he is a later
authority than the writer in Genesis.
The inmates of the ark now felt that it was moving on the
waters, a new and dread sensation which must have deeply
impressed their minds, and they soon became aware that the ark
not merely floated, but 'went,' or made progress in some definite
direction. Remark the simple yet significant notes—'The ark was lift
up from the earth,' and 'the ark went upon the face of the waters.'
The direction of driftage is not stated, but it is a fair inference, from
the probable place of departure in Chaldea and that of final
grounding of the ark, that it was northward or inland, which would
indicate that the chief supply of water was from the Indian Ocean,
and that it was flowing inward toward the great sunken plain of
interior Asia, which, however, the ark did not reach, but grounded in
the hilly region known to the Hebrews as Ararat, to the Chaldeans as
Nisr. A curious statement is made here (Elohist) as to the depth of
the water being fifteen cubits. Even in a flat country so small a
depth would not cover the rising grounds; but this is obviously not
the meaning of the narrator, but something much more sensible and
practical. It is not unlikely that the measure stated was the water-
draught of the loaded ark, and that as the voyagers felt it rise and
fall on the waves, they may have experienced some anxiety lest it
should strike and go to pieces. It was no small part of the
providential arrangement in their case that in the track of the ark
everything was submerged more than fifteen cubits before they
reached it. Hence this note, which is at the same time one of the
criteria of the simple veracity of the history. The only other remark in
this part of the narrative relates to the entire submergence of the
whole country within sight, and the consequent destruction of
animal life; and here the enumeration covers all land animals, and
the terms used are thus more general than those applied to the
animals preserved in the ark. The Deluge culminated, in so far as
our narrator observed, in one hundred and fifty days.
85.
His next experienceis of a gale of wind, accompanied or followed
by cessation of the rain and of the inflow of the oceanic waters. [50]
The waters then decreased, not regularly, but by an intermittent
process, 'going and returning'; but whether this was a tidal
phenomenon or of the nature of earthquake waves we have no
information. At length the ark grounded, apparently on high ground
or in thick weather, for no land was visible; but at length, after two
months, neighbouring hill-tops were seen.
[50] Genesis viii. 1, 2: 'And Elohim made a wind to pass over the
earth, and the waters abated,' &c.
The incident of sending out birds to test the recession of the
waters deserves notice, because of its apparently trivial nature,
because it appears with variations in the Chaldean account, and
because it has been treated in a remarkably unscientific manner by
some critics. It indicates the uncertainty which would arise in the
mind of the patriarch because of the fluctuating decrease of the
waters, and possibly also a misty condition of the air preventing a
distinct view of distant objects. The birds selected for the purpose
were singularly appropriate. The raven is by habit a wanderer, and
remarkable for power of flight and clearness of distant vision. So
long, therefore, as it made the ark its headquarters, 'going and
returning' [51] from its search for food, it might be inferred that no
habitable land was accessible. The dove, sent out immediately after
the raven, [52] is of a different habit. It could not act as a scavenger
of the waters and go and return, but could leave only if it found land
covered with vegetation. As a domesticated bird also, it would
naturally come back to be taken into the ark. Hence it was sent forth
at intervals of seven days, returning with an olive leaf when it found
tree tops above the water, and remaining away when it found food
and shelter. The Chaldean account adds a third bird, the swallow—a
perfectly useless addition, since this bird, if taken into the ark at all,
would from its habits of life be incapable of affording any
information. This addition is a mark of interpolation in the Chaldean
version, and proceeded perhaps from the sacred character attached
86.
by popular superstitionto the swallow, or from the familiar habits of
the bird suggesting to some later editor its appropriateness.
Singularly enough, the usually judicious Schrader, probably from
deficient knowledge of the habits of birds, fails to appreciate all this,
and after a long discussion prefers the Babylonian legend for
reasons of a most unscientific character, actually condemning the
perfectly natural and clear Biblical story as artificial and due to a
recent emendation. He says: 'When the story passed over to the
Hebrews, the name of the swallow has disappeared,' and 'it is only
from the Babylonian narrative that the selection of the different birds
becomes clear.' This little disquisition of Schrader is, indeed, one of
the most amusing instances of that inversion of sound criticism
which results when unscientific commentators tamper with the plain
statements of truthful and observant witnesses.
[51] Margin of Authorised Version; less fully, 'to and fro' in the
text.
[52] There is no reason to suppose, as some have done, a hiatus
here in the narrative.
The uncertainty indicated by the mission of the birds seems to
have continued from the first day of the tenth to the first day of the
first month, when Noah at length ventured to remove the covering
of the ark and inspect the condition of the surrounding country, now
abandoned by the waters, but not thoroughly dried for some time
longer. Still, so timid was the patriarch that he did not dare without a
special command to leave his place of safety. I am aware that if the
two alleged documents are arbitrarily separated it is possible to see
here some apparent contradiction in dates; but this is not necessary
if we leave them in their original relation. [53]
[53] See Green, Hebraica, l. c.
It will be observed that a narrative such as that summarised
above bears unmistakably stamped upon it the characteristics of the
testimony of an eye-witness. By whomsoever reduced to writing and
finally edited, it must, if genuine, have come down nearly in its
87.
present form fromthe time of the catastrophe which it relates. It
follows that the narrator leaves no place for the current questions as
to the universality of the Deluge. It was universal so far as his
experience extended, but that is all. He is not responsible for what
occurred beyond the limits of his observation and beyond the fact
that man, so far as known to him, perished. If, therefore, as some
have held, [54] Balaam in his prophecy refers to Cainite populations
as extant in his time, or if Moses declines to trace to any of the
postdiluvian patriarchs the Rephaim, Emim, Zuzim and other
prehistoric peoples of Palestine, we may infer, without any
contradiction of our narrative, that there were surviving
antediluvians other than the Noachidæ, whatever improbability may
attach to this on other grounds, and more especially from the now
ascertained extension of the post-glacial submergence over nearly all
parts of the northern hemisphere.
[54] Motais, Déluge Biblique.
Let it also be noticed that beyond the prophetic intimation to
Noah, and the one expression, Jahveh 'shut him in,' which may refer
merely to providential care, there is, as already remarked, nothing
miraculous, in the popular sense of that term; and that mythical
elements, such as those introduced into the Babylonian narrative,
are altogether absent. The story relates to plain matters of fact,
which, if they happened at all, any one might observe, and for the
proof of which any ordinary testimony would be sufficient. It may be
profitable, however, to revert here to the probable relation of this
narrative to the geological facts already adverted to, and also its
bearing on the mythical and polytheistic additions which we find in
the Deluge stories of heathen nations.
Regarding the Biblical Deluge as a record of a submergence of a
vast region of Eur-Asia and Northern Africa, at least, while no similar
catastrophe has been recorded subsequently, it is unquestionable
that submergences equally important have occurred again and again
in the geological history of our continents, and have been equally
destructive of animal life. It is true that most of these are believed to
88.
have been ofmore slow and gradual character than that recorded in
Genesis, but in the case of many of them this is a very uncertain
inference from the analogy of modern changes; and it is certain that
the post-glacial submergence, which closed the era of palæocosmic
man and his companion animals, must have been one of the most
transient on record. On the other hand, we need not limit the entire
duration of the Noachic submergence to the single year whose
record has been preserved to us. Local subsidence may have been in
progress throughout the later antediluvian age, and the experience
of the narrator in Genesis may have related only to its culmination in
the central district of human residence. Finally, if man was really a
witness of this last great continental submergence, we cannot be too
thankful that there were so intelligent witnesses to preserve the
record of the event for our information.
It is needless, then, to enter into further details, though these
are sufficient to fill volumes if desired, in proof of the remarkable
convergence of history and geological discovery on the great Flood,
which now constitutes one of the most remarkable illustrations of
the points of contact of science proceeding on its own methods of
investigation and Divine revelation, preserving the records of ancient
events otherwise lost or buried under accretions of myth and fancy. I
have already endeavoured to show that the earliest race of
palæocosmic men, that of Canstadt, very fairly corresponds with
what may have been the characteristics of the ruder tribes of
Cainites, and that if we regard the Truchère skull as representing the
Sethite people, we may suppose the Cro-magnon race to represent
the giants, or Nephelim, who sprung from the union of the two pure
types. I have also referred to the possibility that the Truchère race,
so little known to us as yet, may have been a prot-Iberian people,
possessing even before the Flood domestic animals, agriculture, and
some of the arts of life, corresponding to what we find in the earliest
postdiluvian nations. This is, indeed, implied in the fact that the
postdiluvian nations present themselves to us at once with a
somewhat advanced condition of the arts, especially in Chaldea and
in Egypt. Such possibilities may serve to suggest to speculative
89.
archæologists that theycannot safely assume that all antediluvian or
palæolithic tribes were barbarous or semi-brutal, or that there was a
continuous development of humanity without any diluvial
catastrophe. It is also somewhat rash to carry back the chronology
of Egyptians and Babylonians to times when, as we know on
physical evidence, the Valley of the Nile was an arm of the sea, and
the plain of the Euphrates an extension of the Persian Gulf. It is
fortunate for the Bible that such assumptions are not required by its
history.
CHAPTER X
SPECIAL QUESTIONS RESPECTING THE
DELUGE
In studying the literature relating to the Deluge, we are
constantly met by questions as to its so-called 'universality.' Was it a
local or universal Deluge and if universal in what sense so? This is a
point in which neglect or ignorance of the necessary physical
conditions has led to the strangest misconceptions.
It is obvious that there are four senses in which a catastrophe
like the Deluge of Noah may be affirmed or denied to have been
universal.
1. It may have been universal in the sense of being a deep
stratum of water covering the whole globe, both land and sea. Such
universality could not have been in the mind of the writer, and
probably has been claimed knowingly by no writer in modern times.
Halley in the last century understood the conditions of such
universality, though he seems to have supposed that the impact of a
comet might supply the necessary water. Owen has directed
attention to the fact that such a deluge might be as fatal to the
inhabitants of the waters as to those of the land. In any case, such
90.
Welcome to ourwebsite – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com