WCF and SilverLight With Cross Domain Isssue


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 solving cross domain issues. So I tried to solve that here. Make sure that the content of the ClientAccessPolicy.xml file is totally correct. You might face aproblem, even if there is an extra space there. Replace * in that XML file with valid values like SOAP. You will find details 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 an error because the .Net application is running on your credentials and IIS is running on ASP.Net credentials. So the connection string contains a USER name and password different from what you are providing.
So we need to take care of this also. For that change from Windows Authentication mode of SQL Server to SQL Server Authentication mode. 

Create one user and in the connection string replace the user with the credentials of this user. 

If you have any questions then please ask 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.) 

1.gif

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. 

2.gif

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.
The following screen will be displayed. 

3.gif

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

4.gif

Expand test.dbo. Here there are 2 tables in Test database. One is Test_Details and the 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 to the Test.dbml page. 

5.gif

6.gif

Now if you click on the Test.Dbml.CS file, you will see that code has been created for you. Code is as follows. You don't need to write this code. It was created when you dragged the table from the Server Explorer to the Test.Dbml page. 

Test.Dbml.CS

#pragma warning disable 1591

//------------------------------------------------------------------------------

// <auto-generated>

// 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.

// </auto-generated>

//------------------------------------------------------------------------------

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_Detail> Test_Details

{

get

{

return this.GetTable<Test_Detail>();

}

}

}

[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, the 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 is to change the Binding. 


Open the Web.config file. Go to the highlighted section and update that. 


Even if you are not using a LINQ to SQL class as the DataContract and respective properties as Datamember, it will work. Because from .Net 3.5 Service Pack 1, all classes are by default serilizable.


<?xml version="1.0"?>

<!--

Note: As an alternative to hand editing this file you can use the

web admin tool to configure settings for your application. Use

the Website->Asp.Net Configuration option in Visual Studio.

A full list of settings and comments can be found in

machine.config.comments usually located in

\Windows\Microsoft.Net\Framework\v2.x\Config

-->

<configuration>

<configSections>

<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>

<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>

<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>

<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>

<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>

</sectionGroup>

</sectionGroup>

</sectionGroup>

</configSections>

<appSettings/>

<connectionStrings>

<add name="testConnectionString" connectionString="Data Source=C849USS\SQLEXPRESS;Initial Catalog=test;Integrated Security=True" providerName="System.Data.SqlClient"/>

</connectionStrings>

<system.web>

<!--

Set compilation debug="true" to insert debugging

symbols into the compiled page. Because this

affects performance, set this value to true only

during development.

-->

<compilation debug="true">

<assemblies>

<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>

<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

</assemblies>

</compilation>

<!--

The <authentication> section enables configuration

of the security authentication mode used by

ASP.NET to identify an incoming user.

-->

<authentication mode="Windows"/>

<!--

The <customErrors> section enables configuration

of what to do if/when an unhandled error occurs

during the execution of a request. Specifically,

it enables developers to configure html error pages

to be displayed in place of a error stack trace.

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">

<error statusCode="403" redirect="NoAccess.htm" />

<error statusCode="404" redirect="FileNotFound.htm" />

</customErrors>

-->

<pages>

<controls>

<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

</controls>

</pages>

<httpHandlers>

<remove verb="*" path="*.asmx"/>

<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>

</httpHandlers>

<httpModules>

<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

</httpModules>

</system.web>

<system.codedom>

<compilers>

<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

<providerOption name="CompilerVersion" value="v3.5"/>

<providerOption name="WarnAsError" value="false"/>

</compiler>

</compilers>

</system.codedom>

<!--

The system.webServer section is required for running ASP.NET AJAX under Internet

Information Services 7.0. It is not necessary for previous version of IIS.

-->

<system.webServer>

<validation validateIntegratedModeConfiguration="false"/>

<modules>

<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

</modules>

<handlers>

<remove name="WebServiceHandlerFactory-Integrated"/>

<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

</handlers>

</system.webServer>

<system.serviceModel>

<services>

<service behaviorConfiguration="DataService.Service1Behavior" name="DataService.DataService">

<endpoint address="" binding="wsHttpBinding" contract="DataService.IDataService">

<identity>

<dns value="localhost"/>

</identity>

</endpoint>

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name="DataService.Service1Behavior">

<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->

<serviceMetadata httpGetEnabled="true"/>

<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->

<serviceDebug includeExceptionDetailInFaults="false"/>

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>
</configuration> 


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


<?xml version="1.0"?>

<!--

Note: As an alternative to hand editing this file you can use the

web admin tool to configure settings for your application. Use

the Website->Asp.Net Configuration option in Visual Studio.

A full list of settings and comments can be found in

machine.config.comments usually located in

\Windows\Microsoft.Net\Framework\v2.x\Config

-->

<configuration>

<configSections>

<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>

<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>

<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>

<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>

<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>

</sectionGroup>

</sectionGroup>

</sectionGroup>

</configSections>

<appSettings/>

<connectionStrings>

<add name="testConnectionString" connectionString="Data Source=C849USS\SQLEXPRESS;Initial Catalog=test;Integrated Security=True" providerName="System.Data.SqlClient"/>

</connectionStrings>

<system.web>

<!--

Set compilation debug="true" to insert debugging

symbols into the compiled page. Because this

affects performance, set this value to true only

during development.

-->

<compilation debug="true">

<assemblies>

<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>

<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

</assemblies>

</compilation>

<!--

The <authentication> section enables configuration

of the security authentication mode used by

ASP.NET to identify an incoming user.

-->

<authentication mode="Windows"/>

<!--

The <customErrors> section enables configuration

of what to do if/when an unhandled error occurs

during the execution of a request. Specifically,

it enables developers to configure html error pages

to be displayed in place of a error stack trace.

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">

<error statusCode="403" redirect="NoAccess.htm" />

<error statusCode="404" redirect="FileNotFound.htm" />

</customErrors>

-->

<pages>

<controls>

<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

</controls>

</pages>

<httpHandlers>

<remove verb="*" path="*.asmx"/>

<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>

</httpHandlers>

<httpModules>

<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

</httpModules>

</system.web>

<system.codedom>

<compilers>

<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

<providerOption name="CompilerVersion" value="v3.5"/>

<providerOption name="WarnAsError" value="false"/>

</compiler>

</compilers>

</system.codedom>

<!--

The system.webServer section is required for running ASP.NET AJAX under Internet

Information Services 7.0. It is not necessary for previous version of IIS.

-->

<system.webServer>

<validation validateIntegratedModeConfiguration="false"/>

<modules>

<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

</modules>

<handlers>

<remove name="WebServiceHandlerFactory-Integrated"/>

<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

</handlers>

</system.webServer>

<system.serviceModel>

<services>

<service behaviorConfiguration="DataService.Service1Behavior" name="DataService.DataService">

<endpoint address="" binding="basicHttpBinding" contract="DataService.IDataService">

<identity>

<dns value="localhost"/>

</identity>

</endpoint>

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name="DataService.Service1Behavior">

<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->

<serviceMetadata httpGetEnabled="true"/>

<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->

<serviceDebug includeExceptionDetailInFaults="false"/>

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

</configuration> 


Step 5: 


Now write the 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<Test_Detail> 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<Test_Detail> 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 the name of the folder as DATASERVICE. 


7.gif


a. Click on browse 


8.gif

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


9.gif

c. Click Yes.


10.gif


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

11.gif


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). 


The theory is that we need to save the clientaccesspolicy.xml file in the root directory of the web server on which the server is running. 


<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers
="SOAPAction,Content-Type">
<domain uri="*" />
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
 


Points to be noted in this file:

  1. Check out element http-request-headers="SOAPAction... ". Normally you download this file and save it without changing. The file will contain (*) instead of SOAPAction (Highlighted in the 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 

12.gif

The following window will be opened. Now click DataService in tree view. You will get the following screen.

13.gif

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

14.gif

Now click on the Default Web Sites. In the 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 the browser like below. 

15.gif


16.gif

Up to this step, the 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 the name as you wish. Here I am leaving it to Silverlight1. 

Host it into a Web Application Project. 

Select NO for Test Project creation. 

17.gif

18.gif

Step 2: 

Open the Page.Xaml file and paste the following code. 

Page.Xaml

<UserControl x:Class="SilverlightApplication1.Page"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Width="400" Height="300">

<Grid x:Name="LayoutRoot" Background="White">

<Grid.ColumnDefinitions>

<ColumnDefinition Width="*" />

<ColumnDefinition Width="*" />

</Grid.ColumnDefinitions>

<Grid.RowDefinitions>

<RowDefinition Height="*" />

<RowDefinition Height="*" />

</Grid.RowDefinitions>

<Button x:Name="b1" Width="130" Height="60" Click="b1_Click" Grid.Row="1" Grid.Column="1" />

</Grid>
<
/UserControl> 


I am going to have one Button and one Data grid on my Silverlight page. When the user clicks on the Button, data from the table will be populated into the Data Grid. So due to the above the XAML button has been created. 


Now drag a DataGrid from the toolbox onto the Page.Xaml file. Drag it to below the Button element.


<Button x:Name="b1" Width="130" Height="60" Click="b1_Click" Grid.Row="1" Grid.Column="1" />

<data:DataGrid></data:DataGrid> 

Now modify the Data Grid element as below.

<data:DataGrid x:Name="GridToDisplay" Width="100" Height="100" Grid.Row="1" Grid.Column="0">

</data:DataGrid> 


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


Page.Xaml

<UserControl x:Class="SilverlightApplication1.Page"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"

Width="400" Height="300">

<Grid x:Name="LayoutRoot" Background="White">

<Grid.ColumnDefinitions>

<ColumnDefinition Width="*" />

<ColumnDefinition Width="*" />

</Grid.ColumnDefinitions>

<Grid.RowDefinitions>

<RowDefinition Height="*" />

<RowDefinition Height="*" />

</Grid.RowDefinitions>

<Button x:Name="b1" Width="130" Height="60" Click="b1_Click" Grid.Row="1" Grid.Column="1" />

<data:DataGrid x:Name="GridToDisplay" Width="100" Height="100" Grid.Row="1" Grid.Column="0">

</data:DataGrid>

</Grid>

</UserControl> 


Step 3: 


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


19.gif


20.gif

21.gif


Step 4: 


Now open Page.Xaml.CS file. Include the following namespace:


using SilverlightApplication1.ServiceReference1; 


And type the following 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<ListCompletedEventArgs>(_client_ListCompleted);

_client.ListAsync();

}

void _client_ListCompleted(object sender, ListCompletedEventArgs e)

{

List<Test_Detail> res = e.Result.ToList();

GridToDisplay.ItemsSource = res;

}

}
}
 


Step 5: 


Open the ServiceReferences.ClientConfig file. Here we need to make some changes. 


ServiceReferences.ClientConfig


<configuration>

<system.serviceModel>

<bindings>

<basicHttpBinding>

<binding name="BasicHttpBinding_IDataService" maxBufferSize="2147483647"

maxReceivedMessageSize="2147483647">

<security mode="None" />

</binding>

</basicHttpBinding>

</bindings>

<client>

<endpoint address="http://c849uss.ustr.com/DataService/DataService.svc"

binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IDataService"

contract="ServiceReference1.IDataService" name="BasicHttpBinding_IDataService" />

</client>

</system.serviceModel>

</configuration> 

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 of 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. 

22.gif

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!

Up Next
    Ebook Download
    View all
    Learn
    View all