b

Thursday, 27 December 2012

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

 

1 comment:

  1. Hai this is excellent article, can u send this code suhelsa@gmail.com

    ReplyDelete