After having read part 2 of this tutorial you know how to create a very simple Silverlight application in XAML, displaying some text in the browser. Let's see now how XAML actually works together with C#.
After having read this part you will:
- know how to add content to your application both in XAML and in C# code,
- understand how XAML works together with C#,
- know when to use XAML and when C# in your application.
Let's get started!
One thing you will immediately notice during your Silverlight adventure is that you can very often do the same thing in many different ways and using different tools. This is great news because everyone have their habits and preferred programming methods, and it is important the tools allow everyone do their job the way they like.
XAML vs C#
Remember our "Hello World" application from the the previous part? You didn't write a single line of C# code, everything was written in XAML. Open the Page.xaml file. The code looks like this:
<UserControl x:Class="HelloWorld.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="Yellow">
<TextBlock Text="Hello World!"
VerticalAlignment="Center"
HorizontalAlignment="Center" />
</Grid>
</UserControl>
Remove the TextBlock from XAML now:
<UserControl x:Class="HelloWorld.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="Yellow">
</Grid>
</UserControl>
You'll notice that the "Hello World!" text is now gone in the designer preview in Visual Studio. And indeed, it is gone when you run the application. Switch to the Page.xaml.cs file now, and put the following code in the Page constructor:
public Page()
{
InitializeComponent();
TextBlock text = new TextBlock()
{
Text = "Hello World!",
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
LayoutRoot.Children.Add(text);
}
You just replaced some XAML with some equivalent C# code. You still cannot see the "Hello World!" text in the preview of the Page.xaml file, but when you hit F5, you can see the text is displayed as it was before. That's because the designer preview only parses XAML code and displays its preview. It doesn't execute the entire constructor of your control. But how is XAML actually parsed? Let's have a closer look at this.
XAML behind the scenes
Whenever you're dealing with a class that has both XAML and C# code, there's the InitializeComponent method that should be called in the very first line of the class's constructor. And indeed, it is there for you if you create a new class with the Visual Studio wizard. It is automatically generated for you by Visual Studio whenever you modify the XAML code. If you want to see where exactly this method is defined, turn on the Show All Files option in your project. In the obj/Debug subdirectory of the project you can find these two files: App.g.cs and Page.g.cs.
These are auto generated files, one for each class that contains XAML. If you open Page.g.cs, you will see it contains partial definition of the Page class. The Page class contains the definition of the InitializeComponent method. It also has a field for every element that has the x:Name attribute in the Page.xaml file. For example, it contains an internal field called LayoutRoot that is of type Grid, as defined in XAML:
<UserControl x:Class="HelloWorld.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="Yellow">
</Grid>
</UserControl>
What InitializeComponent does is: it takes all controls defined in XAML, creates instances of them and sets all the properties you set in XAML. It does all the same you would do if you wrote the C# code manually. In our example when an instance of the Page class is created, InitializeComponent sets Page's Width and Height properties. It also initializes the LayoutRoot field with a new instance of the Grid class, and sets its background to yellow. And because the Grid control is inside of the Page control in XAML, the Grid control is set as the Content property of the Page control.
Now try commenting out the InitializeComponent method call in Page's constructor (in the Page.xaml.cs file). When you run the application it crashes with a NullReferenceException at this line:
LayoutRoot.Children.Add(text);
If you debug the code you can see it crashes because LayoutRoot is null. LayoutRoot has never been initialized because InitializeComponent has never been called.
If you want to get rid of all the XAML code and the InitializeComponent method call in your Page control, you can translate all your XAML to C#. You can do it in the Page.xaml.cs file like this:
public class Page : UserControl
{
internal Grid LayoutRoot;
public Page()
{
Width = 400;
Height = 300;
LayoutRoot = new Grid()
{
Background = new SolidColorBrush(Colors.Yellow)
};
Content = LayoutRoot;
TextBlock text = new TextBlock()
{
Text = "Hello World!",
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
LayoutRoot.Children.Add(text);
}
}
Now everything is in C# and we don't use XAML at all (the content from the Page.xaml file is never instantiated). Notice now the entire class is defined just in one place and is not marked as partial anymore. When you used XAML, the class had to be defined as partial, because the other part of the class was defined in the auto generated Page.g.cs file.
If you want the above code to work in your project, you have to also comment out the partial Page class definition in the Page.g.cs file. Otherwise Visual Studio will complain the class is defined twice. Of course, if you modify the Page.xaml file, the Page.g.cs file will get regenerated and your code will stop working again. If you want to get rid of XAML permanently, you should remove the Page.xaml file from the project while keeping the Page.xaml.cs file. If you try to do it in Visual Studio, you'll notice these two files are "grouped" together and you cannot just remove the *.xaml file. To "ungroup" them, you have to open the project file HelloWorld.csproj in a text editor, find this part:
<Compile Include="Page.xaml.cs">
<DependentUpon>Page.xaml</DependentUpon>
</Compile>
and delete the <DependentUpon> element:
<Compile Include="Page.xaml.cs">
</Compile>
Now you should be able to reload the project in Visual Studio and delete the Page.xaml file while keeping the Page.xaml.cs file.
As you probably noticed, some controls have Content property (in our example Page) and can only have one element set as their child. Other controls have Children property (in our example Grid) and can have entire collection of child controls. When you nest controls inside each other in XAML, the XAML parser acts smart and either sets the inner control as the Content of the outer control, or adds the inner control to the Children collection of the outer control. It all depends on which property is available in the outer control.
Another thing you probably noticed is that the Background property of Grid is of type Brush but in XAML it is initialized simply by color name. This is a shortcut.
This XAML code:
<Grid x:Name="LayoutRoot" Background="Yellow">
</Grid>
is equivalent to this one:
<Grid x:Name="LayoutRoot">
<Grid.Background>
<SolidColorBrush Color="Yellow" />
</Grid.Background>
</Grid>
which in turn translates to this C# code:
LayoutRoot = new Grid();
LayoutRoot.Background = new SolidColorBrush(Colors.Yellow);
There are more shortcuts like this that make XAML code more compact than C# code :)
Which way to go?
At this point you are probably confused and don't know when you should use C# and when XAML. Remember, everything you write in XAML, you can write in C# too. The code above is an example. You removed the TextBlock control from XAML and instantiated it in C# instead, giving it the same properties as previously in XAML. The final result is exactly the same. There are however some differences:
-
With XAML you usually write more compact code than with C# (approx. 90 characters vs approx. 180 characters in the example above).
-
With XAML you can see the results in the designer preview without running the code and you cannot see the preview of the C# code.
-
XAML is for static code only, you cannot create controls dynamically (for example create a random number of buttons) but you can do it with C#.
-
XAML is parsed at runtime, so not all errors are caught when the code is compiled. For example, if you try to nest two Grid controls in one Page control, the code will compile and run, and generate a runtime exception: XmlParserException with some obfuscated, not user friendly message. In C# it is simply not possible to make such a mistake. This makes XAML code more difficult to debug than C# code.
As you see, in some more advanced cases you need to write C# code, because you cannot do everything with XAML. But sometimes you have choice and it's up to you how you write your code: in XAML or C#. I think it is important you learn both. Of course, you can act like an old school programmer and stick with the "real" C# code, ignoring XAML completely, and you can write entire applications this way. However XAML usually allows you to code faster, making you more productive. If that doesn't convince you, your UI designer should convince you. Whoever they are, they won't be able to read your C# code. But they can open your XAML code in Expression Blend, and make your application's UI look cool with a few clicks. I will explain how to do that later on.
Silverlight project build process - the big picture
I mentioned the mysterious XAP file before so let's have one last look at what happens when you rebuild your project. You have a bunch of C# files (both written by you and automatically generated for you by Visual Studio), and some XAML files. They are all compiled into a DLL file and the AppManifest.xaml file is generated. You can find them in the Bin/Debug subdirectory of your project. These files are then gathered together and compressed to one ZIP file.. that has the XAP extension. Yes, a ZIP file. If you take the HelloWorld.xap file and rename it to HelloWorld.zip, you can open it by double clicking and see its contents. The TestPage.html file is also generated. In our case the local machine acts as the server that contains TestPage.html and HelloWorld.xap, but you can copy these two files to a real remote HTTP server. Now that you have your Silverlight application published, either locally or on a real server, you can request the TestPage.html from a browser. It references the HelloWorld.xap file so the browser will run the Silverlight plugin which will download the XAP file. When the file is downloaded, Silverlight will extract it and read the AppManifest.xaml file. It contains information which DLL Silverlight needs to load and which class to instantiate first (by default it's the App class). Once an instance of the App class is created, the Silverlight application starts to execute.
Summary
At this point you should feel comfortable with XAML and C#, and using both in your Silverlight projects. You also have the big picture of what happens when you hit F5 - from compiling your code to executing it by the Silverlight plugin.
The source code of the modified "Hello World" application (written in C# without using XAML): HelloWorldWithoutXaml.zip
After having read part 1 of this tutorial you already know a Silverlight application is actually an executable hosted by the Silverlight plugin, client side, in user's browser. It's time you created your first application and had a closer look at it.
After having read this part you will:
- know where to find everything you need to get started with Silverlight,
- know how to create a "Hello world" application and understand what is inside,
- know how to embed the "Hello world" application in a website.
If you already know all of that, you can skip this part and move on straight to the next part.. Silverlight Basics #3: All roads lead to Rome - mixing XAML and C#.
Let's get started!
The Silverlight's home is here: http://silverlight.net. You will find all the resources to get started here: downloads, discussion forums, code samples, tutorial videos and much more. To start developing Silverlight applications you need these:
- Visual Studio 2008 with SP1 (the service pack is very important) or Visual Web Developer Express with SP1
- Silverlight Tools for Visual Studio 2008 SP1
These are the two essential things. There are of course more Silverlight related tools you can optionally download as well but we won't be using all of them here. I will be showing you how to use Blend later on, so it's useful if you install it as well:
- Expression Blend 2
- Service Pack 1 for Expression Blend 2 (once again, the service pack is very important)
Now go ahead, and get them all!
Creating a new Silverlight project
Now that you have everything setup and ready, it's time to make use of it. Open your Visual Studio 2008 SP1, and create a new Silverlight project:
- Press Ctrl+Shift+N (or choose from menu: File » New » Project...). A New Project dialog window pops up:

- In the New Project window:
- Choose the project type on the left side: expand Visual C# and then click Silverlight.
If you can't see Silverlight on the list of supported Visual C# project types it means you didn't install Silverlight Tools for Visual Studio 2008 SP1 correctly. Try to close and reopen Visual Studio. If that doesn't help, close Visual Studio. Open Control Panel, select Add or Remove Programs (XP) or Programs and Features (Vista) and remove Microsoft Silverlight Tools for Visual Studio 2008 SP1. Then go back here, and install it again.
- On the right side, choose the Silverlight Application template.
- Name the project HelloWorld. Fill in the solution name and path as usual and click OK.
- An Add Silverlight Application dialog window pops up:
All this dialog box is asking you about is how you want to run your new application. As you remember from part 1, Silverlight application is hosted by a browser plugin, so it is embedded inside of a website. You cannot just run it standalone. You need a web page, with some HTML and a special Silverlight object embedded inside that HTML. You can create this web page manually or let Visual Studio take care of it, so that you can run your application by clicking Run. If you let Visual Studio do it, this dialog box asks you how you want your web page to be created. You can use a static HTML page that Visual Studio will generate for you each time you build your Silverlight Application. Or you can create an ASP.NET website. As you remember from part 1, ASP.NET is a server side technology and it generates HTML on the fly. ASP.NET website is more flexible and powerful but a bit more complex (you have to manage both server side and client side stuff in one solution). We will need it later, but for now let's just go for the simpler option.
In the dialog window choose Automatically generate a test page to host Silverlight at build time, and click OK.
Running the Silverlight project
At this point you should have an empty Silverlight project with the structure similar to this:

Now hit F5 to run the application. An Internet Explorer window shows up with an empty white page. To make sure it's actually a Silverlight application and not just an empty file, right click on the page. Instead of the familiar standard Internet Explorer popup menu you see the Silverlight popup menu, with only one element: Silverlight Configuration.
This means you clicked inside of the Silverlight plugin content. If you click Silverlight Configuration, you can set some options and check the version of Silverlight you have installed on your computer. The latest version at the moment I'm writing this is: 2.0.31005.0.
Embedding the Silverlight application in HTML
If you check the address of the page you opened by hitting F5, you can see it's just an HTML file, stored locally on your hard drive. Something like this:
C:\MySilverlightApps\HelloWorld\HelloWorld\Bin\Debug\TestPage.html.
You can open this file in any text editor or open it in Visual Studio (after you turn on Show All Files for your project). If you open it, you can see it is just a standard HTML file, nothing fancy there, except for one element:
<object data="data:application/x-silverlight,"
type="application/x-silverlight-2"
width="100%" height="100%">
<param name="source" value="HelloWorld.xap"/>
<param name="onerror" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="2.0.31005.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=124807"
style='text-decoration: none;'>
<img src="http://go.microsoft.com/fwlink/?LinkId=108181"
alt="Get Microsoft Silverlight"
style="border-style: none"/>
</a>
</object>
This is how Silverlight applications are embedded in HTML: as objects. In this case there is only one object that takes up 100% of the window content. When your browser downloads HTML like this and parses it, it looks up the data and type of the object (application/x-silverlight) and runs the Silverlight plugin. The plugin takes care of the rest. It takes the parameters and knows how to display your application. In this example the plugin knows the application is in the HelloWorld.xap file (we will talk about what it is later) and the minimum Silverlight version for it to run is 2.0.31005.0. In case you don't have the required version of Silverlight installed on your computer, you will see an image with a link to the Silverlight download page. If your application encounters any problems, Silverlight plugin will notify you by calling the onSilverlightError Javascript function, which will display the error message.
You can modify this HTML file. Try for example putting this piece of HTML above the Silverlight object:
<p style="background-color: orange">Below is my first Silverlight application:</p>
Save the file but don't hit F5. Instead, just open the file in Internet Explorer. Notice the orange strip at the top of the page. If you right click on it, you will see a standard Internet Explorer menu. This is just simple static HTML content: you can copy the text, view HTML source etc. However when you right click on the white area below, you will see it is Silverlight content. Now you know how to mix HTML and Silverlight content on one page. But you have to remember one thing: the file you edited is just a simple test page for your application and is regenerated each time your project is built. Rebuild your project, and the changes you made are gone. If you need to embed your Silverlight application in a more fancy webpage than just an empty test page, you either have to create the webpage manually and embed the object manually (you already know how), or use the other option when creating a Silverlight project: Add a new ASP.NET Web project to the solution to host Silverlight.
Adding content to the Silverlight application
An empty white application gets boring quite quickly, so let's see how to add some content into it. As you probably already noticed, there are two classes in your HelloWorld project.
Open the App.xaml.cs file. The App class inherits from the Application class and it simply represents the entire Silverlight application. It has a method ReportErrorToDOM that displays Silverlight messages on the website through JavaScript. It also handles all uncaught exceptions by handling the UnhandledException event. And finally, on startup it sets the RootVisual property to a new instance of the Page class. RootVisual is the main element that displays application's content. By setting RootVisual to any UIElement, we say "display whatever this UIElement displays".
Open the Page.xaml.cs file now. The Page class is simply a user control. It could be named whatever, "Page" is just a name chosen by Visual Studio when it creates the first control for you. For your convenience, the Page class consists of two files: one for XAML definition and one for code. But you can as well create controls that do not contain XAML at all. Switch to the Page.xaml file now. You can see something like this:
<UserControl x:Class="HelloWorld.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
</Grid>
</UserControl>
Page is our root control, and it inherits from UserControl (as you saw it already in the Page.xaml.cs file). Its type is defined by the x:Class attribute. And its size is 400x300 pixels. Whatever content we want to display in the application, it needs to be inside of this control (in XAML) or set as the Content property of this control (in code). But it can only contain one element, for example one button only. Now you ask, what if I want to create more buttons? There are specialized controls that can contain more than one element as their content and we will talk about them later. Right now you should only know one of those controls is called Grid. That is why Visual Studio put a Grid for you in the Page class. You can now add some content to the Grid. Try putting some text inside. There is a TextBlock control you can use (new code highlighted with yellow marker):
<UserControl x:Class="HelloWorld.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Text="Hello World!"
VerticalAlignment="Center"
HorizontalAlignment="Center" />
</Grid>
</UserControl>
Hit F5 now and run the application. Yay, we finally display something! But why isn't the text centered on the screen? Wasn't the Silverlight plugin supposed to take up 100% of the window? Yes. The Silverlight plugin takes up entire window (you can easily check it by right clicking wherever and see it's still the Silverlight, not HTML, content). But the Page control was told to be 400x300 pixels size. Try changing its color to see where it actually fits:
<UserControl x:Class="HelloWorld.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="Yellow">
<TextBlock Text="Hello World!"
VerticalAlignment="Center"
HorizontalAlignment="Center" />
</Grid>
</UserControl>
Hit F5 now. You should now see exactly where the Page control fits on the screen. Our final "Hello Application" looks like this:
If you want the Page to take up the entire window, simply remove the Width and Height properties in your Page control:
<UserControl x:Class="HelloWorld.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid x:Name="LayoutRoot" Background="Yellow">
<TextBlock Text="Hello World!"
VerticalAlignment="Center"
HorizontalAlignment="Center" />
</Grid>
</UserControl>
And that's it! You have just created your first Silverlight application! And without typing a single line of C# code, all in XAML :)
Summary
You now know how to create a new Silverlight project and how to put some simple content into it. You should also understand how a Silverlight application is hosted in the browser window.
The source code of the final "Hello World" application: HelloWorld.zip.
Now it's time to move on to the next step.. Silverlight Basics #3: All roads lead to Rome - mixing XAML and C#
You have probably heard a lot about Silverlight, right? It's been a trendy buzzword recently and a technology that is cool to play with. So if you're looking for a gentle introduction to the Silverlight world, you're in the right place!
This tutorial is for you if:
- You want to learn what Silverlight is and how to start developing Silverlight applications.
- You are familiar with C#, .NET framework and Visual Studio.
- You have some idea about web application development (i.e. you are at least familiar with the basics of HTML).
- It is useful (but not required) if you know the following:
- Flash/Java applets - because both Flash (or Java applets) and Silverlight applications are hosted by browser plugins, so there is a similar programming model,
- WPF - because WPF and Silverlight applications have similar architecture, even though WPF is for desktop application development and Silverlight is for website development,
- JavaScript - because in some advanced scenarios you will want your Silverlight application to interact with your HTML page.
After having read this part you will:
- know what other technologies were used before Silverlight,
- know what Silveright is and how it fits among other technologies,
- know when it is best to use Silverlight over other technologies.
If you already know all of that, you can skip this part and move on straight to the next part.. Silverlight Basics #2: The anatomy of a "Hello world" application.
So let's get started!
As you have probably already heard, Silverlight is yet another technology for creating websites. More accurately, it is a browser plugin that hosts Silverlight applications. Yet another buzzword on the list: HTML, CSS, ASP.NET, JavaScript, DOM, AJAX, ActiveX, Flash etc. And now: Silverlight. If you don't know how all these technologies work together, the next chapter is for you.
How all these web technologies work together?
Let's say you want to share with the world the list of your favorite books. The first approach would be to list the books in a text file and put it on an HTTP server, so that anybody in the world can download it and open with any text editor. Quite easy. But then you decide you want the list to look nice: have images of book covers next to the titles, colorful background and best titles to be in bold. You could use Word to achieve it but then you would limit your audience to people who have Word installed on their computers. So you decide to create a website which users can connect to and open in a browser. You learn HTML and put a nicely formatted HTML file on the server. For a maximum visual effect, including fancy borders around each element on the list, you also learn CSS and include CSS styles in your HTML document.
You receive a lot of emails with positive feedback about your new website but some users would prefer the list to be sorted by author name, and some by publication year. So you create one HTML document for each case: one file with unsorted books, one sorted by author and one sorted by year. But because you read a lot and your book list is long, users finally demand the ability to display only books that contain certain words in the title, so they can easily search for books on your list. Creating a separate file for every possible search phrase is impossible, so you decide to use a server side technology. You learn C# (or VB/PHP/Java/C/C++ etc.) and create your website in ASP.NET (or PHP/JSP/CGI etc.). No matter which technology you use, the final result is the same: you write code in your chosen language (for example C#) and this code in turn generates HTML (and optionally CSS styles as well). There is no HTML file on the server anymore, instead there's code that can generate an HTML file. The server now takes user request (i.e. sort order, searched phrase etc.), generates response on the fly (list of books) and sends it to the browser in HTML format. From the browser's perspective nothing has changed: it just receives an HTML document to display, nothing fancy here. The server takes care of the rest.
This way you can create huge, complex websites with the same functionality as desktop applications. The only difference is user interface. Desktop applications usually have intuitive and user friendly interface, including expandable menus, drag & drop, highlighting elements as you move mouse pointer over them etc. Your application doesn't have all of that and you want to make the elements on your book list expandable: the list initially contains only authors and titles but when you click a book title, it shows more details, including book cover, publisher and publication year. Of course you can send a request to the server to generate a new HTML document with detailed book information every time you click on a book title, but that wouldn't be a good user experience. You would have to wait a few seconds for the new page to download each time you click a book title. So you decide to learn yet another language, JavaScript. HTML is no longer just a static document downloaded by the browser because JavaScript modifies it on the fly. When HTML is downloaded, it is stored in browser's memory as a tree structure called DOM (Document Object Model). It contains HTML elements and CSS styles associated with them. After the website finishes loading, JavaScript takes care of the DOM structure and modifies it to reflect user interaction with the website (for example changes the font color when user clicks an element). Any change in DOM in memory is displayed by the browser on the screen. So now you write C# code that generates JavaScript, HTML and CSS, and the generated JavaScript code then modifies the generated HTML and CSS.
Quite complex, huh? But this is how most web applications look like. Such applications can be indeed hard to test and debug. HTML is more less a standard and works in a similar way in all browsers. But JavaScript adds some spice to developer's life: it varies from browser to browser and you basically end up writing separate versions of your JavaScript code for every browser you want to support. And this is not the end of the developer's nightmare! So far we have reached the state in which user clicks on an element on the page, sends a request to the server and waits for a new page with new content to be downloaded and displayed. This click-wait-display model is still far from being the experience user would have with a desktop application. The solution to this problem is AJAX, which is simply more JavaScript. Now JavaScript not only creates fancy effects on the screen but also asynchronously downloads data from the server in the background. So user doesn't have to wait for an entire new page to be downloaded anytime new data from the server needs to be retrieved. Now they can stay on the same page and continue interacting with it, and new data will be downloaded in the background and displayed when ready. This is heaven for application users - the web application finally behaves like desktop application, has intuitive interface and is easy and pleasant to use.. at the cost of developer's hell and endless sleepless nights when trying to debug their applications. If you ended up being the sleepless developer, it's time you learned Silvelight. It's not a miracle, but it can definitely solve some of your problems (and generate new ones ;).
Why Silverlight?
The previous chapter roughly describes trends in web applications in the last 10 years. There are some parts missing:
- ActiveX - At some point Microsoft came up with a technology to run executables (DLL files) in the context of the browser. The executables weren't standard Windows desktop applications but you created them in a very similar way. You embedded your application in HTML as a special ActiveX object and your application could simply render its content to the region of the browser window occupied by that object (instead of having its own separate window). ActiveX gave developers the ultimate freedom - their code could do anything, just like a desktop application, and it gave users great experience. But there were 3 main issues with this solution:
- ActiveX only worked with Internet Explorer, other browsers couldn't execute it, not to mention other operating systems,
- badly written ActiveX controls could crash Internet Explorer, and that wasn't a great user experience,
- and the worst scenario: ActiveX was just executable code so it could be harmful and it often contained viruses. This made users reluctant to install new ActiveX controls.
ActiveX controls are still in use as Internet Explorer plugins or some special content on some websites (for example as sophisticated file upload mechanisms). The rule is you should only install ActiveX content you trust. Users trust Sun, Adobe or Microsoft, they probably won't include viruses in their products. But if you create your own ActiveX control and put it on your website, it's most likely nobody will want to risk and install it. So in result nobody will use your website..
- Java applets - Java applets had their five minutes of fame. They were Java binaries (CLASS files, often compressed and packed as one JAR file). Applets were hosted by a browser Java plugin. The requirement for applets to work was of course to have the JVM (Java Virtual Machine) on the computer but that was not a big deal, as Java works on many operating systems. Applets were also safe, they had very limited access to local hard drive for example, no access to system registry etc., so they couldn't execute any harmful code. The only problem was the language library. Java is a general purpose language and its standard media library only contained some simple raster drawing routines, and very poor audio and video support. Everything fancy had to be coded manually. That's why Flash took over.
- Flash - Yet another browser plugin, called FlashPlayer. It can execute Flash applications (SWF files). It won over Java applets because with Flash you can easily create animations and attractive fancy pansy vector graphics, easily embed audio and video, both in designer and with code (the language used is called ActionScript). Something Java applets didn't have.
And there comes Silverlight! It's not new anymore; it has been out there for around 2 years now. But it's the version 2.0 that gives it some real power. Here's a quick overview of how it is similar to other technologies:
- Silverlight applications are hosted by a browser plugin, just like Flash or Java applets. You have to install the plugin once, and then you can enjoy webpages with Silverlight content. Currently available for Windows and Mac, but there is an open source Linux version called Moonlight.
- Silverlight applications are simply executables (DLL files) yet they are safe. They are executed in a kind of a sandbox; they have very limited access to hard drive etc. (more less like Java applets).
- Silverlight applications are similar to WPF applications: with XAML, similar architecture, layout, template and styling system, very similar class library etc. Silverlight is more limited though, for example it doesn't have 3D graphics support yet (it is planned for Silverlight 3.0).
- Silverlight has a rich media library making it easy to develop rich applications with fancy vector graphics, animations, audio and video - more less like Flash.
- A big advantage over Flash: one language, one environment, one set of development tools. Flash objects have their own separate world, with separate language. Silverlight uses .NET, so if you know C# for example, you know how to write Silverlight code. Plus you use the same tools to develop server side (ASP.NET) and client side code (Silverlight) - you simply use Visual Studio 2008 SP1 for all of that. With all the advanced debugging features and so on.
- And one of the flag features of Silverlight: separation of code and design. You design your application's looks in XAML and this is something a designer can do in Expression Blend. Then you code the logic in Visual Studio, and this is job for a developer.
Now that you know what Silverlight is, you may be wondering why people invented so many technologies over years to make a browser act as an application host, instead of just writing desktop applications. Yes, desktop applications are easier to develop. But imagine you have to install a separate application for every of the 20 websites you visited today, and another 30 yesterday.. Now you understand why there is Flash and Silverlight, right? Cause you just install the plugin once, and then enjoy rich web content. Plus there is still some portability across browsers/operating systems - not 100% because some plugins are not accessible for some browsers/OS, and JavaScript works differently across browsers but still it's better than developing a separate version of your application for every OS version, as it is the case with desktop applications. And we should mention security: web applications run by plugins are usually harmless, but desktop applications can contain a wide range of harmful software. So you usually don't run desktop applications you don't trust or don't know where they come from.
Once again, a quick reminder:
Server side technologies (executed on the server): ASP, ASP.NET, PHP, CGI, JSP.
Client side technologies (executed in the browser): JavaScript, ActiveX, Flash, Java applet, Silverlight.
Summary
You should now understand how websites evolved over years from simple static documents to rich applications similar to desktop applications, and how it made development complex. You should also know what is an advantage of using Flash or Silverlight for such rich web applications over just HTML and JavaScript.
Now it's time to move on to the next step.. Silverlight Basics #2: The anatomy of a "Hello world" application.