Click here to Skip to main content
15,851,503 members
Articles / Database Development / SQL Server

7 Simple Steps to Connect SQL Server using WCF from SilverLight

Rate me:
Please Sign up or sign in to vote.
4.84/5 (29 votes)
12 Aug 2010CPOL5 min read 213.8K   8.7K   115   25
In this article, we will look at how we can do database operations using SilverLight.

Update: Silverlight FAQs - Part 3 link and video added to this article.

7 Simple Steps to Connect SQL Server using WCF from SilverLight

 

Video demonstration One Way, Two Way and One Time Bindings using Silver light

Image 1

 

Introduction and Goal

In this article, we will look at how we can do database operations using Silverlight. We will first try to understand why we cannot call ADO.NET directly from a Silverlight application and then we will browse through 7 steps which we need to follow to do database operation from Silverlight.

I have collected around 400 FAQ questions and answers in WCF, WPF, WWF, SharePoint, design patterns, UML, etc. Feel free to download these FAQ PDFs from my site.

Silverlight does not have ADO.NET

Below are the different ingredients which constitute Silverlight plugin. One of the important points to be noted is that it does not consist of ADO.NET. In other words, you cannot directly call ADO.NET code from a Silverlight application. Now the other point to be noted is that it has the WCF component. In other words, you can call a WCF service.

Image 2

In other words, you can create a WCF service which does database operations and Silverlight application will make calls to the same. One more important point to be noted is to not return ADO.NET objects like dataset, etc. because Silverlight will not be able to understand the same.

Image 3

Below are 7 important steps which we need to follow to consume a database WCF service in Silverlight.

Step 1: Create the Service and Data Service Contract

Below is a simple customer table which has 3 fields ‘CustomerId’ which is an identity column, ‘CustomerCode’ which holds the customer code and ‘CustomerName’ which has the name of the customer. We will fire a simple select query using WCF and then display the data on the Silverlight grid.

Field Datatype
CustomerId int
CustomerCode nvarchar(50)
CustomerName nvarchar(50)

As per the customer table specified above, we need to first define the WCF data contract. Below is the customer WCF data contract.

C#
[DataContract]
    public class clsCustomer
    {
        private string _strCustomer;
        private string _strCustomerCode;

        [DataMember]
        public string Customer
        {
            get { return _strCustomer; }
            set { _strCustomer = value; }
        }

        [DataMember]
        public string CustomerCode
        {
            get { return _strCustomerCode; }
            set { _strCustomerCode = value; }
        }
    }

We also need to define a WCF service contract which will be implemented by WCF concrete classes.

C#
[ServiceContract]
    public interface IServiceCustomer
    {
        [OperationContract]
        clsCustomer getCustomer(int intCustomer);
    }

Step 2: Code the WCF Service

Now that we have defined the data contract and service contract, it’s time to implement the service contract. We have implemented the ‘getCustomer’ function which will return the ‘clsCustomer’ datacontract. ‘getCustomer’ function makes a simple ADO.NET connection and retrieves the customer information using the ‘Select’ SQL query.

C#
public class ServiceCustomer : IServiceCustomer
    {
        public clsCustomer getCustomer(int intCustomer)
        {
            SqlConnection objConnection = new SqlConnection();
            DataSet ObjDataset = new DataSet();
            SqlDataAdapter objAdapater = new SqlDataAdapter();
            SqlCommand objCommand = new SqlCommand
		("Select * from Customer where CustomerId=" + intCustomer.ToString());
            objConnection.ConnectionString = 
		System.Configuration.ConfigurationManager.ConnectionStrings
		["ConnStr"].ToString();
            objConnection.Open();
            objCommand.Connection = objConnection;
            objAdapater.SelectCommand = objCommand;
            objAdapater.Fill(ObjDataset);
            clsCustomer objCustomer = new clsCustomer();
            objCustomer.CustomerCode = ObjDataset.Tables[0].Rows[0][0].ToString();
            objCustomer.Customer = ObjDataset.Tables[0].Rows[0][1].ToString();
            objConnection.Close();
            return objCustomer;
        }
    }

Step 3: Copy the CrossDomain.xml and ClientAccessPolicy.XML File

This WCF service is going to be called from an outside domain, so we need to enable the cross domain policy in the WCF service by creating ‘CrossDomain.xml’ and ‘ClientAccessPolicy.xml’. Below are both the code snippets. The first code snippet is for cross domain and the second for client access policy.

XML
<?xml version="1.0"?>
    <!DOCTYPE cross-domain-policy SYSTEM 
	"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
    <cross-domain-policy>
      <allow-http-request-headers-from domain="*" headers="*"/>
     </cross-domain-policy>
XML
<?xml version="1.0" encoding="utf-8" ?>
    <access-policy>
      <cross-domain-access>
       <policy>
          <allow-from http-request-headers="*">
            <domain uri="*"/>
          </allow-from>
          <grant-to>
            <resource include-subpaths="true" path="/"/>
          </grant-to>
       </policy>
      </cross-domain-access>
    </access-policy>

Step 4: Change the WCF Bindings to ‘basicHttpBinding’

Silverlight consumes and generates proxy for only basicHttpBinding, so we need to change the endpoint bindings accordingly.

XML
<endpoint address="" binding="basicHttpBinding" 
	contract="WCFDatabaseService.IServiceCustomer">

Step 5: Add Service Reference

We need to consume the service reference in Silverlight application using ‘Add service reference’ menu. So right click the Silverlight project and select add service reference.

Step 6: Define the Grid for Customer Name and Customer Code

Now on the Silverlight side, we will create a ‘Grid’ which has two columns, one for ‘CustomerCode’ and the other for ‘CustomerName’. We have also specified the bindings using ‘Binding path’ in the text block.

XML
<Grid x:Name="LayoutRoot" Background="White">
        <Grid.ColumnDefinitions>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
                <RowDefinition Height="20"></RowDefinition>
                <RowDefinition Height="20"></RowDefinition>
            </Grid.RowDefinitions>
            <TextBlock x:Name="LblCustomerCode" Grid.Column="0" 
		Grid.Row="0" Text="Customer Code"></TextBlock>
            <TextBlock x:Name="TxtCustomerCode" Grid.Column="1" 
		Grid.Row="0" Text="{Binding Path=CustomerCode}"></TextBlock>
            <TextBlock x:Name="LblCustomerName" Grid.Column="0" 
		Grid.Row="1" Text="Customer Name"></TextBlock>
            <TextBlock x:Name="TxtCustomerName" Grid.Column="1" 
		Grid.Row="1" Text="{Binding Path=Customer}"></TextBlock>
    </Grid>

Step 7: Bind the WCF Service with the GRID

Now that our grid is created, it's time to bind the WCF service with the grid. So go to the code behind of the XAML file and create the WCF service object. There are two important points to be noted when we call WCF service using from Silverlight:

  • We need to call the WCF asynchronously, so we have called getCustomerAsynch. Please note this function is created by WCF service to make asynchronous calls to the method / function.
  • Once the function completes its work on the WCF service, it sends back the message to the Silverlight client. So we need to have some kind of delegate method which can facilitate this communication. You can see that we have created a getCustomerCompleted method which captures the arguments and ties the results with the grid datacontext.
C#
public partial class Page : UserControl
{
    public Page()
    {
        InitializeComponent();
        ServiceCustomerClient obj = new ServiceCustomerClient();
        obj.getCustomerCompleted += new EventHandler<getCustomerCompletedEventArgs>
				(DisplayResults);
        obj.getCustomerAsync(1);
    }
    void DisplayResults(object sender, getCustomerCompletedEventArgs e)
    {
        LayoutRoot.DataContext = e.Result;
    }
}

You can now run the project and see how the Silverlight client consumes and displays the data.

Image 4

Other Silverlight FAQs

  • Silverlight FAQ Part 1: This tutorial has 21 basic FAQs which will help you understand WPF, XAML, help you build your first Silverlight application and also explains the overall Silverlight architecture.
  • Silverlight FAQ Part 2 (Animations and Transformations): This tutorial has 10 FAQ questions which starts with Silverlight animation fundamentals and then shows a simple animated rectangle. The article then moves ahead and talks about 4 different ways of transforming the objects.
  • Silverlight FAQ Part 3: This article discusses 12 FAQs which revolve around bindings, layouts, consuming WCF services and how to connect to database through Silverlight.

For further reading do watch the below interview preparation videos and step by step video series.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
GeneralMy vote of 5 Pin
Ashish Jain(Be Jovial)16-Jul-15 10:06
Ashish Jain(Be Jovial)16-Jul-15 10:06 
QuestionCommunication Exception Pin
Member 94829105-Dec-13 22:36
Member 94829105-Dec-13 22:36 
AnswerRe: Communication Exception Pin
Jose Miguel Perez Mendez11-Dec-13 9:24
Jose Miguel Perez Mendez11-Dec-13 9:24 
QuestionConfigurationManager not there Pin
Member 98820664-Mar-13 4:48
Member 98820664-Mar-13 4:48 
Questionproblem with reference Pin
Abbath13496-Dec-12 5:44
Abbath13496-Dec-12 5:44 
GeneralMy vote of 5 Pin
YBP_RSA17-Oct-12 20:00
YBP_RSA17-Oct-12 20:00 
QuestionCan't find the type SqlConnection Pin
dpolancom28-Jul-12 16:49
dpolancom28-Jul-12 16:49 
AnswerRe: Can't find the type SqlConnection Pin
Abhijat Chauhan14-Aug-13 1:52
Abhijat Chauhan14-Aug-13 1:52 
QuestionMy vote of 5 Pin
DotNetXenon9-Sep-11 9:32
DotNetXenon9-Sep-11 9:32 
GeneralMy vote of 5 Pin
s.faizaan76-Aug-11 1:18
s.faizaan76-Aug-11 1:18 
QuestionRetrieve data from Multiple tables? Pin
priyanka angotra8-Sep-10 4:16
priyanka angotra8-Sep-10 4:16 
Questionwhat am i missing? Pin
Karlian7122-Jul-10 1:59
Karlian7122-Jul-10 1:59 
AnswerRe: what am i missing? Pin
Glen Banta20-Aug-10 4:51
Glen Banta20-Aug-10 4:51 
AnswerRe: what am i missing? Pin
Abhijat Chauhan14-Aug-13 1:54
Abhijat Chauhan14-Aug-13 1:54 
GeneralMy vote of 1 Pin
liviu12109-Jul-10 5:29
liviu12109-Jul-10 5:29 
GeneralRe: My vote of 1 Pin
Glen Banta20-Aug-10 4:50
Glen Banta20-Aug-10 4:50 
GeneralRe: My vote of 1 Pin
Abhijat Chauhan14-Aug-13 1:56
Abhijat Chauhan14-Aug-13 1:56 
GeneralUPdate on launching the WCF.svc file Pin
kazim bhai28-Dec-09 19:45
kazim bhai28-Dec-09 19:45 
GeneralThanks Pin
kazim bhai24-Dec-09 15:09
kazim bhai24-Dec-09 15:09 
GeneralMy vote of 2 Pin
jszczur8-Oct-09 23:44
jszczur8-Oct-09 23:44 
Generalyour article has helped me! Pin
791671153-Jul-09 18:35
791671153-Jul-09 18:35 
GeneralMy vote of 1 Pin
zlezj22-Jun-09 1:20
zlezj22-Jun-09 1:20 
GeneralRe: My vote of 1 PinPopular
Shivprasad koirala22-Jun-09 2:00
Shivprasad koirala22-Jun-09 2:00 
GeneralRe: My vote of 1 Pin
Himanshu Thawait30-Jun-09 3:37
Himanshu Thawait30-Jun-09 3:37 
GeneralRe: My vote of 1 Pin
blackjack21508-Oct-09 23:08
blackjack21508-Oct-09 23:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.