Click here to Skip to main content
Click here to Skip to main content

Getting Started with Silverlight Application Development

, 2 Mar 2010
Rate this:
Please Sign up or sign in to vote.
How to start basic Silverlight application development using the different development options available.

Overview

When you want to learn a new technology, selecting the right entry point is very important. In this article, I have tried to provide the right starting point for Silverlight application development. You will learn how to start basic Silverlight application development using the different development options available. I have started my first Silverlight application using Notepad, which is the existing correct entry point for Silverlight application development. You will then learn what is happening behind the scenes when you start using Visual Studio to create a Silverlight application. You will also see how to develop a Silverlight application using Visual Studio, and a detailed list of default files created by the Silverlight application template. Finally, you will see the life cycle of a Silverlight application.

Creating a Silverlight Application with Notepad

If you are new to Silverlight technology and want to learn how to start with Silverlight application development, I will encourage you to develop your first Silverlight application using Notepad (not Visual Studio or Expression Blend), so that you will completely understand what is Visual Studio 2008 or 2010 doing behind the scene when you create a Silverlight application using the Visual Studio 2008 project template. You might be wondering how it is possible to start development with Notepad without using any Microsoft development tools. Yes, it is possible; however, you might not be writing your real life Silverlight application using Notepad.

If you are ready for your first Silverlight application, start Notepad and enter the following code snippet, and save it with a .html extension. You might want to give a meaningful name to your application; here, I am calling it SilverlightApplicationInNotePad.html.

<html>
  <head>
    <title>This is my first Silverlight Application developed using Notepad</title>
  </head>
     <script type="text/javascript" >
         // Create the MouseLeftButtonDownClick event handler for the root Canvas object.
         function MouseLeftButtonDownClick(sender, args) {
         
             var x = args.GetPosition(sender).x;
             var y = args.GetPosition(sender).y;
             
             // Retrieve a reference to the plug-in
             var plugin = sender.getHost();
             
             //Creates XAML content dynamically.
             var textblockXaml = '<TextBlock Canvas.Left=" ' + x + '" Canvas.Top="' + y + 
             '" FontSize="18" Text="hello" Foreground="#CCCCCC"/>'

             var textblock = plugin.content.CreateFromXaml(textblockXaml);
             // Add the XAML fragment as a child of the root Canvas object.
             sender.children.add(textblock);
         }
     </script>
 <script type="text/xaml" id ="xamlsource">
        <Canvas xmlns ="http://schemas.microsoft.com/client/2007"
          Width="640"
          Height="480"
          Background="Black"
          MouseLeftButtonDown="MouseLeftButtonDownClick">
            <TextBlock Canvas.Left="4" FontSize="18" 
               Text="My First Silverlight Application" Foreground="#CCCCCC"/>
            <Ellipse Canvas.Left="20"  Canvas.Top="50" 
            Fill="Orange" Width="200" Height="80" />
            <Rectangle Canvas.Left="250"  Canvas.Top="50" 
               Width="80" Height="80" Fill="Red"/>
            <Line Canvas.Left="20"  Canvas.Top="100" 
            X1="20" Y1="20" X2="100" Y2="100" Stroke="Yellow" StrokeThickness="10"/>
            <Polygon Canvas.Left="80"  Canvas.Top="140" 
            Fill="blue" Stroke="Green" StrokeThickness="10"
            Points="20,20 100,100 200,10"/>

            <Path Canvas.Left="160"  Canvas.Top="140" 
            Stroke="yellow" StrokeThickness="10">
                <Path.Data>
                    <PathGeometry>
                        <PathFigure StartPoint="20,20">
                            <BezierSegment Point1="120,0" 
                                Point2="50,300" Point3="200,200"/>
                        </PathFigure>
                    </PathGeometry>
                </Path.Data>
            </Path>
        </Canvas>
    </script>
  <body>
    <object type="application/x-silverlight" 
        id="silverlightControl"
        width="100%" 
        height="100%">
      <param name="background" value="Yellow"/>
      <param name="source" value="#xamlsource"/>
    </object>
  </body>
</html>

Output:

The output is so exiting, isn’t it? Silverlight is all about colorful animated media support rich internet applications (RIA). Let’s now discuss step by step what is there inside the .html file. We will do a walk-through to help you understand what is used for creating the user interface (UI) and what is used for the business logic (BL) and how to host a Silverlight application.

Step 1: Hosting a Silverlight application using HTML

There are different technologies available for hosting a Silverlight application, like HTML, ASP.NET, PHP etc. In this application, we will discuss how to host a Silverlight application using HTML.

To host a Silverlight application using HTML, we need to use the Object element which enables you to embed and configure the Silverlight plug-in in your HTML. This will help your browser to instantiate the plug-in for a Silverlight application.

There are two properties important to configure in the plug-in:

  • Type: You can specify the Silverlight version number using the type attribute. Here, I am not specifying any version, so it will take the available version installed in your PC.
  • Param: The parameter tag is required to specify the XAML code reference. In this code, I am using # (pound character) with the ID, so that it will look for the XAML source ID inside the same file.
<object type="application/x-silverlight" 
        id="silverlightControl"
        width="100%" 
        height="100%">
      <param name="background" value="Yellow"/>
      <param name="source" value="#xamlsource"/>
</object>

Step 2: Create a User Interface using XAML code

XAML stands for Extensible Application Markup Language. It is a simple language based on XML for creating and initializing .NET objects with hierarchical relations. Although it was originally invented for WPF, now we are using XAML for creating Silverlight UIs too; here, I am keeping everything in a single HTML file just to make it simple. However, you will be having a separate file for the XAML code, and will get the XAML file reference to your HTML file using the object element.

The <Param> element with name = Source in the object element above is used to specify the ID called “xamlsource” for the XAML code. Canvas is a container tag holding some XAML elements for the UI. I have specified an event called “MouseLeftButtonDown”; when the user clicks on the left mouse button on the Canvas, it will call the JavaScript function to display some content.

<script type="text/xaml" id ="xamlsource">
    <Canvas xmlns ="http://schemas.microsoft.com/client/2007"
      Width="640"
      Height="480"
      Background="Black"
      MouseLeftButtonDown="MouseLeftButtonDownClick">
        <TextBlock Canvas.Left="4" FontSize="18" 
           Text="My First Silverlight Application" Foreground="#CCCCCC"/>
        <Ellipse Canvas.Left="20"  Canvas.Top="50" 
          Fill="Orange" Width="200" Height="80" />
        <Rectangle Canvas.Left="250"  Canvas.Top="50" 
          Width="80" Height="80" Fill="Red"/>
        <Line Canvas.Left="20"  Canvas.Top="100" 
          X1="20" Y1="20" X2="100" Y2="100" 
          Stroke="Yellow" StrokeThickness="10"/>
        <Polygon Canvas.Left="80"  Canvas.Top="140" 
          Fill="blue" Stroke="Green" StrokeThickness="10"
          Points="20,20 100,100 200,10"/>

        <Path Canvas.Left="160"  Canvas.Top="140" 
                 Stroke="yellow" StrokeThickness="10">
            <Path.Data>
                <PathGeometry>
                    <PathFigure StartPoint="20,20">
                        <BezierSegment Point1="120,0" 
                              Point2="50,300" Point3="200,200"/>
                    </PathFigure>
                </PathGeometry>
            </Path.Data>
        </Path>
    </Canvas>
</script>

Step 3: Writing business logic using JavaScript

Again, you will not be keeping JavaScript code in the same file; instead, you can have a .js file and have a reference to it in the .html file. This browser supported interpreted unmanaged language is used to write business logic. In real life application development, you will be writing the code using managed programming languages like C# or VB.NET.

When the user clicks on his left mouse button, the JavaScript code reads the X, Y position of the Canvas surface and dynamically generates the XAML code and renders it on that position.

The GetHost method retrieves the Silverlight plug-in instance that contains the object. This method is especially useful for retrieving the Silverlight plug-in in an input event-handling function in which the sender parameter is generally a DependencyObject.

Create XAML contents on the fly using the CreateFromXaml method, and add these elements to the parent element of the Canvas using the sender.children.add method.

<script type="text/javascript" >
 // Create the MouseLeftButtonDownClick
 // event handler for the root Canvas object.
 function MouseLeftButtonDownClick(sender, args) {
 
     var x = args.GetPosition(sender).x;
     var y = args.GetPosition(sender).y;
     
     // Retrieve a reference to the plug-in
     var plugin = sender.getHost();
     
     //Creates XAML content dynamically.
     var textblockXaml = '<TextBlock Canvas.Left=" ' + x + 
       '" Canvas.Top="' + y + 
       '" FontSize="18" Text="hello" Foreground="#CCCCCC"/>'

     var textblock = plugin.content.CreateFromXaml(textblockXaml);
     // Add the XAML fragment as a child of the root Canvas object.
     sender.children.add(textblock);
 }
</script>

Creating a Silverlight application with Visual Studio

I am assuming that you already have a Silverlight application development environment ready in your computer before we started Silverlight application development using Visual Studio. If not, please visit my other article, An Introduction to Silverlight, for information on development tools.

This section will walk through a step by step process of creating a very simple Silverlight application using Visual Studio 2008.

Step 1: From the Visual Studio File menu, select the New Project dialog box and select the Silverlight Application template. You can select VB.NET or C# as the programming language for coding, and give a meaningful name to your solution.

Step 2: This is optional; you can select the hosting application template while creating the Silverlight application itself, or if you already have a website for hosting this Silverlight project, you can uncheck the checkbox and click OK to continue.

Step 3: Before we start the actual development, it is very important to understand the Solution Explorer for Silverlight and hosting projects. Visual Studio template does a lot of things for the developer behind the scenes; however, it is the developer’s responsibility to understand what is happening behind the scenes. Here, we will talk about each and every file created by Visual Studio for us.

Silverlight Application project files

A Silverlight application project contains the following configuration, assembly references, and code files:

AppManifest.xml

This is the application manifest file that is required to generate the application package (.XAP file). You must not edit this file. This file will be updated automatically when we build the Silverlight application. This file identifies the packaged assemblies and the application entry point etc…

<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Deployment.Parts>
    </Deployment.Parts>
</Deployment>

AssemblyInfo.cs or AssemblyInfo.vb

Nothing new in this file; if you are .NET developer, you will have seen this file in every .NET application, which contains the name and the version metadata that is embedded into the generated assembly.

Silverlight project references:

  • mscorlib.dll
  • System.dll
  • System.Core.dll
  • System.Net.dll
  • System.Windows.dll
  • System.Windows.Browser.dll
  • System.Xml.dll

App.xaml and App.xaml.cs files

This is almost similar to an ASP.NET application’s Global.asax file. You can have any name for this file, but it should inherit from the Application class. This is the entry point to your Silverlight application.

The App class is required by a Silverlight application to display the application user interface. The App class is implemented by using App.xaml and App.xaml.cs or App.xaml.vb. The App class is instantiated by the Silverlight plug-in after the application package (.xap file) is created.

App.xaml

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             x:Class="SilverlightApplicationWithVS.App">
    <Application.Resources>
    </Application.Resources>
</Application>

This file provides the following services:

  • Application Entry Point
  • Application Lifetime
  • Application Management
  • Application-Scoped Resources
  • Unhandled Exception Detection
//App.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplicationWithVS
{
    public partial class App : Application
    {

        public App()        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            this.RootVisual = new MainPage();
        }
        private void Application_Exit(object sender, EventArgs e)
        {

        }
        private void Application_UnhandledException(object sender, 
                     ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger
            // then report the exception using
            // the browser's exception mechanism.
            // On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // NOTE: This will allow the application
                // to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling
                // should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(
                           delegate { ReportErrorToDOM(e); });
            }
        }
        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + 
                                  e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval(
                  "throw new Error(\"Unhandled Error in Silverlight Application " + 
                  errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
    }
}

MainPage files

This is the main Getting Started page to your application from which you can navigate to different pages of the application. You will be creating all these User Interface (UI) pages using XAML. This class should inherit from the UserControl class.

<!--<span class="code-comment">MainPage.xaml--></span>
<UserControl x:Class="SilverlightApplicationWithVS.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:DesignWidth="640" d:DesignHeight="480">
    <Canvas xmlns ="http://schemas.microsoft.com/client/2007"
          Width="640"
          Height="480"
          Background="Black"
            MouseLeftButtonDown="Canvas_MouseLeftButtonDown" 
           >
        <TextBlock Canvas.Left="4" FontSize="18" 
            Text="My First Silverlight Application" Foreground="#CCCCCC"/>
        <Ellipse Canvas.Left="20"  Canvas.Top="50" 
            Fill="Orange" Width="200" Height="80" />
        <Rectangle Canvas.Left="250"  Canvas.Top="50"  
            Width="80" Height="80" Fill="Red"/>
        <Line Canvas.Left="20"  Canvas.Top="100" 
            X1="20" Y1="20" X2="100" Y2="100" Stroke="Yellow" StrokeThickness="10"/>
        <Polygon Canvas.Left="80"  Canvas.Top="140" 
            Fill="blue" Stroke="Green" StrokeThickness="10"
            Points="20,20 100,100 200,10"/>

        <Path Canvas.Left="160"  Canvas.Top="140" 
            Stroke="yellow" StrokeThickness="10">
            <Path.Data>
                <PathGeometry>
                    <PathFigure StartPoint="20,20">
                        <BezierSegment Point1="120,0" 
                             Point2="50,300" Point3="200,200"/>
                    </PathFigure>
                </PathGeometry>
            </Path.Data>
        </Path>
    </Canvas>
</UserControl>

You can also have a code-behind for writing the event handler logic with C# or VB.NET.

//MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplicationWithVS
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void Canvas_MouseLeftButtonDown(object sender, 
                     MouseButtonEventArgs args)
        {
            MessageBox.Show("Hello");
        }
    }
}

.xap file

Every hosting application should have a folder called “ClientBin” to hold the XAP file which is created when we build the Silverlight application project. This is also called the Silverlight application package. An application package is a compressed zip file that has a .xap file extension, and contains all the files that you need to start your application.

The managed API enables you to bundle managed assemblies and resource files into the application package (.XAP) files. The Silverlight plug-in is responsible for loading an application package and extracting its contents.

To verify the compressed zip file, rename a XAP file like SilverlightApplicationWithVS.xap to SilverlightApplicationWithVS.xap.zip. You can then open the archive and view the files inside.

The XAP file system has two obvious benefits:

  • It compresses your content: Because this content isn’t decompressed until it reaches the client, it reduces the time required to download your application. This is particularly important if your application contains large static resources that can be easily compressed, like XML documents or blocks of text.
  • It simplifies deployment: When you’re ready to take your Silverlight application live, you simply need to copy the XAP file to the web server, along with SilverlightApplicationWithVSTestPage.html or a similar HTML file that includes a Silverlight content region. You don’t need to worry about keeping track of the assemblies and resources.

Silverlight.js

The Silverlight.js file provides JavaScript helper functions for embedding the Silverlight plug-in in a Web page and for customizing the Silverlight installation experience.

You can use the createObject and createObjectEx functions to dynamically embed a Silverlight plug-in in a Web page. These functions generate HTML object elements from the specified parameters.

The Silverlight.js file is installed with the Silverlight SDK in the following location: %ProgramFiles%\Microsoft SDKs\Silverlight\v2.0\Tools.

SilverlightApplicationWithVSTestPage.aspx test page

There are two files created to host the application:

Step 4: Build the solution. Once you build the solution, you will find a XAP file in the “ClientBin" folder, and it will show the following output:

Life cycle of a Silverlight application

The Silverlight application life cycle actually starts when the user requests a page which is developed using Silverlight technology. The Silverlight plug-in loading happens when the request comes from a web user who downloads all the reference files (XAP) including the manifest which help in creating an instance of the application class for rendering Silverlight pages for users.

Conclusion

I hope you enjoyed my article; please write your comments on this article, which is very important for me.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


Comments and Discussions

 
GeneralMy vote of 5 PinmemberYatin Bhagat22-Sep-11 0:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140821.2 | Last Updated 2 Mar 2010
Article Copyright 2010 by keesari_anjaiah
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid