Lesson 1 - Overview to Silverlight and XAML

Upon completion of this lesson, you will be able to:      Understand what Silverlight is and why it exists Describe the technology underpinnings that make Silverlight possible Understand the versions currently available and what functionality exists in each of the versions Identify basic Extensible Application Markup Language (XAML) constructs Setup a Silverlight development environment

What is Silverlight?
Silverlight is characterized in the following way:   Purpose - Silverlight applications allow developers to create a rich interactive application (RIA) through graphics, media and a rich programming model (Think: Adobe’s Flash player) Silverlight Plug-In - Web site visitors are prompted to download and install the Silverlight plugin. This plug-in is available for the most popular web browser software and host operating systems. The plug-in is small (less than 2 megabytes in Silverlight 1.0) and once installed and configured allows web pages to instantiate the Silverlight control host. Silverlight Control Host - The control host is instantiated in a web page via JavaScript and its purpose is to expose the Silverlight object model to application code. There are two helper files that enable this instantiation process: Silverlight.js (supplied by Microsoft is per their license agreement cannot be modified) and a second JavaScript file typically named “CreateSilverlight.js” (supplied as an example implementation of how to call the method responsible for the instantiation of the Silverlight control on the web page. The method is named Silverlight.createObjectEx() and is described in detail later in this lesson.) Note: while referred to as CreateSilverlight.js, when creating a Silverlight project in Visual Studio 2008 with the Microsoft Silverlight Tools Alpha Refresh for Visual Studio 2008 Beta 2 installed, a file called TestPage.html.js is created that serves the exact same purpose – to host the call to createObject() or createObjectEx(). Silverlight Object Model – Similar to the .NET Framework Class Library, this set of classes are available to your application and provide the core instructions that application developers will use to draw and adorn shapes, render media, enable animation, provide programmatic functionality and network access and more. Silverlight 1.0 features an object model for writing unmanaged code. In Silverlight 1.1, an object model for writing managed code is available. We’ll discuss the differences in Lesson 6. Silverlight Application – Applications are created using a combination of XAML, dynamic code (such as JavaScript) and in Silverlight 1.1, .NET static languages such as Visual Basic and C#. Silverlight 101 – Lesson 1 | Page 1

 

XAML – Pronounced “zamel”, this term is an acronym for Extensible Application Markup Language. It is an XML-style syntax that allows developers to define the user interface elements and behavior of those elements. Some Silverlight elements can contain other Silverlight elements, creating a control tree, or rather an object hierarchy which impacts the order in which the elements are interpreted and rendered for display. Canvas – The Canvas is an element used for the purpose of positioning other graphical elements. Canvases can contain other canvases. The root object (or rather the top-most node in the tree structure) must be a Canvas. Graphical Elements –The following graphical elements can be created in a Silverlight Application: Canvas, Ellipse, Rectangle, Line, Polygon, Path, Image, MediaElement, TextBlock. Each element has properties that define its visual qualities as well as its behavior. Most of these elements can raise events when users interact with them via mouse or keyboard. A vector rendering engine ensure that the graphical elements remain sharp regardless of the screen resolution or level of magnification. Event Handling – Mouse and keyboard events raised by the user’s interaction with the Silverlight-based application are handled using JavaScript (in Silverlight 1.0). In Silverlight 1.1 developers can use .NET languages (Visual Basic or C#) or dynamic languages (Ruby, Python, etc.) to handle events and write logic. Media - Sound and video can be loaded into the Silverlight application, or streamed (if Windows Media Server is configured and available). The media can be used in several capacities, such as fills for graphics or in animation. Animation – Graphics and video elements can be infused with motion or properties can be transformed over the course of time as defined by the application. Development Environments – While the authoring tools to create Silverlight applications are not mature, it is clear that there is an established development ecosystem emerging, including Microsoft Expression Blend 2.0 (currently in Beta), Visual Studio 2008 (currently in Beta) and to a lesser extent, Microsoft Expression Designer 1.0 (currently in Beta).

Watch: SL01_01_01 – Silverlight Overview.wmv

Why was Silverlight created?
Often Silverlight is referred to as a “Flash killer”. While there are similarities and overlap, merely branding it as “Flash .NET” would limit its uses (or in some cases, stretch its uses beyond what is intended). Silverlight 1.0 is focused on media applications that have some degree of programmability and user interaction. When combined with Windows Media Server, Microsoft is poised to offer customers a lower cost alternative to the Flash Player and Flash Media Server environment which costs $4500 per license.

Silverlight 101 – Lesson 1 | Page 2

Silverlight 1.1 is focused on allowing developers to write managed code in the browser. This would allow developers to write applications that more closely mimic the functionality of desktop applications without the complexity or quirks of Ajax. Ajax is a marvelous hack. However JavaScript, CSS and the DOM were not originally intended to do what some have stretched it to do. Also, browser differences require multiple implementations of the particular Ajax library for each browser type. Still, some functionality doesn’t translate to every browser. Plug-in style platforms like Flash benefit from a single environment to develop in and provide a consistency across operating systems, browser types and browser versions. It is for this reason the Flash has gained near ubiquity. Flash’s weakness has been that it’s an animation tool first and a serious coding platform secondarily. Adobe has sought to address this with Flex and Apollo, however they must support legacy code and applications. Silverlight seeks to provide a light-weight implementation of the .NET CLR inside most browsers running on Windows, Mac and Linux. Although Microsoft would probably not care for my characterization, Silverlight exists as a hedge against Microsoft’s two largest competitors. Adobe - In recent years, Adobe (or rather, Macromedia, before it was acquired by Adobe) has made a push to bring the Flash development environment to the desktop and to enable interaction with web services. Adobe’s Flex platform has sought to bring applications to the desktop through its Flex software development kit. Aspects of Flex are very similar to Silverlight, including the use of an XML-style syntax to design application user interface and behavior. The development tools and platform has been one way Microsoft has ensured vendor lock-in to their Windows client and server operating systems over the past 15 years. Since the operating system business is one of Microsoft’s “cash cows”, Silverlight is one of many strategic technologies that they use to protect their operating system market share. Google – When Google purchased YouTube, instantly they became more than the de-facto search and contextual ads company on the internet. They also became the largest media company on the web as well. Microsoft desires to diversify into media and ad sales and yet again Google has gotten the jump on Microsoft. Silverlight, and in particular Silverlight hosting through Live.com (http://silverlight.live.com) provides free hosting for large video files. While they have not expressly stated their aim, we assume they are doing this as a precursor to selling advertising on top of user generated video content. Silverlight’s usefulness is most obvious in these scenarios:  Initial focus for Silverlight 1.0 has been on streaming video applications, as evidenced by integration into Major League Baseball’s website, Fox Movies Trailer Library, Netflix streaming and more. Rich internet applications (RIA) that rely on back-end XML or JSON web services are clearly targeted in Silverlight 1.1 and will be made more accessible once a solid set of controls for data display and interaction are available. The ability for Silverlight to interact with JavaScript on the client, as well as Microsoft Ajax, etc. to dynamically load XAML makes Silverlight more than just a video player.

Silverlight 101 – Lesson 1 | Page 3

Some games that resemble Flash-based games in scale and scope have emerged as an example of what is possible in this space. Some have created their own game loops and collision detection algorithms in lieu of any supplied directly in the Silverlight plug-in. However, it would seem that due to its stronger animation tools, Flash is still the better technology choice for this type of application.

Silverlight’s Technology Adoption Hurdles
The following challenges currently exist for Silverlight’s adoption in the marketplace:  Adobe and Apple’s have created a loyal following of creative individuals who can at times be antagonistic towards Microsoft. Microsoft is targeting this niche with its Expression toolset, particularly Blend, which will be the primary tool used to create Silverlight assets Developers who lack creative skills may hurt rather than help perceptions of what is possible with this new technology Lack of tool support (Both Visual Studio 2008 Beta 2 and Blend 2.0 Beta can create Silverlight applications, but better tool support and integration is currently in heavy development) Lack of a baseline set of controls (i.e., no textbox, no buttons, no drop down lists, etc.) Currently, all of these must be custom built (although these controls will probably be ready for the next community preview release. I’m not aware of an estimated date when these will be available.) The richer feature set that allows you to create meaningful applications is currently in Alpha Very small installed user base of the Silverlight plug-in

  

 

Is this a good time to invest in Silverlight?
In financial terms, Silverlight would be considered a “speculative buy”. While there are plenty of people both inside and outside of Microsoft that are promoting it as the “next big thing”, as noted above there are some serious hurdles to overcome. In all honesty, it will be several years before this technology is viable for anything more than a proof of concept. However, Microsoft is pursuing the development and promotion of Silverlight in a way that I’ve not seen before, so depending on their sustained level of aggression that may shorten the adoption cycle somewhat. If Microsoft were to include the Silverlight plug-in in Windows Update, they could achieve near ubiquity in terms of market penetration in a matter of days. No plan to do this has been announced.

What are the key differences between Silverlight 1.0 and 1.1?
The following key features differentiate Silverlight 1.0 RC and Silverlight 1.1 September Technology Preview.

Silverlight 101 – Lesson 1 | Page 4

Managed code support – In Silverlight 1.0, you must use JavaScript to handle events and interact with the Silverlight object model. In Silverlight 1.1, you can use managed .NET languages like C# and Visual Basic. Dynamic languages support (JavaScript, Python, Ruby) – In Silverlight 1.0, JavaScript was the only dynamic (think: non-compiled / interpreted) programming language you could use to handle events and interact with the Silverlight object model. In Silverlight 1.1, you can use dynamic languages like Python and Ruby. Rich UI control model based on WPF – In Silverlight 1.0, you would have to use graphic primitives and JavaScript to create baseline controls. While not yet available as of this writing, Silverlight 1.1 will eventually include the following:  Button  TextBox  Scrollbar  Slider  ListBox  CheckBox  RadioButton  ComboBox The Silverlight 1.1 Alpha Refresh SDK (September 2007) contains source code examples for a Button, Scrollbar, Slider and ListBox. (See the folder called “SilverlightControlsStarterKit” which contains a Visual Studio 2008 solution file with the source code to be used as a basis for creating your own controls). It’s unknown if these are the basis for the actual controls, or just examples. Besides the Canvas, additional layout controls will include:    Grid StackPanel ViewBox

Additionally, Silverlight 1.1 alpha includes the ability to create UserControls. Several third party companies and individuals have already started in earnest creating custom controls.  Improved networking stack with support for REST, RSS, JASON, POX – Allows Silverlight to communicate with server-side web services. For more details about what each of the acronyms above mean, see callout “Terminology”) Enhanced, 2-way HTML/AJAX Bridge – No elaboration is available at this time. Comprehensive and consistent base class library – Provides a scaled-down yet full featured version of the .NET Base Class Library. Types, Collections, etc. Support for LINQ (LINQ to Objects, LINQ to XML) – LINQ is a unified data language to express data manipulation intent. Specific implementations of LINQ parse the query language into instruction sets specific to the type of data that is being handled. As a staple of .NET 3.5 and Visual Studio 2008, the an implementation of LINQ that can be used inside of a Silverlight Silverlight 101 – Lesson 1 | Page 5

  

application allows a more unified approach to handling collections of data (lists, etc.) as well as XML.


REST - Representational State Transfer – An “architectural style” that allows navigation of resources (See: http://en.wikipedia.org/wiki/Representational_State_Transfer) RSS – Really Simple Syndication – An XML format for syndicating news feeds (See: http://en.wikipedia.org/wiki/Really_Simple_Syndication) JSON – JavaScript Object Notation – A simplified convention for transferring related data, such as the properties of an object. (See: http://en.wikipedia.org/wiki/JSON) POX – Acronym for “Plain Old XML” (See: http://en.wikipedia.org/wiki/POX)

XAML Structure
At this point we’ll move away from an overview of Silverlight in general and begin to speak in concrete terms about XAML, the Silverlight Plug-In and the anatomy of a Silverlight application. As I mentioned in the preface I’m assuming that you are already a seasoned developer and therefore I will move quickly into the technical details. Watch: SL101_01_02 – XAML Overview.wmv

The Extensible Application Markup Language, or XAML as it is known, uses a declarative XML-style syntax to express user interface design and behavior with the intent to keep presentation separate from application logic. XAML is generic, and while it has been made famous by the Windows Presentation Framework and now Silverlight it can be used in the context of other forthcoming technologies. While XAML is a relatively new syntax, its borrows enough from XML that you should be able to understand the basic structure of the syntax, even if you don’t completely understand how each individual XAML element contributes to the entire application. The following example creates a very simple Silverlight application. While you can probably guess much of what is going on here without my explanation, I want to use this as a tangible example of several XAML conventions: Silverlight 101 – Lesson 1 | Page 6

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 <Canvas x:Name="parentCanvas" xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Loaded="Page_Loaded" x:Class="Lesson02_Canvas.Page;assembly=ClientBin/Lesson02_Canvas.dll" Width="320" Height="240" Background="#E6E6E6" > <!-- First Rectangle Example --> <Rectangle Canvas.Left="50" Canvas.Top="50" Width="50" Height="50" Fill="Blue" Stroke="Black" StrokeThickness="3" /> <!-- Second Rectangle Example --> <Rectangle Canvas.Left="125" Canvas.Top="50" Width="50" Height="50" Stroke="Black" StrokeThickness="3"> <Rectangle.Fill> <SolidColorBrush Color="Green" /> </Rectangle.Fill> </Rectangle> <!-- Third Rectangle Example --> <Rectangle Canvas.Left="50" Canvas.Top="125" Width="50" Height="50"> <Rectangle.Fill> <RadialGradientBrush> <RadialGradientBrush.GradientStops> <GradientStop Offset="0.0" Color="Blue" /> <GradientStop Offset="1.0" Color="Green" /> </RadialGradientBrush.GradientStops> </RadialGradientBrush> </Rectangle.Fill> </Rectangle> <!-- Fourth Rectangle Example --> <Rectangle Canvas.Left="125" Canvas.Top="125" Width="50" Height="50"> <Rectangle.Fill> <LinearGradientBrush> <GradientStop Offset="0.0" Color="Red" /> <GradientStop Offset="1.0" Color="Orange" /> </LinearGradientBrush> </Rectangle.Fill> </Rectangle> <!-- First Textblock Example --> <TextBlock Canvas.Top ="200" Canvas.Left="50" Text="Hello" /> <!-- Second Textblock Example --> <TextBlock Canvas.Top ="200" Canvas.Left="100">

Silverlight 101 – Lesson 1 | Page 7

61 62 63

World </TextBlock> </Canvas>

This sample XAML creates the following Silverlight application:

From this XAML source code, we can learn the following about XAML:   Declaring Objects - Use standard XML opening and closing tags to define a Silverlight object. Containment – Some objects (like the Canvas) can contain other objects and therefore require an opening and closing tag, and others (like the Rectangle) may not and can opt for closure in a single tag. <Canvas> <Rectangle /> </Canvas>  Properties Attribute Syntax – For simple properties, you can use typical XML Attribute syntax: <Rectangle Width=”50” Height=”50” />  Readability - Properties can be defined on multiple lines in order to make things easier to read. See Canvas and “First Rectangle Example” from the code (above). Content Element Syntax for Properties – In some simple cases, you can set a default property within the context of the opening and closing tags. For example, consider the two TextBlock examples which are equivalent:
<!-- First Textblock Example -->

Silverlight 101 – Lesson 1 | Page 8

<TextBlock Canvas.Top ="200" Canvas.Left="50" Text="Hello" /> <!-- Second Textblock Example --> <TextBlock Canvas.Top ="200" Canvas.Left="100"> World </TextBlock>

Property Element Syntax – Some properties (usually ones that require multiple settings) can be set like the “Second Rectangle Example”. Here, object.property “dot” notation is used to reference the Fill property which is set to a solid green color:
<!-- Second Rectangle Example --> <Rectangle Canvas.Left="125" Canvas.Top="50" Width="50" Height="50" Stroke="Black" StrokeThickness="3"> <Rectangle.Fill> <SolidColorBrush Color="Green" /> </Rectangle.Fill> </Rectangle>

Implicit Collection Syntax – The Property Element Syntax can be extended to allow a collection of related objects to serve as the definition for a property. Consider the “Third Rectangle Example” … it has a collection of RadialGradientBrush.GradientStops which defines the gradient colors and positions:
<Rectangle Canvas.Left="50" Canvas.Top="125" Width="50" Height="50"> <Rectangle.Fill> <RadialGradientBrush> <RadialGradientBrush.GradientStops> <GradientStop Offset="0.0" Color="Blue" /> <GradientStop Offset="1.0" Color="Green" /> </RadialGradientBrush.GradientStops> </RadialGradientBrush> </Rectangle.Fill> </Rectangle>

Compare this example to “Fourth Rectangle Example” which omits the RadialGradientBrush.GradientStops tag. The collection is implied inside the LinearGradientBrush tag and is not required.
<!-- Fourth Rectangle Example --> <Rectangle Canvas.Left="125" Canvas.Top="125" Width="50" Height="50"> <Rectangle.Fill> <LinearGradientBrush> <GradientStop Offset="0.0" Color="Red" /> <GradientStop Offset="1.0" Color="Orange" /> </LinearGradientBrush> </Rectangle.Fill> </Rectangle>

Silverlight 101 – Lesson 1 | Page 9

Event Handler Declaration – While there are ways to accomplish the wiring up of event handlers strictly from imperative code, you can declaratively attach event handlers to events using simple Property attribute syntax. Consider the Loaded event from the Canvas
<Canvas x:Name="parentCanvas" xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Loaded="Page_Loaded"

… There are other small nuances to XAML syntax, but this covers most of what you’ll encounter. For more details, see the article “XAML Syntax Overview” at http://msdn2.microsoft.com/enus/library/bb412392.aspx

Silverlight 101 – Lesson 1 | Page 10

Anatomy of a Silverlight Application
There are four basic parts to a simple Silverlight application. More complex Silverlight applications may require additional resources.  A Web page to host the Silverlight control – This can be any file that delivers HTML, such as a .html file, a .aspx page, a .php page, etc. There are two key items that must be present to load the references to the external files (Silverlight.js and the .js file that contains the Silverlight.createObject() method call which is usually createSilverlight.js when using the file from the SDK, or TestPage.html.js when using Visual Studio 2008 Beta).

Silverlight 101 – Lesson 1 | Page 11

Silverlight.js – This script is responsible for detection, embedding, sizing and positioning of the Silverlight host control into the web page. It is available in the Silverlight 1.1 Alpha SDK and the Silverlight project type when creating a new Silverlight project in Visual Studio (with Silverlight tools installed) or Blend 2.0 Beta. You are not permitted to modify this file per the terms of the license. All whitespace has been removed, so the JavaScript is crammed into one like of the file.

CreateSilverlight.js – By convention, this file contains the JavaScript method createSilverlight that initializes the Silverlight host control. The Silverlight.createObject() (or Silverlight.createObjectEx()) method is where you set the name of the XAML file that will be initially loaded into the host control, where you pass in a reference to the parent element (usually a DIV in the HTML of the hosting web page), and more. See table 1 below for an abbreviated explanation of each of the parameters that can be set. For more detailed information, please consult the article “Using CreateSilverlight.js and Silverlight.js” at http://msdn2.microsoft.com/en-us/library/bb412401.aspx. XAML – Typically, this is a .xaml file, but can also simply be XAML that is embedded in the head section of the web page, XAML delivered from a web service call, etc.

Silverlight 101 – Lesson 1 | Page 12

Important: The SDK uses the convention CreateSilverlight.js, however when working with the Silverlight Tools Alpha in Visual Studio 2008 Beta, the file will be called TestPage.html.js. Their function is identical, and I would assume that as development firms up these names will become consistent across all environments.

Important: There are “breaking changes” in Silverlight 1.1 Alpha Refresh (i.e., changes to Silverlight 1.1 Alpha Refresh that will break older code examples found strewn around the internet, and even in Microsoft’s own documentation). Therefore, if you’ve used a previous version of the SDK you will have to fix several small issues in your code. For a list of breaking changes, see the document “Changes from May 2007 Alpha.docx” after unzipping the Silverlight 1.1 Alpha Refresh SDK. createObject() and createObjectEx() Parameters, Properties and Events The following tables detail the parameters, properties and events that can be set for the createObject() and createObjectEx() methods.

Parameter Name source

Description Name of XAML file to load … when used programmatically, can be used to load XAML in different forms, such as when embedded within the HTML, or when delivered by a web service call, etc. A reference to the HTML element (usually a DIV tag) that will host the Silverlight control Identifier of the Silverlight control to provide programmatic access from both managed and unmanaged code Contains a listing of name / value pairs … see table 2 for a list of properties that can be modified Contains a listing of name / value pairs that represent the event name and the name of the JavaScript function that will handle that event … see table 3 for a list of events that can be handled Contains a listing of name / value pairs that can be used as user defined initialization value … think “command line parameters” If you have multiple Silverlight controls loaded into a single web page the context will define which control’s onLoad event handler function







Silverlight 101 – Lesson 1 | Page 13

Property Name Width

Description Width of the Silverlight host control … can be a percentage … can clip the width of the root Canvas Height of the Silverlight host control … can be a percentage … can clip the height of the root Canvas Background color When set to true, allows the canvas to be transparent. (To achieve this effect, must set the background property to “Transparent” or “#000000”) Display frames per second (fps) … important when working with animation. When set higher, makes motion smoother, but at the risk of system performance. Max is 64 fps. False sends user to http://www.microsoft.com/silverlight to learn more about installation and the EULA. True embeds a different graphic on the page that essentially says that by clicking on the graphic to install Silverlight the user accepts the EULA. True:


Background isWindowless



False (default):

Silverlight 101 – Lesson 1 | Page 14

Note: As far as I can tell in my limited experience, there’s a bug with this feature in both 1.0 and 1.1. In 1.0, if you add “inplaceInstallPrompt” as a parameter, it will always be “true” regardless of whether you set it to true or false. Removing it as a parameter will set it to “false”. Please let me know if you experience something other than this behavior (Silverlight@learnvisualstudio.net). In 1.1, there is no in-place install version. Regardless of this setting, the end user will only see this:

Again, if you experience something different, please contact me. version Which version of the Silverlight plug-in is the XAML and script targeted for? Current valid settings are “1.0” or “1.1”. Default is False, which performs a check to ensure that the browser is able to run the Silverlight application. True skips this check. Default is True, which means that the Silverlight application can interact with the DOM of the web page hosting the Silverlight host control.



Event Name onLoad

Description Sets the event handler for the event that is raised when the XAML has finished loading Sets the event handler for the event that is raised when the Silverlight application encounters an otherwise unhandled exception.


What’s the difference between createObject() and createObjectEx()? Simply put, the “Ex” version explicitly names the property, similar to JSON syntax. Table 4 compares the two calls side by side.

Silverlight.createObject( "Page.xaml",

Silverlight.createObjectEx({ source: 'Page.xaml',

Silverlight 101 – Lesson 1 | Page 15

pe, "AgControl1", { width:'640', height:'480', inplaceInstallPrompt:false, background:'white', isWindowless:'false', framerate:'24', version:'1.1' }, { onError:null, onLoad:null }, null);

parentElement:pe, id:'AgControl1', properties: {

width:'640', height:'480', inplaceInstallPrompt:false, background:'white', isWindowless:'false', framerate:'24', version:'1.1' }, events: {

onError:null, onLoad:null }, context:null});

Controlling the Installation Experience Undoubtedly you’ve already seen the Silverlight installation icon. Since this technology is new and Microsoft has not made Silverlight a part of Windows update (yet), chances are a portion of visitors to your website will need to download and install the Silverlight Plug-In. As a developer, you have two options. By default, the inplaceInstallPrompt parameter of createObject() and createObjectEx() is false which displays the standard (abbreviated) icon. When the user clicks the icon the user will navigate to http://www.microsoft.com/silverlight where the user will be able to read the EULA. If the user agrees to the EULA the download begins and the plug-in installs. Alternatively, the developer can set inplaceInstallPrompt to false, which displays the longer icon. The difference? Notice the hyperlink to the EULA and the notice that by clicking the icon the user is accepting the EULA and installing the plug-in immediately. In some cases, the browser will need to be restarted anyway, so it’s a rather moot point whether to keep the user on your page or send them to Microsoft’s Silverlight site.

Silverlight 101 – Lesson 1 | Page 16

Inline XAML In most examples you will see that the XAML content will be contained in its own file with a .xaml extension. Alternatively however, you can include XAML within the context of the body tags of your HTML. The only additional change required is in the Silverlight.createObject() method where you’ll need to set the source to the id of the script tag that contains the XAML. See screenshots below. See the project folder Lesson01_XAML for the complete implementation of the following example.

Important: When using the inline XAML technique, there is a known work around for FireFox. By default, Visual Studio 2008 puts the following line into TestPage.html: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> However, this causes a known FireFox bug to occur which will not display your Silverlight application. You can remove this line, or if setting the doc-type is important to you, there are several more creative workarounds available. Perform a search for “firefox inline xaml” for more details.

Silverlight 101 – Lesson 1 | Page 17

In this screenshot, you can see that the TestPage.html hosts the XAML within a script tag inside the body of the page. The most important part of this snippet of XAML is the ID property of the script tag which is set to “inlineXAML”. This will correspond to the source parameter of the createObject() method call in the following screenshot.

Silverlight 101 – Lesson 1 | Page 18

Our Development Methodology in this Textbook
While it is entirely possible to build Silverlight applications using any web development tool – including Notepad – we’ll only be using Visual Studio 2008 (Beta 2 at the time of this writing) to develop Silverlight applications. For instructions on setting up your development environment, please see the Lab “Setting Up a Sliverlight Development Environment” in this lesson. Additionally, while Silverlight 1.0 has been officially released, many of the interesting programmatic functionality will appear in Silverlight 1.1. Therefore, this textbook is targeting Silverlight 1.1. There are two caveats in this regard:  Silverlight 1.1 is in “Alpha” and is currently undergoing heavy development. Therefore, the version of the software you are using and this document may become out of sync causing examples to no longer work correctly. Please check back on LearnVisualStudio.NET for updates to this document. This textbook requires the installation of software that is currently in beta. After the official release of Visual Studio 2008 the free “Beta” will no longer exist. Therefore, you will need to acquire a license to use Visual Studio 2008 (as well as other tools we might use, such as Blend) to continue learning from this resource. If the Visual Web Developer 2008 Express Edition allows for creation of Silverlight applications (via an add-in of some sort) then I will use that to appeal to the greatest audience size.

Silverlight 101 – Lesson 1 | Page 19

Installing the Development Tools Since Silverlight 1.1 is in Alpha at the time of this writing, obtaining and installing the correct version of the software you need poses a challenge, albeit minor. The key is finding all the installs for the Refresh version of the 1.1 Alpha, which occurred in September 2007. Install the tools from the following locations in the following order: 1. Microsoft Silverlight 1.1 Alpha Refresh for Windows (http://www.microsoft.com/silverlight/license-win-dev.aspx) 2. Microsoft Visual Studio 2008 Beta 2 (http://www.microsoft.com/downloads/details.aspx?familyid=B98A61BA-99B0-40B7-AB6E5386A2B94217&displaylang=en) 3. Microsoft Silverlight Tools Alpha Refresh for Visual Studio 2008 Beta 2 (http://www.microsoft.com/downloads/details.aspx?FamilyId=B52AEB39-1F10-49A6-85FCA0A19CAC99AF&displaylang=en) For step-by-step instructions, see “Lab1: Setting up a Silverlight Development Environment”. Note: I use Alcohol 120% for opening an ISO file and installing it directly onto a desktop machine’s OS. Otherwise, when installing within a Virtual Machine, both VMWare and VirtualPC can both treat an .iso as a virtualized DVD drive.

There are other optional tools that you might find helpful as I’ll refer to these throughout the textbook and labs. 1. Silverlight 1.1 Alpha Refresh SDK (http://go.microsoft.com/fwlink/?LinkID=89145&clcid=0x409) 2. Microsoft Expression Blend 2.0 August Preview (http://www.microsoft.com/downloads/details.aspx?FamilyId=69540337-B619-4A47-AC2752D8AF3A7830&displaylang=en) 3. Microsoft Expression Design 1.0 (http://www.microsoft.com/downloads/details.aspx?FamilyId=E2F6D411-4CCA-407B-A4343115F76C3C4D&displaylang=en)

The Silverlight 1.1 Alpha Refresh SDK is useful for a clean version of the CreateSilverlight.js and Silverlight.js (assuming you’ll not be using Visual Studio or Blend). It also has documentation, as well as the controls starter kit mentioned previously in the section titled “What are the key differences between Silverlight 1.0 and 1.1?” Microsoft Expression Blend 2.0 will most likely be where most designers and developers prefer to build their XAML since it has tools to draw shapes, place controls, edit timelines and so forth. Blend can open a Visual Studio project and vice versa to enable the interaction between designer and developer. Silverlight 101 – Lesson 1 | Page 20

Microsoft Expression Design has a better set of drawing tools than Blend and will be the preferred tool to design vector images. Adobe Illustrator is a more mature product for composing vector art, and while it is not condoned it certainly is possible to import .ai files (or .pdf files for that matter) into Expression Design using a free third party tool. For more information, watch this video on Channel9: http://channel9.msdn.com/ShowPost.aspx?PostID=338599

Creating a Silverlight Project in Visual Studio 2008 As noted earlier, there are several ways to compose a Silverlight application:    Using any web development tool, even Notepad Using Blend 2.0 Beta Using Visual Studio 2008 with the Microsoft Silverlight Tools Alpha Refresh for Visual Studio 2008 Beta 2 installed.

The third method is what we’ll use throughout this textbook. There are several benefits to embracing this development environment:      Intellisense - especially beneficial when writing managed Silverlight code Syntax highlighting – especially beneficial for writing JavaScript Silverlight Project Template Linking Silverlight projects to ASP.NET projects Debugging environment for both managed and unmanaged code

Watch: SL101_01_03 - Silverlight Projects in Visual Studio 2008.wmv

Creating a new Silverlight project is as easy as selecting the appropriate template from the Silverlight project type in the New Project dialog.

Silverlight 101 – Lesson 1 | Page 21

Anatomy of a Silverlight Project in Visual Studio 2008 Selecting the Show All Files button on the Solution Explorer will reveal files that you may need to interact with.

From the previous discussions earlier in this lesson, the contents of a new Silverlight project should be straightforward. As described earlier, note the presence of the TestPage.html.js file which is depicted as being related to the TestPage.html (again, will need to select the Show All Files button to see this file). This file replaces the createSilverlight.js file that is described in most documentation currently available Silverlight 101 – Lesson 1 | Page 22

from Microsoft. It is the file that contains the createObjectEx() method to instantiate the Silverlight control host. In Lesson 2 “Silverlight Graphical Elements Basics”, most of the work we’ll perform will be exclusively in the Page.xaml file because we’ll only be writing XAML to display shapes and other elements on screen. In Lesson 3 “Scripting and Mouse Events using Unmanaged APIs” and beyond, most of our work will be in the TestPage.html where we’ll write JavaScript between the <script> tags in the <head> section of the HTML document. Beginning in Lesson 6 and 7, “Writing Managed code with Silverlight 1.1 and Visual Basic” and “Writing Managed code with Silverlight 1.1 and C#” respectively, we’ll begin writing managed code inside the context of the Page.xaml.vb and Page.xaml.cs files, respectively.

Linking a Silverlight Project to an ASP.NET Project in Visual Studio 2008 One technique that will begin to be useful in Lesson 3 will be the ability for an ASP.NET application to host a Silverlight application. While there are several ways to accomplish this, Visual Studio 2008 makes it easy to link a Silverlight Project from an ASP.NET Project via a context menu option on the ASP.NET project.

When selected, Visual Studio 2008 will ask which Silverlight application to link to.

Silverlight 101 – Lesson 1 | Page 23

You’ll also get the opportunity to allow Silverlight debugging for the ASP.NET project, which essentially modifies the project settings around script debugging within the browser.

Once the two projects are linked, the assemblies that contain managed Silverlight event handlers will be automatically copied to the \ClientBin directory of the ASP.NET project. Whenever a new Build of the Silverlight project is created, the output assemblies are updated. Additionally, changes made in the Page.xaml file will be copied between the two projects. Silverlight 101 – Lesson 1 | Page 24

What is the benefit of this technique? You certainly could manually add all the necessary files to insert a Silverlight application into a regular ASP.NET web project. The benefit of this approach is that you can continue to enjoy the separation between the designer (who would work on the Silverlight project in Blend, for example) and the developer (who would consume the XAML project in the ASP.NET project).

Watch: SL101_01_04 - Linking a Silverlight Project to an ASP.NET Project in Visual Studio 2008.wmv

Deploying your Silverlight Application
Your server (or hosting company) needs to make sure that XAML is added as a mime type in Internet Information Services. If you are simply deploying a Silverlight 1.0 application (i.e., no managed assemblies) then you simply need to copy the appropriate files to the server. If you are deploying a Silverlight 1.1 application written using Visual Studio 2008, then you will need to ensure that your hosting provider supports .NET 3.5 assemblies. I’ve not tested this but hope to for future releases of this document.

Silverlight 101 – Lesson 1 | Page 25

Adding XAML as a MIME Type in Internet Information Services 6.0 If you manage your own servers, you will need to map the .xaml file extension to the appropriate MIME type in IIS6 otherwise the .xaml page will not be served to your client browser and it will appear as a blank space on your web page. 1. In IIS6, right click your website site in the left-hand pane and select “Properties …” from the context menu 2. In the Properties dialog, select the HTTP Headers tab, then click the “MIME Types …” button.

Silverlight 101 – Lesson 1 | Page 26

3. In the MIME Types dialog, select the New button.


In the MIME Type dialog, enter “.xaml” as the Extension and “application/xaml+xml” as the MIME type. Click Ok.


Click Ok on the next two dialog boxes to return to IIS 6.0.

Silverlight 101 – Lesson 1 | Page 27

 Silverlight is a new cross-browser plug-in that renders XAML and hosts a subset of the .NET Framework Class Library as well as a subset of the Windows Presentation Framework to allow programmatic manipulation to the presentation and behavior of user interface elements Silverlight is currently “pre-natal” and has many hurdles to large-scale adoption While Silverlight 1.0 is nearing official release, functionality that most developers would consider to be baseline will not appear until Silverlight 1.1. Currently there are three ways to build Silverlight applications, 1) use Visual Studio 2008 Beta with the Silverlight Project Add-In to create Silverlight 1.0 or 1.1 applications, 2) use Blend 2.0 Beta 1 to create Silverlight 1.0 applications, or 3) build using text editor and command line compilation tools.

  

Exercise 1-1: View Silverlight Community Videos If you haven’t already done so, please review the following videos to get a better sense of what is possible with Silverlight:

Review Questions
1. Describe the key differences between Silverlight 1.0 and Silverlight 1.1. 2. What is the purpose of the Silverlight.js and createSilverlight.js files? What important method call is contained in the createSilverlight.js file? 3. In XAML, what is the purpose for the Canvas? 4. Does all XAML code have to be in a file with the extension .xaml? Explain. 5. What methods or tools can be employed to compose Silverlight applications?

Case Scenarios
1. Since you are an early adopter, you want to create a smooth installation process of the Silverlight plug-in for your users. What factors will you have to weigh in deciding how to best implement your application to reduce the amount of friction required for them to utilize it? 2. The marketing department enlists your help to conceptualize and built a new rich interactive application for a brand new product line. The marketing department needs video demonstrations as well as copious amounts of animation and interactivity to convey the message about the product’s features and to build excitement. The timeframe is short and this will be a high profile project within the company. What would be your technology recommendation?

Silverlight 101 – Lesson 1 | Page 28

Labs are intended to be step-by-step instructions that you perform as a hands-on exercise.

Lab 1: Setting up a Silverlight Development Environment To watch this procedure, watch video: “SL101_01_05 – Lab 1 -Setting up a Silverlight Development Environment.wmv” To set up a development and testing environment suitable for the examples in this workbook and lab manual, complete the following procedure: 1. Download the Visual Studio 2008 Beta 2 ISO file – You can download from the following location: http://www.microsoft.com/downloads/details.aspx?familyid=B98A61BA-99B0-40B7AB6E-5386A2B94217&displaylang=en The actual file name will be: en_visual_studio_2008_beta_2_professional_edition_dvd.iso, however I’ll simply refer to it as the Visual Studio 2008 Beta 2 ISO file in this lab. 2. Download and install Alcohol 120% - The trial version will work for 30 days with a “nag screen”. This utility will allow you to mount an ISO file so that Vista will see it as another DVD drive in your system. Download from http://www.alcohol-soft.com. (You can use any other software or technique to open or mount an IMG file.) Note: installation of Alcohol 120% requires a reboot. May want to wait until after you finish downloading the Visual Studio ISO file. Caution: Alcohol 120% will affect system drivers. Use at your own risk. 3. Open ISO in Alcohol 120% - Once installed, select File | Open … to display the Open dialog. Navigate to the download location of the Visual Studio 2008 Beta ISO. Select the file and click the Open button. The File should now be displayed in the main area of Alcohol 120%. 4. Mount ISO - Right-click the Visual Studio 2008 Beta ISO in the main area of Alcohol 120% and select Mount On Device. In some cases, you may see Mount On Device and a sub-menu option with the available virtual drives which I’ll refer to as {Your Virtual Drive Letter Here}. Once you click either option, in the lower pane, you should see the file location of {Your Virtual Drive Letter Here} change to the file location you selected in step 3. 5. Install Visual Studio 2008 Beta 2 – Typically in the previous step, the Setup screen for Visual Studio 2008 Beta 2 will appear. (Alternatively in Vista, the Autoplay dialog will appear. Select the option “Run autorun.exe” to display the Visual Studio 2008 Beta 2 Setup screen.) If autoplay is not enabled, use Windows Explorer to locate {Your Virtual Drive Letter Here} and navigate and double-click the autorun.exe file on the virtual drive. Click “Install Visual Studio 2008” link in the Setup dialog. You can agree to all the typical dialogs, or customize the installation to your liking as long as you don’t remove Visual Basic or Visual C# from the installation options. Note: Installation will require a reboot. If you are using Alcohol 120%, after reboot you may encounter a problem … “The Windows Installer package: {Your Virtual Drive Letter Here}\vs_setup.msi could not be opened”. Simply open Alcohol 120%, and once its

Silverlight 101 – Lesson 1 | Page 29

running then and select the “Retry” button on the error dialog. See the video for this Lab for more details. 6. Download and Install the Silverlight 1.1 Tools for Visual Studio 2008 Beta 2 – You can use the following download location: http://www.microsoft.com/downloads/details.aspx?FamilyId=B52AEB39-1F10-49A6-85FCA0A19CAC99AF&displaylang=en Once downloaded, click Run from the dialog to initiate installation. After installation, open Visual Studio 2008 Beta 2 to ensure that both it and the Silverlight Tools have installed correctly.

Silverlight 101 – Lesson 1 | Page 30

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.