b

Sunday, 27 October 2013

Expose WCF Service as SOAP and REST

Expose WCF  Service as SOAP and REST


1) Create WCF Service application

2) Add interface file+Class file+ .svc file

           Interface file:  interface1.cs
           Class file: class1.cs
           Service file: Service2.svc

3)  interface1.cs


using System.ServiceModel;
using System.ServiceModel.Web;
using System.Runtime.Serialization;

namespace WcfService1
{
[ServiceContract]
    interface Interface1
    {
        [WebGet]
        [OperationContract]   
        Person GetPerson();
    }


    [DataContract]
    public class Person
    {
        [DataMember] public int id{get;set;}
        [DataMember] public String Name{get;set;}
        [DataMember] public DateTime Dob{get;set;}
    }
}
}

4) Class1.cs


namespace WcfService1
{
    [ServiceBehavior(IncludeExceptionDetailInFaults=true)]
    public class Class1:Interface1
    {
        public Person GetPerson()
        {
            return new Person { id = 102, Dob = DateTime.Now.AddYears(-40), Name = "Peter"};
        }
    }
}


5) Service2.svc


<%@
    ServiceHost
    Service="WcfService1.Class1"
%>


6) In Web.config

  <system.serviceModel>
    <services>
      <service name="WcfService1.Class1">
        <endpoint binding="webHttpBinding"
                   contract="WcfService1.Interface1"
                   behaviorConfiguration="restBehaviour"
                   address="/web"
                  ></endpoint>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="restBehaviour">
          <webHttp helpEnabled="true" faultExceptionEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

6)  For SOAP Clients

 Just run   http://localhost:port/Service2.svc

For Rest Services

  http://localhost:port/Service2.svc/web
     User  gets help page and list of operations, in this case GetPerson

Saturday, 26 October 2013

How to support multiple formats using query parameter in wcf Rest Service

How to support multiple formats using query parameter in wcf Rest Service

How to get both json and xml formats in WCF Rest Service

1) Create WCF Service application

2) Add interface file+Class file+ .svc file

           Interface file:  interface1.cs
           Class file: class1.cs
           Service file: Service2.svc

3)  interface1.cs


using System.ServiceModel;
using System.ServiceModel.Web;
using System.Runtime.Serialization;

namespace WcfService1
{
[ServiceContract]
    interface Interface1
    {
        [WebGet]
           
        Person GetPerson(String format);
    }


    [DataContract]
    public class Person
    {
        [DataMember] public int id{get;set;}
        [DataMember] public String Name{get;set;}
        [DataMember] public DateTime Dob{get;set;}
    }
}
}

4) Class1.cs


namespace WcfService1
{
    [ServiceBehavior(IncludeExceptionDetailInFaults=true)]
    public class Class1:Interface1
    {
        public Person GetPerson(String format)
        {
            WebOperationContext wc = WebOperationContext.Current;

         
           
                if (format.=="json")
                {
                    wc.OutgoingResponse.ContentType = "application/json";
                    wc.OutgoingResponse.Format = WebMessageFormat.Json;
                }
                else if (format.=="xml")
                {
                    wc.OutgoingResponse.ContentType = "text/xml";
                    wc.OutgoingResponse.Format = WebMessageFormat.Xml;
                }
           
            return new Person { id = 102, Dob = DateTime.Now.AddYears(-40), Name = "Peter"};
        }
    }
}


5) Service2.svc


<%@
    ServiceHost
    Factory="System.ServiceModel.Activation.WebServiceHostFactory"
    Service="WcfService1.Class1"
%>


6) In Web.config

  <system.serviceModel>
    <services>
      <service name="WcfService1.Class1">
        <endpoint binding="webHttpBinding"
                   contract="WcfService1.Interface1"
                   behaviorConfiguration="restBehaviour"
                  ></endpoint>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="restBehaviour">
          <webHttp helpEnabled="true" faultExceptionEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

6) Just run   http://localhost:port/Service2.svc

U will get help page


7) How to consume WCF Rest Service JSON format

            Uri uri = new Uri("http://localhost:23454/Service2.svc/GetPerson?format=json");

            WebClient client = new WebClient();
            client.Headers.Add(HttpRequestHeader.ContentType, "application/json");

            Stream jsonSTream=
                client.OpenRead(uri);

            StreamReader reader =
                new StreamReader(jsonSTream);

            String strPerson=reader.ReadToEnd();
            Console.WriteLine(strPerson);
            Console.ReadLine();

JSON OUTPUT:

{"Dob":"\/Date(120135205873-0700)\/","Name":"Peterapplication\/json","id":102}

7) How to consume WCF Rest Service XML format

            Uri uri = new Uri("http://localhost:23454/Service2.svc/GetPerson?format=xml");

            WebClient client = new WebClient();
            client.Headers.Add(HttpRequestHeader.ContentType, "text/xml");

            Stream jsonSTream=
                client.OpenRead(uri);

            StreamReader reader =
                new StreamReader(jsonSTream);

            String strPerson=reader.ReadToEnd();
            Console.WriteLine(strPerson);
            Console.ReadLine();



XML Output:



<Person xmlns="http://schemas.datacontract.org/2004/07/WcfService1" xmlns:i="htt
p://www.w3.org/2001/XMLSchema-instance"><Dob>1973-10-22T03:53:29.6915206-07:00</
Dob><Name>Petertext/xml</Name><id>102</id></Person>

Create and consume Jsonp Service using WCF Rest Service

Create and consume Jsonp Service using WCF Rest Service

1) Create WCF Rest Service 

   Create a WCF Service Application

               Delete all existing files then add below files.

    1.1 ) Create a Data Contract called Person

     [DataContract]
    public class Person
    {
        [DataMember] public int id{get;set;}
        [DataMember] public String Name{get;set;}
        [DataMember] public DateTime Dob{get;set;}
    }

    1.2) Expose this using Service Contract

         [ServiceContract]
    interface Interface1
    {
        [WebGet(ResponseFormat=WebMessageFormat.Json)]
           
        Person GetPerson();
    }

1.3)  Implement this interface

namespace WcfService1
{
    [ServiceBehavior(IncludeExceptionDetailInFaults=true)]
    [JavascriptCallbackBehavior(UrlParameterName="$callback")]
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
    public class Class1:Interface1
    {
        public Person GetPerson()
        {
            return new Person { id = 102, Dob = DateTime.Now.AddYears(-40), Name = "Peter"};
        }
    }
}

JavascriptCallbackBehavior Attribute specifies actual Callback parameter. in this case "callback"

1.4)  Enable Cross Domain Script Access in Web.config


<system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="mywebb" crossDomainScriptAccessEnabled="true">
         
        </binding>
      </webHttpBinding>
    </bindings>
    <services>
      <service name="WcfService1.Class1">
        <endpoint binding="webHttpBinding" bindingConfiguration="mywebb" contract="WcfService1.Interface1" behaviorConfiguration="restBehaviour"/>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="restBehaviour">
          <webHttp helpEnabled="true" faultExceptionEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>

1.5) Specify Host factory as WebServiceHostFactory in Service2.svc


<%@
    ServiceHost
    Factory="System.ServiceModel.Activation.WebServiceHostFactory"
    Service="WcfService1.Class1"
%>

1.6)Just Run the Service2.svc 

U will see help page and list of Operations


     
  

           
 

2) using javascript Consume Jsonp Rest Service

  2.1) Create a new Empty asp.net Web Application or Simply Html Page


2.2) Add a Callback function

              <script type="text/javascript">
                function fun1(persondata) {

                    alert("Name="+persondata.Name+
                           "Id=" + persondata.id+
                           "DOB=" + persondata.Dob);

                }

    </script>


2.3)  Call   WCF Service URL  using Script tag



<script type="text/javascript" src="http://localhost/WcfService1/Service2.svc/GetPerson?$callback=fun1"></script>

Just  run the web page

U will get

3) How to COnsume WCF REST jsonp service in JQUERY ajax

<script type="text/javascript">
     $(document).ready(function () {
     
         $.ajax({
             url: 'http://localhost/WcfService1/Service2.svc/GetPerson?$callback=localJsonpCallback',
             type: "GET",
             async: false,
             crossDomain: true,
             cache: false,
             jsonp: true,
             dataType: "jsonp",
         });
         //).done(function (data) {
         //    alert(data.Name);
         //}).fail(function (jqXHR, textStatus)
         //{
         //    alert(textStatus+jqXHR.status);
         //});
         //jsonpCallback: function (data) {
         //    alert(data + "callback");
         //}
    
     });
 </script>
    <script type="text/javascript">
        function localJsonpCallback(data) {
            alert(data.Name+" "+data.id+" "+data.Dob);
        }

    </script>

Tuesday, 22 October 2013

How to create and consume wcf rest service in C#

How to create and consume wcf rest service in C#


1) Create WCF Service application

2) Add interface file+Class file+ .svc file

           Interface file:  interface1.cs
           Class file: class1.cs
           Service file: Service2.svc

3)  interface1.cs


using System.ServiceModel;
using System.ServiceModel.Web;
using System.Runtime.Serialization;

namespace WcfService1
{
[ServiceContract]
    interface Interface1
    {
        [WebGet]
           
        Person GetPerson();
    }


    [DataContract]
    public class Person
    {
        [DataMember] public int id{get;set;}
        [DataMember] public String Name{get;set;}
        [DataMember] public DateTime Dob{get;set;}
    }
}
}

4) Class1.cs


namespace WcfService1
{
    [ServiceBehavior(IncludeExceptionDetailInFaults=true)]
    public class Class1:Interface1
    {
        public Person GetPerson()
        {
            WebOperationContext wc = WebOperationContext.Current;
            String contentType=wc.
                IncomingRequest.
                Headers[System.Net.HttpRequestHeader.ContentType];

            if (!String.IsNullOrEmpty(contentType))
            {
                if (contentType.Contains("application/json"))
                {
                    wc.OutgoingResponse.ContentType = "application/json";
                    wc.OutgoingResponse.Format = WebMessageFormat.Json;
                }
                else
                {
                    wc.OutgoingResponse.ContentType = "text/xml";
                    wc.OutgoingResponse.Format = WebMessageFormat.Xml;
                }
            }
            return new Person { id = 102, Dob = DateTime.Now.AddYears(-40), Name = "Peter"};
        }
    }
}


5) Service2.svc


<%@
    ServiceHost
    Factory="System.ServiceModel.Activation.WebServiceHostFactory"
    Service="WcfService1.Class1"
%>


6) In Web.config

  <system.serviceModel>
    <services>
      <service name="WcfService1.Class1">
        <endpoint binding="webHttpBinding"
                   contract="WcfService1.Interface1"
                   behaviorConfiguration="restBehaviour"
                  ></endpoint>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="restBehaviour">
          <webHttp helpEnabled="true" faultExceptionEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

6) Just run   http://localhost:port/Service2.svc

U will get help page

7) How to consume WCF Rest Service JSON format

            Uri uri = new Uri("http://localhost:23454/Service2.svc/GetPerson");

            WebClient client = new WebClient();
            client.Headers.Add(HttpRequestHeader.ContentType, "application/json");

            Stream jsonSTream=
                client.OpenRead(uri);

            StreamReader reader =
                new StreamReader(jsonSTream);

            String strPerson=reader.ReadToEnd();
            Console.WriteLine(strPerson);
            Console.ReadLine();

JSON OUTPUT:

{"Dob":"\/Date(120135205873-0700)\/","Name":"Peterapplication\/json","id":102}

7) How to consume WCF Rest Service XML format

            Uri uri = new Uri("http://localhost:23454/Service2.svc/GetPerson");

            WebClient client = new WebClient();
            client.Headers.Add(HttpRequestHeader.ContentType, "text/xml");

            Stream jsonSTream=
                client.OpenRead(uri);

            StreamReader reader =
                new StreamReader(jsonSTream);

            String strPerson=reader.ReadToEnd();
            Console.WriteLine(strPerson);
            Console.ReadLine();



XML Output:



<Person xmlns="http://schemas.datacontract.org/2004/07/WcfService1" xmlns:i="htt
p://www.w3.org/2001/XMLSchema-instance"><Dob>1973-10-22T03:53:29.6915206-07:00</
Dob><Name>Petertext/xml</Name><id>102</id></Person>


Flags:How to create and consume wcf rest service in C#, How to consume wcf rest service through headers.
How to create wcf rest service for xml and json formats,
How to create wcf rest service for combined formats  xml and json.How to create and consume wcf rest service inasp.net