Reprint Licensing
Essential Silverlight PDF
Essential Silverlight PDF

By Christian Wenz

Cover | Table of Contents


Table of Contents

Chapter 1: WPF Basics
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 information the camera is “seeing”), but there are shortcomings too. For instance, have a look at , where you see a 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? So when you make a pixel-based image larger, you lose quality.
Figure : A text in Microsoft Paint
Figure : The same text, increased in size
That’s obvious, of course. Imagine, for example, that an 100x100 pixel image is resized to 200x200 pixels. Instead of 10,000 pixels, we how have 40,000 pixels. So, where we had a 1x1 pixel in the original image, we now have 2x2 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.
Professional software like Adobe Photoshop comes with several quite sophisticated algorithms to make the quality loss when resizing images less severe (especially when making them smaller); however, there still is a notable effect when increasing an image’s dimensions.
There is an alternative approach: vector-based images. Every element on an image is a geometrical object: a line, a circle, a polygon, a curve, just to name a few. The main advantage is that there is no quality loss when resizing the image: a circle just changes its width, but that’s all. There is no stairway effect, since it is still a circle and not, as with a pixel image, a set of pixel ordered in a circular fashion.
Obviously, not every image can be represented as vectors. Think again of photos―it is theoretically possible to try to find geometrical elements and patterns in a portrait or in a landscape (there even are algorithms for that!), but it is virtually impossible to create an exact representation of a photo by just using vectors. However, in computing there are several areas where vectors make real sense. One such area is fonts. See for a typical Windows font (coincidentally the same font used in and ). Most fonts are vectors, so there is no quality difference whether you use them in 8pt, 10pt, 12pt, or 100pt. If you type a letter in a word processor and then change the font size to something really high, you still get smooth edges. Once you paste a text into a pixel-based imaging software like Paint, you lose the vector information and are back to pixels.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Getting Started With Silverlight
Some people refer to Microsoft’s Silverlight technology as a “Flash killer,” but I’m not sure whether that is really true. However, the similarities are striking. Both Adobe Flash (formerly Macromedia Flash) and Silverlight come as browser plugins. Both support vector graphics, audio and video playback, animations, and scripting support.
The technology basis is different. Flash uses a semi-open binary format, Silverlight is based on WPF. Before it was called Silverlight, the technology was codenamed WPF/E (Windows Presentation Foundation Everywhere). And thanks to good browser support, Silverlight can really be run everywhere, at least in theory.
In practice, the penetration of the browser plugin is a key issue. At the time of this writing, Silverlight plugins are available for the Windows platform (no surprise here) and support the two big players, Microsoft Internet Explorer and Mozilla Firefox. Also, a Mac OS X plugin exists that targets Safari and Mozilla Firefox on the Apple platform. According to Microsoft, other platforms were investigated, but given that Windows has such a high market share in terms of desktop operating systems and Mac OS X is number two on that list, these browsers were given priority.
Silverlight needs Windows XP or higher to run; the 1.0 version might, at some point, be updated to target Windows 2000. Opera support is also planned to be part of a future release; it is currently the third most used browser and has a relatively small but very loyal user base.
The Mono project (http://www.mono-project.com/), renowned for its open source implementation of .NET, is working on an open source Silverlight port that targets the Linux platform (and the Firefox browser there). This project is called Moonlight (see http://www.mono-project.com/Moonlight for a sneak peek). http://www.mono-project.com/MoonlightShots also shows some up-to-date screenshots of those efforts (see ). Microsoft has also announced that it is teaming with Novell to support the Moonlight project and bring Silverlight to Linux.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Silverlight Tools
As you have seen in the previous chapter, there is no kind of compilation or binary data with Silverlight 1.0. All you need to create are the three kinds of files:
  • XAML files with the Silverlight content
  • JavaScript files with both additional code for the Silverlight content and with code to control and access the Silverlight content
  • HTML files to include the Silverlight content
So generally, an XML editor would be enough to create SIlverlight applications. But that’s the same thing as saying “ASP.NET 2.0 applications can be created in Notepad.” Of course that’s possible, but who would want to do that?
Therefore, we will introduce three kinds of editors in this chapter that should be helpful to create Silverlight applications. For each kind of editor, we briefly introduce one specific editor and also have a look at the competition, if there is any.
For editing XAML, a mighty XML editor would be good enough theoretically. And there are many good XML editors out there, including <oXygen/> (http://www.oxygenxml.com/) and XMLSpy (http://www.xmlspy.com/). Even Microsoft has a dedicated XML editor now, XML Notepad 2007 (available at http://www.microsoft.com/downloads/details.aspx?FamilyID=72d6aa49-787d-4118-ba5f-4f30fe913628&DisplayLang=en; see ). Thanks to the availability of an XML schema for XML, code-completion is at least theoretically possible. As you have seen in the previous chapter, Visual Studio 2005 offers IntelliSense, as well, and you get even more IntelliSense (including JavaScript code) in Visual Studio 2008.
Figure : XML Notepad 2007
The one thing pure XML editors are always lacking is WYSIWYG functionality. Many of them try to use CSS and/or XSLT to convert the XML into something viewable (including the XML editor I am writing this book in), but for Silverlight that’s not a feasible option. An editor that does both is, of course, a better option. You may want to have a look at Spket IDE from http://www.spket.com/. It is free for non-commercial use and offers both JavaScript and XAML code completion. shows the XAML editor of Spket IDE in action.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: XAML Basics
XAML is an XML dialect, so we will use a lot of angle brackets throughout this book. In this chapter, we will have a look at the most important XAML elements. It is virtually impossible to cover them all in a book of this size, but we will present as many as possible to let you dive into XAML with maximum speed.
If you have already worked with XAML for WPF applications, you already know most of what is covered in this chapter (and most of , as well). However, there are some subtle differences: Silverlight does not support the full XAML format like WPF, but only a subset. Future versions of Silverlight will increase the percentage of supported elements and attributes, but some things just cannot work in a web browser as they do in a desktop application.
The root element of every XAML file is <Canvas>, which defines the area that holds the Silverlight content. will show other uses for the <Canvas> element. For now, just remember to put this element at the beginning of each XAML file and supply the correct namespaces as follows:
<Canvas xmlns="http://schemas.microsoft.com/client/2007" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  ...
</Canvas>  
The first example used for most technology is a variation of the Hello World example (see for such an example). This chapter will start with something like Hello World as well: we will add text to the Silverlight content. The element used for this is (which you have already seen in ), and there are two ways to provide this text:
  • Within the attribute of the element
  • As a text node within the element
uses the latter approach to output a simple text. Note that you will get a notice in Visual Studio that using text within is not allowed, but proves that it works.
Example . Using simple text, the XAML file (Text1.xaml)
<Canvas xmlns="http://schemas.microsoft.com/client/2007" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <TextBlock>Silverlight</TextBlock>
</Canvas> 
To repeat the structure of a Silverlight application from , you need two more files to make this example work in a web browser. First, you need a helper JavaScript file that initializes the Silverlight content, such as shown in . Since this JavaScript file is tied to an HTML file, it is dubbed “HTML code-behind” throughout this book. In any example captions, we refer to the file as the “HTML JavaScript file” (as opposed to “XAML JavaScript files,” which will be introduced in the next chapter).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Interaction and Event Handling
The declarative means of XAML provide quite a number of possibilities, including creating all kinds of shapes (see ), animating element (see ), and playing audio and video data (see ). However, you can only unleash the real power of Silverlight if you add a bit of JavaScript into the mix. JavaScript itself is a powerful language, but Silverlight also exposes a JavaScript API to developers. The third section of this book, especially , will cover the JavaScript access in greater detail. Although this book part focuses on declarative XAML, we cannot do without a certain amount of scripting.
This chapter explains the Silverlight event handling. Specifically, what events are and how to intercept and process them. Most of the event handling code will be in the “XAML code-behind” file (the Filename.xaml.js file). Technically, the JavaScript code could be placed in any JavaScript file, as long as it is referenced by a tag in the main HTML file. However, it makes applications easier to comprehend and to develop if we stick JavaScript code that is triggered from XAML into the .xaml.js file and JavaScript code triggered by the HTML page in the .html.js file.
Most listings consist of at least three files―the HTML file, the XAML file, and one or more JavaScript files. Some of the information in those files is always very similar, for instance the code for the function. In the next example we are adapting the reference to the embedded XAML file. Therefore, will not be reprinted here. As long as there are no big surprises in the HTML file, it will not always be printed either. However, in the code archive for this book (see http://www.oreilly.com/catalog/9780596516116), you will have the complete set of samples.
When in doubt regarding the roles of the HTML, XAML, and JavaScript files, review where the basic concepts are explained.
A Silverlight event is something that occurs while a Silverlight application is running. This “something” could be a mouse click, a mouse movement, keyboard input, the application receiving or losing the focus, the application being fully loaded, or something else altogether. All events are tied to an object, so it makes a difference whether the mouse click occurs while the mouse pointer is, say, over a given rectangle or text block.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 6: Transformations and Animations
Silverlight applications can be dynamic even if they do not use JavaScript. The content can be transformed and animated, both which will be covered in this chapter. The transformation is nothing that you can watch, it is more or less a calculation that takes effect when the Silverlight content is rendered by the plug-in. For example, you can rotate or skew elements. An animation, on the other hand, can really change the visual appearance of the applications: elements may move or change their color. As always, you will find many small and self-contained examples that showcase the most interesting and important Silverlight options.
A transformation is technically only a change of one or more values. For instance, if an element is rotated, its position and the location of all the drawing points of the element change. If an element is moved to another position (that’s a transformation, as well), basically the positions of all corners of the element change (if we leave fillings aside). Silverlight supports five transformations:
TranslateTransform
Changes the position of an element
ScaleTransform
Scales an element by multiplying its dimension horizontally and vertically
SkewTransform
Skews an element by using a horizontal and a vertical angle
RotateTransform
Rotates an element by using a angle
MatrixTransform
Multiplies all points of an element by a given matrix,and uses the result as the new value
Let’s start with the element, which as just changes the position of an element, much like setting a related property like or would do.
To execute a transformation, you have to use the element. The term needs to be replaced with the type of object you want to transform. For instance, if you want to transform a object, use . If you want to transform a object, use .
Within the element, you need to put the transformation element; in this example it is . This element expects two attributes, and , denoting the new x and y coordinate of the associated element’s left corner, as you can see here:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 7: Multimedia
Adobe Flash has made a remarkable transition in the last years. The market penetration of the Flash player (the plug-in) has always been very high, but whenever a new player version came out, it took several months for it to reach a good-sized audience. However, in the last few months, this has sped up significantly. There may be many reasons for this, but one of the most compelling is that recent Flash versions have much better video support. Given that video sites like YouTube are extremely popular at the moment, they prompt users to install the latest player to see the content.
Multimedia support is a key feature of many browser plugins, and Silverlight clearly does not want to disappoint its users here. For obvious reasons, the supported media formats are biased toward Microsoft’s offerings. Silverlight supports Windows Media Audio (WMA) and Windows Media Video (WMV) files, version 7 through 9. Also WMVA and WMVC1, two rather new video formats by Microsoft, are supported. The only external format Silverlight can process is the very popular MP3 audio format.
There is a reason for this bias, however. The plug-in plays content in these formats without the help of any other software or player. So, it is not necessary to have an MP3 player or even Windows Media Player to play supported multimedia content in Silverlight. This applies to both the Windows and Mac platforms.
Silverlight also supports streaming, either in the form of Windows Media Server streaming data, or ASX files. Note, however, that the stream support has some limitations: the content may not be paused and not all ASX features are supported. Refer to the Silverlight SDK for a list of restrictions when using streamed multimedia data.
Ideally, you already have your audio or video data in the correct format and can directly embed it into your Silverlight application (see for details). However, there is usually at least one step left to do―converting the audio data. For example, the audio data could be in the wrong format, the video data might be too big for reasonable web playback, or you would like to add some markers to a video presentation. Some helpful tools can be used to get your multimedia data into the right format.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 8: Accessing Silverlight Content From JavaScript
The first parts of this book were called “Declarative Silverlight,” but they contained a lot of JavaScript code, like all event handlers. Our focus shifted to add JavaScript to the XAML, which is why most JavaScript files are called <something>.xaml.js.
This chapter introduces a different approach. We will create a number of <something>.html.js files, code-behind JavaScript files for the HTML document containing the Silverlight content, so to speak. The JavaScript code in there will access the Silverlight content, add new Silverlight elements, and read information about the plug-in or the content of the XAML file.
To access Silverlight content embedded on a page, you first need to access the plug-in. There are two ways to retrieve this information: access the plug-in from within the XAML event handler code or use the JavaScript DOM (Document Object Model). Let’s start with the latter option and look at the, by now, well-known JavaScript code to load Silverlight content:
function createSilverlight()
{
  Silverlight.createObjectEx({
    source: 'Info.xaml',
    parentElement: document.getElementById('SilverlightPlugInHost'),
    id: ‘SilverlightPlugIn',
    properties: {
      width: '400',
      height: '300',
      background:'#ffffffff',
      isWindowless: 'false',
      version: '1.0'
    },
    events: {
      onError: null
    }
  });
}
Note the property. This provides the DOM ID JavaScript can use to access the plugin:
var plugin = document.getElementById('SilverlightPlugIn');
If you are using ASP.NET AJAX, you can, of course, save some typing and use instead of .
It is tempting to use the ID of the element holding the Silverlight content (in all of this book’s examples: ), but this will not access the plug-in itself.
Then, starting with the variable, you can access quite a number of data on the plug-in and its contents, but we will come back to that in a minute. First we will have a look at the other option to access the plug-in, from within the XAML event handling code.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 9: Special Silverlight JavaScript APIs
This chapter is a mix of the Silverlight JavaScript capabilities introduced in the second part of this book and the JavaScript access to Silverlight content presented in . This chapter features some JavaScript APIs that are part of the Silverlight features but provide advanced possibilities. To be exact, Silverlight exposes a JavaScript API that lets developers download resources. While these resources are being downloaded, the download progress may be seen and you can process the downloaded data.
The technical background for Silverlight’s downloader API is the JavaScript object, which fuels everything Ajax. The Silverlight API does not copy the XMLHttpRequest API, but provides its own interfaces. You can trigger the API from both “XAML code-behind” and “HTML code-behind” JavaScript code, but generally you will want to start off from XAML.
When downloading content from within Silverlight, you usually have to follow these steps:
  1. Initialize the downloader object by using the plugin’s method
  2. Add event listeners to the object to react upon important “happenings”
  3. Configure the downloader object by providing information about the resource to download (HTTP verb, URL)
  4. Send the HTTP request
  5. Handle any occurring events
Let’s go through these steps step by step. But first we need some XAML backing, so that we can wire up the whole code. shows a suggestion.
Example . Downloading content, the XAML file (Download.xaml)
<Canvas xmlns="http://schemas.microsoft.com/client/2007" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="loadFile”>
  <Rectangle Width="300" Height="150" Stroke="Orange" StrokeThickness="15" />
  <TextBlock x:Name="DownloadText" FontSize="52" 
             Canvas.Left="25" Canvas.Top="35" Foreground="Black" 
             Text="loading ..."/>
</Canvas> 
Once the XAML has been loaded ( event in the element), we start working on the download. Step 1 is creating the downloader object. For that, we first need to access the plugin (see for details) and then call the method:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 10: ASP.NET 2.0, ASP.NET AJAX, and Silverlight
The ASP.NET Futures is a collection of controls and features that did not make it in the release version of ASP.NET 2.0 but may be subject to further inclusion (or may be eternally doomed). It offers a sneak peek at what Microsoft is working on or planning, and is subject to frequent change. The ASP.NET Futures are released in form of Community Technology Previews (CTPs); this chapter is based on the July 2007 CTP.
Probably the best-known part of the ASP.NET Futures are the ASP.NET AJAX Futures, a set of add-ons for the ASP.NET AJAX Extensions. Most elements in the ASP.NET AJAX Futures are features that were part of pre-release versions of ASP.NET AJAX (then codenamed Atlas), but were removed from the core and shelved in the Futures project.
Beginning with the May 2007 CTP, the ASP.NET Futures included special ASP.NET 2.0 web controls that facilitate embedding Silverlight XAML and media content into ASP.NET pages. This chapter will help you set up the ASP.NET Futures on your development machine and then have a look at these two controls.
Before you can install the ASP.NET Futures, you need to get the ASP.NET AJAX Extensions first, since the Futures is an add-on to Microsoft’s AJAX framework. You can go to Microsoft’s ASP.NET AJAX homepage, http://www.asp.net/ajax/, to get the ASP.NET AJAX Extensions. The direct download link is http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en.
The installer copies the ASP.NET AJAX files to your machine, including the server assembly (which will be installed in the Global Assembly Cache, or GAC), and the client script libraries. It also integrates into Visual Studio and Visual Web Developer Express Edition, providing a new web site template. If you are using Visual Studio 2008, ASP.NET AJAX is already included in all .NET Framework 3.5 web sites, so you can skip this step.
The July CTP is available for download in the Microsoft download center at http://www.microsoft.com/downloads/details.aspx?FamilyId=A5189BCB-EF81-4C12-9733-E294D13A58E6&displaylang=en
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 11: Silverlight 1.1 Preview
This book is about Silverlight 1.0. The first release of the Silverlight technology contains quite a number of useful features, as the previous 10 chapters have shown. However, Microsoft is already working on future versions.
Unfortunately, the versioning system is really odd. The Silverlight 1.0 version comes as a small download with a nice but manageable feature set. The next version of Silverlight will add many additional feature, be a much bigger download, currently clocking in at about 4.5 MB on Windows (in contrast: Silverlight 1.0 is less than 1.4 MB). Mac OS X file sizes are bigger (for instance, Silverlight 1.1 currently comes in at almost 10 MB). So, you would expect that the new version number would be 1.5 at least, or maybe 2.0.
However, the next Silverlight version is called 1.1. This marginal increase of version number is not reflected in the feature set, which is vastly revamped and extended. It is also not clear what happens if there is a bugfix release or security update for Silverlight 1.0. Will the new version number be 1.0.1? Or, as Sun Microsystems is doing with Java, Silverlight 1.0 Update 1?
Apart from those irritating version numbering schemes, Silverlight 1.1 is really something to look forward to. This chapter touches very briefly on some of the upcoming features. As of time of writing, Silverlight 1.1 was still in alpha state, so investing too much time into the new version could be dangerous, as APIs can (and will!) change.
Currently, you can download both Silverlight versions (1.0 and 1.1) from the download page at http://www.microsoft.com/silverlight/downloads.aspx. The recommended development platform for Silverlight 1.1 content will be Visual Studio 2008; for its beta 2 release, Microsoft is providing add-ins that install templates and IntelliSense support at http://www.microsoft.com/downloads/details.aspx?familyid=B52AEB39-1F10-49A6-85FC-A0A19CAC99AF&displaylang=en.
JavaScript is, at least in my opinion, an underestimated language. It provides most features you need to enrich Silverlight content. However, to tell the truth, many developers ignored the language for a couple of years, at least until Ajax came up. And since Silverlight is targeted to WPF users, i.e., desktop developers, not all of them are familiar for JavaScript, since this language has been almost exclusively used for web applications.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Appendix : Silverlight JavaScript Reference
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!

Return to Essential Silverlight PDF