To create Silverlight content, you first we need to create a
Silverlight project. There are two ways to do this in Silverlight 2. The
first is to create a web site and "just" use XAML and JavaScript in there.
No compilation is needed, however your coding is limited to the scripting
language. The second option is to create a web project, including
compilation, but also offering .NET support.
Thanks to the Silverlight SDK's Visual Studio template, both options consist of relatively few steps. If
you are using Visual Web Developer Express Edition, you can't use a
project, you need to create all of your files manually (and are limited to
the first option). The best way to begin is to go to http://www.oreilly.com/catalog/9780596519988 and download
the book's samples and start with those files.
In Visual Studio, choose FileNew Web Site (not FileNew Project!).
There, you will find a Silverlight Script Web entry (see
Figure 1).
The web site that the Silverlight template creates initially
consists of the following files:
Default.html
-
An HTML page that contains markup to load Silverlight content, including
JavaScript code setting everything up
Silverlight.js
-
A JavaScript helper library that is used by the Default.html.js file
Scene.xaml
-
A sample XAML file
Scene.js
-
A JavaScript "code-behind" file for the XAML sample
|
On one of my systems, I kept getting strange error messages with
previous Silverlight versions stating that Visual Studio could not
access the Scene.xaml.js file, as
it was called back then. I later found out that the guilty party was my
antivirus software. By default, Windows does not show file extensions,
so Scene.xaml.js shows as Scene.xaml. Because a JavaScript file may
contain malicious code (especially if run locally), some viruses use
this technique and my antivirus software wanted to protect me from that
danger. All I could do at that point was move my Silverlight development
into a secured environment and disable the resident shield of my
antivirus software. With Silverlight 2, this has been fixed with the use
of a different file naming scheme.
|
|
First, open the Default.html
file and run the solutions (press F5 for debugging mode, Ctrl-F5 for
release mode). A browser window will open, but instead of fancy
Silverlight content, you will get a message stating that Silverlight needs
to be installed. (If you have already installed Silverlight, you will
immediately see the content, of course.) Figure 2
shows how this looks, regardless of what supported browser and operating
system you are using.
The plug-in comes as an installation program; Figure 3 shows the Windows version (showing the incorrect version number, by the way, but this
may be fixed once you get your hands on a Silverlight release). You may
need to restart your browser afterward. After installing Silverlight, the
content will appear, as Figure 4 shows.
Before we dive deeper into the world of Silverlight, let's have a
closer look at the files that came with the template. We will
not look at the XAML file (and the associated
JavaScript script), because it uses quite a number of techniques that we
will cover throughout this book. Let's start with the
Default.html file (omitting some JavaScript code). It
is reprinted in Example 1.
Example 1. The sample HTML file (Default.html)
Code View: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Silverlight</title>
<script type="text/javascript" src="Silverlight.js"></script> <script type="text/javascript" src="Scene.js"></script> <style type="text/css"> #errorLocation { font-size: small; color: Gray; } #silverlightControlHost { height: 480px; width: 640px; }
</style> </head>
<body> <!-- Runtime errors from Silverlight will be displayed here. This will contain debugging information and should be removed or hidden when debugging is completed --> <div id='errorLocation'></div> <div id="silverlightPlugInHost"> <!-- omitted some JavaScript code here --> </div> </body> </html>
|
So, quite a number of things happen in this file:
The Silverlight.js helper
library is loaded with a <script>
element.
The Scene.js JavaScript
file (the "code-behind" script of the sample XAML file) is loaded with
a <script> element.
The page contains a <div> element with
ID SilverlightPlugInHost, which will later hold the
Silverlight content.
You especially need to remember the ID of the
<div> container because it will later hold the
Silverlight file. However, you need to tell JavaScript (and the
Silverlight) plug-in explicitly where to put the content. In previous
versions, this was done in a file called Default.html.js; with Silverlight 2, the
associated code resides directly within the <div id="silverlightPlugInHost">
element and is shown in Example 2.
Example 2. The JavaScript file that loads the Silverlight content (from
Default.html)
Code View: <script type="text/javascript"> if (!window.Silverlight) window.Silverlight = {};
Silverlight.createDelegate = function(instance, method) { return function() { return method.apply(instance, arguments); } } var scene = new ScriptWeb1.Scene(); Silverlight.createObjectEx({ source: 'Scene.xaml', parentElement: document.getElementById('silverlightPlugInHost'), id: 'silverlightPlugIn', properties: { width: '100%', height: '100%', background:'white', version: '1.0' }, events: { onLoad: Silverlight.createDelegate(scene, scene.handleLoad), onError: function(sender, args) { var errorDiv = document.getElementById("errorLocation"); if (errorDiv != null) { var errorText = args.errorType + "- " + args.errorMessage; if (args.ErrorType == "ParserError") { errorText += "<br>File: " + args.xamlFile; errorText += ", line " + args.lineNumber; errorText += " character " + args.charPosition; } else if (args.ErrorType == "RuntimeError") { errorText += "<br>line " + args.lineNumber; errorText += " character " + args.charPosition; } errorDiv.innerHTML = errorText; } } }, context: null }); </script>
|
As you can see, the code first instantiates the
Silverlight.Scene object, which we do not need at the
moment, and then executes the
Silverlight.createObjectEx() method. This method is
solely responsible for initializing and loading XAML content with the help
of the browser plug-in. The method expects an object as an argument that
holds all relevant information. The syntax of the object notation
using JSON (JavaScript Object Notation) as part of the JavaScript
language syntax is as follows:
{property1: "value1", property2: "value2", ...}
The following properties are essential:
parentElement
-
The ID of the <div> container where
the Silverlight content will be shown on the page.
source
-
The URL of the XAML file to be loaded.
id
-
An identification for Silverlight content that will later facilitate JavaScript access
to Silverlight.
properties
-
A set of properties, including the dimensions of the content
(width, height), and the
background color (background).
version
-
The Silverlight plug-in version is at least required to run
the example (part of the properties).
The events property is used to wire up events.
Since this first example contains a bit too much complexity for a
simple "Hello World" file, we will now create our own Silverlight
application. Create a new XML file and call it HelloWorld.xaml. The root element of every
Silverlight XAML file is <Canvas> (this may be
compared to a <div> element in HTML or to
ASP.NET's <asp:Panel>). In there, you will put an
orange rectangle (<Rectangle>) element and a text
block (<TextBlock>) element. In the end, your
markup should look like Example 3.
Example 3. A simple "Hello World" XAML file (HelloWorld.xaml)
Code View: <Canvas xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Rectangle Width="300" Height="150" Stroke="Orange" StrokeThickness="15" /> <TextBlock FontFamily="Arial" FontSize="56" Canvas.Left="25" Canvas.Top="40" Foreground="Black" Text="Silverlight" /> </Canvas>
|
IntelliSense will help as you type, as Figure 5
shows.
The next file to be created is HelloWorld.html, which will contain both the
HTML markup and the JavaScript code to load the XAML. You can use the
Default.html file as a basis and
remove all unnecessary elements (e.g., the extra JavaScript code related
to the scene). Don't forget to provide the correct XAML URL in the
source property. At the end, you should have something
similar to Example 4. For brevity, we set the onError property (the Silverlight error handler)
to null and removed onLoad, so errors are not specifically handled
and no code is executed upon loading of the XAML file. You could, of
course, also stick to the error handling code from Default.html.
Example 3-4. A simple "Hello World" HTML file (HelloWorld.html)
Code View: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Silverlight</title>
<script type="text/javascript" src="Silverlight.js"></script> <script type="text/javascript" src="Scene.js"></script> <style type="text/css"> #errorLocation { font-size: small; color: Gray; } #silverlightControlHost { height: 480px; width: 640px; }
</style> </head>
<body> <!-- Runtime errors from Silverlight will be displayed here. This will contain debugging information and should be removed or hidden when debugging is completed --> <div id='errorLocation'></div> <div id="silverlightPlugInHost"> <script type="text/javascript"> if (!window.Silverlight) window.Silverlight = {}; Silverlight.createObjectEx({ source: 'Scene.xaml', parentElement: document.getElementById('silverlightPlugInHost'), id: 'silverlightPlugIn', properties: { width: '400', height: '300', background:'white', version: '1.0' }, events: { onError: null }, context: null }); </script> </div> </body> </html>
|
Running this example in the browser will work like a charm. If you
still don't have the Silverlight plug-in installed, you will be prompted
to do so, and then you will see the text and the orange rectangle, just as
in Figure 6.
The only file we haven't looked at yet is Silverlight.js. This JavaScript library takes care of several things: it tries
to detect the web browser (unfortunately, it has the same habit as ASP.NET
AJAX and only accepts Firefox of all the Mozilla browsers [e.g., SeaMonkey, the soon-to-be-defunct Netscape,
and others]), provides the Silverlight.createObjectEx()
method, and helps access the Silverlight content using a JavaScript API . Just copy the
Silverlight.js file into all
Silverlight applications to have this functionality.