Silverlight and WCF



In this article I am providing a basic explanation of the use of Silverlight and WCF.

What is Silverlight?

The Silverlight is the platform for using mobile, web and desktop applications. In Silverlight the resource utilization is more client side instead of server side.

WCF

WCF is a foundation to develop service-oriented applications.

Why WCF in Silverlight?

Using Silverlight it's not possible to access ADO controls directly. So to get data from a database to Silverlight we can use a WCF service as an intermediate.

Create a Silverlight Application:

Requirements:

  1. VS2008
  2. Silverlight 3
  3. Silverlight Developer

To start: File->New->Project 
WCFSil1.gif

Next step:

WCFSil2.gif

Create WCF File->New->Project:

WCFSil3.gif

In Solution Explorer IService1.cs and Service1.svc will be created automatically. Add a Database Handler class in the Solution Explorer:

WCFSil4.gif

Add appsettings in webconfig:

<appSettings file="">
    <clear/>
    <
add key="ConStr" value="Data Source=LTAPPN1;Initial Catalog=DatabaseName;User ID=ss;Password=ss"/>
  </appSettings>

IService1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfService1
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        EXDetails GetEXDetails();
    }

    // Use a data contract as illustrated in the sample below to add composite types to service operations.

    public class EXDetails
    {
        List<EXinfo> _EXlist = new List<EXinfo>();
        [DataMember]
        public List<EXinfo> EXindex
        {
            get { return _EXlist; }
            set { _EXlist = value; }
        }
    }
    [DataContract]
    public class EXinfo
    {
        [DataMember]
        public string EXM { get; set; }
        [DataMember]
        public string EX { get; set; }

    }}

Service1.svc.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;

namespace WcfService1
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.
    public class Service1 : IService1
    {
        public EXDetails GetEXDetails()
        {
            DatabaseHandler dbObj = new DatabaseHandler();
            DataTable dataTableEXInfo = dbObj.EX();
            EXDetails EXDataMessage = new EXDetails();
            for (int iTagCounter = 0; iTagCounter < dataTableEXInfo.Rows.Count; iTagCounter++)
            {
                EXinfo EXinfo = new EXinfo();
                EXinfo.EXM = dataTableEXInfo.Rows[iTagCounter]["EXM"].ToString();
                EXinfo.EX = dataTableEXInfo.Rows[iTagCounter]["EX"].ToString();
                EXDataMessage.EXindex.Add(EXinfo);
            }
            return EXDataMessage;
        }    }}


DatabaseHandler.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace WcfService1
{
    public class DatabaseHandler
    {
        SqlConnection con;
        string connectionstring;
        SqlCommand oc;
        SqlDataAdapter da;
        DataTable dt;
        public DataTable EX()
        {
            try
            {           
                dt = new DataTable();
                connectionstring = System.Configuration.ConfigurationManager.AppSettings["ConStr"].ToString();
                con = new SqlConnection(connectionstring);
                con.Open();
                oc = new SqlCommand("TableName", con);
                oc.CommandType = CommandType.StoredProcedure;
                da = new SqlDataAdapter(oc);
                da.Fill(dt);
            }
            catch (Exception ex)
            {            
            }
            finally
            {
                con.Close();
                oc = null;
            }        
            return dt;
        }    }}

While running the service you will get the following page (otherwise you may have an error in the service):

WCFSil5.gif

Adding WCF Service in Silverlight application

Step 1:

WCFSil6.gif

Step 2:

WCFSil7.gif

Step 3:

WCFSil8.gif

Step 4:

WCFSil9.gif

Coding in Silverlight:

MainPage.xaml

<UserControl x:Class="SilverlightApplication1.MainPage" Loaded="UserControl_Loaded"
    xmlns:dataInput="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <Grid>

        <my:DataGrid x:Name="grd_Firstyield" GridLinesVisibility="All" AutoGenerateColumns="False" Width="400" Height="350"  Background="Black" AlternatingRowBackground="AliceBlue" Margin="25,0,25,0" VerticalAlignment="Bottom">
            <my:DataGrid.Columns>
                <my:DataGridTextColumn Binding="{Binding EXM}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="EXM" Width="150"  />
                <my:DataGridTextColumn Binding="{Binding EX}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="EX" Width="150" />
            </my:DataGrid.Columns>
        </my:DataGrid>
    </Grid>
</
UserControl>

Code in MainPage.xaml.cs


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 SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            ServiceReference1.Service1Client obj = new SilverlightApplication1.ServiceReference1.Service1Client();
            obj.GetEXDetailsCompleted+=new EventHandler<SilverlightApplication1.ServiceReference1.GetEXDetailsCompletedEventArgs>(obj_GetEXDetailsCompleted);
            obj.GetEXDetailsAsync();
        }
        void obj_GetEXDetailsCompleted(object sender,SilverlightApplication1.ServiceReference1.GetEXDetailsCompletedEventArgs e)
        {
            grd_Firs.ItemsSource = e.Result.EXindex;
 
        }
    }
}


Similar Articles