Wednesday, 17 June 2015

Client use WSDL Generated Proxy Object

Client use WSDL Generated Proxy Object

If your client will be Windows applications or ASP.NET applications, you can use WSDL.EXE utility to created standard .NET Assemble to provide Proxy Class for your clients.
Here are steps you can follow and try:
Use WSDL.EXE utility to create the Proxy Class source file in any language you have chosen and here I use C# and command as follows:
C:\>wsdl    /language:C#     /out:MyProxyClass.cs    http://localhost/ASP.NET/MyWebService.asmx
MyProxyClass.cs is generated and source listing as follows:

File: MyProxyClass.cs

//------------------------------------------------------------------------------
// <autogenerated>
//     This code was generated by a tool.
//     Runtime Version: 1.0.2914.16
//
//     Changes to this file may cause incorrect behavior and will be lost if 
//     the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------

// 
// This source code was auto-generated by wsdl, Version=1.0.2914.16.
// 
using System.Diagnostics;
using System.Xml.Serialization;
using System;
using System.Web.Services.Protocols;
using System.Web.Services;

[System.Web.Services.WebServiceBindingAttribute(Name="MyClassSoap", Namespace="http://tempuri.org/")]
public class MyClass : System.Web.Services.Protocols.SoapHttpClientProtocol {
    
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    public MyClass() {
        this.Url = "http://localhost/ASP.NET/MyWebService.asmx";
    }
    
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Add", 

Use=System.Web.Services.Description.SoapBindingUse.Literal, 

ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
    public int Add(int a, int b) {
        object[] results = this.Invoke("Add", new object[] {
                    a,
                    b});
        return ((int)(results[0]));
    }
    
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    public System.IAsyncResult BeginAdd(int a, int b, System.AsyncCallback callback, object asyncState) {
        return this.BeginInvoke("Add", new object[] {
                    a,
                    b}, callback, asyncState);
    }
    
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    public int EndAdd(System.IAsyncResult asyncResult) {
        object[] results = this.EndInvoke(asyncResult);
        return ((int)(results[0]));
    }
}
Then we need to create the .NET Assembly for used by clients:
C:\> csc /t:library MyProxyClass.cs
The above command will compile the source and create MyProxyClass.dll library file.
I use ASP to depict how to use the proxy object and the file is TestWebServiceWithProxy.aspx source listing as follows:

File: TestWebServiceWithProxy.aspx

<%@ page language="C#" %>
<html>
<script runat="server">
        void btn_click(Object source, EventArgs e)
        {
                MyClass mycls = new MyClass() ;
                int x = Int32.Parse(a.Text) ;
                int y = Int32.Parse(b.Text);
                
                Message.Text = mycls.Add( x, y).ToString() ;
        }
</script>

<body>
<form Action = "TestWebServiceWithProxy.aspx" runat="server">
        <asp:TextBox id="a" runat="server" />
        <asp:TextBox id="b" runat="server" />
        <asp:button id=btn OnClick="btn_click" Text="Enter" runat="server" />
        <p><asp:label id="Message" runat="server" /></P>
</form>
</body>
</html>

Client use XMLHTTP to call Web service via SOAP

To fully explore the SOAP capability, you may choose to call your ASP.NET Web Service via SOAP core protocol and here I provide another example for reference.
To test the ASP.NET service with SOAP protocol, I create an ASP client file TestWebServiceByXML.asp and its source is listed as follows:

File: TestWebServiceByXML.asp

<html>
<body>
<script language="jscript">
        function btn_click (a, b)
        {
                var xmlObj = new ActiveXObject("Msxml2.DOMDocument") ;
                var sXml  = "<?xml version=\"1.0\" ?>" ;
                      sXml += "<soap:Envelope "
                      sXml += "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " ;
                      sXml += "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " ;
                      sXml += "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" ;
                      sXml += "<soap:Body>" ;
                      sXml += "<Add xmlns=\"http://tempuri.org/\">" ;
                      sXml = sXml + "<a>" + a.value  + "</a>" ;
                      sXml = sXml + "<b>" + b.value  + "</b>" ;                      
                      sXml += "</Add></soap:Body></soap:Envelope>"
                
    // Try to parse the XML string into DOM object 
                xmlObj.loadXML(sXml) ;
                
    //To see the validated XML string is well-formed 
                XmlRequest.innerText =  xmlObj.xml  ;
                
                var xmlHTTP = new ActiveXObject("Msxml2.XMLHTTP") ;
                xmlHTTP.Open ( "Post", "http://localhost/ASP.NET/MyWebService.asmx", false) ;
                xmlHTTP.setRequestHeader("SOAPAction", "http://tempuri.org/Add") ;
                xmlHTTP.setRequestHeader("Content-Type", "text/xml; charset=utf-8" ) ;
                xmlHTTP.Send(xmlObj.xml) ;
                MyResult.innerText =  xmlHTTP.responseText ;
                
                var xmlResponse = xmlHTTP.responseXML ;
                answer.innerText = xmlResponse.selectSingleNode("soap:Envelope/soap:Body/AddResponse/AddResult").text ;
        }
</script>

<form>
        <p>Please input a:<input id="a" name="a"></input></p>
        <p>Please input b:<input id="b" name="b"></input></p>
        <p>
        <input type="button" id="btn"  value="Enter" 
                onclick="jscript:btn_click(a, b)"></input>
        </p>
        <p>Answer is <span id="answer"></span></p>
        <hr></hr>
        <p>Request:</p>
        <span id="XmlRequest"></span>
        <p>Response:</p>
        <span id="MyResult"></span>
        
</form>

</body>
</html>
Here I installed Microsoft XML Parser 3.0 in my client machine that give me the XMLHTTP and DOM COM objects to test my application.

consume a web service from a client application

ASP.Net Web Services – How to consume a web service from a client application?

In last day, we were discussing about creating ASP.Net Web Services. You can read that article hereIn this article, we will go over consuming a web service from a client application.
Let’s try to consume the web service which we have created in the previous article. Follow the below steps for this.
Step 1Right click on WebServicesDemo solution in Solution Explorer and add a new ASP.Net Web Application Project and name it as CalculatorWebApplication.
ASP.NetWebServices1
Step 2Now we need to add a reference to the web service. To achieve this, first right click on the References folder in the CalculatorWebApplication project and select Add Service Reference option.
ASP.NetWebServices2
Then in the Address textbox of the Add Service Reference window, type the web service address and click on GO button. In the Namespace textbox, type CalculatorService and clickOK.
ASP.NetWebServices3
Once we click OK, Visual Studio will create a Proxy Class based on the WSDL document. Under the Service References folder, we can see the Namespace we have provided which isCalculatorService.
ASP.NetWebServices4
If you want to look at the generated Proxy Class, first click on the Show All Files button on the top. Then you can see a file named Reference.cs. 
ASP.NetWebServices7
Open that file. You can see a class called CalculatorWebServiceSoapClient. This is theProxy Class. Inside this class, you can see an Add method which is very much similar to theAdd method in the CalculatorWebService.
ASP.NetWebServices8
Step 3Right click on CalculatorWebApplication project in Solution Explorer and add a new Web Form named WebForm1.aspx.
Step 4Copy and paste the following HTML into the Web Form.
<table style=”font-family: Arial”>
<tr>
    <td>
        <b>First Number</b>
    </td>
    <td>
        <asp:TextBox ID=”txtFirstNumber” runat=”server”></asp:TextBox>
    </td>
</tr>
<tr>
    <td>
        <b>Second Number</b>
    </td>
    <td>
        <asp:TextBox ID=”txtSecondNumber” runat=”server”></asp:TextBox>
    </td>
</tr>
<tr>
    <td>
        <b>Result</b>
    </td>
    <td>
        <asp:Label ID=”lblResult” runat=”server”></asp:Label>
    </td>
</tr>
<tr>
    <td colspan=”2″>
        <asp:Button ID=”btnAdd” runat=”server” Text=”Add” 
        OnClick=”btnAdd_Click” />
    </td>
</tr>
</table>
ASP.NetWebServices5
Step 5: Copy and paste the following code to the button click event in the code behind file.
protected void btnAdd_Click(object sender, EventArgs e)
{
CalculatorService.CalculatorWebServiceSoapClient client =
               new CalculatorService.CalculatorWebServiceSoapClient();
int result = client.Add(Convert.ToInt32(txtFirstNumber.Text),
                Convert.ToInt32(txtSecondNumber.Text));
lblResult.Text = result.ToString();
}
ASP.NetWebServices6
Now right click on the WebForm1.aspx and select View in Browser. Give some First Number & Second Number, say 20 and 30 and click on Add button. You will get a result as 50 as expected.
ASP.NetWebServices9
Here if we look at the web application, we don’t have the logic of adding two numbers. The addition is actually done by the web service. The client application accesses the web service using HTTP protocol. Messages with web services are exchanged in SOAP format. TheSerialization which is converting .Net types to SOAP request messages andDeserialization which is converting SOAP response back into .Net types are done by Proxy Class which in our case is CalculatorWebServiceSoapClient class.

The need for web services

Why Web Services ?
  • Exposing the existing function on to network:
A Web service is a unit of managed code that can be remotely invoked using HTTP, that is, it can be activated using HTTP requests. So, Web Services allows you to expose the functionality of your existing code over the network. Once it is exposed on the network, other application can use the functionality of your program.
  • Connecting Different Applications ie Interoperability:
Web Services allows different applications to talk to each other and share data and services among themselves. Other applications can also use the services of the web services. For example VB or .NET application can talk to java web services and vice versa. So, Web services is used to make the application platform and technology independent.
  • Standardized Protocol:
Web Services uses standardized industry standard protocol for the communication. All the four layers (Service Transport, XML Messaging, Service Description and Service Discovery layers) uses the well defined protocol in the Web Services protocol stack. This standardization of protocol stack gives the business many advantages like wide range of choices, reduction in the cost due to competition and increase in the quality.
  • Low Cost of communication:
Web Services uses SOAP over HTTP protocol for the communication, so you can use your existing low cost internet for implementing Web Services. This solution is much less costly compared to proprietary solutions like EDI/B2B. Beside SOAP over HTTP, Web Services can also be implemented on other reliable transport mechanisms like FTP etc.