Saturday, July 2, 2011

Silverlight - WCF in Silverlight 4

In my last article i discussed about how to use Web service in Silverlight 4 application.Web Service in Silverlight.
now in this article i will show you how to use WCF service in silverlight 4 application.


WCF Service
Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or 
word sent as XML, or as complex as a stream of binary data.



In what scenarios must WCF be used
  • A secure service to process business transactions.
  • A service that supplies current data to others, such as a traffic report or other monitoring service.
  • A chat service that allows two people to communicate or exchange data in real time.
  • A dashboard application that polls one or more services for data and presents it in a logical presentation.
  • Exposing a workflow implemented using Windows Workflow Foundation as a WCF service.
  • A Silverlight application to poll a service for the latest data feeds.

What is Difference between Web service and WCF Service ?

  • Web services can be hosted in IIS as well as outside of the IIS. While WCF service can be hosted in IIS, Windows activation service,Self Hosting,WAS and on lots of protocols like Named Pipe,TCP and others.Many people disagree how we can host the web service outside of the IIS but Here is the article.http://msdn.microsoft.com/en-us/library/aa529311.aspx.
  • In Web Services Web Service attribute will added  on the top of class. In WCF there will be a Service Contract attributes will be there. Same way Web Method attribute are added in top of method of Web service while in WCF Service Operation Contract will added on the top method.
  • In Web service System.XML.Serialization is supported while in the WCF Service System.RunTime.Serialization is supported.
  • WCF Services can be multithreaded via ServiceBehavior class while web service can not be.
  • WCF Services supports different type of bindings like BasicHttpBinding, WSHttpBinding, WSDualHttpBinding etc.while Web services only used soap or xml for this.
  • Web services are compiled into a class library assembly. A file called the service file is provided that has the extension .asmx and contains an @ WebService directive that identifies the class that contains the code for the service and the assembly in which it is located while in WCF.WCF services can readily be hosted within IIS 5.1 or 6.0, the Windows Process Activation Service (WAS) that is provided as part of IIS 7.0, and within any .NET application. To host a service in IIS 5.1 or 6.0, the service must use HTTP as the communications transport protocol.
  • The major difference is that Web Services Use XmlSerializer But WCF Uses DataContractSerializer.

Let See how to create a WCF service in silverlight 4

Step 1 
Download Silverlight 4 tools from the following link

Download Silverlight 4 toolkit from the following link
http://silverlight.codeplex.com/

Note : Select only April 2010 Toolkit Silverlight 4

Step 2
Create a Silverlight Application and give the solution name as SolSilverlight_WCF.


Click on image for better view

Note: Select Web Project Type as ASP.NET Web site.

Step 3
Select a ASP.net Web application(SolSilverlight_WCF.Web) and Add a WCF Service,right click on solution,select Add New Item,select WCF Service from installed Visual Studio templates and name it DeveloperService.svc and click on add button.

It will add two .cs (named IDeveloperService.cs and DeveloperService.cs)



Click on image for better view

Step 4
Create a Developer entity class in App_Code folder,it is look like this 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// 
/// Description for Developer
/// 
public class Developer
{
    #region Property

    public String DeveloperName
    {
        get;
        set;
    }

    public String Speciality
    {
        get;
        set;
    }

    public int Experience
    {
        get;
        set;
    }

    #endregion
}

Step 5
Now we will make some modification to the OperationContract.Remove default DoWork method from the IDeveloperService interface.Add a new Method named as GetDeveloperData,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IDeveloperService" in both code and config file together.
[ServiceContract]
public interface IDeveloperService
{
    [OperationContract]
    List<Developer> GetDeveloperData(); // Get Developer Data and store in List Object
}

Step 6
Implement IDeveloperService interface in Developer service class,Add Developer information and store in list object,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "DeveloperService" in code, svc and config file together.
public class DeveloperService : IDeveloperService
{
    /// 
    ///  Get Developer Data
    /// 
    /// List
    public List<Developer> GetDeveloperData()
    {
        try
        {
            // Create List Object
            List<Developer> DeveloperObj = new List<Developer>();

            // Add Developer Data to the list object
            DeveloperObj.Add(new Developer() 
            { 
                DeveloperName="Bhushan Pawar",
                Speciality="ASP.net",
                Experience=5
            });

            DeveloperObj.Add(new Developer()
            {
                DeveloperName="Ramdas Bhosale",
                Speciality="ASP.net",
                Experience=3
            });

            DeveloperObj.Add(new Developer()
            {
                DeveloperName = "Koste Budinoski",
                Speciality="ASP.net MVC",
                Experience=5
            });

            DeveloperObj.Add(new Developer()
            {
                DeveloperName="Kishor Naik",
                Speciality="WPF",
                Experience=3
            });

            DeveloperObj.Add(new Developer()
            {
                DeveloperName = "Kedar Deshpande",
                Speciality = "MS-SQL Server",
                Experience = 1
            });


            return DeveloperObj.ToList<Developer>();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }
}

Step 7
Add a reference of  WCF Service in silverlight application(SolSilverlight_WCF).Right click the Silverlight project and add a Service reference,it is look like this




Click on image for better view


Step 8
Add a WCF service in the silverlight application.Add Service Reference dialog box will open and click on Discover button and give the namesapace name as DeveloperServiceReference.




Click on image for better view


Now WCF service Ready now design silverlight page.


Step 9
Add a DataGrid and button on page,it is look like this
<Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="256*" />
            <RowDefinition Height="44*" />
        </Grid.RowDefinitions>
        <sdk:DataGrid x:Name="DgDeveloper" Grid.Row="0" Grid.Column="0" Margin="0,0,0,2" ItemsSource="{Binding}"></sdk:DataGrid>
        <Button x:Name="btnData" Grid.Row="1" Content="Data" Width="100" Height="30" HorizontalAlignment="Right" Click="btnData_Click" Margin="0,6,4,8" />
    </Grid>

Step 10
In Code Behind,On btnData click event call the WCF service,it is look like this
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 SolSilverlight_WCF
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void btnData_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Call WCF Service
                DeveloperServiceReference.DeveloperServiceClient DServiceClientObj = new DeveloperServiceReference.DeveloperServiceClient();

                // Wire up the Async Completed  handler
                DServiceClientObj.GetDeveloperDataCompleted += new EventHandler<DeveloperServiceReference.GetDeveloperDataCompletedEventArgs>(DServiceClientObj_GetDeveloperDataCompleted);

                // Call WCF Method
                DServiceClientObj.GetDeveloperDataAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

        void DServiceClientObj_GetDeveloperDataCompleted(object sender, DeveloperServiceReference.GetDeveloperDataCompletedEventArgs e)
        {
            try
            {
                // Bind the Developer Data in DataGrid
                DgDeveloper.DataContext = e.Result;

                // The arguments provide us a e.Result object that represents the return type, in this case a List object.
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message); 
            }
        }

      
    }
}

Run the project.


Output


Click on image for better view


Full XAML Code
<UserControl x:Class="SolSilverlight_WCF.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="256*" />
            <RowDefinition Height="44*" />
        </Grid.RowDefinitions>
        <sdk:DataGrid x:Name="DgDeveloper" Grid.Row="0" Grid.Column="0" Margin="0,0,0,2" ItemsSource="{Binding}"></sdk:DataGrid>
        <Button x:Name="btnData" Grid.Row="1" Content="Data" Width="100" Height="30" HorizontalAlignment="Right" Click="btnData_Click" Margin="0,6,4,8" />
    </Grid>
</UserControl>

Download
Download Source Code

No comments:

Post a Comment