b

Thursday, 27 December 2012

How to convert datatable to json string using json.net WCF Rest Service VB.NET


How to convert datatable to json string using json.net  WCF Rest Service

  • Create WCF Service Project using C# 4.0/4.5
  • Add a WCF service name it as IRestWCF
Add namespaces
using System.ServiceModel.Channels;
using System.ServiceModel.Web;

download Json.NET Add reference to   Newtonsoft.JSon  

<ServiceContract> _
    Public Interface IRestWCF
         <OperationContract> _
        <WebGet(BodyStyle = WebMessageBodyStyle.WrappedResponse, ResponseFormat =    WebMessageFormat.Json)> _
        Dim GetDataTableJson() As Message
    End Interface
 
Message class is the base class for all types of operations in WCF.

Public Class RestWCF
     Implements IRestWCF
      Public Function GetDataTableJson() As Message
          Dim dt As DataTable = GetSalesData("json")
         ' Message message = WebOperationContext.Current.CreateJsonResponse<DataTable>(dt);
         Dim strDatatable As String =  Newtonsoft.Json.JsonConvert.SerializeObject(dt)
         Return WebOperationContext.Current.CreateTextResponse(strDatatable,"application/json;charset=utf-8",System.Text.Encoding.UTF8)' Message.CreateMessage(MessageVersion.Default, "json datatable", message);
      End Function
Private Function GetSalesData(ByVal format As String) As DataTable
          Dim salesdata As DataTable =  New DataTable("SalesPerson")
          Try
              Imports (SqlConnection conn = New SqlConnection("server=(local)\sqlexpress2012database=AdventureWorks2012uid=sapwd=password&"))
              {
                  Imports (SqlDataAdapter adapter = New SqlDataAdapter("select * from (AdventureWorks2012).(Sales).(SalesPerson)", conn))
                  {
                      adapter.Fill(salesdata)

                      salesdata.AcceptChanges()
                      conn.Close()
                  }
              }
          Catch ex As SqlException
              Throw ex
          End Try
          If format = "xml" Then
              salesdata.RemotingFormat = SerializationFormat.Xml
          End If
          'else salesdata.RemotingFormat = SerializationFormat.Binary;
          Return salesdata
End Function
End Class



 
Web.Config <?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </assemblies>
    </compilation>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
        <behavior name="restbeh">
          <serviceDebug httpHelpPageEnabled="True" includeExceptionDetailInFaults="true" />
          <serviceMetadata  httpGetEnabled="True"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="restendbeh">
          <!--<soapProcessing processMessages="True"/>-->
          <webHttp helpEnabled="True" faultExceptionEnabled="True"
                   defaultBodyStyle="Bare"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="myrestbinding">
          <security mode="None"></security>
          <readerQuotas maxArrayLength="65536"/>
        </binding>
      </webHttpBinding>
    </bindings>

    <services>
      <service name="WCFServicesREST.RestWCF" behaviorConfiguration="restbeh">
        <endpoint  contract="WCFServicesREST.IRestWCF" binding="webHttpBinding"  bindingConfiguration="myrestbinding"
                   behaviorConfiguration="restendbeh"></endpoint>
       
      </service>
    </services>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"  aspNetCompatibilityEnabled="True"/>
  </system.serviceModel>
  <system.webServer>
   
    <modules runAllManagedModulesForAllRequests="true" />  </system.webServer>
  <system.web.extensions>
    <scripting>
      <scriptResourceHandler enableCaching="true" enableCompression="true" />
    </scripting>
  </system.web.extensions>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
</configuration>

DATATABLE JSON OUTPUT

 


How to convert datatable to json string using json.net WCF Rest Service

How to convert datatable to json string using json.net  WCF Rest Service

  • Create WCF Service Project using C# 4.0/4.5
  • Add a WCF service name it as IRestWCF
Add namespaces
using System.ServiceModel.Channels;
using System.ServiceModel.Web;

download Json.NET Add reference to   Newtonsoft.JSon  

[ServiceContract]
    public interface IRestWCF
    {
         [OperationContract]
        [WebGet(BodyStyle = WebMessageBodyStyle.WrappedResponse, ResponseFormat =    WebMessageFormat.Json)]
        Message GetDataTableJson();
}
Message class is the base class for all types of operations in WCF.

public class RestWCF : IRestWCF
{
      public Message GetDataTableJson()
      {
          DataTable dt =GetSalesData("json");
         // Message message = WebOperationContext.Current.CreateJsonResponse<DataTable>(dt);
         String strDatatable= Newtonsoft.Json.JsonConvert.SerializeObject(dt);
         return WebOperationContext.Current.CreateTextResponse(strDatatable, "application/json;charset=utf-8", System.Text.Encoding.UTF8);// Message.CreateMessage(MessageVersion.Default, "json datatable", message);
      }
private DataTable GetSalesData(String format)
      {
          DataTable salesdata = new DataTable("SalesPerson");
          try
          {
              using (SqlConnection conn = new SqlConnection(@"server=(local)\sqlexpress2012;database=AdventureWorks2012;uid=sa;pwd=password&"))
              {
                  using (SqlDataAdapter adapter = new SqlDataAdapter("select * from [AdventureWorks2012].[Sales].[SalesPerson]", conn))
                  {
                      adapter.Fill(salesdata);

                      salesdata.AcceptChanges();
                      conn.Close();
                  }
              }
          }
          catch (SqlException ex)
          {
              throw ex;
          }
          if (format == "xml")
              salesdata.RemotingFormat = SerializationFormat.Xml;
          //else salesdata.RemotingFormat = SerializationFormat.Binary;
          return salesdata;
      }
}

  • Web.Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </assemblies>
    </compilation>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
        <behavior name="restbeh">
          <serviceDebug httpHelpPageEnabled="True" includeExceptionDetailInFaults="true" />
          <serviceMetadata  httpGetEnabled="True"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="restendbeh">
          <!--<soapProcessing processMessages="True"/>-->
          <webHttp helpEnabled="True" faultExceptionEnabled="True"
                   defaultBodyStyle="Bare"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="myrestbinding">
          <security mode="None"></security>
          <readerQuotas maxArrayLength="65536"/>
        </binding>
      </webHttpBinding>
    </bindings>

    <services>
      <service name="WCFServicesREST.RestWCF" behaviorConfiguration="restbeh">
        <endpoint  contract="WCFServicesREST.IRestWCF" binding="webHttpBinding"  bindingConfiguration="myrestbinding"
                   behaviorConfiguration="restendbeh"></endpoint>
       
      </service>
    </services>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"  aspNetCompatibilityEnabled="True"/>
  </system.serviceModel>
  <system.webServer>
   
    <modules runAllManagedModulesForAllRequests="true" />  </system.webServer>
  <system.web.extensions>
    <scripting>
      <scriptResourceHandler enableCaching="true" enableCompression="true" />
    </scripting>
  </system.web.extensions>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
</configuration>

DATATABLE JSON OUTPUT

 

How to return a datatable from a wcf service rest VB.NET

How to return a datatable from a wcf service rest


  • Create a WCF Service Application
  • Add WCF Service name it as IRESTWCF
    • Add a method called DataTable GetDataTableXml() 
    • <ServiceContract> _
          Public Interface IRestWCF

              <OperationContract> _
              <WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml)> _
              Dim GetDataTableXml() As DataTable

          End Interface
    • Service Implementation class RestWCF.vb
   
Public Class RestWCF
     Implements IRestWCF
                              Public Function GetDataTableXml() As DataTable

Dim salesdata As DataTable =  New DataTable("SalesPerson")

                  Try
                      Imports (SqlConnection conn = New SqlConnection("server=(local)\sqlexpress2012database=AdventureWorks2012uid=sapwd=password&"))
                      {
                          Imports (SqlDataAdapter adapter = New SqlDataAdapter("select * from (AdventureWorks2012).(Sales).(SalesPerson)", conn))
                          {
                              adapter.Fill(salesdata)

                              salesdata.AcceptChanges()
                              conn.Close()
                          }
                      }
                  Catch ex As SqlException
                      Throw ex
                  End Try
                  salesdata.RemotingFormat = SerializationFormat.Xml
                  Return salesdata

                              End Function

End Class



  • Web.config
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false 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="true" />
        </behavior>
        <behavior name="restbeh">
          <serviceDebug httpHelpPageEnabled="True" includeExceptionDetailInFaults="true" />
          <serviceMetadata  httpGetEnabled="True"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="restendbeh">
          <!--<soapProcessing processMessages="True"/>-->
          <webHttp helpEnabled="True" faultExceptionEnabled="True" defaultBodyStyle="Bare" defaultOutgoingResponseFormat="Xml"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="myrestbinding">
          <security mode="None"></security>
          <readerQuotas maxArrayLength="65536"/>
        </binding>
      </webHttpBinding>
    </bindings>

    <services>
      <service name="WCFServicesREST.RestWCF" behaviorConfiguration="restbeh">
        <endpoint  contract="WCFServicesREST.IRestWCF" binding="webHttpBinding"  bindingConfiguration="myrestbinding"
                   behaviorConfiguration="restendbeh"></endpoint>
       
      </service>
    </services>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"  aspNetCompatibilityEnabled="True"/>
  </system.serviceModel>
  <system.webServer>
 </configuration>





Consuming  in WPF Application


  • Create a WPF Application using .NET 4.0/4.5 using VB.NET
  • Add a DataGrid to XAML name it as datagrid1
  • Add namespaces in .cs file
    • using System.Xml;
    • using System.Xml.Serialization;
    • using System.Net;
    Declare a class called SalesPerson class for XML Serialization/DeSerialization.

<XmlRoot(ElementName = "SalesPerson", Namespace = "")> _
    Public Class SalesPerson
        <XmlAttribute(Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1")> _
        Public Property id() As String
        End Property
        <XmlAttribute(Namespace = "urn:schemas-microsoft-com:xml-msdata")> _
        Public Property rowOrder() As Integer
        End Property

        <XmlElement> _
        Public Property BusinessEntityID() As int?
        End Property
        <XmlElement> _
        Public Property Bonus() As decimal?
        End Property
        <XmlElement> _
        Public Property CommissionPct() As decimal?
        End Property
        <XmlElement> _
        Public Property SalesLastYear() As decimal?
        End Property
        <XmlElement> _
        Public Property SalesYTD() As decimal?
        End Property
        <XmlElement> _
        Public Property TerritoryID() As int?
        End Property
        <XmlElement> _
        Public Property ModifiedDate() As DateTime?
        End Property
    End Class

Note: Each element in this class should match columns returned from wcf  Datatable, column names are case sensitive. null columns should use ?. Namespaces also must match, otherwise "serialization error saying <SalesPerson xmlns=''> not expected here" will appear.

Because WCF Rest doesn't serve proxy class. So You need ti call WebRequest/HttpWebRequest in System.Net.

as shown below

Dim req As WebRequest =  WebRequest.Create("http://localhost:3054/RestWCF.svc/GetDataTableXml")
                  req.ContentType = "text/xml"
                    Dim resp As WebResponse =  req.GetResponse()
                    Dim stream As Stream =  resp.GetResponseStream()
                    Dim fact As XmlSerializerFactory =  New XmlSerializerFactory()

                    Dim re As XmlReader =  XmlReader.Create(stream)
                    While re.Read()
                        If re.NodeType = XmlNodeType.Element And re.LocalName.Equals("SalesPerson") Then
                            Dim ser As XmlSerializer =  fact.CreateSerializer(Type.GetType(SalesPerson))

                            Dim p As SalesPerson = CType(ser.Deserialize(re), SalesPerson)
                           'add to list.
                            salesPersonXML.Add(p)
                        End If
                    End While


//Bind to datagrid in WPF
                    datagrid1.ItemsSource = salesPersonXML

OUTPUT

Monday, 24 December 2012

how to return a datatable from a wcf service rest

How to return a datatable from a wcf service rest


  • Create a WCF Service Application
  • Add WCF Service name it as IRESTWCF
    • Add a method called DataTable GetDataTableXml() 
    • [ServiceContract]
          public interface IRestWCF
          {

              [OperationContract]
              [WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml)]
              DataTable GetDataTableXml();

          }
    • Service Implementation class
    public class RestWCF : IRestWCF                       {
                              public DataTable GetDataTableXml()      {

DataTable salesdata = new DataTable("SalesPerson");
    •           try
                {
                    using (SqlConnection conn = new SqlConnection(@"server=(local)\sqlexpress2012;database=AdventureWorks2012;uid=sa;pwd=password&"))
                    {
                        using (SqlDataAdapter adapter = new SqlDataAdapter("select * from [AdventureWorks2012].[Sales].[SalesPerson]", conn))
                        {
                            adapter.Fill(salesdata);

                            salesdata.AcceptChanges();
                            conn.Close();
                        }
                    }
                }
                catch (SqlException ex)
                {
                    throw ex;
                }
                salesdata.RemotingFormat = SerializationFormat.Xml;
                return salesdata;

            }
                  }

  • Web.config
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false 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="true" />
        </behavior>
        <behavior name="restbeh">
          <serviceDebug httpHelpPageEnabled="True" includeExceptionDetailInFaults="true" />
          <serviceMetadata  httpGetEnabled="True"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="restendbeh">
          <!--<soapProcessing processMessages="True"/>-->
          <webHttp helpEnabled="True" faultExceptionEnabled="True" defaultBodyStyle="Bare" defaultOutgoingResponseFormat="Xml"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="myrestbinding">
          <security mode="None"></security>
          <readerQuotas maxArrayLength="65536"/>
        </binding>
      </webHttpBinding>
    </bindings>

    <services>
      <service name="WCFServicesREST.RestWCF" behaviorConfiguration="restbeh">
        <endpoint  contract="WCFServicesREST.IRestWCF" binding="webHttpBinding"  bindingConfiguration="myrestbinding"
                   behaviorConfiguration="restendbeh"></endpoint>
       
      </service>
    </services>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"  aspNetCompatibilityEnabled="True"/>
  </system.serviceModel>
  <system.webServer>
 </configuration>





Consuming  in WPF Application

  • Create a WPF Application using .NET 4.0/4.5 using C#
  • Add a DataGrid to XAML name it as datagrid1
  • Add namespaces in .cs file
    • using System.Xml;
    • using System.Xml.Serialization;
    • using System.Net;
    Declare a class called SalesPerson class for XML Serialization/DeSerialization.
[XmlRoot(ElementName = "SalesPerson", Namespace = "")]
    public class SalesPerson
    {
        [XmlAttribute(Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1")]
        public String id { get; set; }
        [XmlAttribute(Namespace = "urn:schemas-microsoft-com:xml-msdata")]
        public int rowOrder { get; set; }

        [XmlElement]
        public int? BusinessEntityID { get; set; }
        [XmlElement]
        public decimal? Bonus { get; set; }
        [XmlElement]
        public decimal? CommissionPct { get; set; }
        [XmlElement]
        public decimal? SalesLastYear { get; set; }
        [XmlElement]
        public decimal? SalesYTD { get; set; }
        [XmlElement]
        public int? TerritoryID { get; set; }
        [XmlElement]
        public DateTime? ModifiedDate { get; set; }
    }
Note: Each element in this class should match columns returned from wcf  Datatable, column names are case sensitive. null columns should use ?. Namespaces also must match, otherwise "serialization error saying <SalesPerson xmlns=''> not expected here" will appear.

Because WCF Rest doesn't serve proxy class. So You need ti call WebRequest/HttpWebRequest in System.Net.

as shown below

WebRequest req = WebRequest.Create("http://localhost:3054/RestWCF.svc/GetDataTableXml");
                  req.ContentType = "text/xml";
                    WebResponse resp = req.GetResponse();
                    Stream stream = resp.GetResponseStream();
                    XmlSerializerFactory fact = new XmlSerializerFactory();

                    XmlReader re = XmlReader.Create(stream);
                    while (re.Read())
                    {
                        if (re.NodeType == XmlNodeType.Element &&   re.LocalName.Equals("SalesPerson"))
                        {
                            XmlSerializer ser = fact.CreateSerializer(typeof(SalesPerson));

                            SalesPerson p = (SalesPerson)ser.Deserialize(re);
                           //add to list.
                            salesPersonXML.Add(p);
                        }
                    }
//Bind to datagrid in WPF
                    datagrid1.ItemsSource = salesPersonXML;

OUTPUT

Wednesday, 19 December 2012

Returning Datatable from WCF VB.NET


Returning Datatable from WCFVB.NET

 Step1)   Create a WCF Service Application using .NET 4.5 VB.NET
 Step 2)  Add WCF service name it as DatableDemo
    <ServiceContract> _
    Public Interface IDatableDemo
        <OperationContract> _
        Dim GetEmpDetails() As DataTable
    End Interface

Step 3) In the implementation file.
      Public DataTable GetEmpDetails()
        {
          Dim emptable As DataTable =  New DataTable("Employees")
Try
End Try
          {
              Imports (SqlConnection conn = New SqlConnection("server=(local)\sqlexpress2012database=AdventureWorks2012uid=sa;pwd=pwd"))
              {
                  Imports (SqlDataAdapter adapter = New SqlDataAdapter("select * from (AdventureWorks2012).(HumanResources).(Employee)", conn))
                  {
                      adapter.Fill(emptable)
                      emptable.RemotingFormat = SerializationFormat.Xml
                      emptable.AcceptChanges()
                      conn.Close()
                  }
              }
          }
          catch (Exception ex)
          {
              throw ex;
          }
               return emptable;
        }


Step 4)  Create a schema for DataTable using SvcUtil.exe. otherwise "The underlying connection was closed: An unexpected error occurred on a receive" error msg
            will display

Step 5) Open VS2012 Command Prompt in Administrator mode.  


c:\wcf>svcutil http://localhost:3054/idtdemo.svc  /r:"C:\Program Files (x86)\Ref
erence Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Data.dll" /r:C:\
inetpub\wwwroot\Tutorials\WCFServices\bin\wcfservices.dll /t:metadata

c:\wcf>svcutil tempuri.org.wsdl schemas.microsoft.com.2003.10.Serialization.xsd
tempuri.org.xsd WCFServices.xsd tempuri.org.samples.xsd System.Data.xsd /language:VB

Step 6) It will generate Proxy class(IDatableDemo.cs) for datatable.  Add this class to any project
              1) Consume WCF DataTable in Console Application
              2) Consume WCF DataTable in Windows Form Application
              3) Consume WCF DataTable in Windows Presentation Application(WPF).
              4) Consume WCF DataTable in Silverlight Application
              5) Consume WCF DataTable in ASP.NET Application

Step 7)   in WPF
               Dim client2 As IdatabledemoClient =  New IdatabledemoClient()
                 datagrid1.ItemsSource = client2.GetEmpDetails().DefaultView

Returning Datatable from WCF C#

Returning Datatable from WCF C#

 Step1)   Create a WCF Service Application using .NET 4.5 C#
 Step 2)  Add WCF service name it as DatableDemo
     [ServiceContract]
    public interface IDatableDemo
    {
        [OperationContract]
        DataTable GetEmpDetails();
    }
Step 3) In the implementation file.
        public DataTable GetEmpDetails()
        {
          DataTable emptable = new DataTable("Employees");
          try
          {
              using (SqlConnection conn = new SqlConnection(@"server=(local)\sqlexpress2012;database=AdventureWorks2012;uid=sa;pwd=lordsiva2030&"))
              {
                  using (SqlDataAdapter adapter = new SqlDataAdapter("select * from [AdventureWorks2012].[HumanResources].[Employee]", conn))
                  {
                      adapter.Fill(emptable);
                      emptable.RemotingFormat = SerializationFormat.Xml;
                      emptable.AcceptChanges();
                      conn.Close();
                  }
              }

          }
          catch (Exception ex)
          {
              throw ex;
          }
               return emptable;
        }


Step 4)  Create a schema for DataTable using SvcUtil.exe. otherwise "The underlying connection was closed: An unexpected error occurred on a receive" error msg
            will display

Step 5) Open VS2012 Command Prompt in Administrator mode.  


c:\wcf>svcutil http://localhost:3054/idtdemo.svc  /r:"C:\Program Files (x86)\Ref
erence Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Data.dll" /r:C:\
inetpub\wwwroot\Tutorials\WCFServices\bin\wcfservices.dll /t:metadata

c:\wcf>svcutil tempuri.org.wsdl schemas.microsoft.com.2003.10.Serialization.xsd
tempuri.org.xsd WCFServices.xsd tempuri.org.samples.xsd System.Data.xsd

Step 6) It will generate Proxy class(IDatableDemo.cs) for datatable.  Add this class to any project
              1) Consume WCF DataTable in Console Application
              2) Consume WCF DataTable in Windows Form Application
              3) Consume WCF DataTable in Windows Presentation Application(WPF).
              4) Consume WCF DataTable in Silverlight Application
              5) Consume WCF DataTable in ASP.NET Application

Step 7)   in WPF
                 IdatabledemoClient client2 = new IdatabledemoClient ();
                 datagrid1.ItemsSource = client2.GetEmpDetails().DefaultView;