Introducing Silverlight 4

In this post I am going to discuss about some basic things inside Silverlight project. When we start Silverlight the first thing we face is XAML (Extended Application Markup Language). So I am going to start form XAML which is pronounced as /ˈzæməl/.

XAML (Extended Application Markup Language)

It is a XML-based declarative language which was created by Microsoft is used to initialize structured values and objects. XAML file generally rendered by the Silverlight plug-in and displayed inside the browser window. When we compile silverlight projects, it will first converts XAML into BAML (Binary Application Markup Language) and then rendered in the web browser window.

So let’s investigate a simple Silverlight 4 Project.

To create a new Silverlight application project

1. Start Visual Studio 2010.

2. Select File > New Project

3. In the Installed Templates pane, expand the Visual C# node and select Silverlight.

clip_image002[4]

Note: In the list of templates we see that there are Silverlight Application, Silverlight Business Application, Silverlight Navigation Application template. We will check all those one after another in this post.

4. In the list of templates, select Silverlight Application.

5. Specify a name and a location for the application and then click OK.

The New Silverlight Application dialog box appears as shown in the following illustration.

clip_image001

6. From the Silverlight Version drop-down list, select the version of Silverlight. I have chosen Silverlight 4. Click OK.

With is a few second, Visual Studio will create the Silverlight solution which will contain a Silverlight Project and one Web Application Project to host your Silverlight application.

clip_image001[4]

Once done, you will see Visual Studio already created two XAML files (App.xaml & MainPage.xaml) inside the Silverlight Application project.

MainPage.xaml

MainPage.xaml is the startpage for the Silverlight application. It is possible to modify this page as per our need or we can create a new one. Let’s look at it:

  1. <UserControl x:Class="SilverlightApplicationDemo.MainPage"
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6.     mc:Ignorable="d"
  7.     d:DesignHeight="300" d:DesignWidth="400">
  8.  
  9.     <Grid x:Name="LayoutRoot" Background="White">
  10.  
  11.     </Grid>
  12. </UserControl>

App.xaml

In App.xaml file we can define application level resources (like styles, data templates and control templates).

  1. <Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  2.              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  3.              x:Class="SilverlightApplicationDemo.App"
  4.              >
  5.     <Application.Resources>
  6.         <Style x:Key="btnStyle" TargetType="Button">
  7.             <Setter Property="Background" Value="Yellow"/>
  8.             </Style>
  9.     </Application.Resources>
  10. </Application>

The code-behind (App.xaml.cs) is used to handle application level events such as Startup, Exit and UnhandledException. The RootVisual is used to setup the startup Silverlight UserControl. This property needs to be set in the Startup event.

  1. public partial class App : Application
  2.   {
  3.  
  4.       public App()
  5.       {
  6.           this.Startup += this.Application_Startup;
  7.           this.Exit += this.Application_Exit;
  8.           this.UnhandledException += this.Application_UnhandledException;
  9.  
  10.           InitializeComponent();
  11.       }
  12.  
  13.       private void Application_Startup(object sender, StartupEventArgs e)
  14.       {
  15.           this.RootVisual = new MainPage();
  16.       }
  17.  
  18.       private void Application_Exit(object sender, EventArgs e)
  19.       {
  20.  
  21.       }
  22.  
  23.       private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
  24.       {
  25.           // If the app is running outside of the debugger then report the exception using
  26.           // the browser's exception mechanism. On IE this will display it a yellow alert
  27.           // icon in the status bar and Firefox will display a script error.
  28.           if (!System.Diagnostics.Debugger.IsAttached)
  29.           {
  30.  
  31.               // NOTE: This will allow the application to continue running after an exception has been thrown
  32.               // but not handled.
  33.               // For production applications this error handling should be replaced with something that will
  34.               // report the error to the website and stop the application.
  35.               e.Handled = true;
  36.               Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
  37.           }
  38.       }
  39.  
  40.       private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
  41.       {
  42.           try
  43.           {
  44.               string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
  45.               errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");
  46.  
  47.               System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
  48.           }
  49.           catch (Exception)
  50.           {
  51.           }
  52.       }
  53.   }

Other common uses of App.xaml.cs file are:

· This application is accessible via the global static variable Application.Current. You can cast this anywhere in your application.

· Using the Install method you can prompt the user to install the application Out-of-Browser.

· The CheckAndDownloadUpdateAsync method is used when the application is running out-of-browser to ensure that the .xap file is the latest.

Silverlight Navigation Application project

clip_image001[6]

The Silverlight Navigation Template provides a rapid means of developing page-based web applications. The two primary controls in the System.Windows.Control.Navigation namespace are Frame and Page. The Frame control hosts a single Page control utilizes the Navigation APIs to allow the user to navigate between the pages. The Page control resembles the commonly used UserControl control to hold the contents of the respected page. The project generates the default template and files for a sample page-based application. The Views Folder has pre-generated pages (AboutPage, ErrorWindow, and HomePage).

Silverlight Business Application

SilverlightBusinessTemplate

If we investigate Silverlight Business Application Template we will find a new addition that is the User Authentication. That is login and logout functionality. If we run the application we will find Login is displayed.

When we build Silverlight project, it will create the XAP file (SilverlightApplicationNavigationDemo.xap) and put it into the ClientBin directory of the web project. When the page loads it will pickup from the same location as the source you specified inside the aspx/html page.

XAP

A .xap (pronounced as ZAP) file is a compiled compressed output of the Silverlight application. The file is actually a .zip file that contains all the files necessary for the application such as application manifest file, compiled output assembly and other resources.

Silverlight Application (XAP) generally loads inside the ASPX or HTML pages pointing to the path to load the XAP. Web pages use the Silverlight components by loading the .xap files using the <object> tag.

Below is a list of available parameters that can be passed to the Silverlight plug-in using the <param> tag.

 

Parameter

Description

Type

allowHtmlPopupWindow

Specifies whether the HtmlPage.PopupWindow method is allowed. Defaults to true for applications in the same domain, otherwise false.

Boolean

autoUpgrade

Specifies whether the plug-in should attempt to upgrade if minRuntimeVersion is newer than the current Silverlight version. Default is true.

Boolean

background

Plug-in background color. Default is null (white).

Color with or without alpha (RGB, ScRGB)

enableAutoZoom

Indicates whether the host (for certain platforms) can invoke zoom behavior that increases the DPI. Default is true.

Boolean

enableCacheVisualization

Indicates whether to use a non-production analysis visualization mode, which shows areas of a page that are being GPU accelerated with a colored overlay. Default is false. Do not use in production code.

Boolean

enableFramerateCounter

Indicates whether to display the current frame rate in the hosting browser's status bar (IE/Win only).

Boolean

enableGPUAcceleration

Indicates whether to use graphics processor unit (GPU) hardware acceleration for cached compositions, which potentially results in graphics optimization. (false by default)

Boolean

enablehtmlaccess

Specifies whether the plug-in has full access to the browser DOM. Defaults to true for applications in the same domain, otherwise false.

Boolean

enableNavigation

Indicates whether the hosted content in the Silverlight plug-in can use a HyperlinkButton to navigate to external URIs. Default is all.

all: the hosted content can use HyperlinkButton to navigate to any URI.

none: the hosted content cannot use HyperlinkButton for navigation to an external URI. Relative URIs for internal navigation are still permitted.

enableRedrawRegions

Determines whether to visually indicate the areas of the plug-in that are being redrawn with each frame. This property is for performance tuning and visualization during development only; do not specify it for any deployed Silverlight-based application. Default is false.

Boolean

initParams

User-defined string of parameters.

Comma separated key=value pairs

maxframerate

Specifies the maximum number of frames per second that the plug-in can render. The default is 60.

Integer

minRuntimeVersion

Specifies the earliest version of the Silverlight plug-in required.

Version number

onError

Error handler for parse and native code run-time errors.

JavaScript function name

onFullScreenChanged

Function to call when the FullScreen property changes.

JavaScript function name

onLoad

Function to call when the plug-in has finished loading in the DOM.

JavaScript function name

onResize

Function to call when the plug-in size changes.

JavaScript function name

onSourceDownloadComplete

Function to call when the source download has completed.

JavaScript function name

onSourceDownloadProgressChanged

Function to call when the source download progress changes.

JavaScript function name

onZoom

Specifies the handler for a Zoomed event that occurs when the Silverlight plug-in content area receives a host-generated zoom event.

JavaScript function name

source

Specifies the address or relative path of either an initial XAML file or XAP.

URI

splashScreenSource

Specifies a XAML page to use as the splash screen.

URI

windowless

Specifies the rendering mode for the plug-in for Windows versions of Silverlight. The default is false.

Boolean

Here is the object tag :

  1.   <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
  2.           <param name="source" value="ClientBin/SilverlightApplicationNavigationDemo.xap"/>
  3.           <param name="onError" value="onSilverlightError" />
  4.           <param name="background" value="white" />
  5.           <param name="minRuntimeVersion" value="4.0.50401.0" />
  6.           <param name="autoUpgrade" value="true" />
  7.           <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0" style="text-decoration:none">
  8.               <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
  9.           </a>
  10.         </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>

Note: the iframe element is here for cross-browser compatibility.

Summery

In the above post I have tried to integrate all the information related Silverlight Application in one place so that a beginner could get a general overview. Maybe I have missed lots of information. If anyone one would like to add anything please feel free to leave your comments. In the next post I will try to explore Silverlight Layout System.

Published 07-23-2010 9:29 AM by MD.ZAHIDUL ISLAM
Powered by Community Server (Non-Commercial Edition), by Telligent Systems