Saturday 27 July 2013

SILVER LIGHT IN DOT NET BY ANIL KUMAR

                                  silverlight

This gives an introduction to the new Microsoft Silverlight technology.
Silverlight is a web based technology, launched by Microsoft in April 2007. Silverlight is considered as a competitor to Adobes Flash.

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

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 without need of much programming. It allows them to handle events from web pages (like handle start/end of video playing etc)


What is .xap file ?

This chapter explains the purpose of .xap file in Silverlight applications
.xap file is the compressed output file for the Silverlight application. The .xap file includes AppManifest.xaml, compiled output assembly of the Silverlight project (.dll) and any other resource files referred by the Silverlight application.

Web pages like .aspx files and .html files use the Silverlight components by loading the .xap files using the <object> tag in the HTML or by using <asp:Silverlight> tag in the ASP.NET pages.

".xap" files (pronounced "zap") use the standard .zip compression algorithm to minimize client download size. A "hello world" .NET Silverlight application (built using VB or C#) is about 5KB in size.

Let us see how a .xap file look like.

Open Visual Studio and create a new project by selecting "Silverlight Application" under the project type "Silverlight". Choose the project name "SilverlightTest". In the next screen, choose the option "automatically generate a test page to host Silverlight at build time".

Visual Studio creates a project with 2 files:

1. App.xaml
2. Page.xaml

Compile and run the application by pressing Ctrl + F5. You can see the browser opening with an empty page (the page is empty because you have nothing in your default xaml file).

Now open your windows explorer and look in to the bin\debug folder of your project. You can see a file called "SilverlightTest.xap".

Rename this file to SilverlightTest.zip and open it using any decompression tool. You can see that this is just like any other zip file and it includes the projects output dll and another file called "AppManifest.xaml".


How to pass parameters to Silverlight controls from ASP.NET pages ?

In this chapter, you can learn how to pass parameters to Silverlight controls from within your aspx 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 and code behind files.

InitParameters

The Xaml page user control has a property called InitParameters. You can set a value in the form 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:

<asp:Silverlight
   ID="Xaml1"
   runat="server"
   Source="~/ClientBin/MySilverlightApp.xap"
  
InitParameters="City=Houston,State=Texas,Country=USA"
   Width="300"
   Height="300" />


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 be retrieved 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 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<string, string> parameters = null;

public Page1()
{
    InitializeComponent();
}

public Page1(IDictionary<string, string> p)
{
    this.parameters = p;

    InitializeComponent();
}


The above sample shows an additional constructor added which takes a parameter of type IDictionary 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 IDictionary values in your XAML page.

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


Here is the complete code from the XAML page:

<UserControl x:Class="MySilverlightApp.Page1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300"
Loaded="UserControl_Loaded">

    <Grid x:Name="LayoutRoot" Background="White">

<TextBlock x:Name="textblock1" Width="200" Height="30"></TextBlock>

    </Grid>
</UserControl>


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

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


How to call WCF methods from Silverlight controls ?

This tutorial and the attached sample project demonstrates how to access server side data from Silverlight controls using WCF.
Silverlight controls get executed on the client browser. It does not have direct access to the data on the serverside. So, if your Silverlight controls need to retrieve data from database or other data sources on the server, we have to use various approaches like WCF calls or depend on the InitParameters property of the Silverlight controls.

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

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

In this sample, we will create a Silverlight project and another web project to host the Silverlight 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 "Create directory for solution" so that all my project files are organized within a folder structure.

http://www.dotnetspider.com/images/tutorials/silverlight/CreateSilverlightProject.jpg

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

http://www.dotnetspider.com/images/tutorials/silverlight/CreateProject_step2.jpg

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 to an instance .... Ignore this error and proceed.)

You can see the below code:

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = 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 to point 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 WCF client.




Calling WCF from Silverlight controls - Part II

This chapter is a continuation of the previous chapter and explains how to call WCF methods from the Silverlight controls.
This chapter is the continuation of the previous chapter. If you havent read the previous chapter, please read it before you continue here.

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 Startup Page".

Now run the application by pressing Ctrl + F5 (or, using the menu "Debug" > "Start Without 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.svc
The 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 (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".

You should see a screen like this:

http://www.dotnetspider.com/images/tutorials/silverlight/AddWCFService.jpg

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 WCF method call.

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

Complete code from Page1.xaml is given below:

<UserControl x:Class="Silverlight_With_WCF.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300"
    Loaded="UserControl_Loaded">
    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock x:Name="textblock1" Width="200" Height="30"></TextBlock>
    </Grid>
</UserControl>


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

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    MySampleService.Service1Client client = new MySampleService.Service1Client();
    client.GetNameCompleted += new EventHandler(client_GetNameCompleted);
    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 startup page. Now run the project. You can see that the WCF service is called from Silverlight client and the result is displayed in the browser. (In our sample, the result from the WCF call is the name "John" and this name will be displayed in the screen).

No comments:

Post a Comment