Click here to monitor SSC
  • Av rating:
  • Total votes: 12
  • Total comments: 9
John Bower

Let there be Silverlight

05 January 2008

John Bower stays calm, and so will you, whilst guiding you to producing your first Silverlight application. It may just be 'Hello World' but soon...

 

Hi-Oh Silverlight

My first Simple-Talk article on Silverlight is geared towards running through  the basic requirements for working with Silverlight, Microsoft’s latest addition to .NET, so as to get you up and running quickly

If you have any experience with Flash and/or .NET programming languages such as Visual Basic, or C#, Silverlight should be of some interest. It’s an efficient and suitable alternative to Flash that makes use of the Windows Presentation Foundation. It will appeal to those people who want more from their interactive experiences, or who are unsettled by Adobe’s acquisition, (and subsequent “Adobifying”), of Macromedia’s most popular piece of software. It has immediate attractions for the application programmer because of the ease with which one can access data from SQL Server

Even with prior Flash or .NET experience, though, you will be forgiven for the initial reaction of total bafflement with the development process. It isn’t that intuitive.

Unlike Flash, Silverlight development requires several applications. Whereas Flash authoring can be achieved solely within the Flash Development Environment, Silverlight requires VB or C# for coding, and Microsoft’s Expression Tools for graphical assets and video compression. Silverlight is also very different to Flash in that an SWF file is self-contained, and complex Silverlight projects can require a plethora of separate code and XAML files that coalesce into the end-user’s experience.

Silverlight Years Ahead

Because Silverlight is still under development, and so the paint isn't always dry. It also means that a lot of possibly useful features haven’t been included yet: Most of the time you will need to do a certain amount of code ‘hacking’ in order to work around certain issues. Reading from external text files, for example, is currently impossible unless you give them a mock XML file extension, and you parse them using XML string commands. I’ll cover this workaround in a later article.

Also, because Silverlight is so new, it is unlikely that your target audience even has the 11Mb runtime installed. It is included in the .NET 3.5 update but, as I’ve learned from personal experience, the little yellow shield icon in the system tray, along with all the other bric-a-brac,  remains a mystery to a majority of end-users!

Not only that, but the web server hosting your pages online must have .NET 3.5 extensions installed too. Later in 2008 this may be more common, but so far it’s only specialist servers, such as http://www.discountasp.net/., that can offer this. This will soon change, though

“So what’s the point in developing something if people can’t use it?”, I hear you wail.

The point is this: Silverlight is considerably more powerful than Flash. You can easily develop a browser-based application that interacts with SQL Server, and everything runs a LOT faster. Although it is currently unsupported by the majority of PCs, you will soon find it hard to avoid, as it will eventually be forcefully pushed out in future Windows updates.

So, without further ado, this is how to get Silverlight up and running on your computer.

Heading towards the  Silverlight

Before we start installing anything, I must point out that Silverlight makes use of hidden JavaScript extensions, which some Anti Virus programs will regard as suspect, and will simply not allow to be accessed, If you have any problems starting a Silverlight project, you should check your Anti Virus program first. There may be an option to ignore hidden JS extensions in most ‘pro’ versions.

1)     Update .NET on your computer

It should go without saying really, but there is no harm in repeating the fact that you will need to make sure you have .NET 3.5 installed on your computer, otherwise Silverlight will not work.

2)     Download Visual Studio 2008

If you don’t already have Visual Studio 2008, (or “Orcas”, as it’s affectionately known among the programming under-class), you simply need to follow (This link here) to the Visual Studio website, and download one of the 180-day trial versions .Unfortunately, Microsoft’s cut-down Express versions do not currently support Silverlight, but that is liable to change in the future when Microsoft makes Silverlight more accessible to developers.

Both VB and C# can be used to write Silverlight applications. I will supply VB and C# example code in future Silverlight articles but for the purposes of this tutorial we’re sticking to VB.

3)     Download the latest Silverlight runtime

As of the time of writing this article, the latest Silverlight runtime is the Alpha 1.1 Refresh, which can be downloaded by clicking This link

I assume all Silverlight runtime releases will be available from the above site, but there is a link to download it from the official Silverlight website if in doubt

4)     Download the Silverlight project templates for Visual Studio

Again, available from the Microsoft website, the templates allow you to start a new Silverlight project from the New Project wizard inside Visual Studio 2008. Although not vital, they’re worth downloading as they save a lot of effort in the long run. The templates are available via This link

5)     Optional: Download Microsoft Expression Blend 2

You should be ready to go, but if you require graphical assets (which would be nice!), click This link to download Expression Blend 2. This will allow you to create vector-based assets and export them in XAML format to use in your Silverlight application. We won’t be using Expression Blend for this tutorial, but it is handy to have for future ones.

Phew! That’s the easy bit out of the way! Now to get coding!

Your first Silverlight project (Hello World!)

Start Visual Studio 2008 and click File > New Project

If all has gone well so far, you should be presented with a New Project dialog box that looks similar to this:

Choose a suitable location to save your project files in by clicking the “Browse” button, and pick a name for the project. Then click “OK”, and Visual Studio will create the project based on the files contained in the Silverlight template Zip file (the location of this file is usually: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\VisualBasic\Silverlight\1033\).

Note: This is where your Anti-Virus application may throw an error. If it does, you will need to uninstall it and\or get one that allows hidden “JS” file extensions.

Visual Studio will create five files and a ClientBin folder for you, and will then list them in the Solution Explorer. If you want to dive in to the Silverlight quagmire of inter-file references, you can rename them, but for the purposes of this tutorial we’ll keep them as they are.

Page.xaml
contains information about the layout and design of the application in a format similar to XML. In this file you can specify such things as the background colour, embedded controls, and names that you can reference in your code. This file is referenced by TestPage.html.js, so if you rename it, you will have to edit the reference. Visual Studio has created a Canvas tag, which is basically the container for your controls, and all the controls of your application will go within the Canvas tag. It’s worth making a mental note of the “Loaded” parameter and the “x:Name” parameter for later. I won’t go into the full structure of XAML files here because it has been covered before in other articles, e.g. Getting started with XAML, and anyone who has written XML or HTML should be familiar with the tagging syntax already.
Page.xaml.vb
is the code that is interpreted on the server. It contains the logic that makes the XAML file interactive. This is where we do most of the work in a Silverlight application.

You will notice that there is one function already filled in for you called “page_loaded”. This function is referenced by the Canvas’ “Loaded” parameter in the XAML file, and will run when the Canvas is… loaded!
Silverlight.js
is a JavaScript file that contains helper information for detecting web browsers and for compatibility checking. Microsoft have cunningly written this file without any spaces to make it more difficult to read. Luckily, however, you won’t need to do any editing to this under most circumstances. It is referenced by the HTML page hosting your application.
TestPage.html.js
is another JavaScript file referenced by the HTML page hosting your application. The most useful function in this file is “createSilverlight()” which, if you hadn’t guessed, creates your embedded application. In this file you can specify which XAML file to load when your application starts. If you rename this file you will need to edit TestPage.html.
TestPage.html
is a simple HTML file that contains your embedded application. This is the page that needs to be accessed by your end user’s web browser, so it is likely that you will end up renaming this to something like “index.html” in future projects.

Now you have your files, press F5 (or Start Debugging) to see what happens…

If Internet Explorer runs with a blank page, and “Silverlight Project Test Page” as the title, give yourself a pat on the back! You can change this title in the HTML file’s header section if you think your back deserves another patting.

Now, let’s make it do something interesting! We are going to create a TextBlock in the XAML file, give it a name, and then reference it in the XAML.VB file so we can change the text it displays.

  1. Open Page.xaml, and add <TextBlock> and </TextBlock> tags between the Canvas tags.
<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="HelloWorld.Page;assembly=ClientBin/HelloWorld.dll"

        Width="640"

        Height="480"

        Background="White"

        >

  <TextBlock></TextBlock>

</Canvas>

You may notice that Visual Studio’s context sensitive helper will save you a few valuable seconds, and possibly a calorie or two, by filling the tag out for you. Now you have your TextBlock, you need to give it some text to display.

  1. Between the TextBlock tags type “Hello World!”.

<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="HelloWorld.Page;assembly=ClientBin/HelloWorld.dll"

        Width="640"

        Height="480"

        Background="White"

        >

  <TextBlock>Hello World!</TextBlock>

</Canvas>

Now hit F5 and see what happens.

Well done! You’ve created your first Silverlight application that does something! Ok, don’t get too excited, that’s just scratching the surface. What we’ll do now is write some code that changes the text after the page loads.

This is where the Canvas’ “Loaded” parameter, and the TextBlock’s “x:Name” parameter come into use. Firstly we will need to create the “x:Name” parameter for the TextBlock.

  1. Add x:Name=”myText” in the TextBlock’s opening tag

<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="HelloWorld.Page;assembly=ClientBin/HelloWorld.dll"

        Width="640"

        Height="480"

        Background="White"

        >

  <TextBlock x:Name="myText">Hello World!</TextBlock>

</Canvas>

 

 

When you’ve done that, save the file.

Now that the TextBlock has a name, we need to reference it in the Page.xaml.vb file, and change the text parameter to something else when the page is loaded.

  1. Open Page.xaml.vb and add the following line to the “Page_Loaded()” function.

Public Sub Page_Loaded(ByVal o As Object, ByVal e As EventArgs)

   ' Required to initialize variables

   InitializeComponent()

 

   myText.Text = "Hello Silverlight!"

 

End Sub

Hit F5 and see what happens.

The TextBlock still displays “Hello World!”, but once the page has loaded it changes it to “Hello Silverlight!”. This happens before the TextBlock is even rendered, so you can replace “Hello World!” with an extraordinarily inappropriate phrase that would bring displeasure and offence to any sensitive person if you wish, as no one will know!

(Ed: The readers will remember our account of the letter that went to the best customers of a major bank entitled ‘Dear Rich Bastard’, due to a similarly misplaced confidence that nobody would ever see it)

Congratulations! You are now able to update parameters within your code. This is a fundamental part of Silverlight that will prove very useful in any future project you make. Using this technique you can update parameters for any object within your application, be it screen location, colour, font, or anything else for that matter.

This application may seem extraordinarily trivial but, if you have followed all the instructions, you will now have the means to produce real Silverlight applications.

In the next tutorial I will help you to enhance your applications by demonstrating how to set up a loop within Silverlight so you can trigger functions repeatedly for continuous animations, games, and data exchanges.

An alternative to the basic method of manually adding resources directly to a XAML file is to add them at run-time, after the Canvas has loaded. This allows us to create much more dynamic applications. In the next article John Bower will use this more advanced method to create a Storyboard that acts as a high-speed loop - calling a function every few thousandths of a second - to move an Image resource around your Canvas.

John Bower

Author profile:

John Bower spent six years as Lead Web Designer at FreshEgg before getting an MA in 3D Computer Animation at the National Centre of Computer Animation, UK. He is now running DeepSpaceObjects consultancy, specialising in Flash Development and has contributed to a number of celebrity and business websites.

Search for other articles by John Bower

Rate this article:   Avg rating: from a total of 12 votes.


Poor

OK

Good

Great

Must read
Have Your Say
Do you have an opinion on this article? Then add your comment below:
You must be logged in to post to this forum

Click here to log in.


Subject: Hello end-of-the world
Posted by: Anonymous (not signed in)
Posted on: Tuesday, January 08, 2008 at 3:57 PM
Message: Hi.

'Hello world' is a bit trivial, and done well elsewhere. That's not to take anything away from John who writes well. However, SL is being geared toward providing a replacement for browser based user interfaces. Wake up and smell the coffee, it's a coming together of dot Net, WPF and the Internet as the network. Imagine, creating a cross-browser, cross hardware, cross device dev app without the need to hack thru browser differences or kludge code for DOM level support. Put another way, if you are the architect for a web based app project that is at design stage, if you don't have a SL strategy then don't be surprised when the world is under whelmed by your baby. In 12 months, if you aren't involved in SL dev then you'll have fallen down the back of the wave. It's a new millennium, 8 years late !

So, John, how about looking at the architecture to lay down in a SL project to support team development for multi-lingual, multi-locale, skin-able, configurable, modular apps?

Good article, but you can make the next one so much better.

TK/JEE

Subject: Too much kool-aid
Posted by: si (not signed in)
Posted on: Tuesday, January 08, 2008 at 8:45 PM
Message: Mr Anonymous seems to have drunk too deeply from the MS well of hype...SL adoption outside of MS has been pitiful, cross browser/hw/device? Come on!!! I can imagine how it will fly on a mobile or PDA running .NET 3.5 or on a Mac running Safari.

Sure, keep an eye on SL, but I'm far more interested in MS MVC, which at least opens up options in the presentation layer.

Subject: But… Windows isn’t the only game in town…
Posted by: René Kabis (not signed in)
Posted on: Wednesday, January 09, 2008 at 1:15 AM
Message: Nice, but what about Linux? What about MacOSX? What about HaikuOS? What about BSD? These all have Flash capabilities, and so can support Flash apps.

Silverlight? Windows-only, and for the foreseeable future, too.

NOT a good start, especially when Mac usage alone has more than doubled in the last 5 years to nearly 10% of all computers out there.

That’s one in ten people. And as any CEO or COO can tell you, you don’t turn away one in ten customers and still manage to stay in business. So I suspect it will be a *long* time before this becomes a viable alternative (in the commercial realm) to Flash.

Subject: Silverlight is a revolution.
Posted by: Peter Adriaenssesn (not signed in)
Posted on: Wednesday, January 09, 2008 at 3:09 AM
Message: Silverlight is a revolution.

Subject: Re: merits of Silverlight
Posted by: Phil Factor (view profile)
Posted on: Wednesday, January 09, 2008 at 3:26 AM
Message: Whatever the merits of Silverlight, it is definitely worth checking it out. The editor asked John to start off with an article that gives simple instuctions so that anyone can get up and running, and get familiar with the basic technology. ...Like it or not, it will be around.

Subject: Not windows only
Posted by: Mr Leopard (not signed in)
Posted on: Wednesday, January 09, 2008 at 4:48 AM
Message: Hi,
I have successfully run Silverlight (1.0 and 1.1 alpha) on both Safari and Firefox in Mac OS X, so Silverlight is definitely something to consider for mulit platform.
As for Linux, there are the Moonlight project that I hope will be a success:
http://www.mono-project.com/Moonlight

It will be around..

Subject: SDK
Posted by: Max (view profile)
Posted on: Wednesday, January 09, 2008 at 6:12 AM
Message: Hi

I read thru the article (I'm a newbie to SL and I found it explains the basic "what" and "how"). I have a question: What is the role of the SL sDK (http://www.microsoft.com/downloads/details.aspx?familyid=FB7900DB-4380-4B0F-BB95-0BAEC714EE17&displaylang=en) in the SL development environment ?

Subject: Mac - 10% of all users
Posted by: Anonymous (not signed in)
Posted on: Wednesday, January 09, 2008 at 9:15 AM
Message: Hardly. The Apple marketing department is feeding you well me thinks.

Subject: Hello end-of-the world II
Posted by: TK/JEE (not signed in)
Posted on: Wednesday, January 09, 2008 at 2:14 PM
Message: Interesting feedback. I could make a broad assumption that some of my correspondents are not reading up enough on the subject. Joking apart, they may want to read the perceptive article by Pete Brown at

http://community.irritatedvowel.com/blogs/pete_browns_blog/archive/2008/01/08/Why-Silverlight-2.0-will-Change-How-We-Build-Applications.aspx?CommentPosted=true#commentmessage

@si - Moi an MS stooge? No way, I'm as sceptical as the rest. I'd have hitched myself to RIAs built in Flash if SL had not come along. But whilst flash has penetration, it's the lack of a robust and well thought out dev environment and the ridiculous reliance on Java technology that makes Flex ultimately doomed....

@René Kabis: ...to the go the way of the MAC - a nice diversion for the arty and anti-establishment types but a lost dollar opportunity and thorn in the side of many. Also, seeing that MAC adoption has reached a huge 10% then it doesn't have very far to go to reach par with Windows (sic)...anyway how many more sales to reach 20%. ;-). As any CFO will tell you, he'd rather have 90% of the sales whilst producing a compelling product (with half the workforce cost) that is achieved by not having to code to the lowest common denominator, thereby driving up profitability, share price and personal gain. If you want to sell to where the money is then you are writing corporate apps - the MAC just ain't there. MVC ? Maybe, but cursed by the same browser based UI. Sure you can bloat it out with Ahax, but you will be chasing bugs for the rest of your life which just is not profitable use of time. This tedious following of trends by the MS dev team is simply a spoiler to stop anyone else building an empire, the long game must be to abandon reliance on browser UI's and adopt a more robust plug-in UI e.g. SL.

And LinuX, by any measure that stacks up in a commercial sense - sorry what ?

In 2 years time those of us with worthless CV's boasting about our ability to cross-browser hack who failed to catch the SL bandwagon are going to wonder what they've been doing for the last 10 years and how we became unemployable. Wake up, smell the coffee or whatever metaphor you subscribe to.

Finally poser - anyone think it odd that SL marketing is low volume? Methinks a viral marketing campaign is afoot. Come on MS, crank the handle a bit faster and get the tech-focussed info out for the lads!

 

Top Rated

Acceptance Testing with FitNesse: Multiplicities and Comparisons
 FitNesse is one of the most popular tools for unit testing since it is designed with a Wiki-style... Read more...

Acceptance Testing with FitNesse: Symbols, Variables and Code-behind Styles
 Although FitNesse can be used as a generic automated testing tool for both applications and databases,... Read more...

Acceptance Testing with FitNesse: Documentation and Infrastructure
 FitNesse is a popular general-purpose wiki-based framework for writing acceptance tests for software... Read more...

TortoiseSVN and Subversion Cookbook Part 11: Subversion and Oracle
 It is only recently that the tools have existed to make source-control easy for database developers.... Read more...

TortoiseSVN and Subversion Cookbook Part 10: Extending the reach of Subversion
 Subversion provides a good way of source-controlling a database, but many operations are best done from... Read more...

Most Viewed

A Complete URL Rewriting Solution for ASP.NET 2.0
 Ever wondered whether it's possible to create neater URLS, free of bulky Query String parameters?... Read more...

Visual Studio Setup - projects and custom actions
 This article describes the kinds of custom actions that can be used in your Visual Studio setup project. Read more...

.NET Application Architecture: the Data Access Layer
 Find out how to design a robust data access layer for your .NET applications. Read more...

Calling Cross Domain Web Services in AJAX
 The latest craze for mashups involves making cross-domain calls to Web Services from APIs made publicly... Read more...

Web Parts in ASP.NET 2.0
 Most Web Parts implementations allow users to create a single portal page where they can personalize... Read more...

Why Join

Over 400,000 Microsoft professionals subscribe to the Simple-Talk technical journal. Join today, it's fast, simple, free and secure.