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;

Wednesday 6 June 2012

NETTCPBINDING IN IIS 7.0(WAS) WCF SERVICE

NET.TCP BINDING IN IIS 7.0(WAS) WCF SERVICE

Step1)  Create a wcf service in IIS7.0 (as shown below.)

Saturday 26 May 2012

REST & JSON format(Hosting in IIS7 in WCF)


Build Basic WCF Service.

Step 1)  Create a Class Library (name it as wcftest)
                    Add reference System.ServiceModel  


            add 4 files   1)  Interface file 
                                2) Implementation File
                                3) SVC file
                                4) Web config file
Interface file


File name :  interface1.cs


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

namespace restapi
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [WebGet(RequestFormat=WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetPerson")]
        [OperationContract]
        Person getPersoninJSON();
        [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetData")]
        [OperationContract]
        String  GetData();

    }

[DataContract]
    public class Person
{
    [DataMember]
    public String Name;
    [DataMember]
    public int Age;
    [DataMember]
    public string color;
    public Person(string n,int a,string c)
    {
        Name = n;
        Age = a;
        color = c;
    }
}
}



Implementation file

file name is intImpl.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.ServiceModel.Activation;
namespace restapi
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService1
    {
        //Person p = new Person();
        public Person getPersoninJSON()
        {
            
            //p.Age = 38; p.color = "medium"; p.Name = "sitapati";
            
            return new Person("sirpatai",38,"medium");
        }

        public string GetData()
        {
            return "getting JSON data";
        }
    }
}



Add  SVC file
file name is wcftest.svc

<%@ ServiceHost Service="restapi.Service1"  Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>



Add   Web/application config file
file name:  web.config



<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true"/>
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint helpEnabled="true" automaticFormatSelectionEnabled="true">
          
        </standardEndpoint>
      </webHttpEndpoint>
    </standardEndpoints>
    <services>
      <service name="restapi.Service1" behaviorConfiguration="webbeh">
        <endpoint contract="restapi.IService1" binding="webHttpBinding" ></endpoint>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="jsonbe">
          <webHttp helpEnabled="true" automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json"/>
        </behavior> 
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="webbeh">
          <!-- 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="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

<startup><supportedRuntime version="v2.0.50727"/>
</startup>
</configuration>


Build Class Library-> dll will be produced.



Now hosting WCF Service in IIS 7.0


Step 1)  Runt  Inetmgr.msc from run command


Step 2)   Add new Site as shown below


Step 3)   add site name as mywcfone, create folder with same or different in c:\inetpub\wwwroot\wcfone
Step 4)  Click on Connect as...   button and provide ur system's administrator name and password
               to test connection Click on Test Settings Button...(testing purpose only)
Step 5)  Add port as 8080   or some unused port from 1025-65535. Click OK


Step 6)  Previously Created WCF files copy to c:\inetput\wwwroot\wcfone  folder

Step 7)   create a bin folder in wcfone
                    copy   wcftest.dll to bin folder only (not to debug folder)
                  copy  svc file and   web.config file to    c:\inetput\wwwroot\wcfone  folder.

folders & files
 c:\inetput\wwwroot\wcfone\bin  has wcftest.dll
c:\inetput\wwwroot\wcfone   has  wcftest.svc and web.config files

open browser type 

http://localhost:7070/RestJSON.svc/GetData
http://localhost:7070/RestJSON.svc/GetPerson
following output will come for GetPerson method. similar thing for GetData also

Friday 18 May 2012

How to host rest wcf service iis 7.0

Build Basic WCF Service.

Step 1)  Create a Class Library (name it as wcftest)
                    Add reference System.ServiceModel  


            add 4 files   1)  Interface file 
                                2) Implementation File
                                3) SVC file
                                4) Web config file
Interface file


File name :  interface1.cs


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

namespace wcftest
{
    [ServiceContract]
    interface InterfaceOne
    {
        [OperationContract]
        [WebGet]
        int add(int x, int y);

        [OperationContract]
         [WebGet]
        string getUserName(string user);
    }
}


Implementation file

file name is intImpl.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.ServiceModel.Activation;
namespace wcftest
{
    [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
    public class intImpl : InterfaceOne
    {
        public int add(int x, int y)
        {
            return x + y;
        }

        public string getUserName(string user)
        {
            return string.Format("U entered {0} is:",user);
        }
    }
}



Add  SVC file
file name is wcftest.svc

<%@ ServiceHost Service="wcftest.intImpl"  Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>


Add   Web/application config file
file name:  web.config



<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyserBehaviour">
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="WcfService2.Service1" behaviorConfiguration="MyserBehaviour">
        <endpoint contract="WcfService2.IService1" binding="webHttpBinding" bindingConfiguration="myweb"></endpoint>

      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="myweb">
          <security mode="None">
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>


Build Class Library-> dll will be produced.



Now hosting WCF Service in IIS 7.0


Step 1)  Runt  Inetmgr.msc from run command


Step 2)   Add new Site as shown below


Step 3)   add site name as mywcfone, create folder with same or different in c:\inetpub\wwwroot\wcfone
Step 4)  Click on Connect as...   button and provide ur system's administrator name and password
               to test connection Click on Test Settings Button...(testing purpose only)
Step 5)  Add port as 8080   or some unused port from 1025-65535. Click OK


Step 6)  Previously Created WCF files copy to c:\inetput\wwwroot\wcfone  folder

Step 7)   create a bin folder in wcfone
                    copy   wcftest.dll to bin folder only (not to debug folder)
                  copy  svc file and   web.config file to    c:\inetput\wwwroot\wcfone  folder.

folders & files
 c:\inetput\wwwroot\wcfone\bin  has wcftest.dll
c:\inetput\wwwroot\wcfone   has  wcftest.svc and web.config files

open browser type http://localhost:8088/WcfTest.svc/add?x=10&y=20
following output will come.