OReilly Essential Silverlight 2 Up To Date Apr 2008 ISBN 0596519982

  Essential Silverlight 2 Up-to-Date

  by Christian Wenz Publisher: O'Reilly Pub Date: April 15, 2008

  Print ISBN-13: 978-0-596-51998-8 Pages: 212

   Overview

  Now you can design rich Internet applications (RIAs) for the Web using Silverlight 2, the latest version of Microsoft's hot new runtime application -- without waiting for the official release.

  That's right. With Essential Silverlight 2 Up-to-Date, you not only get a concise, easy-to-understand introduction to Silverlight 2, but thorough coverage of the CTPs, betas, and RTM releases as they become available.

  Once you buy this Up-to-Date edition, you'll be able to download free PDFs of all the revisions to Silverlight -- pages that you can print and insert right into the book's unique binder format. Pre-printed updates will also be available for purchase. It combines the the speed of technology with convenience of a book.

  With Essential Silverlight 2 Up-to-Date, you learn to take advantage of Microsoft's cross-browser Silverlight plug-in with tools for animation, vector graphics, and video playback, as well as new .NET support for web services, networking and LINQ (language integrated query). This guide gives you complete step-by-step instructions for using everything Silverlight has to offer, along with:

  Clever ways to create interactive UIs that are more robust and easier to debug and test than what you can achieve on

  Scores of tested JavaScript and C# code examples that you can reuse in your own applications Expert guidance from an author who understands RIA technologies, including ASP.NET, Flash, PHP, and JavaScript

  Ready to deliver a more complete Web experience? Now there's no reason to wait. Essential Silverlight 2 Up to Date offers a whole new world of possibilities.

  Essential Silverlight 2 Up-to-Date

  by Christian Wenz Publisher: O'Reilly Pub Date: April 15, 2008

  Print ISBN-13: 978-0-596-51998-8 Pages: 212

  

  

  

  

  

  Copyright Copyright © 2008, O'Reilly Media. All rights reserved.

  Printed in the United States of America. Published by O'Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.

  O'Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles ( . For more information, contact our corporate/institutional sales department: (800) 998-9938 or Editor: John Osborn Editor: Laurel R.T. Ruma Production Editor: Sarah Schneider Editor: Audrey Doyle Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks of O'Reilly Media, Inc.

  Essential Silverlight 2 Up-to-Date, the image of a collared

  pratincole, and related trade dress are trademarks of O'Reilly Media, Inc. Microsoft, MSDN, Windows, the .NET logo, Visual Studio, Visual C#, Visual Basic, IntelliSense, and Silverlight are registered trademarks or trademarks of Microsoft Corporation. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O'Reilly Media, Inc. was aware of trademark claims, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this errors or omissions, or for damages resulting from the use of the information contained herein.

  Preface

  I would consider myself a web guy. When I first accessed the World Wide Web sometime around 1994, I immediately fell in love with its possibilities and technical challenges. From then on, I almost exclusively worked on web projects and did very little programming apart from that. As the years have passed, I have seen technologies come and go, but some of them stayed. For instance, I remember starting to work with ASP and PHP simultaneously around 1997 or 1998, and finally moving away from ASP because it was so limited. I returned to the ASP world when the first betas of ASP.NET were released, and my interest heightened when ASP.NET 2.0 came up, and it was off to the races again. (Today, I am happily using both.) I appreciate that my JavaScript knowledge is in demand again, thanks to one new term: Ajax.

  One of the technologies I really developed a love-hate relationship with was Macromedia Flash (now Adobe Flash). I really like that the technology can do so much more than HTML and JavaScript, including everything you want to call "Ajax." I am also happy that the browser plug-in has such an enormous market share. I really, really hate the Flash editor. The designers I work with are very happy with it, but from a developer's perspective, I change into explicit lyrics mode whenever I have to use it. This is probably no surprise: Flash is historically a designer's tool and has just recently begun to appeal to developers. I am a terrible designer, so I probably do not deserve better.

  But still, Flash is a very nice technology because it combines advanced graphical features with powerful coding support. So, I was more than happy when I heard that Microsoft was working on a similar technology: Silverlight. (No one at Microsoft will ever tell you that there is a connection between Silverlight and Flash, and that's probably true, but it serves to point out similarities and differences.) Knowing that Microsoft has always to have the features of Flash, with a better development experience (at least for me). And, to be honest, the first steps that were released as "Silverlight 1.0" were really promising. Most programming is done in trusted Visual Studio, but there are designer tools as well. Microsoft still has a long way to go, with the tool and market share, but the first steps are done, and I look forward to seeing the next ones.

  Although Silverlight 1.0 was released a mere few months ago (in September 2007, to be exact), Silverlight 2 is already on the horizon. This book features the latest, prebeta build of Silverlight 2. As Silverlight 2 continues to evolve, this book will adapt to each new version as well. We plan to release an update to Essential Silverlight 2 Up-to-Date whenever a new, significant Silverlight release comes out of the Redmond labs.

  Once Silverlight 2 gos RTM, this book will be updated one last time as well. We did our best to bring you up-to-date information by using sources within Microsoft to get an advance look at new features and releases of Silverlight. However, until the final book is in your hands, some weeks will have passed, so there may be new releases, new features, or some features might even have been dropped. We will always try to come up with a new release as soon as possible, and will add errata and late-breaking changes on the book's catalog page at

   .

  P.1. Who This Book Is For

  There are two target audiences for this book: developers who would like to familiarize themselves with the Silverlight technology, and designers who would like to see what Silverlight has to offer. I've chosen to focus on the developer. True to the promise of an O'Reilly Essentials book, Essential

  

Silverlight 2 Up-to-Date is not a complete reference or in-depth

  tutorial. Instead, you will quickly learn how to get Silverlight 2 put its capabilities to the test through the dozens of working code examples. Support for Silverlight from Microsoft and third parties continues to grow, and whenever possible we point you to sources For Further Reading that you can turn to for information. This book covers Silverlight 2. For details on Silverlight 1.0, you can refer to my book Essential Silverlight 1.0. While knowledge of Windows Presentation Foundation (WPF) is not required, if you have already worked with it, it has many similarities with the Silverlight UI framework. From a programming point of view, JavaScript and C# are the languages of choice. If you have not worked with either language before, refer to the O'Reilly catalog for some excellent choices.

  P.2. How This Book Is Organized

  Part 1 contains background information on Silverlight and related technologies. A brief introduction to Silverlight and other rich Internet applications

   Goes through all the required installation steps and steps

  for creating your first Silverlight application

  Reviews software tools that facilitate the creation of Silverlight content

  Part 2 focuses on the results you can achieve with the declarative means of Silverlight; but some C# coding will also be covered

   Features the most important elements of Microsoft's WPF

  markup language

   Explains how Silverlight applications may become

  interactive by processing events

   Exposes two different approaches to making Silverlight

  animations dynamic

   Shows how to use audio and video data in Silverlight

  applications, including C# access Part 3 focuses on C# development aspects.

   embedding and creation of Silverlight content

  Part 4 focuses on JavaScript development aspects Shows advanced JavaScript possibilities, including the ability to make HTTP requests

  

  Provides a list of properties and methods the Silverlight plug-in exposes

  P.3. What You Need to Use This Book For developing Silverlight content, you need only a text editor.

  It is much more convenient is to use Visual Studio 2008 or the (free) Visual Web Developer Express Edition 2008 (however, the former option is preferable).

  guides you through all the necessary

  installation steps both for developing and for viewing Silverlight content.

  P.4. Conventions Used in This Book

  The following typographical conventions are used in this book:

  Indicates new terms, URLs, email addresses, filenames, and file extensions.

  Constant width

  Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords.

  Constant width bold

  Shows commands or other text that should be typed literally by the user.

  Constant width italic

  Shows text that should be replaced with user-supplied values or by values determined by context.

  This icon signifies a tip, suggestion, or general note.

  This icon indicates a warning or caution.

  P.5. Using Code Examples may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product's documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: "Essential Silverlight 2 Up-to-Date by Christian Wenz. Copyright 2008 O'Reilly Media, Inc., 978-0-596-519-988." If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at

  permissions@oreilly.com .

  P.6. How to Contact Us

  Please address comments and questions concerning this book to the publisher: O'Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707 829-0104 (fax)

  We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at:

   Register this book for updates at:

  

  To comment or ask technical questions about this book, send email to:

  bookquestions@oreilly.com

  For more information about our books, conferences, Resource Centers, and the O'Reilly Network, see our web site at:

   ack P.7. Acknowledgments

  I have expressed the thought on various occasions that technical book authors should not thank their partners/kids/dogs and pretend that writing a book put their private and social lives at risk. In prefaces of fiction or memoirs you never read such complaints, but in technical books they seem to be all too common. I have written several dozens of those and always managed to juggle work and play. This time, however, I understood. I wrote this book on an extremely tough schedule so that it could be published in time for the Silverlight release. So, I had to work crazy hours and neglect some things and some people. (Not that I haven't done that in the past, but this time it was worse than usual.) Therefore, thanks to all who suffered in one way or another— you know who you are.

  I also have to thank my editor at O'Reilly, John Osborn, for joining forces with me again. Andrew Savikas got me set up with DocBook and also tried to convince me that writing a book in XML was not too bad (I still want my word processor back). Keith Fahlgren and Abby Fox set up the Subversion repository, implemented the automated PDF build, and also cleaned up my

  Doyle copyedited the text, and I don't know which they cursed more: my writing or my XML. Yvonne Schimmer provided me with video material for the chapter on multimedia and supported the rest of the book as well.

  This book would not have been possible without the support from people within Microsoft who provided me access to preview bits of Silverlight and additional, nonofficial resources. These people include Scott Guthrie, Brian Goldfarb, and especially Chung Webster. Thank you very much for your trust and support.

  Part 1: Introduction

Chapter 1. Introducing Silverlight 2 Silverlight is Microsoft's new browser-based plug-in for delivering richer interactive applications to users over the web. Silverlight 2 is Microsoft's second release of the Silverlight

  platform. Silverlight 2's biggest change from Silverlight 1.0 is the inclusion of a compact version of the .NET Framework, complete with the .NET Framework 3.0 Common Language Runtime. By adding .NET to Silverlight, Microsoft makes it easy for .NET developers to reuse their existing programming skills, collaborate with designers, and quickly create rich applications for the Web.

  And even though Silverlight 2 brings .NET to the client, it can be integrated easily with many existing Web technologies and backend Web platforms. That means Silverlight will integrate with your existing infrastructure and applications, from IIS and .NET to Apache and PHP to simple JavaScript and XHTML on the client. Silverlight is not a tool meant for exclusive use on ASP.NET web sites, which should result in broader adoption of the new technology.

  Still, one of the key benefits of Silverlight 2 is that it can execute any .NET language, including C# and VB.NET. Unlike the CLR included with the "normal" .NET Framework, multiple instances of the core "Silverlight CLR" can be hosted in a single process. With this, the layout markup in the Silverlight XAML file (.xaml file) can be augmented by code-behind code with all programming logic written in any .NET language. Silverlight 2 ships with a "lightweight" version of the full .NET Framework, which features, among other classes, extensible controls, XML Web Services, networking components, and LINQ APIs. This class library is a subset of (and is considerably smaller than) the .NET Framework's Base Class Library, which enables the Silverlight plug-in to be a fast and small download. For security, all Silverlight code runs in a sandbox environment from malicious code. Silverlight 2 also adds support for DRM in media files, a fact that will make some people happy and others cringe. In addition to the .NET Framework classes, Silverlight 2 also ships with a subset of the WPF UI programming model, including support for shapes, documents, media, and WPF animation objects. The Silverlight 2 December CTP did not ship with many WPF UI controls, though, so out-of-the-box controls will remain limited until beta 1. The Silverlight 2 beta 1 release promises to deliver more controls as well as the ability to bind to data. Microsoft says that the data binding limitations are strictly temporary and that future builds of Silverlight 2 will eliminate the problem. Count on future Silverlight releases to add more UI controls, data binding support, and a much needed

  

  The architecture of Silverlight 1.0 is quite complex (see

  for

  an overview), but it can be broken down into big chunks. The presentation system takes care of everything UI, including animation, text rendering, and audio/video playback. The plug- in itself integrates into the browser so that the content can be shown, as well as accessed using the JavaScript DOM. Finally, using some JavaScript code (or, optimally, the ASP.NET AJAX framework), Silverlight applications can be enriched to access server APIs such as web services. The browser plug-in then parses the markup and runs the code, even if no .NET Framework Redistributable is installed on the client. Silverlight 2 further extends this and offers a partial .NET Framework integration right into Silverlight. So you can write code in languages such as C#; this code will be compiled prior to deployment.

  

Figure 1-1. Silverlight framework model

1.1. Rich Internet Applications

  What exactly is a "RIA" web application? And why would you want to adopt the RIA model for your own web development? Rich Internet Applications, or RIAs, are web applications that have the features and functionality of traditional desktop for the user interface to the web client but keep the bulk of the data processing (such as maintaining the state of the program, the data, etc.) on the application server. Traditional web applications implement a client/server architecture, in which a thin client (the web browser) interacts with a powerful server. Typically, all processing is done on the server and the client is used only to display static HTML content. The biggest drawback to thin-client implementations is that all interaction with the application must pass through the server. That means data must be sent to the server, the server must respond, and then the page must be reloaded on the client with the server's response. By moving more of this processing to client-side technology that can execute instructions on the client's computer, RIAs can circumvent this slow, synchronous loop for many user interactions.

1.1.1. Benefits of Rich Internet Applications

  One of the primary benefits of RIAs is that they can offer user- interface behaviors not possible with only the HTML controls available in standard browser-based web applications. With a RIA platform, web applications are no longer limited by what the browser can do. Rather, they can implement any user interaction that the new RIA platform support, such as drag- and-drop behaviors, smooth animations, and client-side calculations. While some of these interactions are possible without a RIA platform (using Ajax, for example), the RIA approach is typically much more responsive and consistent across platforms.

  The benefits of RIAs, however, go beyond their looks. Using a client engine can also produce other performance benefits:

  Client-server balance applications from the server to the client. This frees up resources on the web server, enabling the same server hardware to handle more concurrent user sessions. On the flip side, the approval it requires that your users have computers that are powerful enough to execute complex client-side code, which is generally not a problem in this day and age.

  Asynchronous communication

  The RIA client engine can interact with the server asynchronously—that is, without waiting for the user to perform an action such as clicking on a button or link. This feature enables RIA designers to move data between the user's PC and the server without making the user wait for the transfer to finish, similar to what Ajax provides today.

  Network efficiency

  Network traffic may also be significantly reduced in a RIA because an application-specific client engine can be more intelligent than a standard web browser when deciding what data needs to be exchanged with servers. Transferring less data for each interaction can speed up individual requests and responses, in turn reducing overall network load. Use of asynchronous prefetching techniques, however, can neutralize or even reverse this potential benefit. Because code cannot anticipate exactly what every user will do next, prefetching extra data is common, not all of which is actually needed by many users.

1.1.2. Shortcomings of Rich Internet Applications

  While RIAs offer some compelling advantages over current approaches to web development, there are a number of are requirements of the browser plug-in itself (in most cases). Among the more serious drawbacks of RIAs are:

  Sandbox

  Because RIAs run within a sandbox, they have restricted access to system resources. If users modify their systems or have reduced permissions that alter a RIA's ability to access system resources, RIAs may fail to operate correctly.

  Disabled scripting

  RIAs usually require JavaScript or another scripting language to operate on the client. If the user has disabled active scripting in his browser, the RIA may not function properly, if at all.

  Script download time

  Although it does not always have to be installed, the additional client-side intelligence (or client engine) of RIA applications needs to be delivered by the server to the client. While much of this is usually automatically cached, it needs to be transferred at least once. Depending on the size and type of delivery, client engine download time may be unpleasantly long, especially for users with slower Internet connections. Some RIA developers can lessen the impact of this delay by compressing scripts and by staging delivery over multiple pages of an application. For client engine s that require a plug-in to be installed, this is not an option.

  Search engines may not be able to index the text content of RIA applications. This can be a major problem for web applications that depend on search engine visibility for their success.

  Dependence on an Internet connection

  While the ideal network-enabled replacement for a desktop application would allow users to be "occasionally connected," wandering in and out of hotspots or from office to office, today (in 2008) the typical RIA requires network connectivity.

  Part 1: Introduction

Chapter 1. Introducing Silverlight 2 Silverlight is Microsoft's new browser-based plug-in for delivering richer interactive applications to users over the web. Silverlight 2 is Microsoft's second release of the Silverlight

  platform. Silverlight 2's biggest change from Silverlight 1.0 is the inclusion of a compact version of the .NET Framework, complete with the .NET Framework 3.0 Common Language Runtime. By adding .NET to Silverlight, Microsoft makes it easy for .NET developers to reuse their existing programming skills, collaborate with designers, and quickly create rich applications for the Web.

  And even though Silverlight 2 brings .NET to the client, it can be integrated easily with many existing Web technologies and backend Web platforms. That means Silverlight will integrate with your existing infrastructure and applications, from IIS and .NET to Apache and PHP to simple JavaScript and XHTML on the client. Silverlight is not a tool meant for exclusive use on ASP.NET web sites, which should result in broader adoption of the new technology.

  Still, one of the key benefits of Silverlight 2 is that it can execute any .NET language, including C# and VB.NET. Unlike the CLR included with the "normal" .NET Framework, multiple instances of the core "Silverlight CLR" can be hosted in a single process. With this, the layout markup in the Silverlight XAML file (.xaml file) can be augmented by code-behind code with all programming logic written in any .NET language. Silverlight 2 ships with a "lightweight" version of the full .NET Framework, which features, among other classes, extensible controls, XML Web Services, networking components, and LINQ APIs. This class library is a subset of (and is considerably smaller than) the .NET Framework's Base Class Library, which enables the Silverlight plug-in to be a fast and small download. For security, all Silverlight code runs in a sandbox environment from malicious code. Silverlight 2 also adds support for DRM in media files, a fact that will make some people happy and others cringe. In addition to the .NET Framework classes, Silverlight 2 also ships with a subset of the WPF UI programming model, including support for shapes, documents, media, and WPF animation objects. The Silverlight 2 December CTP did not ship with many WPF UI controls, though, so out-of-the-box controls will remain limited until beta 1. The Silverlight 2 beta 1 release promises to deliver more controls as well as the ability to bind to data. Microsoft says that the data binding limitations are strictly temporary and that future builds of Silverlight 2 will eliminate the problem. Count on future Silverlight releases to add more UI controls, data binding support, and a much needed

  

  The architecture of Silverlight 1.0 is quite complex (see

  for

  an overview), but it can be broken down into big chunks. The presentation system takes care of everything UI, including animation, text rendering, and audio/video playback. The plug- in itself integrates into the browser so that the content can be shown, as well as accessed using the JavaScript DOM. Finally, using some JavaScript code (or, optimally, the ASP.NET AJAX framework), Silverlight applications can be enriched to access server APIs such as web services. The browser plug-in then parses the markup and runs the code, even if no .NET Framework Redistributable is installed on the client. Silverlight 2 further extends this and offers a partial .NET Framework integration right into Silverlight. So you can write code in languages such as C#; this code will be compiled prior to deployment.

  

Figure 1-1. Silverlight framework model

1.1. Rich Internet Applications

  What exactly is a "RIA" web application? And why would you want to adopt the RIA model for your own web development? Rich Internet Applications, or RIAs, are web applications that have the features and functionality of traditional desktop for the user interface to the web client but keep the bulk of the data processing (such as maintaining the state of the program, the data, etc.) on the application server. Traditional web applications implement a client/server architecture, in which a thin client (the web browser) interacts with a powerful server. Typically, all processing is done on the server and the client is used only to display static HTML content. The biggest drawback to thin-client implementations is that all interaction with the application must pass through the server. That means data must be sent to the server, the server must respond, and then the page must be reloaded on the client with the server's response. By moving more of this processing to client-side technology that can execute instructions on the client's computer, RIAs can circumvent this slow, synchronous loop for many user interactions.

1.1.1. Benefits of Rich Internet Applications

  One of the primary benefits of RIAs is that they can offer user- interface behaviors not possible with only the HTML controls available in standard browser-based web applications. With a RIA platform, web applications are no longer limited by what the browser can do. Rather, they can implement any user interaction that the new RIA platform support, such as drag- and-drop behaviors, smooth animations, and client-side calculations. While some of these interactions are possible without a RIA platform (using Ajax, for example), the RIA approach is typically much more responsive and consistent across platforms.

  The benefits of RIAs, however, go beyond their looks. Using a client engine can also produce other performance benefits:

  Client-server balance applications from the server to the client. This frees up resources on the web server, enabling the same server hardware to handle more concurrent user sessions. On the flip side, the approval it requires that your users have computers that are powerful enough to execute complex client-side code, which is generally not a problem in this day and age.

  Asynchronous communication

  The RIA client engine can interact with the server asynchronously—that is, without waiting for the user to perform an action such as clicking on a button or link. This feature enables RIA designers to move data between the user's PC and the server without making the user wait for the transfer to finish, similar to what Ajax provides today.

  Network efficiency

  Network traffic may also be significantly reduced in a RIA because an application-specific client engine can be more intelligent than a standard web browser when deciding what data needs to be exchanged with servers. Transferring less data for each interaction can speed up individual requests and responses, in turn reducing overall network load. Use of asynchronous prefetching techniques, however, can neutralize or even reverse this potential benefit. Because code cannot anticipate exactly what every user will do next, prefetching extra data is common, not all of which is actually needed by many users.

1.1.2. Shortcomings of Rich Internet Applications

  While RIAs offer some compelling advantages over current approaches to web development, there are a number of are requirements of the browser plug-in itself (in most cases). Among the more serious drawbacks of RIAs are:

  Sandbox

  Because RIAs run within a sandbox, they have restricted access to system resources. If users modify their systems or have reduced permissions that alter a RIA's ability to access system resources, RIAs may fail to operate correctly.

  Disabled scripting

  RIAs usually require JavaScript or another scripting language to operate on the client. If the user has disabled active scripting in his browser, the RIA may not function properly, if at all.

  Script download time

  Although it does not always have to be installed, the additional client-side intelligence (or client engine) of RIA applications needs to be delivered by the server to the client. While much of this is usually automatically cached, it needs to be transferred at least once. Depending on the size and type of delivery, client engine download time may be unpleasantly long, especially for users with slower Internet connections. Some RIA developers can lessen the impact of this delay by compressing scripts and by staging delivery over multiple pages of an application. For client engine s that require a plug-in to be installed, this is not an option.

  Search engines may not be able to index the text content of RIA applications. This can be a major problem for web applications that depend on search engine visibility for their success.

  Dependence on an Internet connection

  While the ideal network-enabled replacement for a desktop application would allow users to be "occasionally connected," wandering in and out of hotspots or from office to office, today (in 2008) the typical RIA requires network connectivity.

  Part 1: Introduction

Chapter 1. Introducing Silverlight 2 Silverlight is Microsoft's new browser-based plug-in for delivering richer interactive applications to users over the web. Silverlight 2 is Microsoft's second release of the Silverlight

  platform. Silverlight 2's biggest change from Silverlight 1.0 is the inclusion of a compact version of the .NET Framework, complete with the .NET Framework 3.0 Common Language Runtime. By adding .NET to Silverlight, Microsoft makes it easy for .NET developers to reuse their existing programming skills, collaborate with designers, and quickly create rich applications for the Web.

  And even though Silverlight 2 brings .NET to the client, it can be integrated easily with many existing Web technologies and backend Web platforms. That means Silverlight will integrate with your existing infrastructure and applications, from IIS and .NET to Apache and PHP to simple JavaScript and XHTML on the client. Silverlight is not a tool meant for exclusive use on ASP.NET web sites, which should result in broader adoption of the new technology.

  Still, one of the key benefits of Silverlight 2 is that it can execute any .NET language, including C# and VB.NET. Unlike the CLR included with the "normal" .NET Framework, multiple instances of the core "Silverlight CLR" can be hosted in a single process. With this, the layout markup in the Silverlight XAML file (.xaml file) can be augmented by code-behind code with all programming logic written in any .NET language. Silverlight 2 ships with a "lightweight" version of the full .NET Framework, which features, among other classes, extensible controls, XML Web Services, networking components, and LINQ APIs. This class library is a subset of (and is considerably smaller than) the .NET Framework's Base Class Library, which enables the Silverlight plug-in to be a fast and small download. For security, all Silverlight code runs in a sandbox environment from malicious code. Silverlight 2 also adds support for DRM in media files, a fact that will make some people happy and others cringe. In addition to the .NET Framework classes, Silverlight 2 also ships with a subset of the WPF UI programming model, including support for shapes, documents, media, and WPF animation objects. The Silverlight 2 December CTP did not ship with many WPF UI controls, though, so out-of-the-box controls will remain limited until beta 1. The Silverlight 2 beta 1 release promises to deliver more controls as well as the ability to bind to data. Microsoft says that the data binding limitations are strictly temporary and that future builds of Silverlight 2 will eliminate the problem. Count on future Silverlight releases to add more UI controls, data binding support, and a much needed

  

  The architecture of Silverlight 1.0 is quite complex (see

  for

  an overview), but it can be broken down into big chunks. The presentation system takes care of everything UI, including animation, text rendering, and audio/video playback. The plug- in itself integrates into the browser so that the content can be shown, as well as accessed using the JavaScript DOM. Finally, using some JavaScript code (or, optimally, the ASP.NET AJAX framework), Silverlight applications can be enriched to access server APIs such as web services. The browser plug-in then parses the markup and runs the code, even if no .NET Framework Redistributable is installed on the client. Silverlight 2 further extends this and offers a partial .NET Framework integration right into Silverlight. So you can write code in languages such as C#; this code will be compiled prior to deployment.

  

Figure 1-1. Silverlight framework model

1.1. Rich Internet Applications

  What exactly is a "RIA" web application? And why would you want to adopt the RIA model for your own web development? Rich Internet Applications, or RIAs, are web applications that have the features and functionality of traditional desktop for the user interface to the web client but keep the bulk of the data processing (such as maintaining the state of the program, the data, etc.) on the application server. Traditional web applications implement a client/server architecture, in which a thin client (the web browser) interacts with a powerful server. Typically, all processing is done on the server and the client is used only to display static HTML content. The biggest drawback to thin-client implementations is that all interaction with the application must pass through the server. That means data must be sent to the server, the server must respond, and then the page must be reloaded on the client with the server's response. By moving more of this processing to client-side technology that can execute instructions on the client's computer, RIAs can circumvent this slow, synchronous loop for many user interactions.

1.1.1. Benefits of Rich Internet Applications

  One of the primary benefits of RIAs is that they can offer user- interface behaviors not possible with only the HTML controls available in standard browser-based web applications. With a RIA platform, web applications are no longer limited by what the browser can do. Rather, they can implement any user interaction that the new RIA platform support, such as drag- and-drop behaviors, smooth animations, and client-side calculations. While some of these interactions are possible without a RIA platform (using Ajax, for example), the RIA approach is typically much more responsive and consistent across platforms.

  The benefits of RIAs, however, go beyond their looks. Using a client engine can also produce other performance benefits:

  Client-server balance applications from the server to the client. This frees up resources on the web server, enabling the same server hardware to handle more concurrent user sessions. On the flip side, the approval it requires that your users have computers that are powerful enough to execute complex client-side code, which is generally not a problem in this day and age.

  Asynchronous communication

  The RIA client engine can interact with the server asynchronously—that is, without waiting for the user to perform an action such as clicking on a button or link. This feature enables RIA designers to move data between the user's PC and the server without making the user wait for the transfer to finish, similar to what Ajax provides today.

  Network efficiency

  Network traffic may also be significantly reduced in a RIA because an application-specific client engine can be more intelligent than a standard web browser when deciding what data needs to be exchanged with servers. Transferring less data for each interaction can speed up individual requests and responses, in turn reducing overall network load. Use of asynchronous prefetching techniques, however, can neutralize or even reverse this potential benefit. Because code cannot anticipate exactly what every user will do next, prefetching extra data is common, not all of which is actually needed by many users.

1.1.2. Shortcomings of Rich Internet Applications

  While RIAs offer some compelling advantages over current approaches to web development, there are a number of are requirements of the browser plug-in itself (in most cases). Among the more serious drawbacks of RIAs are:

  Sandbox

  Because RIAs run within a sandbox, they have restricted access to system resources. If users modify their systems or have reduced permissions that alter a RIA's ability to access system resources, RIAs may fail to operate correctly.

  Disabled scripting

  RIAs usually require JavaScript or another scripting language to operate on the client. If the user has disabled active scripting in his browser, the RIA may not function properly, if at all.

  Script download time

  Although it does not always have to be installed, the additional client-side intelligence (or client engine) of RIA applications needs to be delivered by the server to the client. While much of this is usually automatically cached, it needs to be transferred at least once. Depending on the size and type of delivery, client engine download time may be unpleasantly long, especially for users with slower Internet connections. Some RIA developers can lessen the impact of this delay by compressing scripts and by staging delivery over multiple pages of an application. For client engine s that require a plug-in to be installed, this is not an option.

  Search engines may not be able to index the text content of RIA applications. This can be a major problem for web applications that depend on search engine visibility for their success.

  Dependence on an Internet connection

  While the ideal network-enabled replacement for a desktop application would allow users to be "occasionally connected," wandering in and out of hotspots or from office to office, today (in 2008) the typical RIA requires network connectivity.

1.2. RIA Technologies

  Microsoft's Silverlight is certainly one of the newest entries in the RIA space, but it is not the only show in town. A number of platforms on the market enable developers to create RIA applications, including the perennial favorite, Adobe Flash. Some of the top RIA platforms available today are:

  Microsoft Silverlight

  Silverlight provides a rich graphics and animation display via XAML integration, and it also includes support for multimedia and HTML interaction. With Version 2, the .NET Framework is included, enabling client-side programming with managed languages such as C# and supported dynamic languages such as IronRuby. Like Adobe Flash Player, Silverlight code runs in a sandbox without direct access to platform APIs for security.

  Adobe Flash Player and Adobe Flex

  Another way to build RIAs—and probably the most popular to date—is via Adobe Flash Player and Adobe Flex. These technologies are cross-platform and quite powerful for creating rich client-side interactions. Adobe Flex provides the option to create Flash UIs by compiling MXML, an XML- based interface description language. But perhaps the largest advantage of the Flash RIA platform is the install base of the plug-in, which at last count was 98% of the world's computers.

  Ajax frameworks

  Ajax, or Asynchronous JavaScript and XML (or ), is a script-based RIA approach.

  XMLHttpRequest

  JavaScript is the programming language with which Ajax calls are made, and the browser object

  XMLHttpRequest

  enables asynchronous communication with the server. Data retrieved using this technique is commonly formatted using

  XML, though it is not a requirement. Ajax has quickly risen in popularity as it is supported by all modern browsers without the requirement for additional plug-ins. Like other RIAs, though, it is not well suited for search engine optimization or for handling clients that have disabled client-side scripts.

  Adobe AIR

  Adobe AIR (Adobe Integrated Runtime), previously code- named Adobe "Apollo," is a cross-operating-system runtime that allows web application developers to use their existing web development skills with RIA technologies (such as Flash/Flex, JavaScript/Ajax, and HTML) to build and deploy RIAs to the desktop. While not entirely RIA, this technology is closely related to rich applications technology as it targets the same developers.

  JavaFX

  JavaFX is a new offering from Sun Microsystems that complements the Java family of tools. It addresses the growing demand in the Java community for RIA tools and technologies to deliver rich content to the client. Today the technology spans two releases: JavaFX Script and JavaFX Mobile. JavaFX Script gives Java developers the power to quickly create content-rich applications for the widest variety of clients, including mobile devices, desktops, and home electronics units. In theory, content creators now have a simple way to develop content for any Java-enabled software system for mobile devices.

  Google Gears

  Google Gears is beta software offered by Google to enable offline access to services that normally only work online. It installs a database engine, based on SQLite, on the client system to locally cache web application data. Google Gears- enabled pages use data from the local cache rather than from the online service. Using Google Gears, a web application may periodically synchronize the data in the local cache with the online service whenever a network connection is available. If a network connection is unavailable, the synchronization is deferred until a network connection is established. This allows Google Gears-enabled web applications to work disconnected from the Internet, making them more like their robust desktop counterparts. While not entirely RIA, this technology is closely related to rich applications technology as it addresses the key problem of application connectivity. In coming chapters, we'll explore the various elements of the framework for developing Silverlight applications. We'll begin with a look at one of the most important features Silverlight brings to developers: WPF-like support for rich user interfaces.

Chapter 2. Introducing WPF Most graphics nowadays are pixel-based. Every point in the

  graphic is represented by one pixel. This is a really good solution for most scenarios, including digital photography (where you really want to maintain every single piece of information the camera is "seeing"), but there are shortcomings too. For instance, have a look at , where you see some simple text created in Microsoft Paint. This text is pixel- based. In , you see the same text, but this time the image width and height have been enlarged. Do you see the stairway effect that appears along the edge of each letter? So, when you make a pixel-based image larger, you lose quality.

  

Figure 2-1. The word "Silverlight" displayed by Paint, a

pixel based tool

Figure 2-2. Increased in size, text in a pixel-based tool

displays "stair step" edges That's obvious, of course. Imagine that a 100 x 100 pixel image is resized to 200 x 200 pixels. Instead of 10,000 pixels, we now have 40,000 pixels. So, where we had a 1 x 1 pixel in the original image, we now have 2 x 2 pixels. Paint is using a very simple algorithm to resize images: if the graphic becomes larger, just clone the pixels. This then creates the stairway effect.

  NOTE