Saturday, 3 October 2015

WCF Service with JSON formate both service and client

(A)Service
=======================================================================
=======================================================================

(1)ServiceContract
========================================================================

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

namespace JsonFormate
{
    // 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
    {

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/GetAllCustomersJson")]
        List<Customer> GetAllCustomersJson();

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/GetAllCustomersSoap")]
        List<Customer> GetAllCustomersSoap();

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/GetCustomersJson")]
        Customer GetCustomersJson();

        [OperationContract]
        //[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/GetAllCustomersDynamicSerialization")]
        string GetAllCustomersDynamicSerialization();
   
    }


    [DataContract]
    public class Customer
    {
        [DataMember]
        public int CustomerId { get; set; }

        [DataMember]
        public string CustomerName { get; set; }

        [DataMember]
        public string CustomerMobile { get; set; }

        [DataMember]
        public DateTime CustomerDob { get; set; }

        [DataMember]
        public List<Address> Address { get; set; }

    }
    [DataContract]
    public class Address
    {
        [DataMember]
        public string Lan1 { get; set; }

        [DataMember]
        public BillingAddress BAddress { get; set; }

        [DataMember]
        public ShippingAddress SAddress { get; set; }
    }

    [DataContract]
    public class BillingAddress
    {
        [DataMember]
        public string Blan1 { get; set; }

        [DataMember]
        public string Blan2 { get; set; }

    }

    [DataContract]
    public class ShippingAddress
    {
        [DataMember]
        public string Slan1 { get; set; }

        [DataMember]
        public string Slan2 { get; set; }
    }
}

(2)Service implementer
===================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace JsonFormate
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {
        public readonly List<Customer> _customerList;
        public Service1()
        {
            _customerList = new List<Customer>(){
               new Customer{
                   CustomerId=1,
                   CustomerName="Das",
                   CustomerMobile="8500014303",
                   CustomerDob=DateTime.Now,
                   Address=new List<Address>(){
                       new Address(){
                           Lan1="Lan1",
                           BAddress=new BillingAddress{
                               Blan1="BLan1",
                               Blan2="BLan2"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan1",
                               Slan2="Slan2"
                           }
                       },
                       new Address(){
                           Lan1="Lan11",
                           BAddress=new BillingAddress{
                               Blan1="BLan11",
                               Blan2="BLan21"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan11",
                               Slan2="Slan21"
                           }
                       }
                   }
               },
                new Customer{
                   CustomerId=1,
                   CustomerName="Das",
                   CustomerMobile="8500014303",
                   CustomerDob=DateTime.Now,
                   Address=new List<Address>(){
                       new Address(){
                           Lan1="Lan1",
                           BAddress=new BillingAddress{
                               Blan1="BLan1",
                               Blan2="BLan2"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan1",
                               Slan2="Slan2"
                           }
                       },
                       new Address(){
                           Lan1="Lan11",
                           BAddress=new BillingAddress{
                               Blan1="BLan11",
                               Blan2="BLan21"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan11",
                               Slan2="Slan21"
                           }
                       }
                   }
               },
                new Customer{
                   CustomerId=1,
                   CustomerName="Das",
                   CustomerMobile="8500014303",
                   CustomerDob=DateTime.Now,
                   Address=new List<Address>(){
                       new Address(){
                           Lan1="Lan1",
                           BAddress=new BillingAddress{
                               Blan1="BLan1",
                               Blan2="BLan2"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan1",
                               Slan2="Slan2"
                           }
                       },
                       new Address(){
                           Lan1="Lan11",
                           BAddress=new BillingAddress{
                               Blan1="BLan11",
                               Blan2="BLan21"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan11",
                               Slan2="Slan21"
                           }
                       }
                   }
               },
                new Customer{
                   CustomerId=1,
                   CustomerName="Das",
                   CustomerMobile="8500014303",
                   CustomerDob=DateTime.Now,
                   Address=new List<Address>(){
                       new Address(){
                           Lan1="Lan1",
                           BAddress=new BillingAddress{
                               Blan1="BLan1",
                               Blan2="BLan2"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan1",
                               Slan2="Slan2"
                           }
                       },
                       new Address(){
                           Lan1="Lan11",
                           BAddress=new BillingAddress{
                               Blan1="BLan11",
                               Blan2="BLan21"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan11",
                               Slan2="Slan21"
                           }
                       }
                   }
               },
                new Customer{
                   CustomerId=1,
                   CustomerName="Das",
                   CustomerMobile="8500014303",
                   CustomerDob=DateTime.Now,
                   Address=new List<Address>(){
                       new Address(){
                           Lan1="Lan1",
                           BAddress=new BillingAddress{
                               Blan1="BLan1",
                               Blan2="BLan2"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan1",
                               Slan2="Slan2"
                           }
                       },
                       new Address(){
                           Lan1="Lan11",
                           BAddress=new BillingAddress{
                               Blan1="BLan11",
                               Blan2="BLan21"
                           },
                           SAddress=new ShippingAddress{
                               Slan1="Slan11",
                               Slan2="Slan21"
                           }
                       }
                   }
               }
           };
         }
        public List<Customer> GetAllCustomersJson()
        {
            return _customerList;
        }

        public List<Customer> GetAllCustomersSoap()
        {
            return _customerList;
        }


        public Customer GetCustomersJson()
        {
            return new Customer
              {
                  CustomerId = 1,
                  CustomerName = "Das",
                  CustomerMobile = "8500014303"
              };
        }


        public string GetAllCustomersDynamicSerialization()
        {
            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(List<Customer>));
            MemoryStream ms = new MemoryStream();
            js.WriteObject(ms, _customerList);
         
            ms.Position = 0;
            StreamReader sr = new StreamReader(ms);
            string data123 = sr.ReadToEnd();
            sr.Close();
            ms.Close();
            return data123;
        }
    }
}
(3)Wb.config 
==================================================================
<?xml version="1.0"?>
<configuration>

  <connectionStrings>
    <add name="WcfNorthWindConnectionString" connectionString="Data Source=Dasu;Initial Catalog=WcfNorthWind;User ID=sa;Password=anandarao67"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="JsonFormate.Service1" behaviorConfiguration="ServiceBehaviour">
        <!-- Service Endpoints -->
        <!-- Unless fully qualified, address is relative to base address supplied above -->
        <endpoint address="" binding="webHttpBinding" contract="JsonFormate.IService1" behaviorConfiguration="Web">
          <!-- 
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
              automatically.
          -->
        </endpoint>
       <endpoint address="soap" binding="basicHttpBinding" contract="JsonFormate.IService1"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
           <!-- 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>
    <endpointBehaviors>
      <behavior name="Web">
        <webHttp/>
      </behavior>
    </endpointBehaviors>
    </behaviors>
    <standardEndpoints>
      <webScriptEndpoint>
      <standardEndpoint name="" crossDomainScriptAccessEnabled="true" />
      </webScriptEndpoint>
    </standardEndpoints>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
 <modules runAllManagedModulesForAllRequests="true" />
 <httpProtocol>
 <customHeaders>
 <add name="Access-Control-Allow-Origin" value="*" />
 <add name="Access-Control-Allow-Headers" value="Content-Type" /> 
 </customHeaders>
 </httpProtocol> 
</system.webServer>

</configuration>
(B)Client call service from jquery
=======================================================================
=======================================================================
Note: only json return type will work in jquery ajax call

 <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                url: "http://localhost:49931/Service1.svc/GetAllCustomersJson"
            }).then(function (data) {
                alert(data);
            });
        });
    </script>

(C)Client call service from .aspx.cs
=====================================================================
=====================================================================
(I)Json type with webmethod attribute
=================
 HttpClient client1 = new HttpClient();
        HttpResponseMessage wcfResponse = client1.GetAsync("http://localhost:49931/Service1.svc/GetAllCustomersJson").Result;
        HttpContent stream = wcfResponse.Content;
        var data = stream.ReadAsStringAsync();
        var data1 = data.Result;

(ii)Normal call
===================
Service1Client client2 = new Service1Client();
        var responce = client2.GetAllCustomersJson();
(iii)Json type with out webmethod attribute
==================
string  ms = client2.GetAllCustomersDynamicSerialization();
(iv)Xml type
==================
HttpClient client1 = new HttpClient();
        HttpResponseMessage wcfResponse = client1.GetAsync("http://localhost:49931/Service1.svc/GetAllCustomersSoap").Result;
        HttpContent stream = wcfResponse.Content;
        var data = stream.ReadAsStringAsync();
        var data1 = data.Result;

(D)Client web.config
==================
<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService1" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:49931/Service1.svc/soap"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"
        contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" />
    </client>
  </system.serviceModel>

No comments:

Post a Comment