MCTS: Microsoft Silverlight 4 Development (70-506) Certification Guide

By Johnny Tordgeman
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Overview of Silverlight

About this book

Microsoft Silverlight is a powerful development platform for creating engaging, interactive applications for many screens across the Web, desktop, and mobile devices. Silverlight is also a great (and growing) Line-Of-Business platform and is increasingly being used to build data-driven business applications. Silverlight is based on familiar .NET languages such as C# which enables existing .NET developers to get started developing rich internet applications almost immediately.

"MCTS: Microsoft Silverlight 4 Development (70-506) Certification Guide" will show you how to prepare for and pass the (70-506): TS: Microsoft Silverlight 4 Development exam.

Packed with practical examples and Q&As, MCTS: Microsoft Silverlight 4 Development (70-506) Certification Guide starts by showing you how to lay out a user interface, enhance the user interface, implement application logic, work with data and interact with a host platform amongst others.

Publication date:
June 2012
Publisher
Packt
Pages
290
ISBN
9781849684668

 

Chapter 1. Overview of Silverlight

Just like everything in life, we start things off with an overview. If you have picked up this book on purpose, then I'm sure you have at least some idea what Silverlight is. But, if you just picked this book because the cover looked inviting, fear not, as this chapter will provide all the basics you'll need in your journey to become a certified Silverlight guru.

As Confucius once said, "A journey of a thousand miles begins with a single step", so let's take the first step now and get to know all the basics of Silverlight.

In this chapter we will cover the following topics:

  • What is Microsoft Silverlight

  • Introducing XAML

  • The Silverlight application model

  • Integrating Silverlight with HTML

  • In and out-of-browser support

  • Self-test (Q&A)

What is Microsoft Silverlight

Silverlight is Microsoft's cross-platform, cross-browser, and a .NET-based framework for building in and out-of-browser Rich Internet Applications (RIAs). In simple words, you can write Silverlight applications using a language you already know (be it C# or VB), and run it on all major operating systems (such as OSX, Windows, and Linux) and browsers (such as Internet Explorer, Chrome, Firefox, and Safari).

It's worth noting that the Linux variation of Silverlight is not developed or maintained by Microsoft. Moonlight, which is the name of the Linux variation, is developed by the Mono project with aid from Microsoft and Novell, and is primarily targeted for Linux and other Unix/X11-based operating systems. In addition, your Silverlight application doesn't have to stay inside the browser. Using the out-of-browser capabilities of Silverlight, you can take your application out of the browser and into the desktop, but we will learn more on that later.

Using Silverlight you can build just about anything—from a simple media player that streams movies from your server, to a complex line of business (LOB) application that fetches data from a database and uses some business logic to transform that data into a visually stunning executive dashboard with interactive charts and gauges.

Many companies nowadays are using Silverlight to enrich their applications. Take a look at Seesmic Desktop 2 for example (http://www.seesmic.com/products/desktop), which is a social media tool for Windows and Mac built entirely in Silverlight.

The main competition to Silverlight comes from Adobe Flash. Both are browser plugins targeting rich media applications. While not a direct competitor, HTML5 can also be considered as an alternative in some cases. While Silverlight has matured into a rich line of business platform that is getting increasingly popular for creating intranet applications, HTML5 offers greater reach, as it can be viewed on more devices. But, it is also much harder to develop the same level of business applications using HTML5 instead of Silverlight.

In addition, the HTML5 specifications are not finalized yet and, thus, not all the browsers implement it evenly. For example, while some browsers fully support the Canvas control, others support just some of its features, making it difficult to use the "code once, run everywhere" approach.

Whether you are an ASP.NET developer trying to decide if Silverlight is the right technology for your next project or you are a part of a development team in a big enterprise, here are some reasons to use Silverlight over other technologies:

  • Cross-browser and OS support: The code you write will run exactly the same on every supported browser and OS, so you don't have to waste time with making your application supportable on other browsers than your own

  • Authoring tools: Silverlight is developed on Visual Studio 2010, which you, as a .NET developer, already know and love

  • Plugins with a small size: The Silverlight plugin weighs just a few megabytes, which is a small size compared to the entire .NET framework

  • .NET-based framework: Silverlight is based on the .NET framework, which means that if you are already a .NET developer, learning Silverlight will be like a walk in the park

  • Out-of-browser support: The ability to take your application out of the web world and into the desktop world opens a lot of opportunities to enrich the user's experience from your application

  • Enterprise-ready: Silverlight can integrate with components such as Microsoft Enterprise Library 5 (http://msdn.microsoft.com/en-us/library/ff648951.aspx) and WCF RIA services (http://msdn.microsoft.com/en-us/library/ee707344%28v=vs.91%29.aspx), so you can complete the development of your LOB applications faster and more efficiently

  • Prism: The Microsoft patterns and practices group has published Prism, which guides you on how to increase modularity and helps you to architect your application better

The adoption rate of Silverlight has recently reached the 70 percent milestone (http://www.riastats.com/), which means that almost every three out of four PCs already have Silverlight installed! With the rise in the adaptation rate comes the rise in the need for developers. A leading job-hunting site—http://www.dice.com/—has recently found that Silverlight-related jobs experienced a 12.6 percent growth in demand over the last three months, while Adobe Flash-related jobs experienced just 2.2 percent growth over the same period of time (http://www.readwriteweb.com/enterprise/2011/05/it-hiring-and-salaries-up---wh.php). In addition, Silverlight is the language of choice to develop applications for Microsoft's newest mobile phone system—Windows Phone 7, which means that if you know Silverlight, you are not only a web and desktop developer, you are also a mobile developer!

If I have to sum up the last paragraph in simple words, I would say that you couldn't have picked a better time to become a certified Silverlight developer.

Now that you know what Silverlight is, what it can do, and why you should use it, let's move on to set up your development environment. Your development environment requires the following hardware and software components:

  • A 1.6 GHz or faster CPU

  • At least 1 GB RAM for 32-bit OS or 2 GB RAM for 64-bit OS

  • 3 GB of available hard disk space

  • A PC running Windows XP/Vista/7/Server 2003/Server 2008

Setting up your development environment

Setting up your development environment is as easy as it can get. The process consists of three downloads (two are mandatory and one is optional) and the installation of those components.

The first thing you need is Visual Studio 2010. If you have Visual Studio 2008 or an earlier version, you will need to upgrade it, as the Silverlight 4 developer tools don't support these versions. You can download a free version of Visual Studio 2010 from the Microsoft website at http://www.microsoft.com/express/Downloads/.

Once you have Visual Studio 2010 installed, you will need the Silverlight 4 developer tools. These tools add the support for developing and designing Silverlight 4 applications in Visual Studio 2010. If you have Service Pack 1 for Visual Studio 2010 installed, you already have the tools; if not, you can get them either by using the installed Microsoft/web platform located at http://www.microsoft.com/web/gallery/install.aspx?appid=silverlight4tools;silverlight4toolkit;riaservicestoolkit or downloading the Microsoft Silverlight 4 Tools for Visual Studio 2010 directly from http://go.microsoft.com/fwlink/?LinkID=177428.

The last thing you should download and install is the Silverlight 4 Toolkit from CodePlex. This toolkit adds new components and functionality to the developer tools, and it is highly recommended that you install it. This toolkit can be downloaded from http://silverlight.codeplex.com/releases/view/43528.

Note

While it is completely possible to develop Silverlight 4 applications without the Silverlight 4 Toolkit, it is highly recommended that you download it as it adds many frequently used components, such as an auto-complete box, to the arsenal of components that you can use in your applications.

Now you have a fully equipped development environment for Silverlight. With this accomplishment, we can move on and talk about the first major concept of working with Silverlight—XAML.

 

What is Microsoft Silverlight


Silverlight is Microsoft's cross-platform, cross-browser, and a .NET-based framework for building in and out-of-browser Rich Internet Applications (RIAs). In simple words, you can write Silverlight applications using a language you already know (be it C# or VB), and run it on all major operating systems (such as OSX, Windows, and Linux) and browsers (such as Internet Explorer, Chrome, Firefox, and Safari).

It's worth noting that the Linux variation of Silverlight is not developed or maintained by Microsoft. Moonlight, which is the name of the Linux variation, is developed by the Mono project with aid from Microsoft and Novell, and is primarily targeted for Linux and other Unix/X11-based operating systems. In addition, your Silverlight application doesn't have to stay inside the browser. Using the out-of-browser capabilities of Silverlight, you can take your application out of the browser and into the desktop, but we will learn more on that later.

Using Silverlight you can build just about anything—from a simple media player that streams movies from your server, to a complex line of business (LOB) application that fetches data from a database and uses some business logic to transform that data into a visually stunning executive dashboard with interactive charts and gauges.

Many companies nowadays are using Silverlight to enrich their applications. Take a look at Seesmic Desktop 2 for example (http://www.seesmic.com/products/desktop), which is a social media tool for Windows and Mac built entirely in Silverlight.

The main competition to Silverlight comes from Adobe Flash. Both are browser plugins targeting rich media applications. While not a direct competitor, HTML5 can also be considered as an alternative in some cases. While Silverlight has matured into a rich line of business platform that is getting increasingly popular for creating intranet applications, HTML5 offers greater reach, as it can be viewed on more devices. But, it is also much harder to develop the same level of business applications using HTML5 instead of Silverlight.

In addition, the HTML5 specifications are not finalized yet and, thus, not all the browsers implement it evenly. For example, while some browsers fully support the Canvas control, others support just some of its features, making it difficult to use the "code once, run everywhere" approach.

Whether you are an ASP.NET developer trying to decide if Silverlight is the right technology for your next project or you are a part of a development team in a big enterprise, here are some reasons to use Silverlight over other technologies:

  • Cross-browser and OS support: The code you write will run exactly the same on every supported browser and OS, so you don't have to waste time with making your application supportable on other browsers than your own

  • Authoring tools: Silverlight is developed on Visual Studio 2010, which you, as a .NET developer, already know and love

  • Plugins with a small size: The Silverlight plugin weighs just a few megabytes, which is a small size compared to the entire .NET framework

  • .NET-based framework: Silverlight is based on the .NET framework, which means that if you are already a .NET developer, learning Silverlight will be like a walk in the park

  • Out-of-browser support: The ability to take your application out of the web world and into the desktop world opens a lot of opportunities to enrich the user's experience from your application

  • Enterprise-ready: Silverlight can integrate with components such as Microsoft Enterprise Library 5 (http://msdn.microsoft.com/en-us/library/ff648951.aspx) and WCF RIA services (http://msdn.microsoft.com/en-us/library/ee707344%28v=vs.91%29.aspx), so you can complete the development of your LOB applications faster and more efficiently

  • Prism: The Microsoft patterns and practices group has published Prism, which guides you on how to increase modularity and helps you to architect your application better

The adoption rate of Silverlight has recently reached the 70 percent milestone (http://www.riastats.com/), which means that almost every three out of four PCs already have Silverlight installed! With the rise in the adaptation rate comes the rise in the need for developers. A leading job-hunting site—http://www.dice.com/—has recently found that Silverlight-related jobs experienced a 12.6 percent growth in demand over the last three months, while Adobe Flash-related jobs experienced just 2.2 percent growth over the same period of time (http://www.readwriteweb.com/enterprise/2011/05/it-hiring-and-salaries-up---wh.php). In addition, Silverlight is the language of choice to develop applications for Microsoft's newest mobile phone system—Windows Phone 7, which means that if you know Silverlight, you are not only a web and desktop developer, you are also a mobile developer!

If I have to sum up the last paragraph in simple words, I would say that you couldn't have picked a better time to become a certified Silverlight developer.

Now that you know what Silverlight is, what it can do, and why you should use it, let's move on to set up your development environment. Your development environment requires the following hardware and software components:

  • A 1.6 GHz or faster CPU

  • At least 1 GB RAM for 32-bit OS or 2 GB RAM for 64-bit OS

  • 3 GB of available hard disk space

  • A PC running Windows XP/Vista/7/Server 2003/Server 2008

Setting up your development environment

Setting up your development environment is as easy as it can get. The process consists of three downloads (two are mandatory and one is optional) and the installation of those components.

The first thing you need is Visual Studio 2010. If you have Visual Studio 2008 or an earlier version, you will need to upgrade it, as the Silverlight 4 developer tools don't support these versions. You can download a free version of Visual Studio 2010 from the Microsoft website at http://www.microsoft.com/express/Downloads/.

Once you have Visual Studio 2010 installed, you will need the Silverlight 4 developer tools. These tools add the support for developing and designing Silverlight 4 applications in Visual Studio 2010. If you have Service Pack 1 for Visual Studio 2010 installed, you already have the tools; if not, you can get them either by using the installed Microsoft/web platform located at http://www.microsoft.com/web/gallery/install.aspx?appid=silverlight4tools;silverlight4toolkit;riaservicestoolkit or downloading the Microsoft Silverlight 4 Tools for Visual Studio 2010 directly from http://go.microsoft.com/fwlink/?LinkID=177428.

The last thing you should download and install is the Silverlight 4 Toolkit from CodePlex. This toolkit adds new components and functionality to the developer tools, and it is highly recommended that you install it. This toolkit can be downloaded from http://silverlight.codeplex.com/releases/view/43528.

Note

While it is completely possible to develop Silverlight 4 applications without the Silverlight 4 Toolkit, it is highly recommended that you download it as it adds many frequently used components, such as an auto-complete box, to the arsenal of components that you can use in your applications.

Now you have a fully equipped development environment for Silverlight. With this accomplishment, we can move on and talk about the first major concept of working with Silverlight—XAML.

 

Introducing XAML


XAML is an acronym for Extensible Application Markup Language. Being a markup language, XAML isn't any different from your everyday-used XML or HTML. XAML is, at its core, an XML file that is used by Silverlight (and WPF) to create the user interface layer of your application. You can use just about any application to create XAML such as Visual Studio, Expression Blend, or even just plain old-school Notepad.

Not every XAML file is used by Silverlight for rendering the user interface layer. In every Silverlight project you will create, you'll notice a file named App.xaml. This file doesn't have any controls added to it, nor does it have the ability to host any controls. Instead, this file is used to host the application-level style resources (such as a Resource Dictionary, which we will talk about in a later chapter) and all of the application lifecycle events' receivers (such as the startup or exit events).

XAML gives us the ability to separate the user interface (UI) layer from the code layer. A XAML element will always represent a .NET element, so every attribute we set on the UI layer using XAML actually corresponds to a property within that .NET element it represents. This direct representation is also the reason why everything you can do with XAML on the UI layer, you can do in code (using C# or VB) as well.

To see how XAML makes our life easier when working with user interface components, let's examine the following line of code:

<input type="button" style='width:100px;height:40px;' value="Submit"/>

The preceding line of code should look familiar to you as it's the basic HTML syntax for adding a button to the screen.

Now, let's add the same button using the ASP.NET syntax:

Button btn = new Button();
btn.Width = Unit.Pixel(100);
btn.Height = Unit.Pixel(40);
btn.Text = "Submit";

Finally, let's add this button using XAML:

<Button Width="100" Height="40" Content="Submit"/>

As you can see, using XAML cuts down our code from four lines in ASP.NET to one short line of code.

Button, among other controls, also known as content controls, allow us to add a child control to display the control's content. If we take our button as an example, we can add an image as its content instead of the usual text:

<Button Width="100" Height="40">
<Button.Content>
<Image Source="fun.jpg"/>
</Button.Content>
</Button>

Content controls

Content controls are used very often in Silverlight and we will dig more into them later on, but the one key concept to remember about content controls is that they can only hold one child control as content. This limitation may look strange to you right now, but as we discuss layout controls, such as the Grid control in Chapter 2, Laying out Our User Interface, you will see that this limitation is hardly a limitation at all.

The easiest way to work with XAML controls is to drag them out of the toolbox and into the design surface. We can do this using both Visual Studio 2010 or a more designer-oriented application, for example Microsoft Expression Blend 4.

The following screenshot shows what the controls toolbox looks like in Visual Studio:

The following screenshot shows what the Controls toolbox looks like in Microsoft Expression Blend 4:

Namespaces

Just like many other programming languages, XAML uses namespaces to organize related controls into groups. Each namespace represents a group of controls and in order to use any of those controls, the namespace must be added to the XAML file (either at the root element level which affects the entire page, or at a lower-level container control which affects only the children of that control).

As we will probably need more than one group of controls within our application, XAML supports multiple namespaces within a single application. To differentiate the different namespaces, each is assigned a prefix value. That prefix value will later be used when we want to add a control from that specific group.

Of course, a declaration of a namespace without reference to the assembly file that actually has the control is useless, so make sure you reference the correct assembly file before adding the namespace.

Let's examine the basic MainPage.xaml file, which gets created whenever you create a new Silverlight project:

<UserControl x:Class="SilverlightApplication2.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
...
</UserControl>

From the preceding code snippet, we can see that http://schemas.microsoft.com/winfx/2006/xaml/presentation is the default namespace that the page will use (we can tell it's the default namespace as it has no prefix). This namespace hosts a bunch of the core controls you can add to your Silverlight application.

Another namespace that gets declared by default is http://schemas.microsoft.com/winfx/2006/xaml. Unlike the default namespace, this namespace gets declared with a prefix (x). That means that whenever we wish to use a control or a property from this namespace, we will have to first mention its prefix value, followed by the name of the property. This namespace provides functionality that is common across our application. We can also add our own namespaces to our application. We will discuss all about namespaces in Chapter 2,Laying out Our User Interface.

Naming your objects

If we look back at the button we defined previously in this chapter, we will notice that it has no name/ID attribute, which means that we won't be able to access this object in our code behind by name, but we will have to use more complicated methods such as the FindChildByType or FindName methods of the visual tree object to access it. To give an object a name in Silverlight, we can use either the x:Name attribute (can you guess where the x prefix came from?) or just the plain Name attribute. The following line of code shows the XAML code for our button with the newly added property:

<Button Width="100" Height="40" Content="Submit" x:Name="btnSubmit"/>

If you play around a bit with adding controls in Visual Studio, you will notice that many of the controls you add from the toolbox will automatically add a reference to the right assembly and declare the correct namespace for you. We will discuss in detail how to reference namespaces in the next chapter of this book.

Setting properties

XAML allows us to set properties of our objects in two ways—Using the Inline property and using the Element property. We have already seen the Inline properties when we declared our Button control—Width, Height, Content, and x:Name are all Inline properties. When we wish to set a simple property of our element, we will usually use the Inline properties as they are fast and easy to set, but if we want to set an image as the content of our button, we would need a way to represent a more complex value for the property. To set an image as the content of a button, we will set an Element property. An Element property of the content will look like this:

<Button Width="100" Height="40" x:Name="btnSubmit">
<Button.Content>
<Image Source="fun.png"/>
</Button.Content>
</Button>

Notice the syntax for the content Element property in the following line of code:

<ControlType.PropertyName>some-value</ControlType.PropertyName>

You don't have to remember this syntax by heart, as Visual Studio's IntelliSense will help you write it.

With this we conclude our overview of XAML, but obviously there is a lot more in the language than what we've covered. As XAML is a key concept in Silverlight, we will deal with it a lot more in the coming chapters, so even if you didn't understand everything we talked about so far, you definitely will, once we get to use it more.

 

The Silverlight application model


A Silverlight application, once compiled, will end up as a XAP (pronounced as zap) file. That XAP file, which is actually a ZIP file renamed, will contain your compiled code in the form of a DLL file, which is a manifest file named AppManifest.xaml that describes your application to the Silverlight runtime engine and possibly some resources such as images, web service connection information, or any other type of content your application might need.

Due to the fact that a XAP file contains more than just compiled code, there may be times when we need to edit its content, which is where knowing the fact that "the XAP files are basically the ZIP files" comes in handy.

Consider the following scenario:

You are developing a Silverlight application that needs to access a database in order to display data from it. To access the database, you will connect to a WCF web service that grabs the data and sends it back to your application in the XML format. In most cases, the WCF web service won't be hosted on the same machine in both development and production environments and, thus, will have a different IP address on each. As we have mentioned earlier, the XAP file contains, among other things, the web service connection information for our application inside a file called ServiceReferences.ClientConfig. So, before we move our application from a development to a production environment we need to edit this file and change the address of the WCF web service from a testing environment address to the production address.

In order to run our Silverlight application, the browser will download our XAP file to the client computer, which means file size may be an issue for users with limited bandwidth or a slower connection. We may try to reduce the size of our XAP file by re-zipping it using a stronger compression rate. But, this will come at the expense of slower decompression of the XAP file on older machines, and the slower the decompression rate is, the longer it will take for your application to start running.

A better method to decrease the size of your XAP file would be using the "application library caching" option. The application library caching, also known as assembly caching, is a packing method, which avoids packing the DLL files into your XAP file, and instead zips them into individual files alongside it. Using assembly caching may greatly reduce the size of your XAP file, providing faster initial loading time for your application.

To use assembly caching, right-click on the project name in Visual Studio 2010 and select Properties. In the new dialog box, select the Reduce XAP size by using application library caching option, as shown in the following screenshot:

Note

You cannot use assembly caching if you are building an out-of-browser application. We will discuss the out-of-browser applications later on in this chapter.

You may be wondering at this point how the Silverlight runtime engine knows that we used the assembly caching option, and that it needs to download a list of external DLL files. The answer to this question is simpler than you might imagine—the AppManifest.xaml file.

We have mentioned the AppManifest.xaml file earlier when we discussed the content of a XAP file and now we can elaborate more about it. The AppManifest.xaml file has one important role—it is responsible for describing our application to the Silverlight runtime engine. Whenever you create a new Silverlight project, Visual Studio 2010 creates this file as part of the project and updates it throughout the project lifetime if necessary. As Visual Studio is responsible for updating this file, it would be rare that we need to update this file by hand ourselves.

Visual Studio 2010 will generate the content of the file, once you compile your Silverlight project. Let's take a look at a basic example of an AppManifest.xaml file:

<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" EntryPointAssembly="SilverlightApplication2" EntryPointType="SilverlightApplication2.App" RuntimeVersion="4.0.60310.0">
<Deployment.Parts>
<AssemblyPart x:Name="SilverlightApplication2" Source="SilverlightApplication2.dll" />
<AssemblyPart x:Name="System.Windows.Controls.Navigation" Source="System.Windows.Controls.Navigation.dll" />
<AssemblyPart x:Name="System.Xml.Linq" Source="System.Xml.Linq.dll" />
</Deployment.Parts>
</Deployment>

As can be seen from the preceding code snippet, the Deployment element has three attributes as follows:

  • EntryPointAssembly: This attribute will always point to the name of the assembly. We will always see this same assembly referenced under the Deployment.Parts section as well.

  • EntryPointType: This attribute will always point to the class that should be used to start the application (we will discuss the App.xaml file later in this book).

  • RuntimeVersion: This attribute will tell the runtime engine which version of Silverlight the application was built with.

Under Deployment lies the Parts section. This section houses one or more AssemblyPart entries, each of which point to a DLL file that our application is using. The first entry is usually our compiled Silverlight application, which also contains the entry point class that was specified under the EntryPointType attribute of the parent Deployment tag.

Other than Parts, the Deployment element may also contain an ExternalParts section. This section will be visible only if we have used the application caching option. This section tells the Silverlight runtime engine which files it needs to download, other than the XAP file, in order to run the application. The ExternalParts section will contain one or more ExtentionPart entries, each of which point to an external ZIP file.

An example of the ExternalParts section may look like the following code snippet:

<Deployment.ExternalParts>
<ExtensionPart Source="System.Windows.Controls.Navigation.zip" />
<ExtensionPart Source="System.Xml.Linq.zip" />
</Deployment.ExternalParts>

In our sample, the Silverlight runtime engine will have to download two external files to get the application running.

 

Integrating Silverlight with HTML


Now that we know how the Silverlight application model works, let's see how Silverlight interacts and integrates with HTML to actually display the application to the user.

There are two ways to add a Silverlight application to your HTML page as follows:

  • Using the object tag

  • Using the JavaScript helper files

Using the object tag

The object tag method is the easiest way to add a Silverlight application to your page. Using this method, you won't need to use any external JavaScript files for adding a Silverlight application to your page. This method is also supported by all the browsers that are supported by Silverlight. A basic Silverlight object tag will look as follows:

<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
<param name="source" value=" MyCoolApp.xap"/>
<param name="onError" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="4.0.60310.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID= 149156&v=4.0.60310.0" style="text-decoration:none">
<img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border- style:none"/>
</a>
</object>

The object tag has four mandatory attributes as follows:

  • data: While not used by most browsers in the context of Silverlight, it is recommended by Microsoft to have the value of this attribute set to"data:application/x-silverlight-2," to prevent decreased performance in some browsers. You can think of this attribute as a sort of MIME type.

  • type: This attribute actually represents the MIME type. It identifies the object tag as a Silverlight object, which will cause the browser to initiate the Silverlight plugin in order to render the object.

  • width and height: They specify the width and height of the Silverlight application. You can specify the measurements in pixels or percentages.

Inside the object tag we have several param entries, as listed in the following table:

Name

Description

Required

Default

source

This specifies the URI to the XAP file. It can be a relative or absolute URI.

Yes

None

onError

This specifies a JavaScript function to call when an error occurs while loading the Silverlight application.

No

None

background

This specifies the background color for the object tag rectangular area that displays the Silverlight application. It can accept color names (such as Red) or hexadecimal values with or without alpha (#ff000000 or #000000).

No

white

minRuntimeVersion

This specifies the earliest Silverlight version required to run the application.

No

Currently installed version

autoUpgrade

This specifies whether or not to automatically update to the specified version in the minRuntimeVersion attribute if the currently installed version is an older version.

No

true

initParams

This specifies user-defined initialization parameters using comma-separated key-value pairs, for example, UserName=JohnnyT

No

None

There are many more parameters you can use with your Silverlight object tag, and you can read more about them at Microsoft's MSDN web page—http://msdn.microsoft.com/en-us/library/cc838259(v=vs.95).aspx.

If the browser fails to render the Silverlight application, it will fall back to the content inside of the object tag. The default content of a Silverlight object tag will look like the following screenshot:

You can always change the content of the object tag to your liking by simply removing all the content the object tag currently has (remember, don't delete the param entries!) and writing your own HTML code instead.

Using the JavaScript helper files

If you need greater control on the object tag or the installing/upgrading process, you can use the JavaScript method.

The JavaScript method makes use of a helper file called Silverlight.js, which can be found in the Tools directory under the Silverlight SDK folder usually located at C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Tools.

Once referenced, the Silverlight.js file creates a class called Silverlight, which will provide you with different methods and properties related to Silverlight, such as Silverlight.CreateObject, Silverlight.IsInstalled, and more.

Adding Silverlight using JavaScript is out of the scope of this book, but you can find all the information you need for it on MSDN at http://msdn.microsoft.com/en-us/library/cc265155(v=vs.95).aspx.

Silverlight's interaction with JavaScript certainly doesn't end here. In Chapter 6, Interacting with the Host Platform, we will discuss many features of Silverlight-JavaScript-HTML integration, such as calling a JavaScript method from Silverlight, calling a Silverlight method from JavaScript, manipulating the Document Object Model (DOM) from Silverlight, accessing cookies, and more.

As you might recall, we have mentioned earlier in this chapter that Silverlight isn't limited to running inside the browser anymore. This new concept, called out-of-browser applications, was introduced back in Silverlight 3 and got heavily enhanced in Silverlight 4, so introducing it now would be the perfect way to finish off this chapter.

 

In and out-of-browser support


Silverlight started its life as an in-browser technology offering rich UX, media playing capabilities, and animation. Starting with Version 3, Silverlight gained the ability to run applications outside the browser, as sandboxed desktop applications. In Silverlight 4, the out-of-browser feature gained a serious boost with the introduction of "elevated trust". Not only can you now access local files and folders on the user's computer (pending his/her approval for your application to run in elevated trust mode) but you can also use COM automation to connect to other applications, for example Microsoft Office. Other important features of out-of-browser applications are toast notifications (a notification API), full screen mode support (for kiosk-based applications), and complete control over the application window. A great example for an out-of-browser Silverlight application is Seesmic Desktop 2, which you can see in the following screenshot:

While we won't go into detail here on how to create and work with out-of-browser applications, as we have a chapter dedicated to this subject later on, we will address some of the differences between in and out-of-browser applications as follows:

  • In-browser applications have 1 MB of isolation storage quota, as opposed to 25 MB quota for out-of-browser applications. Both quotas can be extended upon a request from the user.

  • Out-of-browser applications cannot interact with JavaScript and the HTML DOM (they don't have any HTML DOM to interact with as they aren't running inside a browser).

  • Out-of-browser applications can interact with the Windows 7 taskbar using COM automation in elevated trust mode and they can be pinned to the taskbar in Windows 7 while in-browser applications cannot.

  • Out-of-browser applications have no initial parameters like in-browser applications.

  • In order to update an out-of-browser application, the developer is required to implement a check for a newer version in his code, whereas in browser applications, it is done automatically.

The installation process of an out-of-browser application is quick and painless; the user either right-clicks on the application surface or chooses install, as shown in the following screenshot:

To make things easier for the user, we can create an installation button that will initiate the installation process. We will discuss this method in Chapter 6, Interacting with the Host Platform of the book.

There is a lot more in the subject of out-of-browser applications and while this chapter only provided a glimpse of the possibilities of the features,Chapter 6, Interacting with the Host Platform, will dive much deeper into it.

 

Summary


With this we will end the introductory chapter of this book. We've learned about what Silverlight is and what we can do with it. We've set up a development environment for Silverlight. We've learned about XAML—what it does and how to use it. We've also looked into the Silverlight application model and learned what a XAP file is and what it contains, and we finished off with an introduction to the integration of Silverlight with HTML and the concept of out-of-browser applications.

I hope that you gained as much as possible from this chapter and grasped all the basics of Silverlight, as we are now ready to move on to laying out a user interface, which is the topic of our next chapter.

About the Author

  • Johnny Tordgeman

    Johnny Tordgeman is the CTO of E4D Solutions Ltd., a boutique development and consulting firm in Israel. Johnny specializes in architecting enterprise-level solutions built on top of Microsoft's SharePoint platform. Johnny utilizes the latest in web technology and methodology in his solutions, such as HTML5, SPA, and MVC4. Johnny is the author of MCTS: Microsoft Silverlight 4 Development (70-506) Certification Guide, Packt Publishing, which was published in 2012. Johnny is a skilled lecturer and a Microsoft-certified trainer and can be found speaking at various conferences, open houses, and user groups. You can always find Johnny at http://blog.johnnyt.me, on Twitter at @JTordgeman, and on LinkedIn at http://www.linkedin.com/in/johnnytor.

    Browse publications by this author
Book Title
Access this book, plus 7,500 other titles for FREE
Access now