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

Wednesday 27 February 2013

Self Hosting WCF Service VB.NET


Self Hosting WCF Service in Console Applictaion Vb.NET


1) Create Contract and Implementation
     Here I use ADO.NET connecting to Northwind Database to get Number of Orders.

2) In Program Entry.
              Create Service Host  
3) Using ChannelFactory query above WCF Service

ServiceContract

    <ServiceContract> _
    Public Interface IOrder
        <OperationContract> _
        Dim GetOrderCount() As Integer
    End Interface
Implementation Class for Service Contract
Service Contract has single method called GetOrderCount from NorthWind Database.
 
    Public Class Orders
     Implements IOrder
        Public Function GetOrderCount() As Integer
            SqlConnection conn = New
                SqlConnection("Data Source=localhost\sqlexpress2012;Initial Catalog=northwind;trusted_connection=yes;")
            conn.Open()

            Dim cmd As SqlCommand =  New SqlCommand("select count(*) from orders",conn)
            Dim obj As Object = cmd.ExecuteScalar()

           Return Int32.Parse(obj.ToString())
        End Function
    End Class
 
In Program Entry Point

                1) Create/Host a WCF Service  assign some port number(unused) here

                 2) Consume same service using ChannelFactory

                1) Create/Host a WCF Service  assign some port number(unused) here
                'Create or Host WCF Service Here
                Dim baseAdd() As Uri =  New Uri() {New Uri("http://localhost:7070/")}

                Dim host As ServiceHost =  New ServiceHost(Type.GetType(Orders),baseAdd)
                host.AddServiceEndpoint(Type.GetType(IOrder), New WSHttpBinding(),
                "http://localhost:7070/selfhost")

                Dim mb As ServiceMetadataBehavior =  New ServiceMetadataBehavior()
                mb.HttpGetEnabled = True
                host.Description.Behaviors.Add(mb)

                'Open the Service
                host.Open()

 
                 2) Consume same service using ChannelFactory
               //Consume the above WCF Service using ChannelFactory
                 'Consume the above WCF Service using ChannelFactory
                '
                Dim binding As WSHttpBinding =  New WSHttpBinding()
                Dim address As EndpointAddress =  New EndpointAddress(
                "http://localhost:7070/selfhost")

                Dim channel As selfhostwcf.IOrder =  New ChannelFactory
                <selfhostwcf.IOrder>(binding,address).CreateChannel()
                Console.WriteLine("Order Count={0}",channel.GetOrderCount())

                Console.ReadLine()
That's it ,Hosting and consuming WCF service in console application without web.config settings.


Type :  
http://localhost:7070/  in your browser u will see metadata.

as long as console application is running you can access service metdata and other applications also can consume this service.
After Excuting Console Application U will get Output as
Order Count=830


Complete Source Code
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.ServiceModel
Imports System.Runtime.Serialization
Imports System.ServiceModel.Description
Imports System.Data
Imports System.Data.SqlClient
Imports System.ServiceModel.Channels
Namespace selfhostwcf

    <ServiceContract> _
    Public Interface IOrder
        <OperationContract> _
        Dim GetOrderCount() As Integer
    End Interface

    Public Class Orders
     Implements IOrder
        Public Function GetOrderCount() As Integer
            SqlConnection conn = New
                SqlConnection("Data Source=localhost\sqlexpress2012;Initial Catalog=northwind;trusted_connection=yes;")
            conn.Open()

            Dim cmd As SqlCommand =  New SqlCommand("select count(*) from orders",conn)
            Dim obj As Object = cmd.ExecuteScalar()

           Return Int32.Parse(obj.ToString())
        End Function
    End Class

    Class Program
        Shared  Sub Main(ByVal args() As String)
            Try
                'Create or Host WCF Service Here
                Dim baseAdd() As Uri =  New Uri() {New Uri("http://localhost:7070/")}

                Dim host As ServiceHost =  New ServiceHost(Type.GetType(Orders),baseAdd)
                host.AddServiceEndpoint(Type.GetType(IOrder), New WSHttpBinding(),
                "http://localhost:7070/selfhost")

                Dim mb As ServiceMetadataBehavior =  New ServiceMetadataBehavior()
                mb.HttpGetEnabled = True
                host.Description.Behaviors.Add(mb)

                Dim 'Open the Service As host.Open()


                'Consume the above WCF Service using ChannelFactory
                '
                Dim binding As WSHttpBinding =  New WSHttpBinding()
                Dim address As EndpointAddress =  New EndpointAddress("http://localhost:7070/selfhost")

                Dim channel As selfhostwcf.IOrder =  New ChannelFactory<selfhostwcf.IOrder>(binding,address).CreateChannel()
                Console.WriteLine("Order Count={0}",channel.GetOrderCount())

                Console.ReadLine()
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try

        End Sub
    End Class
End Namespace
 
Tags:Self Hosting WCF Service VB.NET,ado.net in wcf service,
Hosting and consuming WCF service in console application without web.config,WCF Service contract,WCF Operation contract,Host service in console applictaion,Consume WCF service using ChannelFactory,Consume WCF service using ChannelFactory in console application

Wednesday 23 January 2013

WCF HelpPage

WCF HelpPage

WCF metaData

WCF metaData

CRUD in WCF Service

CRUD in WCF Service

CRUD in WCF REST Service

CRUD in WCF REST Service

WCF ATOM format

WCF ATOM format

WCF RSS format

WCF RSS format

Authentication and Authorization in WCF REST Service

Authentication and Authorization in WCF REST Service

WCF JSONP

WCF JSONP

WCF Formats

WCF Formats

WCF Peer Networking

WCF Peer Networking

WCF Performance Counters

WCF Performance Counters

WCF Tracing

WCF Tracing

WCF FaultException

WCF FaultException

WCF Logging

WCF Logging

WCF Form Authentication

WCF Form Authentication

WCF Authentication using MemberShip Providers

WCF Authentication using MemberShip Providers

Message Level Security in WCF

Message Level Security in WCF

Transport Level Security in WCF

Transport Level Security in WCF

WCF hosting in Console Application

WCF hosting in Console Application

WCF hosting in XAML/WPF

WCF hosting in XAML/WPF

WCF Hosting in Windows Forms

WCF Hosting in Windows Forms

Self Hosting WCF Service C#

Self Hosting WCF Service in Console Applictaion


1) Create Contract and Implementation
     Here I use ADO.NET connecting to Northwind Database to get Number of Orders.

2) In Program Entry.
              Create Service Host  
3) Using ChannelFactory query above WCF Service

ServiceContract

    [ServiceContract]
    public interface IOrder
    {
        [OperationContract]
        int GetOrderCount();
    }

Implementation Class for Service Contract
Service Contract has single method called GetOrderCount from NorthWind Database.
 
    public class Orders : IOrder
    {
        public int GetOrderCount()
        {
            SqlConnection conn = new
                SqlConnection(@"Data Source=localhost\sqlexpress2012;Initial Catalog=northwind;trusted_connection=yes;");
            conn.Open();

            SqlCommand cmd = new SqlCommand("select count(*) from orders",conn);
            object obj=cmd.ExecuteScalar();

           return Int32.Parse(obj.ToString());
        }
 

In Program Entry Point

                1) Create/Host a WCF Service  assign some port number(unused) here

                 2) Consume same service using ChannelFactory


                1) Create/Host a WCF Service  assign some port number(unused) here

                //Create or Host WCF Service Here
                Uri[] baseAdd = new Uri[] { new Uri("http://localhost:7070/") };
                ServiceHost host = new ServiceHost(typeof(Orders), baseAdd);
                host.AddServiceEndpoint(typeof(IOrder), new WSHttpBinding(),
                "http://localhost:7070/selfhost");

                ServiceMetadataBehavior mb = new ServiceMetadataBehavior();
                mb.HttpGetEnabled = true;
                host.Description.Behaviors.Add(mb);

                host.Open(); //Open the Service
 
                 2) Consume same service using ChannelFactory

               //Consume the above WCF Service using ChannelFactory
                //
                WSHttpBinding binding = new WSHttpBinding();
                EndpointAddress address = new EndpointAddress("http://localhost:7070/selfhost");

                selfhostwcf.IOrder channel = new ChannelFactory<selfhostwcf.IOrder>(
               binding, address).CreateChannel();
                Console.WriteLine("Order Count={0}",channel.GetOrderCount());

                Console.ReadLine();

That's it ,Hosting and consuming WCF service in console application without web.config settings.


Type :  
http://localhost:7070/  in your browser u will see metadata.

as long as console application is running you can access service metdata and other applications also can consume this service.


After Excuting Console Application U will get Output as
Order Count=830


Complete Source Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.ServiceModel.Description;
using System.Data;
using System.Data.SqlClient;
using System.ServiceModel.Channels;
namespace selfhostwcf
{

    [ServiceContract]
    public interface IOrder
    {
        [OperationContract]
        int GetOrderCount();
    }

    public class Orders : IOrder
    {
        public int GetOrderCount()
        {
            SqlConnection conn = new
                SqlConnection(@"Data Source=localhost\sqlexpress2012;Initial Catalog=northwind;trusted_connection=yes;");
            conn.Open();

            SqlCommand cmd = new SqlCommand("select count(*) from orders",conn);
            object obj=cmd.ExecuteScalar();

           return Int32.Parse(obj.ToString());
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //Create or Host WCF Service Here
                Uri[] baseAdd = new Uri[] { new Uri("http://localhost:7070/") };
                ServiceHost host = new ServiceHost(typeof(Orders), baseAdd);
                host.AddServiceEndpoint(typeof(IOrder), new WSHttpBinding(),
                "http://localhost:7070/selfhost");

                ServiceMetadataBehavior mb = new ServiceMetadataBehavior();
                mb.HttpGetEnabled = true;
                host.Description.Behaviors.Add(mb);

                host.Open(); //Open the Service


                //Consume the above WCF Service using ChannelFactory
                //
                WSHttpBinding binding = new WSHttpBinding();
                EndpointAddress address = new EndpointAddress("http://localhost:7070/selfhost");

                selfhostwcf.IOrder channel = new ChannelFactory<selfhostwcf.IOrder>(binding, address).CreateChannel();
                Console.WriteLine("Order Count={0}",channel.GetOrderCount());

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
          
        }
    }
}
 
Tags:Self Hosting WCF Service,ado.net in wcf service,
Hosting and consuming WCF service in console application without web.config,WCF Service contract,WCF Operation contract,Host service in console applictaion,Consume WCF service using ChannelFactory,Consume WCF service using ChannelFactory in console application

LINQ to Objects in WCF

LINQ to Objects in WCF

LINQ to Entities in WCF

LINQ to Entities in WCF

LINQ to SQL in WCF

LINQ to SQL in WCF

Wednesday 2 January 2013

Calling Cross Domain WCF service in Javascript using VB.NET 4.5

 Calling Cross Domain WCF service in Javascript  using VB.NET 4.5

Step 1) Create a WCF Service Application using VB.NET 4.5
Calling Cross Domain WCF service in Javascript  using VB.NET 4.5













Delete IService1.vb and IService1.svc

Step 2) Add WCF Service .name it as"ProfileService"

Calling Cross Domain WCF service in Javascript  using VB.NET 4.5
  • IProfileService.vb(Service Contract file)
  • ProfileService.svc.vb(Service Implementation file)
  • ProfileService.svc(Link between above 2 , & Here we specify Hosting Factory  for creating ScriptEnabled WCF Service).

We need 2 operation contracts
  • GetAllProfilesAsXML
  • GetAllProfilesAsJSON
Interface file has 2 contracts

ProfileService.svc.vb Implementation file for above 2 contracts

ProfileService.svc here we specify hosting Factory name. This is very important

<%@ ServiceHost
    Language="VB"
    Debug="true"
    Service="WcfService1.ProfileService"
    CodeBehind="ProfileService.svc.vb"
     Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"
    %>









Web.config file we need to enable crosssitescripting=true and help page.

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

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
<!-- for help page -->
      <endpointBehaviors>
        <behavior name="myServiceEndPoint">
          <webHttp helpEnabled="true" defaultBodyStyle="Bare" faultExceptionEnabled="true"/>
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>

    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>   
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service name="WcfService1.ProfileService">
        <endpoint address="" contract="WcfService1.IProfileService" binding="webHttpBinding" behaviorConfiguration="myServiceEndPoint"></endpoint>
      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="myrestBinding" crossDomainScriptAccessEnabled="true">
         
        </binding>
      </webHttpBinding>
    </bindings>
    <standardEndpoints>
      <webScriptEndpoint>
        <standardEndpoint crossDomainScriptAccessEnabled="True">
          <security mode="None"></security>
        </standardEndpoint>
      </webScriptEndpoint>
    </standardEndpoints>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>



Help Page  located at http://localhost:26678/ProfileService.svc/help

Calling Cross Domain WCF service in Javascript  using VB.NET 4.5








Click on GET   for GetAllProfilesAsJSON, u will get as shown below

Calling Cross Domain WCF service in Javascript  using VB.NET 4.5

Click on GET   for GetAllProfilesAsXML, u will get as shown below





  for cross domain WCF service, Binding Should be WebHttpBinding. Hosting Factory must be System.ServiceModel.Activation.WebScriptServiceHostFactory.
Once WCF Service creation is done.

Create A  Empty Web Site using   ASP.NET VB.NET 4.5


Calling Cross Domain WCF service using Javascript in asp.net 4.5 C#


Calling Cross Domain WCF service in Javascript  using VB.NET 4.5


 Select .NET 4.5 and Empty Web Site

Add new item -> select Web form name it as Default.aspx

Add  ScriptManager  and reference the Service Path in that

        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
            <Services>
                <asp:ServiceReference Path="http://localhost:26678/ProfileService.svc" />
            </Services>
        </asp:ScriptManager>


 Add 2 button controls(1 for xml another one for json)
Add 2 div/table elements for display xml and json data.

as shown below
 
for XML DATA
        <asp:Button CssClass="buttonStyle" ID="Button1" runat="server" Text="Call Cross Domain  WCF Service XML"  title="Call Cross Domain  WCF Service XML returning complex object"
            OnClientClick="javascript:calling_WCF_in_JavascriptXML()" />

        <asp:UpdatePanel ID="UpdatePanel1" runat="server" RenderMode="Block" UpdateMode="Conditional">
            <ContentTemplate>
                 <div style="color:green;font-size:1.6em;border-width:thick;border-color:red;"
                     id="wcf_ajax_response"
                     runat="server">
                         (POX) Plain Old XML Response from WCF Service

         <table  border="1">
        <thead style="font-weight: bold;">
            <tr>
                <td>Age</td>
                <td>Contry</td>
                <td>EmailID</td>
                <td>FirstName</td>
                <td>LastName</td>
                <td>ProfileID</td>
                <td>ZIPCode</td>
                <td>JoinedDate</td>
               
            </tr>
        </thead>
        <tbody id="resTable"></tbody>
    </table>
                  </div>
               
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
            </Triggers>
        </asp:UpdatePanel>

for JSON Data

     <asp:Button CssClass="buttonStyle" ID="Button2" runat="server" Text="Call Cross Domain  WCF Service  JSON"  title="Call Cross Domain  WCF Service JSON returning complex object"
            OnClientClick="javascript:calling_WCF_in_JavascriptJSON()" />

         <asp:UpdatePanel ID="UpdatePanel2" runat="server" RenderMode="Block" UpdateMode="Conditional">
            <ContentTemplate>
                JSON Response from WCF Service
                         <table border="1px">
        <thead style="color:green;font-size:1.6em;border-width:thick;border-color:red;">
            <tr>
                <td>ProfileID</td>
                <td>FirstName</td>
                <td>LastName</td>
                <td>Age</td>
                <td>JoinedDate</td>
                <td>EmailID</td>
                <td>ZIPCode</td>
                <td>Contry</td>
            </tr>
        </thead>
        <tbody id="x"></tbody>
    </table>

                 <div style="color:green;font-size:1.6em;border-width:thick;border-color:red;"
                     id="resTableJSON"
                     runat="server">
                         No JSON Response

                  </div>
               
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
            </Triggers>
        </asp:UpdatePanel>

Now we need to  creating WCF Rest Service in javascript. Note. ScriptManager will generate proxy class in OnPrerender itself.
Here we need to create ServiceContract in javascript.

Calling cross domain WCF service for XML Response

        function calling_WCF_in_JavascriptXML() {
            try {
                //Create a WCF Service in javascript
                var proxy = new SP.IProfileService();
                //note NameSpace is Empty.
                //Calling WCF methods in javascript.
               
               
                proxy.GetAllProfilesAsXML(onSuccessXML, OnFailedXML, null);
            }
            catch (error) {
                alert(error.message);
            }
        }

        function onSuccessXML(result) {
          
            var dom = new DOMParser();
            var xmldoc=dom.parseFromString(result,'text/xml');
            var childNodes = xmldoc.childNodes[0];
            var ProfileNodes = childNodes.childNodes;
            for (i = 0; i < ProfileNodes.length; i++)
               
                if (ProfileNodes[i].tagName == "Profile") {
                    var j = 0;
                    var resTable = document.getElementById("resTable");
                    resTable.insertRow(i);

                    resTable.rows[i].insertCell(j);
                    resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("Age")[i].childNodes[0].nodeValue;
                       resTable.rows[i].insertCell(j);
                       resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("Country")[i].childNodes[0].nodeValue;
                       resTable.rows[i].insertCell(j);
                       resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("EmailID")[i].childNodes[0].nodeValue;
                       resTable.rows[i].insertCell(j);
                      
                       resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("FirstName")[i].childNodes[0].nodeValue;
                       resTable.rows[i].insertCell(j);
                       resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("LastName")[i].childNodes[0].nodeValue;
                       resTable.rows[i].insertCell(j);
                       resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("ProfileID")[i].childNodes[0].nodeValue;
                       resTable.rows[i].insertCell(j);
                       resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("ZIPCode")[i].childNodes[0].nodeValue;
                       resTable.rows[i].insertCell(j);
                       resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("JoinedDate")[i].childNodes[0].nodeValue;
       
                }
           
           
            return;

        }

        function OnFailedXML(result) {
            alert(result+'Failed');
        }


Calling cross domain WCF service for JSON Response

        function calling_WCF_in_JavascriptJSON() {
            try {
                //Create a WCF Service in javascript
                var proxy = new SP.IProfileService();
                //note NameSpace is Empty.

                //Calling WCF methods in javascript.
               // proxy.s
                proxy.GetAllProfilesAsJSON(onSuccessJSON, OnFailedJSON, null);
            }
            catch (error) {
                alert(error.message);
            }
        }

        function onSuccessJSON(result) {
            var str = "<table border='2'>";
            if (Array.isArray(result)) {
                for (var i = 0; i < result.length; i++) {
                    var dt = new Date(result[i].JoinedDate.toString());
                    str += "<tr>";
                    str += "<td>" + result[i].ProfileID + "</td>";
                    str += "<td>" + result[i].FirstName + "</td>";
                    str += "<td>" + result[i].LastName + "</td>";
                    str += "<td>" + result[i].Age + "</td>";
                    str += "<td>" + dt.getFullYear() + "/" + dt.getDate() + "/" + dt.getDay() + "</td>";
                    str += "<td>" + result[i].EmailID + "</td>";
                    str += "<td>" + result[i].ZIPCode + "</td>";
                    str += "<td>" + result[i].Country + "</td>";


                }
                str += "</tr>";
                str += "</table>";

                document.getElementById('resTableJSON').innerHTML = str;
            }

        }

        function OnFailedJSON(result) {
            alert(result+'failed');
        }
 



Run the Application.

OUTPUT

Calling Cross Domain WCF service using Javascript in asp.net 4.5 C#

 Click on "Call Cross Domain WCF Service XML"
Calling Cross Domain WCF service in Javascript  using VB.NET 4.5


 Click on "Call Cross Domain WCF Service JSON"

Calling Cross Domain WCF service in Javascript  using VB.NET 4.5




This example explains how to consume complex object returned by WCF Rest Service as XML and JSON, and also How to parse XML in javascript & How to parse JSON object in javascript. and display as formatted HTML content.
 

               Complete Source Code

Cross Domain WCF service

IProfileService.vb

 Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.Text
Imports System.ServiceModel.Web
Imports System.ServiceModel.Channels
Namespace WcfService1


    <ServiceContract(Namespace="SP")> _
    Public Interface IProfileService
        <OperationContract> _
        <WebGet(ResponseFormat=WebMessageFormat.Xml)> _
        Dim GetAllProfilesAsXML() As List<Profile>

        <OperationContract> _
        <WebGet(ResponseFormat = WebMessageFormat.Json)> _
        Dim GetAllProfilesAsJSON() As List<Profile>
    End Interface
End Namespace

 
ProfileService.svc.vb
 
 Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.Text
Imports System.ServiceModel.Web
Imports System.ServiceModel.Channels
Namespace WcfService1
    ' NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ProfileService" in code, svc and config file together.
    ' NOTE: In order to launch WCF Test Client for testing this service, please select ProfileService.svc or ProfileService.svc.cs at the Solution Explorer and start debugging.
    Public Class ProfileService
     Implements IProfileService
        Private profiles As List<Profile> =  New List<Profile>()
        Public Function GetAllProfilesAsXML() As List<Profile>
            BuildProfile()
            Return profiles
        End Function

        Public Function GetAllProfilesAsJSON() As List<Profile>
            BuildProfile()            Return profiles
        End Function
        Private  Sub BuildProfile()
            If profiles.Count = 0 Then
                profiles.Add(New Profile
                {
                     Age = 21, CounTry = "USA", EmailID = "jhon@gmail.com", FirstName = "jhon", LastName = "Peter", ProfileID = 1, ZIPCode = "94086-2422", JoinedDate = New System.DateTime(1998, 1, 12)
                }
)
                profiles.Add(New Profile
                {
                     Age = 18, CounTry = "USA", EmailID = "macy@yahoo.com", FirstName = "macy", LastName = "William", ProfileID = 2, ZIPCode = "67897-2422", JoinedDate = New System.DateTime(2000, 11, 1)
                }
)
                profiles.Add(New Profile
                {
                     Age = 28, CounTry = "UK", EmailID = "alex@gmail.com", FirstName = "alex", LastName = "Samuel", ProfileID = 3, ZIPCode = "STHL 1ZZ", JoinedDate = New System.DateTime(2002, 10, 9)
                }
)
                profiles.Add(New Profile
                {
                     Age = 35, CounTry = "UK", EmailID = "bearns@gmail.com", FirstName = "beans", LastName = "Jessica", ProfileID = 4, ZIPCode = "AA9A 9AA", JoinedDate = New System.DateTime(2004, 10, 12)
                }
)
                profiles.Add(New Profile
                {
                     Age = 36, CounTry = "INDIA", EmailID = "prasad@gmail.com", FirstName = "prasad", LastName = "kanuturi", ProfileID = 5, ZIPCode = "110011", JoinedDate = New System.DateTime(1990, 1, 2)
                }
)
            End If

        End Sub


    End Class
    <DataContract> _
    Public Class Profile
        <DataMember> _
        Public Property ProfileID() As Integer
        End Property
        <DataMember> _
        Public Property FirstName() As String
        End Property
        <DataMember> _
        Public Property LastName() As String
        End Property
        <DataMember> _
        Public Property Age() As Integer
        End Property
        <DataMember> _
        Public Property JoinedDate() As DateTime
        End Property

        <DataMember> _
        Public Property EmailID() As String
        End Property
        <DataMember> _
        Public Property ZIPCode() As String
        End Property
        <DataMember> _
        Public Property CounTry() As String
        End Property
    End Class

End Namespace
 

ProfileService.svc
<%@ ServiceHost
    Language="C#"
    Debug="true"
    Service="WcfService1.ProfileService"
    CodeBehind="ProfileService.svc.cs"
     Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"
    %>
 
WCF web.config
<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
   
      <endpointBehaviors>
        <behavior name="myServiceEndPoint">
          <webHttp helpEnabled="true" defaultBodyStyle="Bare" faultExceptionEnabled="true"/>
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>   
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service name="WcfService1.ProfileService">
        <endpoint address="" contract="WcfService1.IProfileService" 
binding="webHttpBinding" behaviorConfiguration="myServiceEndPoint"></endpoint>
      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="myrestBinding" crossDomainScriptAccessEnabled="true">
         
        </binding>
      </webHttpBinding>
    </bindings>
    <standardEndpoints>
      <webScriptEndpoint>
        <standardEndpoint crossDomainScriptAccessEnabled="True">
          <security mode="None"></security>
        </standardEndpoint>
      </webScriptEndpoint>
    </standardEndpoints>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

ASP.NET  WEBSITE

DEFAULT.ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">

    <title>Calling Cross Domain WCF service using Javascript Example</title>
    <style type="text/css">
        .buttonStyle
        {
            color:white;
            background-color:darkblue;
            border-radius:10px;
            font-size:1.6em;
        }
    </style>
    <script type="text/javascript">

        function calling_WCF_in_JavascriptJSON() {
            try {
                //Create a WCF Service in javascript
                var proxy = new SP.IProfileService();
                //note NameSpace is Empty.

                //Calling WCF methods in javascript.
               // proxy.s
                proxy.GetAllProfilesAsJSON(onSuccessJSON, OnFailedJSON, null);
            }
            catch (error) {
                alert(error.message);
            }
        }

        function onSuccessJSON(result) {
            var str = "<table border='2'>";
            if (Array.isArray(result)) {
                for (var i = 0; i < result.length; i++) {
                    var dt = new Date(result[i].JoinedDate.toString());
                    str += "<tr>";
                    str += "<td>" + result[i].ProfileID + "</td>";
                    str += "<td>" + result[i].FirstName + "</td>";
                    str += "<td>" + result[i].LastName + "</td>";
                    str += "<td>" + result[i].Age + "</td>";
                    str += "<td>" + dt.getFullYear() + "/" + dt.getDate() + "/" + dt.getDay() + "</td>";
                    str += "<td>" + result[i].EmailID + "</td>";
                    str += "<td>" + result[i].ZIPCode + "</td>";
                    str += "<td>" + result[i].Country + "</td>";


                }
                str += "</tr>";
                str += "</table>";

                document.getElementById('resTableJSON').innerHTML = str;
            }

        }

        function OnFailedJSON(result) {
            alert(result+'failed');
        }

        function calling_WCF_in_JavascriptXML() {
            try {
                //Create a WCF Service in javascript
                var proxy = new SP.IProfileService();
                //note NameSpace is Empty.
                //Calling WCF methods in javascript.
               
               
                proxy.GetAllProfilesAsXML(onSuccessXML, OnFailedXML, null);
            }
            catch (error) {
                alert(error.message);
            }
        }

        function onSuccessXML(result) {
          
            var dom = new DOMParser();
            var xmldoc=dom.parseFromString(result,'text/xml');
            var childNodes = xmldoc.childNodes[0];
            var ProfileNodes = childNodes.childNodes;
            for (i = 0; i < ProfileNodes.length; i++)
               
                if (ProfileNodes[i].tagName == "Profile") {
                    var j = 0;
                    var resTable = document.getElementById("resTable");
                    resTable.insertRow(i);

                    resTable.rows[i].insertCell(j);
                    resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("Age")[i].childNodes[0].nodeValue;
                       resTable.rows[i].insertCell(j);
                       resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("Country")[i].childNodes[0].nodeValue;
                       resTable.rows[i].insertCell(j);
                       resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("EmailID")[i].childNodes[0].nodeValue;
                       resTable.rows[i].insertCell(j);
                      
                       resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("FirstName")[i].childNodes[0].nodeValue;
                       resTable.rows[i].insertCell(j);
                       resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("LastName")[i].childNodes[0].nodeValue;
                       resTable.rows[i].insertCell(j);
                       resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("ProfileID")[i].childNodes[0].nodeValue;
                       resTable.rows[i].insertCell(j);
                       resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("ZIPCode")[i].childNodes[0].nodeValue;
                       resTable.rows[i].insertCell(j);
                       resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("JoinedDate")[i].childNodes[0].nodeValue;
       
                }
           
           
            return;

        }

        function OnFailedXML(result) {
            alert(result+'Failed');
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
            <Services>
                <asp:ServiceReference Path="http://localhost:26678/ProfileService.svc" />
            </Services>
        </asp:ScriptManager>
        <asp:Button CssClass="buttonStyle" ID="Button1" runat="server" Text="Call Cross Domain  WCF Service XML"  title="Call Cross Domain  WCF Service XML returning complex object"
            OnClientClick="javascript:calling_WCF_in_JavascriptXML()" />

        <asp:UpdatePanel ID="UpdatePanel1" runat="server" RenderMode="Block" UpdateMode="Conditional">
            <ContentTemplate>
                 <div style="color:green;font-size:1.6em;border-width:thick;border-color:red;"
                     id="wcf_ajax_response"
                     runat="server">
                         (POX) Plain Old XML Response from WCF Service

         <table  border="1">
        <thead style="font-weight: bold;">
            <tr>
                <td>Age</td>
                <td>Contry</td>
                <td>EmailID</td>
                <td>FirstName</td>
                <td>LastName</td>
                <td>ProfileID</td>
                <td>ZIPCode</td>
                <td>JoinedDate</td>
               
            </tr>
        </thead>
        <tbody id="resTable"></tbody>
    </table>
                  </div>
               
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
            </Triggers>
        </asp:UpdatePanel>

     <asp:Button CssClass="buttonStyle" ID="Button2" runat="server" Text="Call Cross Domain  WCF Service  JSON"  title="Call Cross Domain  WCF Service JSON returning complex object"
            OnClientClick="javascript:calling_WCF_in_JavascriptJSON()" />

         <asp:UpdatePanel ID="UpdatePanel2" runat="server" RenderMode="Block" UpdateMode="Conditional">
            <ContentTemplate>
                JSON Response from WCF Service
                         <table border="1px">
        <thead style="color:green;font-size:1.6em;border-width:thick;border-color:red;">
            <tr>
                <td>ProfileID</td>
                <td>FirstName</td>
                <td>LastName</td>
                <td>Age</td>
                <td>JoinedDate</td>
                <td>EmailID</td>
                <td>ZIPCode</td>
                <td>Contry</td>
            </tr>
        </thead>
        <tbody id="x"></tbody>
    </table>

                 <div style="color:green;font-size:1.6em;border-width:thick;border-color:red;"
                     id="resTableJSON"
                     runat="server">
                         No JSON Response

                  </div>
               
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
            </Triggers>
        </asp:UpdatePanel>
    </form>
</body>
</html>