Tuesday, May 19, 2009

Silverlight Basics

1.     Introduction

This document provides details regarding how to use Silverlight applications in asp.net application.

2.     What is Silverlight?

Microsoft Silverlight is a programmable web browser plug-in that enables features such as animation, vector graphics and audio-video playback that characterizes rich internet applications. Silverlight 2.0 brought additional interactivity features and support for .Net languages and development tool. It is compatible with multiple web browser used in Win OS and Mac OS. Mobile devices will also be supported.

3.     Features of Silverlight

Silverlight has many features with the .Net framework. Silverlight 2.0 is implemented in .Net framework3.0 to execute the silverlight in the .Net applications. It provides a retained mode graphics system similar to Windows Presentation Foundation (WPF) and integrates multimedia, graphics, animation and interactivity into a single runtime environment. JavaScript scripting can be used to interact with silverlight. Silverlight has the feature to playback the audio and video files with out requiring any plug-in. The Silverlight xaml file and the code behind are compiled and compressed using ZIP and stored in a xap file.

 

Silverlight with a lightweight class library which includes features such as extensible controls, xml web service, networking components and LINQ APIs, Silverlight is a platform independent.

The .Net Framework3.5 in Silverlight adds a subset of WPF UI-programming model, including support for shapes, documents, media and animation objects of WPF. Reusing of Silverlight Design code in WPF is possible with slight modifications. We can develop a xaml application and use for both WPF and Silverlight applications.

 

Silverlight will not support AJAX; there are no validators for the input controls in silverlight. To implement the validation in silverlight forms, we can write validation scripting using JavaScript or we can use special validators for silverlight from Microsoft.

 

Silverlight also includes classes for data access over XML based Web Services, WCF Services and ADO.NET Data Services. 

3.1. Silverlight & WPF

            WPF applications can be deployed to the desktop or run in Internet Explorer (on Windows only). When WPF application run in Internet Explorer they run in a sandbox, so users simply point Internet Explorer at an URL and your application appears without any installation or confirmation need. All development tools are the same (Visual Studio) when making desktop and browser-based WPF applications and you can use the same widgets for both. WPF running in Internet Explorer have some restrictions compared to a program running on the desktop. For example, opening new windows is not possible and communication (WCF) is not allowed. Apparently SOAP calls can be used instead. But Silverlight applications can be deployed to more platforms (OS X and Linux) and more browsers. Like browsers-based WPF applications lose access to some functions compared to desktop applications, Silverlight applications can build on even less infrastructure. Silverlight running sandboxed on "major browsers" on Windows, Linux and OS X -- heavily reduced WPF (missing some 3D functions, widgets gone, etc.) Depend on other 3rd party tools for this functionality. If you develop a Rich Internet Application, it seems like choosing between WPF and Silverlight will be an important decision that will heavily shape your project. When reusing the same code for WPF and Silverlight user controls, the WPF will align the controls in absolute positioning. So when importing the same code inside the silverlight, the slight code changes in alignment of controls should be implemented. In silverlight, there are only limited controls. Silverlight code can be easily implemented in WPF application as the silverlight is a subset of WPF.

3.2. Ajax implementation in Silverlight

            The silverlight will not support AJAX. The validations can be done in silverlight only with the help of javascript or microsoft introduces the validation control toolkit for silverlight. This validation toolkit can be used easily in the silverlight application by referencing the silverlightvalidator assembly in the application. There are seven validators in this assembly namely,

 

·        RequiredField Validator

·        Range Validator

·        Length Validator

·        Regex Validator

·        Phone Validator

·        Numeric Validator

·        SSN Validator

 

Sample code for validation:

 

<TextBox x:Name="txtRange" Height="25" Width="100" >

<slv:ValidatorService.Validator>

<slv:RangeValidator

Min="0"

Max="10"

IsRequired="True"

ManagerName="Group1"

ErrorMessage="Type only between the range"/>     

</slv:ValidatorService.Validator>

</TextBox>

 

            Here the Range Validator is used for the textbox in silverlight. The range falls between 0 to 10. The validator will not allow the user to enter other than the range. Here this validator will also validates the text box as required field.

3.3. Communication

In Silverlight 2.0, the communications of Silverlight and JavaScript in 3 cases are as follows,

·        Silverlight to Silverlight Navigation.

·        Silverlight to JavaScript communication.

·        JavaScript to Silverlight communication. 

The above cases are explained as follows.
 

3.3.1. Silverlight to Silverlight Navigation 

The Navigation of silverlight forms with one another can be easily made in the client side with the help of the some code in the codebehind. If there is two xaml forms  in the silverlight application. We can navigate by the code "this.content= new Page();". By changing the Page() to the next page xaml name. We can also pass values to the second page by initializing an object for that class and we can access all the control of the second class and can pass the value. Sample code for passing values and navigation is as follows

 

Page obj = new Page();

      obj.txtName.Text = cbxEnter.SelectedItem.ToString().Trim();

      this.Content = obj;

Here the Page() is a xaml file, which has a textbox named 'txtName'.  The value which is selected in the combo box of this page namely 'cbxEnter' is assigned to the textbox 'txtName' of Page(). Then the same object is given to the 'this.content'. So that the xaml navigation occurs and the value is moved from one xaml page to another.

3.3.2. Silverlight to JavaScript Communication

The silverlight can communicate with javascript easily. By adding the attribute '[ScriptableType]' for the partial class of the UserControl, in the constructor, we have to register a scriptable object and we have to invoke a javascript function which is placed in javascript file or in the aspx page. The sample code for silverlight to javascript communication is as follows

Code behind code:

[ScriptableType]

    public partial class NewSample : UserControl

    {

        public NewSample()

        {

            InitializeComponent();

 

            HtmlPage.RegisterScriptableObject("Page", this);         

        }

  private void btnTest_Click(object sender, RoutedEventArgs e)

        {

            System.Windows.Browser.HtmlPage.Window.Invoke("ShowTitle",

"Hello from silverlight");

        }

    }

 

Aspx code:

 

<script type="text/javascript">

       function ShowTitle(msg)

 {

            alert("Message From Silverlight :" + msg);

       }

      </script>

 

            Here in the sample code, the javascript function 'ShowTitle(msg)' is called in the button click event in codebehind. By this way, we can interact with the parent page from xaml silverlight.

3.3.3. JavaScript to Silverlight Communication

The silverlight can communicate with javascript easily. The interaction between javascript and silverlight can be done easily by adding the attribute '[ScriptableType]' for the partial class of the UserControl, in the constructor, we have to register a scriptable object and we have to invoke a javascript function which is placed in javascript file or in the aspx page.

In the javascript function, get the elementid of the silverlight xaml. To call the code behind function from javascript, the attribute '[ScriptableMember]' should be added to the function. We can call the code behind function as shown in the sample code as follows

Aspx code:

<script type="text/javascript">

      function ShowTitle(msg)

{

      alert("Message From Silverlight :" + msg);

            var ctrl = document.getElementById("Xaml1");

            ctrl.Content.Page.DisplayText("Hello from javascript");

      }

</script>

 

Code behind code:

[ScriptableType]

    public partial class NewSample : UserControl

    {

        public NewSample()

        {

            InitializeComponent();

 

            HtmlPage.RegisterScriptableObject("Page", this);

            System.Windows.Browser.HtmlPage.Window.Invoke("ShowTitle",

 "Hello from silverlight");

        }

 

        [ScriptableMember]

        public void DisplayText(string msg)

        {

            txtTitle.Text = msg;

        }

 

        private void btnTest_Click(object sender, RoutedEventArgs e)

        {

            System.Windows.Browser.HtmlPage.Window.Invoke("ShowTitle",

"Hello from silverlight");

        }

     }

Here in the sample code, the javascript function 'ShowTitle(msg)' is called in the button click event in codebehind. This javascript function again calls a code behind function. Thus the javascript and silverlight interaction can be implemented with the parent page from xaml silverlight.

 4.     Windows Communication Foundation (WCF)

 

 4.1. Introduction

                       

                                    WCF simplifiesdevelopment of connected applications

 through a new service-oriented programming model.

 

4.2. Step by step web service creation in WCF

           

             à Create new project,Select WCF select Application.

 

  à New project will open ,there will be interface class and .sve (service file). 

 

à In interface class IService1.cs

 

                        è Service Contract

è Operation contract

                        è Data contract

                        è Data member

è Message Contract         

 

Service contract:

                       

                         Service contract is the entire suite of offerings of the service. It can be   

           thought of as a definition of what the service provides.

 

Operation contract:

 

                        Operation contract is the method/operation which does a specific task.

            They actually carry out the implementations within them.

 

Data Contract:

       

Data contract can be consider as vehicles of data.

 

Data member:

 

                        Data member is mark property for data.

 

Message Contract:

           

                        Message contract is the embodiment of the messages that flow between

 the service and the client.

 

             Silverlight will not accept the Dataset so return value from WCF service should

       be in the generic list.

 

Code Interface class

public interface IService1

      {

                [OperationContract]

        IEnumerable<branch> check();

}

 

[DataContract]

      public class branch

      {

        int brId;

        string brName;

        public branch(int bId, string bNam)

        {

            brId = bId;

            brName = bNam;

 

        }

        [DataMember]

        public int BranchId

        {

            get { return brId; }

            set { brId = value; }

        }

        [DataMember]

        public string BranchName

        {

            get { return brName; }

            set { brName = value; }

        }

 

}

 

 

à In Service1.svc.cs

 

    Right click on IService Select Implement Interfaceà Implement Interface

    Method in interface class will come to Service.svc.cs     

Code Interface class 

List<branch> br = new List<branch>();

SqlConnection sc = new SqlConnection(ConfigurationManager.AppSettings["connection"].ToString());

#region IService1 Members    

        public IEnumerable<branch> check()

        {

            try

            {

                sc.Open();

                string str = "SELECT * FROM [RequestBranch]";

                SqlDataAdapter da = new SqlDataAdapter(str, sc);

                DataSet ds = new DataSet();

                da.Fill(ds);

                sc.Close();

 

                foreach (DataRow dr in ds.Tables[0].Rows)

                {

                    br.Add(new branch(Convert.ToInt32(dr[0]), dr[1].ToString()));

                }

 

                IEnumerable<branch> brs = from bran1 in br

select bran1;

return brs;

LINQ concept for return list collection to silverlight

            }

            catch (Exception ex)

            {

                

                throw ex;

            }

        }

 

       

No comments:

Post a Comment

HTML/JAVASCRIPT BLOG

You can find the help for html and javascript codes

Any Doubts Contact my Mail-ID:
kannan.mkv@gmail.com