Ok, so you have developed a nice WCF Service with proper implementation of custom fault exception handling, now you want to call this service in a web application or other client application and catch the fault exception in your client code. For simplicity I am using a web page, the following code is self explanatory.

  1: Protected Sub btnGetCustomers_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGetCustomers.Click
  2: 
  3:         Using wcfSrv As CustomerWcfService.CustomerServiceClient = New CustomerWcfService.CustomerServiceClient("WSHttpBinding_ICustomerService")
  4:             Try
  5:                 Dim custArr() As CustomerWcfService.Customer
  6:                 custArr = wcfSrv.GetCustomers()
  7:                 For Each cust As CustomerWcfService.Customer In custArr
  8:                     Response.Write("ID: " & cust.ID.ToString & " Name: " & cust.Name & "<br/>")
  9:                 Next
 10:                 lblStatus.Text = "No of Customer Records found: " & custArr.Length.ToString
 11: 
 12:                 'Custom Fault Exception Response from Service
 13:             Catch ex As ServiceModel.FaultException(Of CustomerWcfService.ErrorResponse)
 14:                 lblStatus.Text = "Code:" & ex.Detail.Code.ToString() & " Messgage:" & ex.Detail.Message & " Details:" & ex.Detail.Details
 15:                 wcfSrv.Abort()
 16: 
 17:                 'General Fault Exception
 18:             Catch ex As ServiceModel.FaultException
 19:                 lblStatus.Text = ex.ToString()
 20:                 wcfSrv.Abort() 
 21: 
 22:                 'General Exception
 23:             Catch exp As System.Exception
 24:                 lblStatus.Text = "Error:" & exp.ToString()
 25:                 wcfSrv.Abort()
 26: 
 27:             Finally
 28:                 wcfSrv.Close()
 29:             End Try
 30: 
 31:         End Using
 32: 
 33:     End Sub
 34: 

Signature

If you are using a WCF (Web) Service in client application and dealing with large data, at some point you may come across an error message:

{"The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element."}

 

Solutions:

Open your web.config or App.Config file at client and change the values in your bindings. Change the value of following configurations from 65536 (default) to 2147483647. That means it will allow up to 2GB.

<wsHttpBinding>
    <binding name="WSHttpBinding_IMyService" closeTimeout="00:01:00"
     openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
     bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
     maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text"
     textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
     <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
      maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
     <reliableSession ordered="true" inactivityTimeout="00:10:00"
      enabled="false" />
     <security mode="Message">
      <transport clientCredentialType="Windows" proxyCredentialType="None"
       realm="" />
      <message clientCredentialType="Windows" negotiateServiceCredential="true"
       algorithmSuite="Default" establishSecurityContext="true" />
     </security>
    </binding>
   </wsHttpBinding>
Signature

In WCF, there are five major contracts – Service Contract, Operation Contract, Data Contract, Fault Contract and Message Contract. In my previous examples I used first three. In this example, I will implement the Fault Contract. I am not very fond of using Message Contract as some guidelines suggest using the least or based on requirement, however you cannot get away from the first four contracts. In the event of Fault (exception), WCF throws a fault containing detail error message which you may not like to be passed back to the caller. In other words, this example focuses on how to hide full error details and provide a custom error code, message and details. You can use multiple Fault Contracts on one Operation Contract in similar way. This example provides a simple and generic way to handle Faults.

In order to show this example, I will add or modify following classes.

1.       ErrorResponse Class - New
   1:  <DataContract(Name:="ErrorResponse", Namespace:="http://http://schemas.vishwamohan.net/2008/03/ErrorResponse")> _
   2:  Public Class ErrorResponse
   3:  #Region "Public Fields"
   4:      <DataMember(Name:="Code", Order:=0)> _
   5:      Public Code As String = "Error"
   6:      <DataMember(Name:="Message", Order:=1)> _
   7:      Public Message As String = "Sorry! An exception occured."
   8:      <DataMember(Name:="Details", Order:=2)> _
   9:      Public Details As String = "Please contact support."
  10:   
  11:  #End Region
  12:   
  13:  #Region "Constructors"
  14:      Public Sub New()
  15:   
  16:      End Sub
  17:   
  18:      Public Sub New(ByVal code As String, ByVal message As String, ByVal details As String)
  19:          Me.Code = code
  20:          Me.Message = message
  21:          Me.Details = details
  22:      End Sub
  23:  #End Region
  24:  End Class
 
2.       ICustomerService.vb Class – Modifying Existing Operation Contract, by adding Fault Contract
   1:  <OperationContract(Name:="GetCustomer")> _
   2:          <FaultContract(GetType(ErrorResponse))> _
   3:          Function GetCustomer(ByVal ID As Integer) As Customer
 
3.       CustomerService.svc – Modifying Existing Service Contract, by Handling the Exception and Throwing Fault
 
   1:  Public Function GetCustomer(ByVal ID As Integer) As Customer Implements ICustomerService.GetCustomer
   2:              Try
   3:                  Return ServiceHelper.GetCustomerData(ID)
   4:              Catch ex As Exception
   5:                  Throw New FaultException(Of ErrorResponse)(New ErrorResponse, ex.Message)
   6:                  'or
   7:                  'Throw New FaultException(Of ErrorResponse)(New ErrorResponse("ErrorCode", "ErrorMessage", "ErrorDetails"), ex.Message)
   8:              End Try
   9:  End Function
 
Note: The value of for reason which is provided by ex.Message is optional, but if you will not provide, WCF Service will generate a message that creator of this fault did not specify the reason. So it will be advisable to pass a proper message in reason.
Signature

This post will focus on implementing POX (Plain Old XML) and REST (Representational State Transfer) in WCF. In other words this is an implementation of the old HTTP XML Post. I spent not several hours but several days to figure out the solution. As all of you know making HTTP GET is easy in WCF but HTTP Post (without using SOAP) is a different story. I researched all around the web but nowhere found a simple example for this option, yes not even on Microsoft site. Many people just post their opinion in few lines and then you keep guessing, and if you are new to this then keep doing trial and error method for hours and days provided you keep your patience on. Once you will find the solution, it will look so easy.

 
So, In order to make this happen, we will have to make changes at following places

1.       Web.Config – Both at Service and Client side for new binding
2.       ICustomerService.vb
3.       CustomerService.svc.vb
4.       CustomerWcfServiceTest.aspx – For adding new HTML form fields and JavaScript functions
 
So let’s see step by step what we need to make change in each file.
Web.Config (WCF Service) – Add the following in respective sections
Web.Config (WCF Client or WebSite) : Once you made the above change in your service Config file, you can update your service reference in client application or web site.When you click on update Web/Service references, It will automatically add the following sections in respective area, if not make sure that you add it in client web site Web.config file.
<customBinding>
    <binding name="WebHttpBinding_ICustomerService">
     <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
      messageVersion="Soap12" writeEncoding="utf-8">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
       maxBytesPerRead="4096" maxNameTableCharCount="16384" />
     </textMessageEncoding>
    </binding>
   </customBinding>
 
<endpoint address="http://vishwa/ExampleService/CustomerService.svc/pox"
    binding="customBinding" bindingConfiguration="WebHttpBinding_ICustomerService"
    contract="CustomerWcfService.ICustomerService" name="WebHttpBinding_ICustomerService" />
 
ICustomerService.vb:  First we need to modify the Service Contract, you can use the existing methods for implementing HTTP GET, but for HTTP POST, you will need separate interface. Replace the existing code of this file with following code
Imports System.ServiceModel.Web
 
Namespace Example.WcfService
    <ServiceContract(Name:="ICustomerService", NameSpace:="http://wcfservices.vishwamohan.net")> _
    Public Interface ICustomerService
 
        'Implementing HTTP GET using WebGet()
 
        <OperationContract(Name:="GetCustomer"), WebGet()> _
        Function GetCustomer(ByVal ID As Integer) As Customer
 
        <OperationContract(Name:="GetCustomers"), WebGet()> _
       Function GetCustomers() As List(Of Customer)
 
        <OperationContract(Name:="AddCustomer")> _
        Function AddCustomer(ByVal CustomerRecord As Customer) As Integer
 
        <OperationContract(Name:="UpdateCustomer")> _
        Function UpdateCustomer(ByVal CustomerRecord As Customer) As Boolean
 
        <OperationContract(Name:="DeleteCustomer")> _
        Function DeleteCustomer(ByVal ID As Integer) As Boolean
 
        'Implementing POX/REST - HTTP POST
 
        <OperationContract(Name:="GetCustomerByPOX"), _
            WebInvoke(Method:="POST", BodyStyle:=WebMessageBodyStyle.Bare, _
            RequestFormat:=WebMessageFormat.Xml, ResponseFormat:=WebMessageFormat.Xml)> _
        Function GetCustomerByPOX(ByVal XMLString As System.Xml.XmlElement) As Customer
 
        <OperationContract(Name:="GetCustomersByPOX"), WebInvoke(Method:="POST", _
                            BodyStyle:=WebMessageBodyStyle.Bare, _
                            RequestFormat:=WebMessageFormat.Xml, _
                            ResponseFormat:=WebMessageFormat.Xml)> _
        Function GetCustomersByPOX() As List(Of Customer)
 
        <OperationContract(Name:="AddCustomerByPOX"), WebInvoke(Method:="POST", _
                            BodyStyle:=WebMessageBodyStyle.Bare, _
                            RequestFormat:=WebMessageFormat.Xml, _
                            ResponseFormat:=WebMessageFormat.Xml)> _
        Function AddCustomerByPOX(ByVal RequestXML As System.Xml.XmlElement) As Integer
 
        <OperationContract(Name:="UpdateCustomerByPOX"), WebInvoke(Method:="POST", _
                            BodyStyle:=WebMessageBodyStyle.Bare, _
                            RequestFormat:=WebMessageFormat.Xml, _
                            ResponseFormat:=WebMessageFormat.Xml)> _
        Function UpdateCustomerByPOX(ByVal RequestXML As System.Xml.XmlElement) As Boolean
 
        <OperationContract(Name:="DeleteCustomerByPOX"), _
           WebInvoke(Method:="POST", BodyStyle:=WebMessageBodyStyle.Bare, _
           RequestFormat:=WebMessageFormat.Xml, ResponseFormat:=WebMessageFormat.Xml)> _
        Function DeleteCustomerByPOX(ByVal XMLString As System.Xml.XmlElement) As Boolean
 
    End Interface
End Namespace
CustomerService.svc.vb: Once the service contracts are implemented, now we need these methods to be added to actual service page to accept the request and send the response. Add the following code.
Public Function GetCustomerByPOX(ByVal RequestXML As System.Xml.XmlElement) As Customer Implements ICustomerService.GetCustomerByPOX
            Dim custID As Integer = 0
 
            If Not RequestXML.Item("ID") Is Nothing AndAlso IsNumeric(RequestXML.Item("ID").InnerText) Then
                custID = CInt(RequestXML.Item("ID").InnerText)
            End If
 
            Return ServiceHelper.GetCustomerData(custID)
 
        End Function
 
        Public Function AddCustomerByPOX(ByVal RequestXML As System.Xml.XmlElement) As Integer Implements ICustomerService.AddCustomerByPOX
            Dim returnID As Integer = 0
            If Not RequestXML.Item("CustomerRecord") Is Nothing Then
                Dim customerRecord As New Customer
                If Not RequestXML.Item("CustomerRecord").Item("ID") Is Nothing AndAlso _
                    IsNumeric(RequestXML.Item("CustomerRecord").Item("ID").InnerText) Then
                    customerRecord.CustID = CInt(RequestXML.Item("CustomerRecord").Item("ID").InnerText)
                End If
                If Not RequestXML.Item("CustomerRecord").Item("Name") Is Nothing Then _
                    customerRecord.CustName = RequestXML.Item("CustomerRecord").Item("Name").InnerText
                If Not RequestXML.Item("CustomerRecord").Item("DOB") Is Nothing AndAlso _
                    IsDate(RequestXML.Item("CustomerRecord").Item("DOB").InnerText) Then
                    customerRecord.CustDOB = CDate(RequestXML.Item("CustomerRecord").Item("DOB").InnerText)
                End If
                If Not RequestXML.Item("CustomerRecord").Item("Address") Is Nothing Then _
                    customerRecord.CustAddress = RequestXML.Item("CustomerRecord").Item("Address").InnerText
 
                returnID = ServiceHelper.AddCustomerData(customerRecord)
            End If
            Return returnID
 
        End Function
 
        Public Function GetCustomersByPOX() As System.Collections.Generic.List(Of Customer) Implements ICustomerService.GetCustomersByPOX
            Return ServiceHelper.GetCustomersData()
        End Function
 
        Public Function UpdateCustomerByPOX(ByVal RequestXML As System.Xml.XmlElement) As Boolean Implements ICustomerService.UpdateCustomerByPOX
            Dim returnValue As Boolean = False
            If Not RequestXML.Item("CustomerRecord") Is Nothing Then
                Dim customerRecord As New Customer
                If Not RequestXML.Item("CustomerRecord").Item("ID") Is Nothing AndAlso _
                    IsNumeric(RequestXML.Item("CustomerRecord").Item("ID").InnerText) Then
                    customerRecord.CustID = CInt(RequestXML.Item("CustomerRecord").Item("ID").InnerText)
                End If
                If Not RequestXML.Item("CustomerRecord").Item("Name") Is Nothing Then _
                        customerRecord.CustName = RequestXML.Item("CustomerRecord").Item("Name").InnerText
                If Not RequestXML.Item("CustomerRecord").Item("DOB") Is Nothing AndAlso _
                    IsDate(RequestXML.Item("CustomerRecord").Item("DOB").InnerText) Then
                    customerRecord.CustDOB = CDate(RequestXML.Item("CustomerRecord").Item("DOB").InnerText)
                End If
                If Not RequestXML.Item("CustomerRecord").Item("Address") Is Nothing Then _
                    customerRecord.CustAddress = RequestXML.Item("CustomerRecord").Item("Address").InnerText
 
                returnValue = ServiceHelper.UpdateCustomerData(customerRecord)
 
            End If
            Return returnValue
        End Function
 
        Public Function DeleteCustomerByPOX(ByVal RequestXML As System.Xml.XmlElement) As Boolean Implements ICustomerService.DeleteCustomerByPOX
            Dim custID As Integer = 0
            Dim returnValue As Boolean = False
            If Not RequestXML.Item("ID") Is Nothing AndAlso IsNumeric(RequestXML.Item("ID").InnerText) Then
                custID = CInt(RequestXML.Item("ID").InnerText)
                returnValue = ServiceHelper.DeleteCustomerData(custID)
            End If
            Return returnValue
        End Function
Now you are done from service side. Compile the project and deploy to the same place where you did before.
 CustomerWcfServiceTest.aspx: Now I am back to same old page in which I tested earlier posts. This time I will add following HTML code and JavaScript inside body tag. This will allow you use simple XML for transaction without SOAP.
  <form id="frmCustomerGet1" method="get" action="http://vishwa/exampleservice/customerservice.svc/pox/GetCustomer">                   
                    <table>
                    <tr><td colspan="2"><b>Through Client Side HTML Form HTTP GET</b></td></tr>
                    <tr><td>Customer ID :</td><td><input name="ID" type="text" value="969225896" /> </td></tr>
                     <tr>
                        <td colspan="2"><input type="submit" name="btnGetCustomer" value="Get a Customer"/></td>
                    </tr>   
                    </table>                
                </form>
                
                <form id="frmCustomerGet2" method="get" action="http://vishwa/exampleservice/customerservice.svc/pox/GetCustomers">
                    <div>    
                        <input type="submit" name="btnGetAllCustomers" value="Get All Customers"/>
                    </div>   
                </form>                
                
                 <br />
                <form id="frmCustomerPost1" method="post" action="http://vishwa/exampleservice/customerservice.svc/pox">
                   <table>
                    <tr><td colspan="2"><b>Through Client Side Plain Old XML (POX) HTTP POST</b></td></tr>
                     <tr><td>Customer ID :</td><td><input name="ID" type="text" value="969225896" /> </td></tr>
                    <tr><td>Customer Name :</td><td><input name="Name" type="text" value="Chris Clark" /> </td></tr>
                    <tr><td>Customer DOB (yyyy-mm-dd):</td><td><input name="DOB" type="text" value="1980-08-08"/> </td></tr>
                    <tr><td>Customer Address :</td><td><input name="Address" type="text" value="unknown"/> </td></tr>
                     <tr>
                        <td><input type="button" name="btnGetCustomer" value="Get Customer" onclick="GetCustomerByPOX()" /></td>
                        <td><input type="button" name="btnAddCustomer" value="Add Customer" onclick="AddCustomerByPOX()" /></td>
                    </tr>
                     <tr>
                        <td><input type="button" name="btnUpdateCustomer" value="Update Customer" onclick="UpdateCustomerByPOX()" /></td>
                        <td><input type="button" name="btnDeleteCustomer" value="Delete Customer" onclick="DeleteCustomerByPOX()"/></td>
                    </tr>     
                    <tr>
                        <td colspan="2"><input type="button" name="btnGetAllCustomers" value="Get All Customers" onclick="GetCustomersByPOX()"/></td>
                    </tr>    
                </table>    
                </form>
Add Following JavaScript in the page
<script type="text/javascript" language="javascript">
            
function GetCustomerByPOX() 
                {
                  var dataText = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; 
                      dataText += "<GetCustomer><ID>" + frmCustomerPost1.ID.value + "</ID>"; 
                      dataText += "</GetCustomer>";
                               
                      alert(dataText);
                      
                  urlToPost = "http://vishwa/exampleservice/customerservice.svc/pox/GetCustomerByPOX"
                  var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");                  
                      xmlHttp.open("POST", urlToPost,false);               
                      xmlHttp.setRequestHeader("Content-Type", "text/xml");
                      xmlHttp.send(dataText);
                      alert(xmlHttp.responseText);
                }
            
            
             function AddCustomerByPOX() 
                {
                  var dataText = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; 
                      dataText += "<AddCustomer><CustomerRecord>"; 
                      dataText += "<ID>" + frmCustomerPost1.ID.value + "</ID>"; 
                      dataText += "<Name>" + frmCustomerPost1.Name.value + "</Name>"; 
                      dataText += "<DOB>" + frmCustomerPost1.DOB.value + "</DOB>";                       
                      dataText += "<Address>" + frmCustomerPost1.Address.value + "</Address>";              
                      dataText += "</CustomerRecord></AddCustomer>"; 
             
                      alert(dataText);
                  urlToPost = "http://vishwa/exampleservice/customerservice.svc/pox/AddCustomerByPOX"
                  var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");                  
                      xmlHttp.open("POST", urlToPost,false);               
                      xmlHttp.setRequestHeader("Content-Type", "text/xml");
                      xmlHttp.send(dataText);
                      alert(xmlHttp.responseText);
                }
            
             function UpdateCustomerByPOX() 
                {
                  var dataText = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; 
                      dataText += "<UpdateCustomer><CustomerRecord>"; 
                      dataText += "<ID>" + frmCustomerPost1.ID.value + "</ID>"; 
                      dataText += "<Name>" + frmCustomerPost1.Name.value + "</Name>"; 
                      dataText += "<DOB>" + frmCustomerPost1.DOB.value + "</DOB>"; 
                      dataText += "<Address>" + frmCustomerPost1.Address.value + "</Address>";
                      dataText += "</CustomerRecord></UpdateCustomer>"; 
             
                      alert(dataText);
                  urlToPost = "http://vishwa/exampleservice/customerservice.svc/pox/UpdateCustomerByPOX"
                  var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");                  
                      xmlHttp.open("POST", urlToPost,false);               
                      xmlHttp.setRequestHeader("Content-Type", "text/xml");
                      xmlHttp.send(dataText);
                      alert(xmlHttp.responseText);
                }
            
            function DeleteCustomerByPOX() 
                {
                  var dataText = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; 
                      dataText += "<DeleteCustomer><ID>" + frmCustomerPost1.ID.value + "</ID>"; 
                      dataText += "</DeleteCustomer>";
                               
                      alert(dataText);
                      
                  urlToPost = "http://vishwa/exampleservice/customerservice.svc/pox/DeleteCustomerByPOX"
                  var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");                  
                      xmlHttp.open("POST", urlToPost,false);               
                      xmlHttp.setRequestHeader("Content-Type", "text/xml");
                      xmlHttp.send(dataText);
                      alert(xmlHttp.responseText);
                }
                
                
             function GetCustomersByPOX() 
                {
                                        
                  urlToPost = "http://vishwa/exampleservice/customerservice.svc/pox/GetCustomersByPOX"
                  var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");                  
                      xmlHttp.open("POST", urlToPost,false);               
                      xmlHttp.setRequestHeader("Content-Type", "text/xml");
                      xmlHttp.send(null);
                      alert(xmlHttp.responseText);
                }
                
    </script>
So, now you are ready to run this page and click the button you like by filling appropriate data. You should be able to see the transaction request and response in form of plain XML as alert.
 

I believe, if you are integrating with an outside customer you will most likely choose WSHttpBinding, BasicHttpBinding or WebHttpBinding in the order of high to lower interoperability  and security preference. Either one you choose performance wise it will be always lower than NetTcpBinding , NetMsmqBinding or NetNamedPipeBinding. However, Net* bindings will only work .NET consumers. If you wish to have best performance then you will have to choose NetNamedPipeBinding but this will require you to have the Service and Consumer on the same machine, if both are on the same network, use NetTcpBinding.
Signature

In this post, I will implement the basicHttpBinding, through which you can even use a HTML page and JavaScript to consume the WCF Service via SOAP based XML. I spent several hours to exactly figure out the SOAP format. In ASMX web service, if you will click on a method, it shows you the sample SOAP format for request and response. Unfortunately, that is not available in WCF Service page right now, so you have to figure out or use a tool to see what is being passed or expected. The Serialization used in ASMX Web Service is based on XML Serialization; however WCF uses a different mechanism for the same. You can use the old SOAP format (which I used in ASMX Web Service) to post the transaction but you will always get SOAP 1.2 format response. In order to keep consistency, I kept the request format similar to response.

So, In order to make this happen, we will have to make changes at following places
1.       Web.Config – Both at Service and Client side for new binding
2.       CustomerWcfServiceTest.aspx – For adding new HTML form fields and JavaScript functions
 
So let’s see step by step what we need to make change in each file.
Web.Config (WCF Service) – Add the following in respective sections
        <endpoint address="basic" binding="basicHttpBinding" bindingConfiguration="basicBinding" contract="Vishwa.Example.WcfService.ICustomerService" bindingNamespace="http://wcfservices.vishwamohan.net/basic"/>
     <bindings>   
      <basicHttpBinding>
        <binding name="basicBinding">         
          <security mode="None">           
          </security>         
        </binding>       
      </basicHttpBinding>
     
    </bindings>
   
Web.Config (WCF Client or WebSite) : Once you made the above change in your service Config file, you can update your service reference in client application or web site.When you click on update Web/Service references, It will automatically add the following sections in respective area, if not make sure that you add it in client web site Web.config file.
 
                   <basicHttpBinding>
                        <binding name="BasicHttpBinding_ICustomerService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
                              <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
                              <securitymode="None">
                                    <transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
                                    <message clientCredentialType="UserName" algorithmSuite="Default"/>
                              </security>
                        </binding>
                  </basicHttpBinding>
 
<endpoint address="http://vishwa/ExampleService/CustomerService.svc/basic" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ICustomerService" contract="CustomerWcfService.ICustomerService" name="BasicHttpBinding_ICustomerService"/>
 
CustomerWcfServiceTest.aspx: Now I am back to same old page in which I tested earlier post. This time I will add following HTML code and JavaScript inside body tag.
 
 <form id="frmCustomerS" method="post" action="CustomerWcfServiceTest.aspx">
            <div>   
                <table>
                <tr><td colspan="2"><b>Through Client Side SOAP/XML HTTP POST</b></td></tr>
                <tr><td>Customer ID :</td><td><input name="ID" id="ID" type="text" value="12345" /> </td></tr>
                <tr><td>Customer Name :</td><td><input name="Name" id="Name" type="text" value="Chris Clark" /> </td></tr>
                <tr><td>Customer DOB (yyyy-mm-dd):</td><td><input name="DOB" id="DOB" type="text" value="1988-08-08"/> </td></tr>
                <tr><td>Customer Address:</td><td><input name="Address" id="Address" type="text" value="unknown"/> </td></tr>
                 <tr>
                    <td><input type="button" name="btnGetCustomer" value="Get Customer" onclick="GetCustomerSOAP()" /></td>
                    <td><input type="button" name="btnAddCustomer" value="Add Customer" onclick="AddCustomerSOAP()" /></td>
                </tr>
                 <tr>
                    <td><input type="button" name="btnUpdateCustomer" value="Update Customer" onclick="UpdateCustomerSOAP()" /></td>
                    <td><input type="button" name="btnDeleteCustomer" value="Delete Customer" onclick="DeleteCustomerSOAP()"/></td>
                </tr>    
                <tr>
                    <td colspan="2"><input type="button" name="btnGetAllCustomers" value="Get All Customers" onclick="GetCustomersSOAP()"/></td>
                </tr>   
                </table>               
            </div>  
            </form>
<script type="text/javascript" language="javascript">
   
        var urlToPost = "http://vishwa/ExampleService/CustomerService.svc/basic";
        var fixedSoapAction = "http://wcfservices.vishwamohan.net/ICustomerService/";
        var serviceNameSpace = "\"http://wcfservices.vishwamohan.net\"";
       
        var d = new Date();
       
        function getFullDate()
            {
            if (d.getDate()<10)
                return "0" + d.getDate();
            else
                return d.getDate();
             }
            
         function getFullMonth()
            {
            if (d.getMonth()<10)
                return "0" + parseInt(d.getMonth()+1);
            else
                return parseInt(d.getMonth()+1);
             }  
       
        var curdate = d.getFullYear() + "-" + getFullMonth()+ "-" + getFullDate();
            function GetCustomerSOAP()
                {
                  var dataText = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body>";
                      dataText += " <GetCustomer xmlns=" + serviceNameSpace + ">";
                      dataText += " <ID>" + frmCustomerS.ID.value + "</ID>";
                      dataText += " </GetCustomer>";
                      dataText += " </s:Body></s:Envelope>";
                      alert(dataText);
                     
                  var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");                 
                      xmlHttp.open("POST", urlToPost,false);              
                      xmlHttp.setRequestHeader("Content-Type", "text/xml");
                      xmlHttp.setRequestHeader("SOAPAction", fixedSoapAction +"GetCustomer");
                      xmlHttp.send(dataText);
                      alert(xmlHttp.responseText);
                }
               
                function GetCustomersSOAP()
                {
                  var dataText = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body>";
                      dataText += " <GetCustomers xmlns=" + serviceNameSpace + ">";
                      dataText += " </GetCustomers>";
                      dataText += " </s:Body></s:Envelope>";
                      alert(dataText);
                 
                  var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");                 
                      xmlHttp.open("POST", urlToPost,false);              
                      xmlHttp.setRequestHeader("Content-Type", "text/xml");
                      xmlHttp.setRequestHeader("SOAPAction", fixedSoapAction +"GetCustomers");
                      xmlHttp.send(dataText);
                      alert(xmlHttp.responseText);
                }
   
                  
            function AddCustomerSOAP()
                {
                   var dataText = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body>";
                      dataText += " <AddCustomer xmlns=" + serviceNameSpace + ">";
                      dataText += " <CustomerRecord xmlns:a=\"http://schemas.vishwamohan.net/2008/01/Customer\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
                      dataText += " <a:ID>0</a:ID><a:Name>" + frmCustomerS.Name.value + "</a:Name><a:DOB>" + frmCustomerS.DOB.value +"</a:DOB>" ;
                      dataText += " <a:Address>" + frmCustomerS.Address.value + "</a:Address>" ;
                      dataText += " <a:DateCreated>" + curdate + "</a:DateCreated><a:DateModified>" + curdate + "</a:DateModified>" ;
                      dataText += " </CustomerRecord></AddCustomer>"
                      dataText += " </s:Body></s:Envelope>";
                      alert(dataText);
                 
                  var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");                 
                      xmlHttp.open("POST", urlToPost,false);              
                      xmlHttp.setRequestHeader("Content-Type", "text/xml");
                      xmlHttp.setRequestHeader("SOAPAction", fixedSoapAction +"AddCustomer");
                      xmlHttp.send(dataText);
                      alert(xmlHttp.responseText);
                }
           
            function UpdateCustomerSOAP()
                {
                   var dataText = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body>";
                      dataText += " <UpdateCustomer xmlns=" + serviceNameSpace + ">";
                      dataText += " <CustomerRecord xmlns:a=\"http://schemas.vishwamohan.net/2008/01/Customer\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
                      dataText += " <a:ID>" + frmCustomerS.ID.value + "</a:ID><a:Name>" + frmCustomerS.Name.value + "</a:Name><a:DOB>" + frmCustomerS.DOB.value +"</a:DOB>" ;
                      dataText += " <a:Address>" + frmCustomerS.Address.value + "</a:Address>" ;
                      dataText += " <a:DateCreated>" + curdate + "</a:DateCreated><a:DateModified>" + curdate + "</a:DateModified>" ;
                      dataText += " </CustomerRecord></UpdateCustomer>"
                      dataText += " </s:Body></s:Envelope>";
                      alert(dataText);
                                   
                  var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");                 
                      xmlHttp.open("POST", urlToPost,false);              
                      xmlHttp.setRequestHeader("Content-Type", "text/xml");
                      xmlHttp.setRequestHeader("SOAPAction", fixedSoapAction +"UpdateCustomer");
                      xmlHttp.send(dataText);
                      alert(xmlHttp.responseText);
                }
           
          
             function DeleteCustomerSOAP()
                {
                  var dataText = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body>";
                      dataText += " <DeleteCustomer xmlns=" + serviceNameSpace + ">";
                      dataText += " <ID>" + frmCustomerS.ID.value + "</ID>";
                      dataText += " </DeleteCustomer>";
                      dataText += " </s:Body></s:Envelope>";
                      alert(dataText);
                 
                  var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");                 
                      xmlHttp.open("POST", urlToPost,false);              
                      xmlHttp.setRequestHeader("Content-Type", "text/xml");
                      xmlHttp.setRequestHeader("SOAPAction", fixedSoapAction +"DeleteCustomer");
                      xmlHttp.send(dataText);
                      alert(xmlHttp.responseText);
                }
     
               
    </script>
 
Note: If you are planning to use this binding at server side. Just change the binding name in code behind file from “WSHttpBinding_ICustomerService” to “BasicHttpBinding_ICustomerService”
So, now you are ready to run this page and click the button you like by filling appropriate data. You should be able to see the transaction request and response in form of SOAP/XML as alert.
Signature

I will consume the Customer WCF Service which I developed in Part 1 on WS* Http Binding, you can implement the best security, transactions and many more things using this way. However, I will consume in a very simplistic way in this post. I assume that you have already deployed the WCF Service under IIS and have a working URL ready to be referenced and you are planning to use the customer WCF service in ASPX web Page.

 

Create a Test Web Site Project using Visual Studio 2008/5 and focus on following 3 files
1.       Web.Config
2.       CustomerWcfServiceTest.aspx – The page you added for testing the WCF Service
3.       CustomerWcfServiceTest.aspmx.vb – Code behind file for WCF Service Test Page
 
 
Steps: Right Click on the project and click add the Customer WCF Service using Add Service Reference. Let’s say you give it a name called CustomerWcfService.
 
Web.Config
After adding the above service, verify the web.config file that binding and endpoint information is added to it. This information gets automatically added or removed when you add or remove a service reference. The address will vary as per your machine. You should be able to see like
 
<system.serviceModel>
   <bindings>
    <wsHttpBinding>
    <bindingname="WSHttpBinding_ICustomerService"closeTimeout="00:01:00"
     openTimeout="00:01:00"receiveTimeout="00:10:00"sendTimeout="00:01:00"
     bypassProxyOnLocal="false"transactionFlow="false"hostNameComparisonMode="StrongWildcard"
     maxBufferPoolSize="524288"maxReceivedMessageSize="65536"messageEncoding="Text"
     textEncoding="utf-8"useDefaultWebProxy="true"allowCookies="false">
     <readerQuotasmaxDepth="32"maxStringContentLength="8192"maxArrayLength="16384"
      maxBytesPerRead="4096"maxNameTableCharCount="16384" />
     <reliableSessionordered="true"inactivityTimeout="00:10:00"
      enabled="false" />
     <securitymode="Message">
      <transportclientCredentialType="Windows"proxyCredentialType="None"
       realm="" />
      <messageclientCredentialType="Windows"negotiateServiceCredential="true"
       algorithmSuite="Default"establishSecurityContext="true" />
     </security>
    </binding>
   </wsHttpBinding>
</bindings>
<client>
   <endpointaddress="http://vishwa/ExampleService/CustomerService.svc"
    binding="wsHttpBinding"bindingConfiguration="WSHttpBinding_ICustomerService"
    contract="CustomerWcfService.ICustomerService"name="WSHttpBinding_ICustomerService">
    <identity>
     <dnsvalue="localhost" />
    </identity>
   </endpoint>  
</client>
 
</system.serviceModel>
 
Remember, you will be using binding Name WSHttpBinding_ICustomerService for consuming this service in code behind file.
 CustomerWCFServiceTest.aspx: Add the following code inside the body of this page
 <form id="form1" runat="server">               
                <table>
                <tr>
                    <td colspan="2"><b>Through Server Side Service Reference</b></td>
                </tr>
                <tr>
                    <td >Customer ID :</td>
                    <td><asp:TextBox ID="txtCustID" runat="server" Text="12345"></asp:TextBox></td>
                </tr>    
                <tr>
                    <td>Customer Name :</td>
                <td>
                    <asp:TextBox ID="txtCustName" runat="server" Text="Joe Smith"></asp:TextBox>
                </td>
                </tr>
                <tr>
                    <td>Customer DOB (yyyy-mm-dd):</td>
                    <td><asp:TextBox ID="txtCustDOB" runat="server" Text="1988-08-08"></asp:TextBox></td>
                </tr>
               <tr>
                    <td>Customer Address:</td>
                    <td><asp:TextBox ID="txtCustAddress" runat="server" Text="unknown"></asp:TextBox></td>
                </tr>
                <tr>
                    <td><asp:Button ID="btnGetCustomer" runat="server" Text="Get Customer" /></td>
                    <td><asp:Button ID="btnAddCustomer" runat="server" Text="Add Customer" /></td>
                </tr>
                <tr>
                    <td><asp:Button ID="btnUpdateCustomer" runat="server" Text="Update Customer" /></td>
                    <td><asp:Button ID="btnDeleteCustomer" runat="server" Text="Delete Customer" /></td>
                </tr>
                <tr>
                    <td>
                    <asp:Button id="btnGetCustomers" runat="server" Text="Get All Customers"/></td>
                    <td><asp:Label ID="lblStatus" runat="server" Text="Status"
                            ForeColor="#CC3300" style="font-weight: 700"></asp:Label></td>
                </tr>               
               </table>        
              
           </form>
            <br />
            <form id="frmCustomerS" method="post" action="CustomerWcfServiceTest.aspx">
            <div>   
                <table>
                <tr><td colspan="2"><b>Through Client Side SOAP/XML HTTP POST</b></td></tr>
                <tr><td>Customer ID :</td><td><input name="ID" id="ID" type="text" value="12345" /> </td></tr>
                <tr><td>Customer Name :</td><td><input name="Name" id="Name" type="text" value="Chris Clark" /> </td></tr>
                <tr><td>Customer DOB (yyyy-mm-dd):</td><td><input name="DOB" id="DOB" type="text" value="1988-08-08"/> </td></tr>
                <tr><td>Customer Address:</td><td><input name="Address" id="Address" type="text" value="unknown"/> </td></tr>
                 <tr>
                    <td><input type="button" name="btnGetCustomer" value="Get Customer" onclick="GetCustomerSOAP()" /></td>
                    <td><input type="button" name="btnAddCustomer" value="Add Customer" onclick="AddCustomerSOAP()" /></td>
                </tr>
                 <tr>
                    <td><input type="button" name="btnUpdateCustomer" value="Update Customer" onclick="UpdateCustomerSOAP()" /></td>
                    <td><input type="button" name="btnDeleteCustomer" value="Delete Customer" onclick="DeleteCustomerSOAP()"/></td>
                </tr>    
                <tr>
                    <td colspan="2"><input type="button" name="btnGetAllCustomers" value="Get All Customers" onclick="GetCustomersSOAP()"/></td>
                </tr>   
                </table>               
            </div>  
            </form>
 
CustomerWCFServiceTest.aspx.vb: Add the following code to handle the events
 Partial Class CustomerServiceTest
    Inherits System.Web.UI.Page
 
    Protected Sub btnGetCustomer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGetCustomer.Click
        Dim wcfSrv As New CustomerWcfService.CustomerServiceClient("WSHttpBinding_ICustomerService")
        Dim cust As CustomerWcfService.Customer = wcfSrv.GetCustomer(CInt(Me.txtCustID.Text))
        If cust.ID > 0 Then
            Me.txtCustID.Text = cust.ID
            Me.txtCustName.Text = cust.Name
            Me.txtCustDOB.Text = cust.DOB
            Me.txtCustAddress.Text = cust.Address
            Me.lblStatus.Text = "Customer found."
        Else
            Me.lblStatus.Text = "Customer not found."
            Me.txtCustName.Text = ""
            Me.txtCustDOB.Text = ""
        End If
        wcfSrv.Close()
    End Sub
 
    Protected Sub btnAddCustomer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddCustomer.Click
        Dim wcfSrv As New CustomerWcfService.CustomerServiceClient("WSHttpBinding_ICustomerService")
        Dim cust As New CustomerWcfService.Customer
        cust.Name = Me.txtCustName.Text
        cust.DOB = CDate(Me.txtCustDOB.Text)
        cust.Address = Me.txtCustAddress.Text
        Dim rtn As Integer = wcfSrv.AddCustomer(cust)
        lblStatus.Text = "Cust ID: " & rtn.ToString
        wcfSrv.Close()
    End Sub
 
    Protected Sub btnUpdateCustomer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdateCustomer.Click
        Dim wcfSrv As New CustomerWcfService.CustomerServiceClient("WSHttpBinding_ICustomerService")
        Dim cust As New CustomerWcfService.Customer
        cust.ID = CInt(Me.txtCustID.Text)
        cust.Name = Me.txtCustName.Text
        cust.DOB = CDate(Me.txtCustDOB.Text)
        cust.Address = Me.txtCustAddress.Text
        Dim rtn As Boolean = wcfSrv.UpdateCustomer(cust)
        lblStatus.Text = "Update Status is : " & rtn.ToString
        wcfSrv.Close()
    End Sub
 
    Protected Sub btnDeleteCustomer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDeleteCustomer.Click
        Dim wcfSrv As New CustomerWcfService.CustomerServiceClient("WSHttpBinding_ICustomerService")
        Dim rtn As Boolean = wcfSrv.DeleteCustomer(CInt(Me.txtCustID.Text))
        lblStatus.Text = "Delete Status is : " & rtn.ToString
        wcfSrv.Close()
    End Sub
 
    Protected Sub btnGetCustomers_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGetCustomers.Click
        Dim wcfSrv As New CustomerWcfService.CustomerServiceClient("WSHttpBinding_ICustomerService")
        Dim custArr() As CustomerWcfService.Customer
        custArr = wcfSrv.GetCustomers()
 
        For Each cust As CustomerWcfService.Customer In custArr
            Response.Write("ID: " & cust.ID.ToString & " Name: " & cust.Name & "<br/>")
        Next
        lblStatus.Text = "No of Customer Records found: " & custArr.Length.ToString
        wcfSrv.Close()
    End Sub
 
 
End Class
 
You are done. Run the project and test the page, you should be able to Add, Modify, Delete and Get Customer records.

 

Signature

As you know, the New Windows Communication Services (WCF) will replace the existing ASP.NET ASMX Web Services. So, it will be wise to plan it from today as how to transit in this new service model era. I first tried experimenting with WCF Service almost a year ago with the release of .NET 3.0 but VS 2005 and VISTA did work happily on my machine but now I like VS 2008. I revisited WCF again with the release of .NET 3.5, all the sample available on the web are either old or do not give enough information if you are looking for information as how to use this service in different way over different protocol, which can closely mimic a small real word example . So, I had to spend hours trying to find solutions and put the pieces together. So, I finally thought to create an example to help others who are facing the same situation. I have tried to closely mimic the ASMX Web Service uses, which I posted in my earlier post because most of us will be planning to convert from existing old one. With all the experiments I would give one key Mantra for WCF, dig the Config file specially to understand how to configure BEB (Binding, Endpoint and Behavior). This example deals with CRUD operation on Customer data which I used in earlier post. For the simplicity I am using XML file for the data source and will consume this service with WS* Standard, SOAP based XML POST, Plain Old XML (POX) and HTTP GET and POST. I believe these are the common uses along with TCP, named pipe and MSMQ.

 As you know, the New Windows Communication Services (WCF) will replace the existing ASP.NET ASMX Web Services. So, it will be wise to plan it from today as how to transit in this new service model era. I first tried experimenting with WCF Service almost a year ago with the release of .NET 3.0 but VS 2005 and VISTA did work happily on my machine but now I like VS 2008.  I revisited WCF again with the release of .NET 3.5, all the sample available on the web are either old or do not give enough information if you are looking for information as how to use this service in different way over different protocol, which can closely mimic a small real word example .  So, I had to spend hours trying to find solutions and put the pieces together. So, I finally thought to create an example to help others who are facing the same situation. I have tried to closely mimic the ASMX Web Service uses, which I posted in my earlier post because most of us will be planning to convert from existing old one. With  all the experiments I would give one key Mantra for WCF, dig the Config file specially to understand how to configure BEB (Binding, Endpoint and Behavior). This example deals with CRUD operation on Customer data which I used in earlier post. For the simplicity I am using XML file for the data source and will consume this service with WS* Standard, SOAP based XML POST, Plain Old XML (POX) and HTTP GET and POST. I believe these are the common uses along with TCP, named pipe and MSMQ.

I have created a WCF Service Project Vishwa.Example.WcfService in Visual Studio Version: 2008 with NET 3.5. This project contains following main files.
1.       Web.config – Config file ( you have always pay the highest attention here for making sure the right configuration)
2.       Customer.vb – Customer class – DataContract and Data Members ( you can compare the same exact file with ASMX Web Service)
3.       ServiceHelper.VB – Collection of CRUD Methods –exactly the same file I used in ASMX Web Service
4.       ICustomerService.vb – Interface Class – Service Contracts
5.       CustomerService.svc – WCF Customer Service Page
6.       CustomerService.svc.vb – Code behind file for the WCF Customer Service Page
 
Steps – Create a WCF Service Application and Rename the default files as mentioned above for Service1.scv or just follow the code. Next ..
Web.Config : Make sure the following Service section is correct in web.config
<services>
      <service  name="Vishwa.Example.WcfService.CustomerService"
                                    behaviorConfiguration="Vishwa.Example.WcfService.CustomerServiceBehavior">
            <endpointaddress=""  binding="wsHttpBindingcontract="Vishwa.Example.WcfService.ICustomerService"
                                   bindingNamespace="http://wcfservices.vishwamohan.net/ws">
                  <identity>
                        <dnsvalue="localhost"/>
                  </identity>
            </endpoint>
            <endpointaddress="mex"binding="mexHttpBinding"   contract="IMetadataExchange"
                                       bindingNamespace="http://wcfservices.vishwamohan.net/mex"/>
      </service>
</services>
 
Customer.vb: Add this class with following code. This class is a Data Transfer Object which defines the Data Contract and Data Members.
Namespace Example.WcfService
    <DataContract(Name:="Customer", Namespace:="http://schemas.vishwamohan.net/2008/01/Customer")> _
    Public Class Customer
 
        <DataMember(Name:="ID", Order:=0)> _
        Public CustID As Integer = 0
 
        <DataMember(Name:="Name", Order:=1)> _
        Public CustName As String = String.Empty
 
        <DataMember(Name:="DOB", Order:=2)> _
        Public CustDOB As DateTime = DateTime.MinValue
 
        <DataMember(Name:="Address", Order:=3)> _
        Public CustAddress As String = String.Empty
 
        <DataMember(Name:="DateCreated", Order:=4)> _
        Public DateCreated As DateTime = DateTime.Now
 
        <DataMember(Name:="DateModified", Order:=5)> _
        Public DateModified As DateTime = DateTime.Now
 
        Public Sub New()
 
        End Sub
 
    End Class
End Namespace
 
 
ServiceHelper.vb: Add following code. Please note that I am using a Customer Business Object which was created in my earlier post. This class is exactly same which I used in ASMX Web Service.
Imports Vishwa.Example.Business
 
Namespace Example.WebService
    Public NotInheritable Class ServiceHelper
 
        Private Shared instance As New ServiceHelper
        Private Shared  bizObj As New CustomerBiz
        Private Sub New()
 
        EndSub
 
        Friend Shared Function GetCustomerData(ByVal ID AsInteger) As Customer
            Dim bizCustomer As CustomerBiz = Nothing
            bizCustomer = bizObj.GetCustomer(ID)
            Return GetCustomerDataFromBizCustomer(bizCustomer)
        End Function
 
        Friend Shared Function GetCustomersData() As List(Of Customer)
            Dim customers AsNew List(Of Customer)
            Dim bizCustomers AsNew List(Of CustomerBiz)
            bizCustomers = bizObj.GetCustomers()
 
            ForEach bizCustRec As CustomerBiz In bizCustomers
                customers.Add(GetCustomerDataFromBizCustomer(bizCustRec))
            Next
            Return customers
 
        End Function
 
        Friend Shared Function AddCustomerData(ByVal custRecord As Customer) As Integer
            Return bizObj.AddCustomer(custRecord.CustName, custRecord.CustDOB, custRecord.CustAddress)
        End Function
 
        Friend Shared Function UpdateCustomerData(ByVal custRecord As Customer) As Boolean
            Return bizObj.UpdateCustomer(custRecord.CustID, custRecord.CustName, custRecord.CustDOB, custRecord.CustAddress)
        End Function
 
        Friend Shared Function DeleteCustomerData(ByVal ID AsInteger) As Boolean
            Return bizObj.DeleteCustomer(ID)
        End Function
 
        Private Shared Function GetCustomerDataFromBizCustomer(ByVal bizCust As CustomerBiz) As Customer
            Dim custRecord AsNew Customer
            If Not bizCust Is Nothing AndAlso bizCust.CustID > 0 Then
                custRecord.CustID = bizCust.CustID
                custRecord.CustName = bizCust.CustName
                custRecord.CustDOB = bizCust.CustDOB
                custRecord.CustAddress = bizCust.CustAddress
                custRecord.DateCreated = bizCust.DateCreated
                custRecord.DateModified = bizCust.DateModified
            End If
            Return custRecord
        End Function
 
    End Class
End Namespace
 
ICustomerService.vb – Add following code which defines a Service Contract
Namespace Example.WcfService
    <ServiceContract(Name:="ICustomerService", NameSpace:="http://wcfservices.vishwamohan.net")> _
    Public Interface ICustomerService
 
        <OperationContract(Name:="GetCustomer")> _
        Function GetCustomer(ByVal ID As Integer) As Customer
 
        <OperationContract(Name:="GetCustomers")> _
       Function GetCustomers() As List(Of Customer)
 
        <OperationContract(Name:="AddCustomer")> _
        Function AddCustomer(ByVal CustomerRecord As Customer) As Integer
 
        <OperationContract(Name:="UpdateCustomer")> _
        Function UpdateCustomer(ByVal CustomerRecord As Customer) As Boolean
 
        <OperationContract(Name:="DeleteCustomer")> _
        Function DeleteCustomer(ByVal ID As Integer) As Boolean
    End Interface
End Namespace
 
CustomerService.svc –Make sure you have following code as the markup in the service page
<%@ ServiceHost Language="VB" Debug="true" Service="Vishwa.Example.WcfService.CustomerService" CodeBehind="CustomerService.svc.vb" %>
 
CustomerService.svc .vb – Add following code for this service
Namespace Example.WcfService
    <ServiceBehavior(Name:="CustomerService", NameSpace:="http://wcfservices.vishwamohan.net")> _
    Public Class CustomerService
        Implements ICustomerService
 
        Public Sub New()
        End Sub
 
        Public Function GetCustomer(ByVal ID As Integer) As Customer Implements ICustomerService.GetCustomer
            Return ServiceHelper.GetCustomerData(ID)
        End Function
 
        Public Function GetCustomers() As List(Of Customer) Implements ICustomerService.GetCustomers
            Return ServiceHelper.GetCustomersData()
        End Function
 
        Public Function AddCustomer(ByVal CustomerRecord As Customer) As Integer Implements ICustomerService.AddCustomer
            Return ServiceHelper.AddCustomerData(CustomerRecord)
        End Function
 
        Public Function DeleteCustomer(ByVal ID As Integer) As Boolean Implements ICustomerService.DeleteCustomer
            Return ServiceHelper.DeleteCustomerData(ID)
        End Function
 
        Public Function UpdateCustomer(ByVal CustomerRecord As Customer) As Boolean Implements ICustomerService.UpdateCustomer
            Return ServiceHelper.UpdateCustomerData(CustomerRecord)
        End Function
 
    End Class
 
End Namespace
 
That’s all, you are done. Now, compile the project and make sure that you see the service page. It will look like as
 

 

This service is ready to be hosted in IIS, which I believe is the easiest way to put the example together. So put it under a virtual directly let’s say ExampleService under IIS.  In next post I will consume this service on WS* Http Binding. Till now, you might have created a test service and used it anyway, so it might be sounding easy, but as I will move to different bindings, and how to consume that will be interesting. For each type I will make a new post to keep it clear and easy. 
Signature

About Me

Me Hello,my name is Vishwa Mohan Kumar.
I am a Software Architect. This blog is result of my experiments.

Flickr Photos

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Recent Comments

Comment RSS

Live Traffic Feed