.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> WCF >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Consuming WCF service hosted in IIS in a Silverlight application

Posted By:Dhananjay Kumar       Posted Date: January 15, 2010    Points: 25    Category: WCF    URL: http://www.dotnetspark.com  

This tutorial will expalin about how to consume WCF in SilverLight, solve Cross Domain issue and to host WCF service in IIS
 

Objective:

This tutorial is going to explain
  1. How to handle Cross Domain issue. 
  2. How to retrieve data from SQL Server using LINQ and pass that to Silverlight application using WCF service.
Note:
  1. I have had a very tough time in solving cross domain issue. So I tried to solve that here. Make sure content of ClientAccessPolicy.xml file is very much correct. You might face problem , even if there is a extra space there. Replace * in that XML file with valid values like SOAP. You will find detail below.
  2. The other issue was
     
    1. Let your WCF is hosted in IIS 5.2
    2. Service is accessing database
    3. Database is configured only for Window Authentication
    4. Now when you try to consume WCF service in any type of application. It will throw error because .Net application is running on your credential and IIS is running on aspnet credential. So connection string is containing different USER name and password while you are providing different.
So we need to take care of this also. For that change Widows authentication mode of SQL Server to  SQL Server authentication mode.
Create one user. and replace connection string with credential of this user.
If having any question please asked me. I shall try to reply.

Here we Start

Step 1:

Create a new WCF service application. Click on File->New->Project->Web->WCF Service Application. Give name as DataService.( You are free to give any name)



Step 2
:

Rename Iservice to IDataService and Service1 to DataService. And delete all the default code from both file IDataService and DataService.

Step 3
:

Right click on DataService project tab then select Add-> New Item.  Go to Data tab and choose LINQ to SQL classes. Give name as Test.dbml. I am going to use Test_Details table of Test database, which I have already created in my SQL SERVER.



Step 4
:

Here, I have already created a TEST data base in my database.  I am going to display data from this database.
  1. Open Server Explorer 
  2. Right click on  Data Connection 
  3. Click Add New Data Connection.
Below screen will get display.



Now give a Server name and select database to connect. In my case name of database is Test.



Expand test.dbo. Here there are 2 tables in Test database.  One is Test_Details and other is testsample.  In this tutorial, I am going to display data from Test_Detatils table. So select this table from Server explorer and drag it on Test.dbml page.




Now if you click on Test.Dbml.CS file. You will find code has been created for you. Code is as follows. You don't need to write this code. It has been already created once you drag table from server explorer to Test.Dbml page.

Test.Dbml.CS


#pragma warning disable 1591
//------------------------------------------------------------------------------
// 
//  This code was generated by a tool.
//  Runtime Version:2.0.50727.3053
//
//  Changes to this file may cause incorrect behavior and will be lost if
//  the code is regenerated.
// 
//------------------------------------------------------------------------------
 
namespace DataService
{
  using System.Data.Linq;
  using System.Data.Linq.Mapping;
  using System.Data;
  using System.Collections.Generic;
  using System.Reflection;
  using System.Linq;
  using System.Linq.Expressions;
  using System.ComponentModel;
  using System;
  using System.Runtime.Serialization;
  
  
  [System.Data.Linq.Mapping.DatabaseAttribute(Name="test")]
  public partial class TestDataContext : System.Data.Linq.DataContext
  {
  
  private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
  
  #region Extensibility Method Definitions
  partial void OnCreated();
  #endregion
  
  public TestDataContext() : 
    base(global::System.Configuration.ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString, mappingSource)
  {
  OnCreated();
  }
  
  public TestDataContext(string connection) : 
  base(connection, mappingSource)
  {
  OnCreated();
  }
  
  public TestDataContext(System.Data.IDbConnection connection) : 
  base(connection, mappingSource)
  {
  OnCreated();
  }
  
  public TestDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
  base(connection, mappingSource)
  {
  OnCreated();
  }
  
  public TestDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
  base(connection, mappingSource)
  {
  OnCreated();
  }
  
  public System.Data.Linq.Table Test_Details
  {
  get
  {
  return this.GetTable();
  }
  }
  }
  [DataContract]
  [Table(Name="dbo.Test_Details")]
  public partial class Test_Detail
  {
  
  private string _testId;
  
  private string _testName;
  
  private int _testMaxMarks;
  
  public Test_Detail()
  {
  }
  [DataMember]
  [Column(Storage="_testId", DbType="NVarChar(50) NOT NULL", CanBeNull=false)]
  public string testId
  {
  get
  {
  return this._testId;
  }
  set
  {
  if ((this._testId != value))
  {
  this._testId = value;
  }
  }
  }
  [DataMember]
  [Column(Storage="_testName", DbType="NVarChar(50) NOT NULL", CanBeNull=false)]
  public string testName
  {
  get
  {
  return this._testName;
  }
  set
  {
  if ((this._testName != value))
  {
  this._testName = value;
  }
  }
  }
  [DataMember]
  [Column(Storage="_testMaxMarks", DbType="Int NOT NULL")]
  public int testMaxMarks
  {
  get
  {
  return this._testMaxMarks;
  }
  set
  {
  if ((this._testMaxMarks != value))
  {
  this._testMaxMarks = value;
  }
  }
  }
  }
}
#pragma warning restore 1591

Up to this step, LINQ class has been created. 
I have added highlighted green code in the code created by default for LINQ to SQL class.  So you need to add too.
One more thing we need to do, change the Binding
Open Web.config file. Go to highlighted section and update that.
Even if you are not making LINQ to SQL class as DataContract and respective properties as Datamember . It will work. Because from .Net 3.5 Service Pack 1, all classes are by default serilizable.

 




  
  
  
  
We need to change wsHttpBinding to basicHttpBinding. So after chaging web.config will look like,

Step 5:

Now  write service

IDataService.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
 
namespace DataService
{
  // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
  [ServiceContract]
  public interface IDataService
  {
  [OperationContract]
  IList List();  
  }  
  
}


DataService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
 
namespace DataService
{
  // 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 DataService : IDataService
  {
  public  IList List()
  {
  
  TestDataContext _dbContext = new TestDataContext();
  var res = from r in _dbContext.Test_Details
  select r;
  return res.ToList(); 
  }
  
  }
}


Step 6:

Publish the service in IIS.  For that right click on DataService project. And select PUBLISH.

Note
: Before publishing create a Virtual Folder. Go to C:\Inetpub\wwwroot. Create a new folder. Give name of the folder as DATASERVICE.



a. Click on browse


 
b. Select Local IIS tab and then select DataService virtual folder, which we just made.


 
c. Click Yes.



d.  Click on Publish. And WCF service got published in IIS.



Step 7:

The Cross domain issue.

Now here we are with cross domain. How to solve it?
Since, we are hosting our service in IIS. So we need to save clientaccesspolicy.xml file in root directory of IIS ( Web server).
Theory says, we need to save clientaccesspolicy.xml file in root directory of web server on which server is running.

 

  
  
  
   
  
  
   
  
  
  

Point to be noted in this file

  1. Check out element http-request-headers="SOAPAction... ". Normally when you download this file and save it without changing. File will content (*) in place of SOAPAction (Highlighted in above code). Make sure to change it to SOAPAction.
  2. Save clientaccesspolicy.xml to  c:\Inetpub\wwwroot
Step 8:

Go to Start-> Run and type inetmgr



Below window will get open. Now click DataService in tree view. you will get below screen.




Right click on DataService.cs and click Browse. You should able to browse the service in browser. Just copy, address of service from address bar of browser. In this case it is http://localhost/DataService/DataService.svc



Now click on Default Web Sites.  In right panel, you will see many things. From there select clientaccesspolicy.xml .  Right click it. Then select browse.  You should able to see it in browser like below.





Up to this step, WCF service is created and running. This WCF service is hosted in IIS.

Creating Silverlight client.


Step 1
:

Create a new Silverlight application. Select File->New->Project->Silverlight->Silverlight Application. Give name as per your wish. Here I am leaving it to Silverlight1
Host it into a Web Application Project.
Select NO for Test Project creation.





Step 2
:

Open Page.Xaml file  and paste the below code.

Page.Xaml



  
  
  
  
  
  
  
  
  
  

I am going to have one Button and one Data grid on my Silverlight page.  When user will click on Button, data from the table will get populated in Data Grid.  So due to above XAML button has been created.
Now drag a DataGrid from tool box on Page.Xaml file . Drag it below the Button element.


Now modify Data Grid element as below.



So the complete code of Page.Xaml will look like as below

Page.Xaml



  
  
  
  
  
  
  
  
  
  

Step 3
:

Now add service reference to Silverlight application. To do so right click on references then add Service Reference .Now here pastes the URL of service which you copied at Step 7.  And click on Go.  Here I am not changing name of the Service Reference. For me it is ServiceRefernece1. You can change , if you wish .  Now Service has been added to Silverlight client.







Step 4
:

Now open Page.Xaml.CS file. Include the below namespace
using SilverlightApplication1.ServiceReference1;
and type the below code.

Page.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;
using SilverlightApplication1.ServiceReference1; 
 
 
namespace SilverlightApplication1
{
  public partial class Page : UserControl
  {
  public Page()
  {
  InitializeComponent();
  }
 
  private void b1_Click(object sender, RoutedEventArgs e)
  {
  
  DataServiceClient _client = new DataServiceClient();
  _client.ListCompleted += new EventHandler(_client_ListCompleted);
  _client.ListAsync();
  
  }
 
  void _client_ListCompleted(object sender, ListCompletedEventArgs e)
  {
 
  List res = e.Result.ToList();
  GridToDisplay.ItemsSource = res;  
  } 
  }
}

Step 5
:

Open ServiceReferences.ClientConfig file.  Here we need to do some changing.

ServiceReferences.ClientConfig



  
  
  
  
  
  
  
  
  
  
  
  

Very Important Note
:

For me its c849Uss something like that is coming. It is because my system name where I am running this application is c849uss. Make sure one thing here that this address must be the same as the address which you are getting when browsing your service using IIS.
Refer step 8. After browsing service in browser copy paste URL and replace the above highlighted URL.
IF both URL is same for you. Then you don't need to worry. Everything is fine.

Step 6
:

GO ahead and Run your Silverlight application.
On clicking of Button, you should able to get below output.


 
How to use Zip File
  1. Unzip the file 
  2. Open DataService folder 
  3. Build it 
  4. Right click solution of DataService 
  5. And host it in IIS 
  6. Open SilverlightAppliaction1. 
  7. Update config file as instructions given in above steps. And you are set to run
Happy Coding!

 Subscribe to Articles

     

Further Readings:

Responses
Author: bindu         Company URL: http://www.dotnetspark.com
Posted Date: September 08, 2010

hi
i have been trying many examples from various sites to access database from silverlight using wcf service but constantly getting a sinle error....
Error: Unhandled Error in Silverlight Application The method or operation is not implemented. at SilverlightDataService.MainPage._client_ListCompleted(Object sender, ListCompletedEventArgs e)
at SilverlightDataService.ServiceReference1.Service1Client.OnListCompleted(Object state)

i am a beginner. please help me. i am working on a single domain. tried out everything i could but couldn't solve it.
regards,
bindu
Author: bindu         Company URL: http://www.dotnetspark.com
Posted Date: September 08, 2010

i have got 1 more doubt....here we are creting a 2 grid controls. one is for displaying data. what is the other used for?
please clarify

regards
bindu
Author: bindu         Company URL: http://www.dotnetspark.com
Posted Date: September 08, 2010

here i had to create a service file again inthe silverlight application to proceed further in the web project. i ahve been doind the same without which it is throwing error.
so in order to continue i had to rework on y=the service again at the silverlight applkication.
is there any solution for this.
the erroe directly prompting to add the service file in the silverlight application.
please suggest an alternative
i am using Visual Studio2010 and SQL Server 2008 with IIS 7.0 version.i am working in a workgropu environment and hence cannot deploy my project in IIS due to security constraints

regards
bindu

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend