Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Silverlight Controls » ASP.NET Silverlight Server Control

ASP.NET Silverlight Server Control

The ASP.NET Silverlight server control lets you provide a Rich Internet Application (RIA) experience with your Web application, beyond what can be done with AJAX and DHTML alone.

Author Rank :
Page Views : 2693
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Gauge for SharePoint
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


The ASP.NET Silverlight server control lets you provide a Rich Internet Application (RIA) experience with your Web application, beyond what can be done with AJAX and DHTML alone. By using this control, you can integrate XAML and any supporting code (a managed-code assembly, a managed dynamic-language script module, or client JavaScript libraries) into your Web site.

The Silverlight server control uses XAML in combination with the Silverlight plug-in and the JavaScript Sys.UI.Silverlight.Control class. Unlike the MediaPlayer server control, the Silverlight server control is generic and is designed to manage more than media files.

You can use managed code to handle interaction with the Silverlight server control (a Silverlight 2 scenario). Alternatively, you can use JavaScript to create a JavaScript type to handle the interaction (supported in Silverlight 1.0 and Silverlight 2). To use the JavaScript type, you reference the type by using the ScriptType property of the server control. Then in the Scripts collection of the ScriptManager control, you add a reference to the script library that contains the type definition.
 

Note: Web pages that use the Silverlight server control must include a ScriptManager control.

Using the Silverlight Server Control

The Silverlight control enables you to render a .xap application package which is created by using XAML and managed code.

The following example shows the declarative markup for a Silverlight server control that is configured to reference the .xap application packaged named myExample.xap.

  <asp:Silverlight
    ID="Xaml1"
    runat="server"
    Source="~/ClientBin/myExample.xap"
    MinimumVersion="2.0.30523"
    Width="100%"
    Height="100%">
  </asp:Silverlight>

The Silverlight control creates the Sys.UI.Silverlight.Control client script class (based on the model used in the ASP.NET AJAX Extensions) that provides a JavaScript programming model to control the client player.

Creating a Managed-Code Assembly to Use with the Silverlight Server Control

A XAML file can reference code written in a managed assembly by using the x:Class attribute. Event handlers can be attached by using attributes in XAML. You can create a Silverlight project in development environments such as Visual Studio 2008, in which you can create XAML and a managed-code assembly. These outputs can be referenced in the Silverlight server control.

Note:
To run .xap files from IIS, you must have the .xap file name extension associated with a MIME type of " application/x-silverlight-app".

The following example shows the contents of a XAML element that references a managed-code assembly.

<Canvas x:Name="parentCanvas"
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Loaded="OnPageLoaded"
  x:Class="CustomClass;assembly=CustomAssembly.dll"
  Width="640"
  Height="480"
  Background="White" >


You can reference this XAML file through the Source property of the Silverlight server control. You must also make sure that the MinimumVersion property is set appropriately. The following example shows how to do this. Although the XAML that is downloaded references the managed code, the framework generates a client base Sys.UI.Silverlight.Control instance. This lets you provide additional JavaScript interaction in a manner consistent with the Microsoft ASP.NET AJAX Extensions model.

The following example shows how to use the Silverlight control with a managed-code assembly. The Silverlight control enables you to render a .xap application package which is created by using XAML and managed code. This example includes a Web page (.aspx), a XAML page (.xaml) and the code-behind for the XAML page.

The following code shows how to include the Silverlight server control in a Web page. The Source attribute of the Silverlight server control references the .xap application package.

<%@ Page Language="C#" AutoEventWireup="true" %>

<%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls"
    TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;">
<head id="Head1" runat="server">
    <title>Test Page For myExample</title>
</head>
<
body style="height:100%;margin:0;">
    <form id="form1" runat="server" style="height:100%;">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <div  style="height:100%;">
            <asp:Silverlight ID="Xaml1" runat="server" Source="../ClientBin/myExample.xap" MinimumVersion="2.0" Width="100%" Height="100%" />
        </div>
    </form>
</body>
</html>
 

The following code shows a XAML example (page.xaml) that is included in the .xap application package referenced in the earlier code example.

XAML

<UserControl x:Class="myExample.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.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="Button Demonstration" Margin="0,20,10,15"
            FontFamily="Verdana" FontSize="18" FontWeight="Bold"
            Foreground="#FF5C9AC9" Grid.Row="0" Grid.ColumnSpan="2"/>
        <Button x:Name="btn1" Grid.Row="1" Margin ="0,5,5,5"
            HorizontalAlignment="Left"
            Foreground="Green" Width="120" Click="OnClick1"
            Content="Hover to Click" ClickMode="Hover" />
        <TextBlock x:Name="text1" Grid.Row="1" Grid.Column="1"
            Margin ="0,8,0,0" />
        <Button x:Name="btn2" Grid.Row="2" Margin ="0,5,5,5"
            HorizontalAlignment="Left"
            Foreground="Blue" Width="120" Click="OnClick2"
            Content="Press to Click" ClickMode="Press" />
        <TextBlock x:Name="text2" Grid.Row="2" Grid.Column="1"
            Margin="0,8,0,0" />
        <Button x:Name="btn3" Grid.Row="3" Margin ="0,5,5,5"
            HorizontalAlignment="Left"
            Click="OnClick3" Width="120" Content="Reset"
            ClickMode="Release"/>
        <TextBlock x:Name="text3" Grid.Row="3" Grid.Column="1"
            Margin ="0,8,0,0" />
    </Grid>
</UserControl>
 

The following code shows the supporting code-behind (page.xaml.cs or page.xaml.vb) for the previous XAML example (page.xaml).

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 myExample
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }
        void OnClick1(object sender, RoutedEventArgs e)
        {
            btn1.Foreground = new SolidColorBrush(Colors.Blue);
            text1.Text = "Click event handled on Hover.";
            text3.Text = "";
        }

        void OnClick2(object sender, RoutedEventArgs e)
        {
            btn2.Foreground = new SolidColorBrush(Colors.Green);
            text2.Text = "Click event handled on Press.";
            text3.Text = "";
        }

        void OnClick3(object sender, RoutedEventArgs e)
        {
            btn1.Foreground = new SolidColorBrush(Colors.Green);
            btn2.Foreground = new SolidColorBrush(Colors.Blue);
            text1.Text = "";
            text2.Text = "";
            text3.Text = "Click event handled on Release.";
        }
    }
}

Using JavaScript and XAML with the Silverlight Server Control

The following example shows the markup for a Silverlight server control that defines a simple calculator in XAML. The logic for interacting with the XAML is defined in a separate JavaScript class. The Silverlight server control references the file that contains the XAML markup (Calculator.xaml). You can also see how to reference the client-script library (Calculator.js) for the calculator code, and how to reference the JavaScript class (Custom.Calculator).

        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Scripts>
                <asp:ScriptReference Name="SilverlightControl.js"
         Assembly="System.Web.Silverlight"/>
                <asp:ScriptReference Path="calculator.js" />
            </Scripts>
        </asp:ScriptManager>

        <asp:Silverlight runat="server" ID="Silverlight1"
    Height="340"
    Width="320"
    Source="../calculator.xaml"
    ScriptType="Custom.Calculator"
    OnPluginError="onXamlError">


In its basic form, the Silverlight server control provides a JavaScript type that includes members such as the onPluginLoaded method and the onPluginError method. The Silverlight server control references a XAML file through the Source property. The code for interacting with the XAML can be in a managed-code assembly or in a client JavaScript library (.js file).

Creating a Class in JavaScript to Use with the Silverlight Server Control

To create a class in JavaScript to use with the Silverlight server control, you can use the Microsoft ASP.NET AJAX Extensions client framework and create a type that derives from the Sys.UI.Silverlight.Control base class. This enables you to attach event handlers to XAML DOM elements during the pluginLoaded event. This event is raised when the XAML DOM is loaded and ready. The framework provides error handling for your custom type and provides default cleanup of resources (such as attached events) in its pluginDispose method.

The following example shows a client class that derives from the Control base class.

Type.registerNamespace("Custom");

Custom.Calculator = function(element) {
      Custom.Calculator.initializeBase(this, [element]);
     
      this._designer = new designerCalc();
      this._value1 = "";|
    this._operator = "=";
    this._recentOperator = true;
}

Custom.Calculator.prototype = {
    _events: null,
      onPluginLoaded : function(args) {
            Custom.Calculator.callBaseMethod(this, 'onPluginLoaded', new Array(args));
 
        // Call on the component initialized to get the specific component's XAML element fields.          
            this._designer.initializeComponent(this.get_element());
           
            // Hookup event handlers as required in this custom type.
            var f = Function.createDelegate(this, this._numClick);

            this.addEventListener(this._designer.n0, "mouseLeftButtonUp", f);
            this.addEventListener(this._designer.n1, "mouseLeftButtonUp", f);
            this.addEventListener(this._designer.n2, "mouseLeftButtonUp", f);
            this.addEventListener(this._designer.n3, "mouseLeftButtonUp", f);
            this.addEventListener(this._designer.n4, "mouseLeftButtonUp", f);
            this.addEventListener(this._designer.n5, "mouseLeftButtonUp", f);
            this.addEventListener(this._designer.n6, "mouseLeftButtonUp", f);
            this.addEventListener(this._designer.n7, "mouseLeftButtonUp", f);
            this.addEventListener(this._designer.n8, "mouseLeftButtonUp", f);
            this.addEventListener(this._designer.n9, "mouseLeftButtonUp", f);
            this.addEventListener(this._designer.fplus, "mouseLeftButtonUp", f);
            this.addEventListener(this._designer.fminus, "mouseLeftButtonUp", f);
            this.addEventListener(this._designer.fmultiply, "mouseLeftButtonUp", f);
            this.addEventListener(this._designer.fequals, "mouseLeftButtonUp", f);
            this.addEventListener(this._designer.fdivide, "mouseLeftButtonUp", f);                       
            // Set initial value
            this._designer.result.Text = "0";
      },
      _numClick : function(sender, e) {
        var s = sender.children.getItem(2).Text;

        if ("=-+/*".indexOf(s) !== -1) {
            if (!this._recentOperator) {
                if (this._operator === "=") {
                    this._value1 = this._designer.result.Text;
                }
                else {
                    if ((this._operator === "/") && (parseFloat(this._designer.result.Text) === 0)) {
                        this._designer.result.Text = "Error";
                        this._value1 = "0";
                        s = "=";
                    }
                    else {
                        var value = eval("parseFloat(this._value1) " + this._operator + " parseFloat(this._designer.result.Text);");
                        value = String(value).substr(0, 12);
                        this._value1 = value;
                        this._designer.result.Text = this._value1;
                    }
                }
            }

            this._operator = s;
            this._recentOperator = true;
            return;
        }

        if (this._recentOperator) {            
            this._designer.result.Text = s;
            this._recentOperator = false;
        }
        else {
            this._designer.result.Text += s;    
        }
      }
}
Custom.Calculator.registerClass('Custom.Calculator', Sys.UI.Silverlight.Control);

Extending the Silverlight Server Control

The Silverlight server control is a control that provides the basics for XAML in addition to supporting the Silverlight installation logic for you. In some cases, you might want to create a class that inherits from the Silverlight control and then expose your own members, much like the implementation of the MediaPlayer control.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Dinesh Beniwal
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Need more contols information by Alagiri On August 2, 2010
Hi,

 I need more information about silver light controls and its attributes .
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.