what is silver light

Upload: vivekanand-upadhyay

Post on 07-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/4/2019 What is Silver Light

    1/41

    What is silverlight ?Silverlight is a web based technology, launched by Microsoft in April 2007. Silverlight is considered asa competitor to Adobes Flash.

    Silverlight applications are delivered to browsers in a text-based markup language called XAML. Oneimportant difference between Flash and XAML is, Flash is a compiled application where as XAML istext based. Search engines can analyze and index such content, which is a huge benefit forwebmasters.

    For regular internet users, Silverlight is a browser plug-in that supports video, audio and animations.

    For web developers, Silverlight offers much more. Silverlight supports video and audio files withoutneed of much programming. It allows them to handle events from web pages (like handle start/endof video playing etc)

    Difference between Silverlight 1 andSilverlight 2Silverlight 1 is purely AJAX and Javascript based. All the code has to be written in Javascript andXAML.

    Silverlight 2 supports managed code. When Silverlight 2 runtime is installed, it installs a limitedversion of .NET runtime on the client machine. This allows .NET programmers to write managedcode to be executed on the client PC and provide a better user experience to the users. Of course,there is security and restrictions built in to it so that the code has limited access to the clientcomputer.

    Developers must be aware that if the end user decline to install the .NET runtime on their clientcomputer, the Silverlight 2 applications will not run.

    Difference between Silverlight and WPFSilverlight and Windows Presentation Foundation (WPF) are 2 different products from Microsoft, buthas lot of overlap. Silverlight is a sub set of WPF in terms of features and functionality.

    Silverlight is a Microsoft technology, competing with Adobes Flash and is meant for developing rich

  • 8/4/2019 What is Silver Light

    2/41

    browser based internet applications.

    WPF is a Microsoft technology meant for developing enhanced graphics applications for desktopplatform. In addition, WPF applications can be hosted on web browsers which offers rich graphicsfeatures for web applications. Web Browser Appliactions (WBA) developed on WPF technology usesXAML to host user interface for browser applications. XAML stands for eXtended Application MarkupLanguage which is a new declarative programming model from Microsoft. XAML files are hosted asdescrete files in the Web server, but are downloaded to the browsers and converted to userinterface by the .NET runtime in the client browsers.

    WPF runs on .NET runtime and developers can take advantage of the rich .NET Framework and WPFlibraries to build really cool windows applications. WPF supports 3-D graphics, complex animations,hardware acceleration etc.

    Tools required to develop SilverlightapplicationsTo run Silverlight applcations in a web browser, you need to have Silverlight run time installed on theclient browser as a plug in. This is a light weight version of .NET runtime.

    However, to develop a Silverlight application, you need something more.

    Silverlight SDK

    This include a set of tools required to compile and build Silverlight controls.

    If you are comfortable writing HTML using notepad and compiling .NET applications from consoletools, then you just need the Silverlight SDK to develop Silverlight applications.

    However, most people use some kind of IDE to develop applications faster.

    Microsoft offers 2 separate tools to develop Silverlight applications:

    1. Microsoft Expression Studio - this tool is meant for web designers to create rich visual elementsfor Silverlight applications. Expression Studio is recommended for web designers who create richinternet applications with enhanced visual content and graphics. There are several features providedfor creating enhanced graphics elements with lot of options to pick color, font etc.

    2. Microsoft Visual Studio - this is the integrated development environment from Microsoft todevelop .NET applications. Programmers can use Visual Studio to develop Silverlight applications

    which require programming. Visual Studio allows programmers to develop sophisticated Silverlightapplications in any .NET language (like C#, VB.NET etc).

  • 8/4/2019 What is Silver Light

    3/41

    If you are using Visual Studio, you can download the Silverlight development tools from here . Thisdownload include the Service pack1 for VS.NET and the Silverlight SDK.

    Which tool to use - Expression Studio or Visual Studio ?

    If your Silverlight application include just graphics adn visual elements, then you can use ExpressionStudio. However, if you are a programmer and if your Silverlight application include programminglogic, then you might want to choose Visual Studio.

    Difference between Silverlight Runtime and

    Silverlight SDKSilverlight Runtime is a plug-in for browsers to support Silverlight enabled applications. If Silverlightruntime is not installed, browsers will not be able to run Silverlight elements in the browser. You canset up your Silverlight tags such a way that your browser will automatically prompt the user todownload and install the Silverlight plug in when your application is launched in the browser.

    Installing the run time is a one time operation on the client. Once installed, it will be automaticallylaunched when any Silverlight application is loaded in the browser.

    Silverlight SDK is a set of tools, documentation, samples and templates for the web developers tohelp them easily develop Silverlight enabled applications. The SDK is not really mandatory to developSilverlight applications, however, SDK will make development much easier.

    What is XAML ?XAML stands for eXtended Application Markup Language. XAML contain XML that is

    used to declaratively specify the user interface for Silverlight or WPF applications.

    For example, if you need to display a rectangle, this is the XAML you need to use:

    When the above xaml is executed, it will display a rectangle filled with red color.

    You may notice is that XAML is very similar to HTML in nature.

    http://www.microsoft.com/downloads/details.aspx?FamilyId=c22d6a7b-546f-4407-8ef6-d60c8ee221ed&displaylang=enhttp://www.microsoft.com/downloads/details.aspx?FamilyId=c22d6a7b-546f-4407-8ef6-d60c8ee221ed&displaylang=enhttp://www.microsoft.com/downloads/details.aspx?FamilyId=c22d6a7b-546f-4407-8ef6-d60c8ee221ed&displaylang=enhttp://www.microsoft.com/downloads/details.aspx?FamilyId=c22d6a7b-546f-4407-8ef6-d60c8ee221ed&displaylang=en
  • 8/4/2019 What is Silver Light

    4/41

    "Hello World" Silverlight applicationOpen Visual Studio and select the menu "File" > "New" > "Project"Select the Project Type as "Silverlight" under your favorite language and choose the template

    "Silverlight Application". I have selected Visual C# as the tutorials here.

    I have named my project as "MySilverlightApp" and have selected the option "Create directory forsolution" so that all my project files are organized within a folder structure.

    We need a web page to host the Silverlight components that we develop. Visual Studio makes this job easier in the next step by prompting you to automatically create a website. Choose the options

    as shown in the attachment.

  • 8/4/2019 What is Silver Light

    5/41

    You are ready to rock ! Just press OK and Visual Studio will create 2 projects and a bunch of files foryou. We will analyze some of the files created by Visual Studio in the next chapter.

    Files created by Visual Studio by defaultWhen we create a new Silverlight application using Visual Studio 2008, it creates several files bydefault. See the solution explorer immediately after creating a new Silverlight project with a hostwebsite:

  • 8/4/2019 What is Silver Light

    6/41

    We will analyse some of the files.

    AppManifest.xml

    This file defines the assemblies that are deployed to the client applications.

    Build and run your Silverlight hello WorldapplicationIt is time to build and run your first Silverlight application. Press Ctrl+F5 to build and run

    your application. If everything is setup correctly, then Internet Explorer will be launchedautomatically with your default page which hosts your Silverlight object.

    Since you have not done much for your control, you will see a blank page opened in thebrowser.

    Go back to your Visual Studio and open your web page which hosts the Silverlight object. Inmy sample project, the file is named "MySilverlightAppTestPage.aspx" and the content of thefile looks like this:

  • 8/4/2019 What is Silver Light

    7/41

    TagPrefix="asp" %>Test Page For MySilverlightApp

    Most of the stuff above look familiar to ASP.NET developers. Some of the lines that needsome attention are:

    The second line defines the Silverlight control to be hosted in the web page. The attribute

    "Source" defines the .xap file to be used by the web page. This .xap file contains the XAMLand code from your .xaml files and will be executed by the Silverlight plugin.

    In the current sample, you have just one xaml file called Page.xaml. When you compile thesolution, this file is compiled into a special file (MySilverlightApp.xap) with the extension.xap.

    What is app.xaml ?App.xaml is a file used by Silverlight applications to declare shared resources like brushes,various style objects etc. Also, the code behind file of app.xaml is used to handle globalapplication level events like Application_Startup, Application_Exit andApplication_UnhandledException. (Similar to Global.asax file for ASP.NET applications)

    When Visual Studio creates the app.xaml file automatically, it creates few event handlerswith some default code. You can change the code appropriately.

    private void Application_Startup(object sender, StartupEventArgs e){}

  • 8/4/2019 What is Silver Light

    8/41

    private void Application_Exit(object sender, EventArgs e){}

    private void Application_UnhandledException(object sender,ApplicationUnhandledExceptionEventArgs e)

    {}

    For ASP.NET developers, the above code will look familiar. This is similar to the aplicationlevel event handlers in Global.asax.

    Page.xaml file

    When you create a Silverlight project using Visual Studio 2008, it creates a default xaml filecalled "Page.xaml". This is just a dummy start page created by Visual Studio and it does notcontain any visible UI elements. The default content of the page.xaml file looks like this:

    The above code shows a user control and a Grid control. The UserControl is a high levelcontrol that holds all other UI elements in a xaml file.

    The Grid control is used as a layout panel and it can hold other UI elements. All UI elementsin a .xaml control must be placed within a layout panel. There 3 different types of layout

    panels available in Silverlight 2.0. You will learn more about layout controls in a laterchapter.

    When you compile your Silverlight Application project, it will compile all .xaml files andvarious other resources in to a single assembly file. This assembly file will have the extension.xap and will have the same file name as your project name.

    To place your Silverlight control in a web page, you must refer to this .xap file in your webpage. When the .xap file is referred in a web page, the default .xaml page will be shown.Based on user actions, you may open or close various .xaml files included in your .xapassembly (Silverlight Application project).

  • 8/4/2019 What is Silver Light

    9/41

    Getting started with XAML tagsLet us add a xaml tag to your Page.xaml file and see how it works.

    Open page.xaml file from your Visual Studio project and place the following code within the Gridelement:

    Now compile and run the application. You can see a blue rectangle displayed in your web page.

    As demonstrated above, the elements in a Silverlight xaml page are declared using XAML tags.Silverlight 2 offers several XAML tags including common form tags like textbox, button etc andvarious other UI elements like rectangle.

    One nice thing about Visual studio is, it will show you a preview of the page as you type the xamltags. When you complete typing the above xaml tags in your .xaml page, you will see the designpreview in Visual Studio as shown below:

  • 8/4/2019 What is Silver Light

    10/41

    You can swap the position of the code and preview by pressing the icon with 2 arrows in the middleof the screen (between the tabs "XAML" and "Design". Also, you can use the icons on the right end

    between the code and design panes to change the position of the code pane and design preview.

    How to place a Silverlight control in a webpage ?Each Silverlight Application project can have multiple .xaml pages. When you create a newSilverlight Application project, Visual Studio creates a default .xaml file called Page1.xaml.To add more .xaml pages, right click on the project in the Solution Explorer and select "Add"and "New Item". Then select "Silverlight User Control"

  • 8/4/2019 What is Silver Light

    11/41

    One or more Silverlight Applications can be placed in a web page using xaml tags as shownbelow:

    In the above tag, the attribute "source" represents the name of the xap file which is thecompiled output of the Silverlight project. The .xap files contains the compiled version of all.xaml files included in the Silverlight Application project.

    When you compile the Silverlight Application project, it will be compiled to an assemblywith the extension .xap . For example, if your Silverlight project name is"MySilverlightControl", when compiled, it will produce the assemblyMySilverlightControl.xap

    Each Silverlight project can have multiple .xaml files. Each .xaml file is like a page or formby itself. When you place a Silverlight Application in a web page, only one .xaml control willbe visible at a time. Based on various user actions, you may dynamically open various .xamlpages (Just like you open forms in a windows application).

    How to set default .xaml page in aSilverlight control ?Each Silverlight project can have multiple .xaml files. However, only one .xaml file will bevisible at a time.

    When you create a Silverlight project in Visual Studio, it will create a .xaml file called"Page1.xaml" by default and this .xaml control will be displayed by default when you openthe web page.

    You can change the default .xaml page by setting the property "Application.RootVisual".

    To try this, add a .xaml file called "Page2.xaml" in your silverlight project.

    Now, open your App.xaml.cs file in the Silverlight project. Look at the Application_Startupevent handler. There you can see the default .xaml page being set. To change the default.xaml page, you have to specify the name of the class used in the .xaml page and set it to theApplication.RootVisual property as shown below:

    private void Application_Startup(object sender, StartupEventArgs e){

    this.RootVisual = new Page2();}

  • 8/4/2019 What is Silver Light

    12/41

    After you change the value here, compile the application and run. When the web page isopened, you can see that the new .xaml control is displayed in the web page.

    How to open XAML pages from anotherXAML page ?In a Silverlight application, you can have multiple XAML pages. When you use the .xap filein the web page, only one XAML control will be displayed at a time. The default XAML filedisplayed is determined by the following code in the App.xaml file:

    this.RootVisual = new Page1();

    You can change the above line to the class name of any oher xaml file to open that file bydefault.

    Another scenario is, you may want to open different xaml files from the default xaml page.For example, consider that you have a xaml control that prompt user to enter logininformation. After the login credentials are validated, you may want to redirect to anotherxaml file when the user click the "Submit" button.

    This can be done by setting the "Content" property of the xaml page.

    private void SubmitButton_Click(object sender, RoutedEventArgs e){

    this.Content = new NewXamlPage();}

    The above code shows how to set the "Content" property of the xaml control in the buttonclick event handler. When the user click on the submit button, the new xaml file(NewXamlpage) will be opened and original xaml file will be recycled.

    Open a specific xaml page from aSilverlight controlEach Silverlight application project may include multiple xaml pages. When you refer to a.xap file from a web page, the xaml page set using the Application.RootVisual property willbe displayed by default.

    There may be cases where you want different XAML files to be displayed when you refer to

  • 8/4/2019 What is Silver Light

    13/41

    the same .xap file from different web pages. You can do this by passing the xaml file name orsome other kind of identification using InitParameters property of the Silverlight control.This property can be set to the Silverlight control from the web page. The value set from webpage will be read by the Silverlight control and appropriate xaml page will be opened.

    To demonstrate this, let us create a sample Silverlight project with the name"OpenSpecificXaml". (You can read the steps to create a new Silverlight project .)

    After you compile and build your project, place the Silverlight control in your web page asshown below:

    In the above code, see the code:

    InitParameters="PageName=Page1"

    Here we are setting the property "InitParameters" with a key-value pair indicating whichxaml page we want to open by default.

    Now, we will read this property in the App.xaml file and set the appropriate page to theApplication.RootVisual property. Here is the sample code to use in the App.xaml.cs toachieve this:

    private void Application_Startup(object sender, StartupEventArgs e){

    IDictionary parameters = e.InitParams;

    if (parameters == null){

    // No parameter passed.. open the default xamlthis.RootVisual = new DefaultPage();

    }else if (parameters["PageName"] == "Page1"){

    this.RootVisual = new Page1();}else if (parameters["PageName"] == "Page2"){

    this.RootVisual = new Page2();}else{

    // Open the default xamlthis.RootVisual = new DefaultPage();

    http://www.dotnetspider.com/tutorials/Silverlight-Tutorial-301.aspxhttp://www.dotnetspider.com/tutorials/Silverlight-Tutorial-301.aspxhttp://www.dotnetspider.com/tutorials/Silverlight-Tutorial-301.aspxhttp://www.dotnetspider.com/tutorials/Silverlight-Tutorial-301.aspx
  • 8/4/2019 What is Silver Light

    14/41

    }}

    Layout controls in Silverlighthere are 3 different types of layout panels provided by Silverlight. The Grid control is one of them.

    These are the 3 different types of layout panels provided by Silverlight:

    1. Canvas - Position child elements absolutely in x,y space.2. StackPanel - Position child elements relative to one another in horizontal or vertical stacks.3. Grid - Position child elements in rows and columns.

    You have to add a layout panel to every xaml page we create. All other UI elements must be addedinside one of the layout panels. Each page can have exactly one layout panel control.

    Layout panel controls in Silverlight -CanvasSilverlight offers 3 panel controls which can be used to define the layout and positioning of the controls in a page. Canvas is one of the available layout controls.

    Canvas defines a area within which you can place other controls by specifying the x and ycoordinate position. It is possible to overlap multiple controls within a canvas. Contrary toregular HTML, when controls are overlapped in a Canvas, overlapped controls can hide othercontrols.

    When controls are placed within a Canvas, the x and y coordinates must be specified for eachcontrol using the attributes Canvas.Left and Canvas.Top

    This sample shows how to place a rectangle control within a Canvas by specifying x and ycoordinates:

    The above xaml tags defines a rectangle, filled with green color, of size 100x100 pixels. Therectangle will be placed 25 pixels from the left of the Canvas and 40 pixels from the top of the Canvas.

    The below example shows 3 rectangles overlapped each other:

  • 8/4/2019 What is Silver Light

    15/41

    The below images shows how the output look like:

    How to display image in a Silverlight

    control ?

    In Silverlight, the image control can be used to display images. The usage is pretty straight forward.The syntax of using Image control is shown below:

    Image.stretch Property

    The Stretch attribute can have the following values:

    1. None

    This will do no modification on the size of the image. If the image size is more than the size of thecontainer, then the image will be cut to fit in the container.

  • 8/4/2019 What is Silver Light

    16/41

    2. Fill

    In this case, the image will be expanded to fill the region of the container. The aspect ratio(proportion of width and height) will not be maintained.

    3. Uniform

    This is the default value. In this case, the image will be resized to fit the container, but the aspectratio will be maintained. So, there may be blank space in the container depending on the width andheight of the image and container.

    4. UniformToFill

    In this case, the image will be resized and will fill the container, but aspect ratio will be maintained

    by trimming some portion of the image if required.

    Width and Height properties

    The width and height properties of the image can be used to override the stretch property. If widthand height properties are specified, then Stretch property will be ignored.

    Image.Clip property

    The clip property of Image control can be used in Silverlight to make certain portion of the image

    visible and hide some part of it.

    See an example of how to display an image in a elliptical form:

    The above code will produce an image like this:

  • 8/4/2019 What is Silver Light

    17/41

    How to drag and move an image or objectin Silverlight ?The control that you like drag or move with the mouse can be embedded within a Bordercontrol and then handle the mouse down, up and move events to make the object move withinyour layout panel.

    See sample .xaml code:

    In the above code, a Border control is placed in the Canvas. The most important code to noteis:

    MouseLeftButtonDown="border1_MouseLeftButtonDown"MouseLeftButtonUp="border1_MouseLeftButtonUp"MouseMove="border1_MouseMove"

    The above lines define 3 events that we like to handle. As the name indicates, we arehandling the mouse button down, mouse button up and mouse move events for the leftmouse.

  • 8/4/2019 What is Silver Light

    18/41

    In the code behind, when the left button is pressed, we will set a global variable to indicatethat user has started moving. In the mouse move event, we will get the current location of themouse pointer and then set the new position for the border control. When the left mousebutton is released, we will reset the global variable so that we will not move the object anymore.

    See the code for the code behind class:

    public partial class Page : UserControl{

    // Global variable to indicate if user has clicked border// and started/stopped moving.private bool moving = false;

    private double offSetX;private double offSetY;

    public Page(){

    InitializeComponent();}

    private void border1_MouseLeftButtonDown(object sender,MouseButtonEventArgs e)

    {// Left mouse button clicked within border. start moving.moving = true;

    Point offset = e.GetPosition(border1);offSetX = offset.X;offSetY = offset.Y;

    }

    private void border1_MouseLeftButtonUp(object sender,MouseButtonEventArgs e)

    {// Left mouse button release. Stop moving.moving = false;

    }

    private void border1_MouseMove(object sender, MouseEventArgs e){

    if (moving){

    // Get the new mouse pointer positionCanvas parent = (Canvas)this.border1.Parent;Point p = e.GetPosition(parent);double x = p.X - offSetX;double y = p.Y - offSetY;

    // Set the new position for the border control.this.border1.SetValue(Canvas.LeftProperty, x);this.border1.SetValue(Canvas.TopProperty, y);

    }}

    }

  • 8/4/2019 What is Silver Light

    19/41

    You can download a sample project for this tutorial.

    How to pass parameters to Silverlightcontrols from ASP.NET pages ?You can pass parameters from your aspx pages and html pages to the Silverlight controls.This chapter explains how to pass parameters to Silverlight controls from your aspx page andcode behind files.

    InitParameters

    The Xaml page user control has a property called InitParameters . You can set a value in theform of key-value pairs from your ASPX pages. Since this property accepts key-value pairs,you can pass any set of string values.

    How to set InitParameters

    Example - Set InitParameters property from ASPX page:

    You can set this property from the code behind file of your ASPX page as well.

    Example - Set InitParameters property from the code behind file:

    Xaml1.InitParameters = "City=Houston,State=Texas,Country=USA";

    How to retrieve the InitParameters value ?

    The value you pass to a Silverlight control through the InitParameters property can beretrieved from the Application_Startup even handler in the App.xaml page.

    private void Application_Startup(object sender, StartupEventArgs e){

    IDictionary parameters = e.InitParams;

    this.RootVisual = new Page1();

    Now, in most cases, you may want to pass this value to the xaml page itself instead of doing

    http://www.dotnetspider.com/downloads/tutorials/silverlight/DragAndMove.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/DragAndMove.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/DragAndMove.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/DragAndMove.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/DragAndMove.zip
  • 8/4/2019 What is Silver Light

    20/41

    anything with in it the App.xaml.

    Pass parameters from App.xaml to other pages

    To pass the parameters from the App.xaml pages to other pages, you must modify the

    constructor of xaml page class to accept parameters.

    private IDictionary parameters = null;

    public Page1(){

    InitializeComponent();}

    public Page1(IDictionary p){

    this.parameters = p;

    InitializeComponent();}

    The above sample shows an additional constructor added which takes a parameter of typeIDictionary and then sets the value to a member variable.

    Now go back to your App.xaml and pass the parameters to the page:

    private void Application_Startup(object sender, StartupEventArgs e){

    IDictionary parameters = e.InitParams;

    this.RootVisual = new Page1( parameters );

    Use the IDictionary parameter values in the XAML pages

    If you have followed the above steps correctly, you should be able to access the IDictionaryvalues in your XAML page.

    textblock1.Text = this.parameters["City"];

    Here is the complete code from the XAML page:

  • 8/4/2019 What is Silver Light

    21/41

    In the code behind file for your page1.xaml, you can set the Text for the textblock1 control asshown below:

    private void UserControl_Loaded(object sender, RoutedEventArgs e){textblock1.Text = parameters["City"];

    }

    You can download a sample project for this tutorial.

    How to call WCF methods from Silverlight

    controls ?Silverlight controls get executed on the client browser. It does not have direct access to thedata on the serverside. So, if your Silverlight controls need to retrieve data from database orother data sources on the server, we have to use various approaches like WCF calls or dependon the InitParameters property of the Silverlight controls.

    The recommended approach to get server side data to Silverlight controls is using WCFmethod calls. The most important benefit is the type safety.

    The following sample demonstrates how to use WCF to retrieve data from Server side toSilverlight controls on the client side.

    In this sample, we will create a Silverlight project and another web project to host theSilverlight control. Also, we will add a WCF Service to the web project.

    Silverlight with WCF sample

    Create a new Silverlight project with a web project to host the Silverlight control.

    Open Visual Studio and select the menu "File" > "New" > "Project"Select the Project Type as "Silverlight" under your favorite language and choose the template"Silverlight Application". I have selected Visual C# as the tutorials here.

    I have named my project as "MySilverlightApp" and have selected the option "Createdirectory for solution" so that all my project files are organized within a folder structure.

    http://www.dotnetspider.com/downloads/tutorials/silverlight/PassParameters.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/PassParameters.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/PassParameters.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/PassParameters.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/PassParameters.zip
  • 8/4/2019 What is Silver Light

    22/41

    In the next screen, choose the option "Add a new web to the solution for hosting the control".

    Right click on the web project in the Solution Explorer and select "Add New Item".

    Select the category "Silverlight" from the left panel in the dialog box.

    From the right panel, select the template "Silverlight-enabled WCF Service"

    Choose the default name "Service1.svc" and press the "Add" button.

    (The current beta version of Visual Studio may show you an error object reference not set toan instance .... Ignore this error and proceed.)

    You can see the below code:

    [ServiceContract(Namespace = "")][AspNetCompatibilityRequirements(RequirementsMode =

  • 8/4/2019 What is Silver Light

    23/41

    AspNetCompatibilityRequirementsMode.Allowed)]public class Service1{

    [OperationContract]public void DoWork(){

    return;}}

    Explaining the concepts of WCF is beyond the scope of this tutorial. However, I just want topoint out 2 things here:

    [ServiceContract(Namespace = "")]- This attribute above the class name indicates that this class is a WCF service.

    [OperationContract]

    - This attribute above the method name indicates that this method can be called from a WCFclient.

    Let us add a new method to our WCF service class, decorated with the [OperationContract]attribute. Add a method as shown below:

    [OperationContract]public string GetName(){

    return "John";

    }

    As you can see, it is a simple method which returns a hard coded name.

    Open your solution explorer. Right click on the file "Service1.svc" and select "Set as StartupPage".

    Now run the application by pressing Ctrl + F5 (or, using the menu "Debug" > "Start WithoutDebugging")

    The browser will be opened and Service1 meta data will be displayed. Ignore the content inthe page, but copy the URL from the browser. The URL will look something like this:http://localhost:1873/Service1.svcThe port number may be different in your case, but that is OK.

    Return to your Solution Explorer in Visual Studio. Right click on your Silverlight project (notweb project) and select "Add Service Reference".

    In the field for Address, specify the URL you copied from the browser and press "GO".

    In the bottom left, change the namespace to "MySampleService".

    You should see a screen like this:

  • 8/4/2019 What is Silver Light

    24/41

    Press "OK" to add the service reference.

    Now you can call our WCF service from the Silverlight client.

    To test this, follow these steps:

    1. Open the Page1.xaml file and add a textblock to display the string returned from the WCFmethod call.

    2. Add an event handler for the "Loaded" event of the UserControl.

    Complete code from Page1.xaml is given below:

    Now go to the code behind file (Page1.xaml.cs) and add the WCF service call as shownbelow:

    private void UserControl_Loaded(object sender, RoutedEventArgs e){

    MySampleService.Service1Client client = newMySampleService.Service1Client();

    client.GetNameCompleted += new EventHandler(client_GetNameCompleted);

  • 8/4/2019 What is Silver Light

    25/41

    client.GetNameAsync();}void client_GetNameCompleted(object sender,MySampleService.GetNameCompletedEventArgs e){

    textblock1.Text = (string)e.Result;

    }

    Open the web project in Solution Explorer and set the Silverlight test page as the startuppage. Now run the project. You can see that the WCF service is called from Silverlight clientand the result is displayed in the browser. (In our sample, the result from the WCF call is thename "John" and this name will be displayed in the screen).

    You can download a sample project for this tutorial.

    Access Session variables from SilverlightcontrolsSilverlight controls are client side controls. They get executed on the browser on the clientmachines and they do not have direct access to the server side data.

    Since Session variables live on the web server, Silverlight controls cannot access themdirectly. However, there are several ways Silverlight can retrieve the server side dataincluding Session information.

    Let us explore some of the possible options to make Session data available to Silverlightcontrols.

    Option 1: Push session data to the client in the form of VIEWSTATE data or data for UIcontrols. The dis advantage with this approach are no type safety, only minimal data can besent, data is visible to users etc.

    Option 2: Use the InitParameters property of the Silverlight controls to push data to theSilverlight controls. This approach also have problems like no type safety, only minimal datacan be sent etc.

    Option 3: Use WCF service calls to retrieve data from server. Using this approach, Silverlightcontrols can call WCF services to retrieve larger volume of data without having thedisadvantages of the above 2 options.

    To use WCF to get Session data from server to Silverlight controls, all you need to do iscreate a simple WCF service. This service should have a method that takes the session key as

    input parameter and return the corresponding value from the session, as shown below:[OperationContract]

    http://www.dotnetspider.com/downloads/tutorials/silverlight/Silverlight_With_WCF.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/Silverlight_With_WCF.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/Silverlight_With_WCF.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/Silverlight_With_WCF.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/Silverlight_With_WCF.zip
  • 8/4/2019 What is Silver Light

    26/41

    public object GetSessionVariable(string key){

    return System.Web.HttpContext.Current.Session[key];}

    Create a new Silverlight project with a web project to host the Silverlight control.

    Steps:

    1. Open Visual Studio and select the menu "File" > "New" > "Project"

    2. Select the Project Type as "Silverlight" under your favorite language and choose thetemplate "Silverlight Application". I have selected Visual C# as the tutorials here. I havenamed my project as "AccessSessionFromSilverlight" and have selected the option "Createdirectory for solution" so that all my project files are organized within a folder structure.

    3. In the next screen, choose the option "Add a new web to the solution for hosting thecontrol".

    4. After Visual Studio creates the solution, right click on the web project in the SolutionExplorer and select "Add New Item".

    5. Select the category "Silverlight" from the left panel in the dialog box. From the right panel,select the template "Silverlight-enabled WCF Service"

    6. Choose the default name "Service1.svc" and press the "Add" button.

    7. You can see the below code:

    [ServiceContract(Namespace = "")][AspNetCompatibilityRequirements(RequirementsMode =AspNetCompatibilityRequirementsMode.Allowed)]public class Service1{

    [OperationContract]public void DoWork(){

    return;}

    }

    Add another mthod as shown below:

    [OperationContract]public object GetSessionVariable(string key){

    return System.Web.HttpContext.Current.Session[key];}

    8. Open your solution explorer. Right click on the file "Service1.svc" and select "Set asStartup Page".

  • 8/4/2019 What is Silver Light

    27/41

    9. Now run the application by pressing Ctrl + F5 (or, using the menu "Debug" > "StartWithout Debugging")

    The browser will be opened and Service1 meta data will be displayed. Ignore the content in

    the page, but copy the URL from the browser. The URL will look something like this:http://localhost:1873/Service1.svcThe port number may be different in your case, but that is OK.

    10. Return to your Solution Explorer in Visual Studio. Right click on your Silverlight project(not web project) and select "Add Service Reference".In the field for Address, specify the URL you copied from the browser and press "GO".In the bottom left, change the namespace to "MySampleService".Press "OK" to add the service reference.

    Now you can call our WCF service from the Silverlight client.

    To test this, follow these steps:

    1. Open the Page1.xaml file and add a textblock to display the string returned from the WCFmethod call.

    2. Add an event handler for the "Loaded" event of the UserControl.

    Complete code from Page1.xaml is given below:

    Now go to the code behind file (Page1.xaml.cs) and add the WCF service call as shownbelow:

    private void UserControl_Loaded(object sender, RoutedEventArgs e){

    MyService.Service1Client client = newAccessSessionFromSilverlight.MyService.Service1Client();

    client.GetSessionVariableCompleted += newEventHandler(client_GetSessionVariableCompleted);

    client.GetSessionVariableAsync("Name");}

    void client_GetSessionVariableCompleted(object sender,

    AccessSessionFromSilverlight.MyService.GetSessionVariableCompletedEventArgse){

  • 8/4/2019 What is Silver Light

    28/41

    if (e.Result == null)textblock1.Text = "Session variable not set";

    elsetextblock1.Text = e.Result.ToString();

    }

    Open the web project in Solution Explorer and set the Silverlight test page as the startuppage. Now run the project. You can see that the WCF service is called from Silverlight clientand the result is displayed in the browser.

    You can download a sample project for this tutorial.

    How to call Javascript functions fromSilverlight code ?

    One of the advantages of Silverlight is, it has access to the Html document of the web page inwhich it is hosted. This enables Silverlight to access HTML elements in the page and alsocall Javascript methods.

    The following steps shows how to call a Javascript method from Silverlight.

    Open the ASP.NET or HTML page which hosts the Silverlight control. Add the Javascriptmethod as shown below:

  • 8/4/2019 What is Silver Light

    29/41

    private void btnSayHello_Click(object sender, RoutedEventArgs e){

    HtmlPage.Window.Invoke("SayHello");}

    In order to use the HtmlPage class, you need to include the System.Windows.Browser

    using System.Windows.Browser;

    You are done. Run your Silverlight application and see. When you click on the button in theSilverlight control, you can see the popup message from the Javascript function.

    You can download a sample project for this tutorial.

    How to show a popup layer within aSilverlight web page?Add a button to your xaml page as shown below:

    Add the following code to your code behind file (page.xaml.cs)

    Popup p = new Popup();private void showPopup_Click(object sender, RoutedEventArgs e){

    // Create a panel control to host other controlsStackPanel panel1 = new StackPanel();panel1.Background = new SolidColorBrush(Colors.Gray);

    // Create a buttonButton button1 = new Button();button1.Content = "Close";button1.Margin = new Thickness(5.0);button1.Click += new RoutedEventHandler(button1_Click);

    // Create a text labelTextBlock textblock1 = new TextBlock();textblock1.Text = "The popup control";textblock1.Margin = new Thickness(5.0);

    // Add text label and button to the panel

    panel1.Children.Add(textblock1);panel1.Children.Add(button1);

    http://www.dotnetspider.com/downloads/tutorials/silverlight/CallJavascript.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/CallJavascript.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/CallJavascript.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/CallJavascript.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/CallJavascript.zip
  • 8/4/2019 What is Silver Light

    30/41

    // Now, make the panel a child of the popup so that// the panel will be shown within the Popup when displayed.p.Child = panel1;

    // Set the position.

    p.VerticalOffset = 25;p.HorizontalOffset = 25;

    // Show the popup.p.IsOpen = true;

    }

    void button1_Click(object sender, RoutedEventArgs e){

    // Close the popup.p.IsOpen = false;

    }

    Now run the application. You can see the page with a button. When you click on the button, apopup layer will appear with a text label and a button in it. When you click on the button inthe popup, it will close the popup.

    Display Tooltip for Silverlight controls

    The below sample code shows how to display a simple text tooltip for a Button control:

    See this example which sets a tooltip for a textbox control:

    Display rich UI elements in tooltip

    Silverlights ability to support UI elements in tooltip can be used to provide great user experience.We can use almost any UI element within a Tooltip. See various examples below.

  • 8/4/2019 What is Silver Light

    31/41

    Display image within a tooltip

    This sample code shows how to display an image within a tooltip in Silverlight:

    Tooltip for entire Silverlight control

    You can set a tooltip for the entire Silverlight control. See the below sample code:

    Programmatically set Tooltip

    You can set or change Tooltips from the code behind file. This example shows how to set a Tooltipfor a button control from the code behind file:

    ToolTipService.SetToolTip(MyButton, "This is new tooltip");

    How to play audio or sound files fromSilverlightSilverlight provides a class called MediaElement which can be used to play audio or videofiles.

    Silverlight MediaElement supports playing video/audio files in MP3 and WMV formats. Thecurrent version of Silverlight does not support .WAV files and .AVI files.

  • 8/4/2019 What is Silver Light

    32/41

    If you attempt to use .WAV or .AVI files with the MediaElement control, you will get thefollowing error:

    Error: Unhandled Error in Silverlight 2 Application Code: 3001

    Category: MediaErrorMessage: AG_E_INVALID_FILE_FORMAT

    In order to play an .MP3 or .WMV file, you must first include the file in your Silverlightproject and then set it as an Embedded Resource.

    In order to make an audio file an embedded resource, right click on the file in your projectand select 'properties'. Then set the 'Build Action' as 'Embedded Resource. This will make theaudio file embedded in to your .XAP file when compiled.

    Once you make the audio file as an embedded resource, you can play the file either bydefining the MediaElement within your XAML or by using the code. Here is the sample codeto play an audio file:

    MediaElement media = new MediaElement();Stream stream =Assembly.GetExecutingAssembly().GetManifestResourceStream("MyNamespace.Sound1.wav");media.SetSource(stream);media.AutoPlay = false;

    media.Stop();media.Play();

    Let us analyze the code.

    Stream stream =Assembly.GetExecutingAssembly().GetManifestResourceStream("MyNamespace.Sound1.wav");

    The above line retrieves the audio stream from the executing assembly. Remember that theaudio file is embedded in to the assembly since we set the Build Action as 'EmbeddedResource.

    In the above code, "MyNamespace" represents the namespace of your application."Sound1.wav" is the name of the audio file, assuming the file is located in the root of theapplication. If the file is within a sub directory, you may have to include the directory nameas well, separated by a period.

    media.SetSource(stream);

    In the above line, we are setting the source for the media player.

    media.AutoPlay = false;

  • 8/4/2019 What is Silver Light

    33/41

    The above line says that the player should not play the audio until we explicitly start it toplay.

    media.Stop();media.Play();

    In the above code, you can see that I am doing a .Stop() before .Play(). The Stop is requiredonly if you have to play the same MediaElement more than once.

    How to display custom Rightclick context

    menu in Silverlight controls?When you right click on any Silverlight controls in a web page, it display the defaultSilverlight context menu which with a single option view the Silverlight Configuration. Youmay intercept this context menu and display your own menu.

    The first step you have to do is, go to the aspx page where you are hosting the Silverlightcontrol and set the property "Windowless" to "True"

    Now, you can use the "AttachEvent" property of the browsers Document object to attachyour own event handler to the "oncontextmenu" event from your xaml pages.

    Sample code:

    System.Windows.Browser.HtmlPage.Document.AttachEvent("oncontextmenu",

    this.OnContextMenu);

    You may attach your event handler from the constructor of your XAML page. You can evendo this from the constructor of your App.xaml, in which case the event handler will betriggered from every xaml page you use in the project.

    And here is the code to handle the event:

    private void OnContextMenu(object sender,System.Windows.Browser.HtmlEventArgs e){

    MessageBox.Show("You click at " + e.OffsetX + "," + e.OffsetY);

  • 8/4/2019 What is Silver Light

    34/41

    e.PreventDefault();}

    The above code sample displays the coordinates you clicked. You may replace that code to

    display your own menu or popup window.

    The code e.PreventDefault();" prevents the events from being propagated to other childcontrols

    You can download a sample project for this tutorial.

    Introduction to DataBinding in SilverlightDataBinding is a link between a data source and a user interface. The data source providesdata to the user interface. The data in the user interface may be changed by the user whichwill be updated to the source and could be saved back to the database.The data source could be business objects, collections, database tables or any other form of data that support data binding.

    In this chapter, we will use a simple class called "Address" with the following properties:

    1. Name2. Address13. Address24. City5. State6. Zip code

    Let us create a Silverlight control which accepts user's name and address. You can create axaml control which has the following TextBlock elements:

    1. Name

    2. Address13. Address24. City5. State6. Zip code

    Here is the XAML which defines a grid and places the appropraite controls for our sample:

    http://www.dotnetspider.com/downloads/tutorials/silverlight/ContextMenu.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/ContextMenu.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/ContextMenu.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/ContextMenu.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/ContextMenu.zip
  • 8/4/2019 What is Silver Light

    35/41

    The above XAML defines a grid with 7 rows and 2 columns. The controls are places inappropriate rows and columns using the Grid.Row and Grid.Column property of individualcontrols. When placed in a web page, our Silverlight control will look like this:

  • 8/4/2019 What is Silver Light

    36/41

    Now create a class called "Address" which has properties representing various fields weneed. See the sample code for the "Address" class:

    public class Address{

    public string Name { get; set; }public string Address1 { get; set; }public string Address2 { get; set; }public string City { get; set; }public string State { get; set; }public string Zipcode { get; set; }

    }

    Go to the code behind file of the xaml class and create an instance of the Address class asshown below:

    Address address;

    In the constructor of the XAML page class, initialize the Address class and bind it to the UIelements as shown below:

    address = new Address();txtName.DataContext = address;txtAddress1.DataContext = address;txtAddress2.DataContext = address;txtCity.DataContext = address;txtState.DataContext = address;txtZipcode.DataContext = address;

    In the above code, we are setting the DataContext property of each UI control to our"Address" object. But how do the control know which property of the address object to beused ? This is handled in the XAML. Take a look at the "txtAddress1" control. You can seethat the property "Text" is set as shown below:

    Text="{Binding Address1, Mode=TwoWay}"

    The above line defines that we are using data binding for the "Text" property of this control,and it will use the property "Address1" of whatever object it will be bound to. Also, it statesthat the Mode is "TwoWay" which means the value will be read from the object and set to the"Text" property and also when the value is changed in the textbox control, it is saved back tothe data source. In our case, we are binding our Address object to the textbox control. Whenloaded, it will display the default value from our object in the textbox. When the value ischanged by the user, the datasource object will be updated with the new value from text box.

    Typically, when we add a new address, the object will be initialized to empty values and thetextboxes will be empty. When we edit an existing address, the object will have values

    populated from database and it will be displayed in the UI controls using the databinding.When values are modified by the user, the datasource object will be automatically modified.

  • 8/4/2019 What is Silver Light

    37/41

    All we have to do is, save the modified datasource object in to the database.

    You can download a sample project for this tutorial.

    Silverlight databinding examples:BindingMode EnumerationIn the previous chapter, I gave an introduction to databinding in Silverlight . In the previousexample, we used the databinding mode "TwoWay". I will explain what it means and how tochange the previous sample to make it a "real two way binding".

    The DataBindingMode is an enumeration with 3 possible values:OneTime : In this mode, the data is updated from the source to the target (UI) once. Anychanges to the data source after this will not be reflected to the UI. This mode is used todisplay static data that does not change often.

    OneWay : In this mode, the target will be updated as and when the source changes. This isuseful if you need to display data which changes often in the background.

    TwoWay : As the name indicates, this mode will update both ways. When the sourcechanges, the target is updated. When the values in the target is changed, the source is

    updated.

    In order to support the modes "OneWay" and "TwoWay", the binding source must implementthe interface INotifyPropertyChanged . In addition, the properties of the data source musttrigger the PropertyChanged event so that the databinding target will be notified of thechanges in the source. Without this, the background changes on the data source will not beupdated to the binding target.

    Here is the source code of a sample Address class we can use to bind data to our UI controls:

    using System.ComponentModel;

    namespace DataBinding_Address{

    public class Address : INotifyPropertyChanged {

    public event PropertyChangedEventHandler PropertyChanged;

    private string _name = "";

    public string Name{

    get{

    return _name;}set

    http://www.dotnetspider.com/downloads/tutorials/silverlight/DataBinding_Address.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/DataBinding_Address.ziphttp://www.dotnetspider.com/downloads/tutorials/silverlight/DataBinding_Address.ziphttp://www.dotnetspider.com/tutorials/Silverlight-Tutorial-322.aspxhttp://www.dotnetspider.com/tutorials/Silverlight-Tutorial-322.aspxhttp://www.dotnetspider.com/tutorials/Silverlight-Tutorial-322.aspxhttp://www.dotnetspider.com/downloads/tutorials/silverlight/DataBinding_Address.ziphttp://www.dotnetspider.com/tutorials/Silverlight-Tutorial-322.aspxhttp://www.dotnetspider.com/downloads/tutorials/silverlight/DataBinding_Address.zip
  • 8/4/2019 What is Silver Light

    38/41

    {_name = value;

    if (PropertyChanged != null){

    PropertyChanged(this, new

    PropertyChangedEventArgs("Name"));}}

    }}

    }

    I have included only 1 property ( Name ) in the above code. You may extend the class to addadditional properties like City, State etc.

    The above sample code shows it is raising the PropertyChanged event when the Name isupdated for the object. This will notify the bound control about the change and the target

    control will update it's value accordingly.

    The attached sample project uses a class called 'Address' as the data source. Each property of the address object is bound to a TextBlock control in the UI using "TwoWay" binding mode.When user type any text in the UI controls, the data is updated to the address object datasource. Similarly, if the address object is changed in the background, the UI is automaticallyupdated.

    The UI include a "Clear" button. On the click event of this button, I am reseting theproperties of the address object to empty string.

    private void btnClear_Click(object sender, RoutedEventArgs e){

    address.Name = string.Empty;address.Address1 = string.Empty;address.Address2 = string.Empty;address.City = string.Empty;address.State = string.Empty;address.Zipcode = string.Empty;

    }

    Through the 2-way databinding, this will automatically clear the text in the respective UIcontrols.

    You can download a sample project for this tutorial.

    How to set a background image for yourSilverlight control

    In Silverlight, the ImageBrush element can be used to fill an area with an image. The areacould be various shape elements or the entire Canvas itself.

    http://www.dotnetspider.com/attachments/tutorials/silverlight/DataBinding_Address_TwoWay.ziphttp://www.dotnetspider.com/attachments/tutorials/silverlight/DataBinding_Address_TwoWay.ziphttp://www.dotnetspider.com/attachments/tutorials/silverlight/DataBinding_Address_TwoWay.ziphttp://www.dotnetspider.com/attachments/tutorials/silverlight/DataBinding_Address_TwoWay.ziphttp://www.dotnetspider.com/attachments/tutorials/silverlight/DataBinding_Address_TwoWay.zip
  • 8/4/2019 What is Silver Light

    39/41

    This code sample shows how to use the ImageBrush to set a background image for theSilverlight canvas control.

    The below example shows how to Fill an ellipse area with an image control. In addition, I amusing the Mouse Enter and Mouse Leave events to dynamically change the image used to fillthe Ellipse shape.

    Here is the C# code to handle the Mouse Enter and Mouse Leave events and dynamicallychange the image in these events:

    private void ellipse1_MouseEnter(object sender, MouseEventArgs e){

    ImageBrush brush = new ImageBrush();brush.ImageSource = new BitmapImage(new

    Uri(@"Images/Flower1.png", UriKind.Relative)); ;ellipse1.Fill = brush;

    }

    private void ellipse1_MouseLeave(object sender, MouseEventArgs e){ImageBrush brush = new ImageBrush();brush.ImageSource = new BitmapImage(new

    Uri(@"Images/Flower2.png", UriKind.Relative)); ;ellipse1.Fill = brush;

    }

    Javascript to detect if Silverlight is installed

  • 8/4/2019 What is Silver Light

    40/41

  • 8/4/2019 What is Silver Light

    41/41