40
I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS 1)Write a program to implement WSDL Service (Hello Service , WSDL File) As communications protocols and message formats are standardized in the web community, it becomes increasingly possible and important to be able to describe the communications in some structured way. WSDL addresses this need by defining an XML grammar for describing network services as collections of communication endpoints capable of exchanging messages. WSDL service definitions provide documentation for distributed systems and serve as a recipe for automating the details involved in applications communication. Types– a container for data type definitions using some type system (such as XSD). Message– an abstract, typed definition of the data being communicated. Operation– an abstract description of an action supported by the service. Port Type–an abstract set of operations supported by one or more endpoints. Binding– a concrete protocol and data format specification for a particular port type. Port– a single endpoint defined as a combination of a binding and a network address. Service– a collection of related endpoints.A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format 1

Web Services Lab for CSE CS

Embed Size (px)

DESCRIPTION

jntu

Citation preview

Page 1: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

1)Write a program to implement WSDL Service (Hello Service , WSDL File)

As communications protocols and message formats are standardized in the web community, it becomes increasingly possible and important to be able to describe the communications in some structured way. WSDL addresses this need by defining an XML grammar for describing network services as collections of communication endpoints capable of exchanging messages. WSDL service definitions provide documentation for distributed systems and serve as a recipe for automating the details involved in applications communication.

Types– a container for data type definitions using some type system (such as XSD).

Message– an abstract, typed definition of the data being communicated.

Operation– an abstract description of an action supported by the service.

Port Type–an abstract set of operations supported by one or more endpoints.

Binding– a concrete protocol and data format specification for a particular port type.

Port– a single endpoint defined as a combination of a binding and a network address.

Service– a collection of related endpoints.A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:

Following is the WSDL file that is provided to demonstrate a simple WSDL program.

Assuming the service provides a single publicly available function, called sayHello. This function expects a single string parameter and returns a single string greeting. For example if you pass the parameter world then service function sayHello returns the greeting, "Hello, world!".

1

Page 2: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

PROGRAM:

Content of HelloService.wsdl file

<definitions name="HelloService"

targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl"

xmlns="http://schemas.xmlsoap.org/wsdl/"

xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"

xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl"

xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<message name="SayHelloRequest">

<part name="firstName" type="xsd:string"/>

</message>

<message name="SayHelloResponse">

<part name="greeting" type="xsd:string"/>

</message>

<portType name="Hello_PortType">

<operation name="sayHello">

<input message="tns:SayHelloRequest"/>

<output message="tns:SayHelloResponse"/>

</operation>

</portType>

<binding name="Hello_Binding" type="tns:Hello_PortType">

<soap:binding style="rpc"

2

Page 3: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

transport="http://schemas.xmlsoap.org/soap/http"/>

<operation name="sayHello">

<soap:operation soapAction="sayHello"/>

<input>

<soap:body

encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"

namespace="urn:examples:helloservice"

use="encoded"/>

</input>

<output>

<soap:body

encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"

namespace="urn:examples:helloservice"

use="encoded"/>

</output>

</operation>

</binding>

<service name="Hello_Service">

<documentation>WSDL File for HelloService</documentation>

<port binding="tns:Hello_Binding" name="Hello Port">

<soap: address

location="http://www.examples.com/SayHello/">

</port>

</service>

</definitions>

Analysis of the Example

3

Page 4: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

Definition : Hello Service

Type : Using built-in data types and they are defined in XMLSchema.

Message :

sayHelloRequest : firstName parameter

sayHelloresponse: greeting return value

Port Type: sayHello operation that consists of a request and response service.

Binding: Direction to use the SOAP HTTP transport protocol.

Service: Service available at http://www.examples.com/SayHello/.

Port: Associates the binding with the URI http://www.examples.com/SayHello/ where the running service can be accessed.

A detailed description of these elements is given in subsequent sections of the tutorial.

4

Page 5: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

2. Write a program to implement to create a simple web service that converts the temperature from Fahrenheit to Celsius (using HTTP Post Protocol)

This will show how we can create a Web Service that will allow us to convert from Fahrenheit to Celsius, or vice versa. C# version.

Web Services allow you to use applications in your Web Project. In this demonstration, we will show how we can easily implement an application into our Web Project. We will write two simple methods that will enable us to convert Fahrenheit into Celsius, and vice versa. The methods will be the Web Service, and theoretically, be stored on a different web server than our Web Project that is using it.

First, we start off with a Web Service Porject in Visual Studio .NET

Then we will add the logic to the App_Code folder, in the .cs file:

Program :

using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Service : System.Web.Services.WebService

{public Service () {

//Uncomment the following line if using designed components

//InitializeComponent();

}[WebMethod]

public string HelloWorld() {

return "Hello World";

}

5

Page 6: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

[WebMethod]

public string FahrenheitToCelsius(string Fahrenheit)

{

object fahr = null;

fahr = Fahrenheit.Replace(",", ".").Trim(' ');

if (fahr == "")

{

return "Error";

}

int returnVal = ((((Convert.ToInt32(fahr)) - 32) / 9) * 5);

return returnVal.ToString();

}

[WebMethod]

public string CelsiusToFahrenheit(string Celsius)

{

object cel = null;

cel = Celsius.Replace(",", ".").Trim(' ');

if (cel == "")

{

return "Error";

}

int returnVal = ((((Convert.ToInt32(cel)) * 9) / 5) + 32);

return returnVal.ToString();

}

}

Here, there are three methods. One is the simple Hello World method, which will retrieve a string when called. The other two will convert a number into either Fahrenheit or Celsius, depending on which method is called.

6

Page 7: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

We now need a form to call the Web Service, as well as send the number to convert. For this, we create a web form and allow the user to either convert from Fahrenheit to Celsius, or Celsius to Fahrenheit.

<form target="_blank" action="Service.asmx/FahrenheitToCelsius" method="POST">

<table>

<tr>

<td>Fahrenheit to Celsius:</td>

<td><input class="frmInput" type="text"

size="30" name="Fahrenheit"></td>

</tr>

<tr>

<td></td>

<td align="right"> <input type="submit" value="Submit" class="button"></td>

</tr>

</table>

</form>

<form target="_blank" action="Service.asmx/CelsiusToFahrenheit" method="POST">

<table>

<tr>

<td>Celsius to Fahrenheit:</td>

<td><input class="frmInput" type="text"

size="30" name="Celsius"></td>

</tr>

<tr>

<td></td>

<td align="right"> <input type="submit" value="Submit" class="button"></td>

</tr>

</table></form>

7

Page 8: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

3) write a program to implement business uddi registry entry

UDDI: Universal Description, Discovery, and Integration

The Universal Description, Discovery, and Integration (UDDI) Project provides a standardized method for publishing and discovering information about web services. The UDDI Project is an industry initiative that attempts to create a platform-independent, open framework for describing services, discovering businesses, and integrating business services. UDDI focuses on the process of discovery in the service-oriented architecture.

The UDDI Project is an initiative that communicates with the public through . The UDDI Community runs the UDDI Project. The Community consists of a group of Working Group members who develop the specifications and Advisory Group members who provide requirements and review the specifications. The Working Group is an invitation-based group and the Advisory Group is open to everyone.

Web services are becoming the basis for electronic commerce of all forms. Companies invoke the services of other companies to accomplish a business transaction. In an environment in which only a few companies participate, managing the discovery of business partners manually would be simple. After all, how difficult would it be to figure out if one of your few business partners has an access point that adheres to your requirements? This model breaks down, however, as the number of companies that you need to interact with grows, along with the number and types of interfaces they export. How do you discover all the business partners that you can do business with? If you attempted to account for them manually, you could never be sure that you discovered every partner. UDDI is a single conceptual registry distributed among many nodes that replicate the participating businesses' data with one another. The UDDI registry of services (hosted by different businesses on the Internet) attempts to solve this problem.

This chapter presents an overview of UDDI and how to put it to work. It includes a discussion about the information stored in a UDDI registry, the different potential uses of UDDI, and its technical architecture; the specifications that comprise the UDDI effort, with a focus on their relevance to developers and a list of different Java approaches for programming with UDDI; and an introduction to interacting with a UDDI registry programmatically. The following sections cover the UDDI data structures and XML APIs available for accessing a registry.

Prior to the UDDI project, no industry-wide approach was available for businesses to reach their customers and partners with information about their products and web services. Nor was there a uniform method that detailed how to integrate the systems and processes that are already in place at and between business partners. Nothing attempted to cover both the business and development aspects of publishing and locating information associated with a piece of software on a global scale.

Conceptually, a business can register three types of information into a UDDI registry. The specification does not call out these types specifically, but they provide a good summary of what UDDI can store for a business:

8

Page 9: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

White pagesBasic contact information and identifiers about a company, including business name, address, contact information, and unique identifiers such as D-U-N-S numbers or tax IDs. This information allows others to discover your web service based upon your business identification.

Yellow pagesInformation that describes a web service using different categorizations (taxonomies). This information allows others to discover your web service based upon its categorization (such as being in the manufacturing or car sales business).

Green pagesTechnical information that describes the behaviors and supported functions of a web service hosted by your business. This information includes pointers to the grouping information of web services and where the web services are located.

UDDI Specifications

The UDDI project also defines a set of XML Schema definitions that describe the data formats used by the various specification APIs. These documents are all available for download at http://www.uddi.org. The UDDI project releases their specifications in unison. The current version of all specification groups is Version 2.0. The specifications include:

UDDI replicationThis document describes the data replication processes and interfaces to which a registry operator must conform to achieve data replication between sites. This specification is not a programmer's API; it defines the replication mechanism used among UBR nodes.

UDDI operatorsThis document outlines the behavior and operational parameters required by UDDI node operators. This specification defines data management requirements to which operators must adhere. For example, node operators are responsible for durable recording and backup of all data, ensuring that each business registration has a valid email address associated with it, and the integrity of the data during deletions (e.g., deleting a business means that all of its service entries must also be deleted). This document is not a programmer's API and private registries are not required to support it.

UDDI Programmer's APIThis specification defines a set of functions that all UDDI registries support for inquiring about services hosted in a registry and for publishing information about a business or a service to a registry. This specification defines a series of SOAP messages containing XML documents that a UDDI registry accepts, parses, and responds to. This specification, along with the UDDI XML API schema and the UDDI Data Structure specification, makes up a complete programming interface to a UDDI registry.

UDDI data structuresThis specification covers the specifics of the XML structures contained within the SOAP messages defined by the UDDI Programmer's API. This specification defines five core data structures and their relationships to one another.

The UDDI XML API schema is not contained in a specification; rather, it is stored as an XML Schema document that defines the structure and datatypes of the UDDI data structures.

9

Page 10: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

Now that we've seen what the client does and examined the documents it sends and receives, it is time to look at UDDISoapClient.java in its entirety:

import java.io.*;

import java.util.*;

public class UDDISoapClient

{

// Default values used if no command line parameters are set

private static final String DEFAULT_HOST_URL =

"http://localhost:8080/wasp/uddi/inquiry/";

private static final String DEFAULT_DATA_FILENAME = "./Default.xml";

// In the SOAP chapter, we used "urn:oreilly:jaws:samples",

// but Systinet UDDI requires this to be blank.

private static final String URI = "";

private String m_hostURL;

private String m_dataFileName;

public UDDISoapClient(String hostURL, String dataFileName) throws Exception

{

m_hostURL = hostURL;

m_dataFileName = dataFileName;

System.out.println( );

System.out.println("______________________________________");

10

Page 11: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

System.out.println("Starting UDDISoapClient:");

System.out.println(" host url = " + m_hostURL);

System.out.println(" data file = " + m_dataFileName);

System.out.println("______________________________________");

System.out.println( );

} public void sendSOAPMessage( ) {

try {

// Get soap body to include in the SOAP envelope from FILE

FileReader fr = new FileReader (m_dataFileName);

javax.xml.parsers.DocumentBuilder xdb =

org.apache.soap.util.xml.XMLParserUtils.getXMLDocBuilder( );

org.w3c.dom.Document doc =

xdb.parse (new org.xml.sax.InputSource (fr));

if (doc == null) {

throw new org.apache.soap.SOAPException

(org.apache.soap.Constants.FAULT_CODE_CLIENT, "parsing error");

}

// Create a vector for collecting the body elements

Vector bodyElements = new Vector( );

// Parse XML element as soap body element

bodyElements.add(doc.getDocumentElement ( ));

// Create the SOAP envelope

org.apache.soap.Envelope envelope = new org.apache.soap.Envelope( );

envelope.declareNamespace("idoox", "http://idoox.com/uddiface");

11

Page 12: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

envelope.declareNamespace("ua", "http://idoox.com/uddiface/account");

envelope.declareNamespace("config",

"http://idoox.com/uddiface/config");

envelope.declareNamespace("attr", "http://idoox.com/uddiface/attr");

envelope.declareNamespace("fxml", "http://idoox.com/uddiface/formxml");

envelope.declareNamespace("inner", "http://idoox.com/uddiface/inner");

envelope.declareNamespace("", "http://idoox.com/uddiface/inner");

envelope.declareNamespace("uddi", "urn:uddi-org:api_v2");

//

// NO SOAP HEADER ELEMENT AS SYSTINET WASP DOES NOT REQUIRE IT

//

// Create the SOAP body element

org.apache.soap.Body body = new org.apache.soap.Body( );

body.setBodyEntries(bodyElements);

envelope.setBody(body);

// Build and send the Message.

org.apache.soap.messaging.Message msg =

new org.apache.soap.messaging.Message( );

msg.send (new java.net.URL(m_hostURL), URI, envelope);

System.out.println("Sent SOAP Message with Apache HTTP SOAP Client.");

// Receive response from the transport and dump it to the screen

System.out.println("Waiting for response....");

org.apache.soap.transport.SOAPTransport st = msg.getSOAPTransport ( );

BufferedReader br = st.receive ( );

if(line == null) {

12

Page 13: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

System.out.println("HTTP POST was unsuccessful. \n");

} else {

while (line != null) {

System.out.println (line);

line = br.readLine( );

}

}

// Version in examples has XML pretty printing logic here.

} catch(Exception e) {

e.printStackTrace( );

}

} public static void main(String args[]) {

}

}

Here's a listing of the Systenet-based client in its entirety:

import org.idoox.uddi.client.api.v2.request.inquiry.*;

import org.idoox.uddi.client.structure.v2.tmodel.*;

import org.idoox.uddi.client.api.v2.response.*;

import org.idoox.uddi.client.structure.v2.base.*;

import org.idoox.uddi.client.structure.v2.business.*;

import org.idoox.uddi.client.api.v2.*;

import org.idoox.uddi.client.*;

/**

13

Page 14: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

* This is simple example of Systinet's UDDI Java API for accessing

* a UDDI registry.

* This program does a find_business call by name.

*/

public class SystinetFindBusiness {

// Program Entry Point

public static void main(String args[]) throws Exception

{

String company = "Demi Credit";

findBusinessByName(company);

}

public static void findBusinessByName(String name) throws Exception

{

System.out.println("Searching for businesses named '" +

name + "'...");

// Create a FindBusiness instance.

// This creates a SOAP message.

FindBusiness findBusiness = new FindBusiness( );

// Set the name to use in the query.

findBusiness.addName(new Name(name));

14

Page 15: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

// This will limit the number of returned matches.

// maxRows is an optional attribute.

findBusiness.setMaxRows(new MaxRows("10"));

// This will retrieve a stub to the UDDI inquiry port.

UDDIApiInquiry inquiry =

UDDILookup.getInquiry("http://localhost:8080/wasp/uddi/inquiry/");

// Send the message and retrieve the response.

BusinessList businessList=inquiry.find_business(findBusiness);

// Show the results

if (businessList==null) {

System.err.println("ERROR: Business list is null!");

}

else {

// Business list is holder for results - business infos.

BusinessInfos businessInfos = businessList.getBusinessInfos( );

System.out.println("\nFound: " +

businessInfos.size( ) +

" businesses.\n");

// Iterate through each company found in the query.

BusinessInfo businessInfo = businessInfos.getFirst( );

BusinessKey result;

if (businessInfo != null) {

result=businessInfo.getBusinessKey( );

15

Page 16: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

while (businessInfo!=null) {

System.out.println("BusinessEntity name = " +

businessInfo.getNames().getFirst().getValue( ));

System.out.println("BusinessEntity UUID = " +

businessInfo.getBusinessKey( ));

System.out.println("***");

businessInfo = businessInfos.getNext( );

}

}

}

}

}

16

Page 17: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

4) write a program to implement

a) web based service consumer

What Are Web Services?

A Web service is a program that can be accessed remotely using different standards-based languages. What this program can do (that is, the functionality it implements) is described in a standard vocabulary.

Major benefits of Web services include:

Interoperability among distributed applications that span diverse hardware and software platforms

Easy, widespread access to applications through firewalls using Web protocols

A cross-platform, cross-language data model (XML) that facilitates developing heterogeneous distributed applications

Web services are characterized by three factors:

What they do (the business functionality they expose).

Where they are (the web site which exposes that functionality).

How they can be accessed (the set of published interfaces necessary to use the exposed functionality).

Web services rely on XML-based and other industry standards:

Extensible Markup Language (XML)—A data format that allows uniform communication between Web services consumers and Web services providers.

XML Schema—A framework that describes XML vocabularies used in business transactions.

Simple Object Access Protocol (SOAP)—A protocol for exchanging structured information in the implementation of Web services.

Web Services Description Language (WSDL)—An XML-based language providing a model for describing SOAP-based Web services.

Web Application Description Language (WADL)—An XML-based language providing a model for describing RESTful Web services.

17

Page 18: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

WS-Policy—The WS-Policy framework provides a flexible and extensible grammar for describing the capabilities, requirements, and general characteristics of Web services using policies.

Universal Description, Discovery, and Integration (UDDI)—A framework to publish and look up Web services on the Internet.

For example, a banking Web service may implement functions to check an account, print a statement, and deposit and withdraw funds. These functions are described in a WSDL file that any consumer can invoke to access the banking Web service. As a result, a consumer does not have to know anything more about a Web service than the WSDL file that describes what it can do.

A Web service consumer (such as, a desktop application or a Java Platform, Enterprise Edition client such as a portlet) invokes a Web service by submitting a request in the form of an XML document to a Web service provider. The Web service provider processes the request and returns the result to the Web service consumer in an XML document as shown in the example below.

Figure 1 Example of SOAP Message Exchange Between Web Service Consumer and Provider

18

Page 19: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

19

Page 20: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

b) windows application based web service consumer

Service provider or publisher:

This is the provider of the web service. The service provider implements the service and makes it available on the Internet or intranet.

We will write and publish a simple web Service using .NET SDK.

Service requestor or consumer

This is any consumer of the web service. The requestor utilizes an existing web service by opening a network connection and sending an XML request.

We will also write two Web Service requestors: one Web-based consumer (ASP.NET application) and another Windows application-based consumer.

Following is our First Web Service example which works as a service provider and exposes two methods (add and SayHello) as Web Services to be used by applications. This is a standard template for a Web Service. .NET Web Services use the .asmx extension. Note that a method exposed as a Web Service has the WebMethod attribute. Save this file as FirstService.asmx in the IIS virtual directory (as explained in configuring IIS; for example, c:\MyWebSerces).

FirstService.asmx

<%@ WebService language="C" class="FirstService" %>

using System;

using System.Web.Services;

using System.Xml.Serialization;

[WebService(Namespace="http://localhost/MyWebServices/")]

public class FirstService : WebService

{

[WebMethod]

public int Add(int a, int b)

{

20

Page 21: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

return a + b;

}

[WebMethod]

public String SayHello()

{

return "Hello World";

}

}

Testing the Web Service

As we have just seen, writing Web Services is easy in the .NET Framework. Writing Web Service consumers is also easy in the .NET framework; however, it is a bit more involved. As said earlier, we will write two types of service consumers, one Web- and another Windows application-based consumer. Let's write our first Web Service consumer.

Web-Based Service Consumer

Write a Web-based consumer as given below. Call it WebApp.aspx. Note that it is an ASP.NET application. Save this in the virtual directory of the Web Service (c:\MyWebServices\WebApp.axpx).

This application has two text fields that are used to get numbers from the user to be added. It has one button, Execute, that, when clicked, gets the Add and SayHello Web Services.

WebApp.axpx

<%@ Page Language="C#" %>

<script runat="server">

void runSrvice_Click(Object sender, EventArgs e)

{

FirstService mySvc = new FirstService();

Label1.Text = mySvc.SayHello();

Label2.Text = mySvc.Add(Int32.Parse(txtNum1.Text),

21

Page 22: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

Int32.Parse(txtNum2.Text)).ToString();

}

</script>

<html>

<head>

</head>

<body>

<form runat="server">

<p>

<em>First Number to Add </em>:

<asp:TextBox id="txtNum1" runat="server"

Width="43px">4</asp:TextBox>

</p>

<p>

<em>Second Number To Add </em>:

<asp:TextBox id="txtNum2" runat="server"

Width="44px">5</asp:TextBox>

</p>

<p>

<strong><u>Web Service Result -</u></strong>

</p>

<p>

<em>Hello world Service</em> :

<asp:Label id="Label1" runat="server"

Font-Underline="True">Label</asp:Label>

</p>

22

Page 23: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

<p>

<em>Add Service</em> :

& <asp:Label id="Label2" runat="server"

Font-Underline="True">Label</asp:Label>

</p>

<p align="left">

<asp:Button id="runSrvice" onclick="runSrvice_Click"

runat="server" Text="Execute"></asp:Button>

</p>

</form>

</body>

</html>

After the consumer is created, we need to create a proxy for the Web Service to be consumed. This work is done automatically by Visual Studio .NET for us when referencing a Web Service that has been added. Here are the steps to be followed:

Create a proxy for the Web Service to be consumed. The proxy is created using the wsdl utility supplied with the .NET SDK. This utility extracts information from the Web Service and creates a proxy. Thus, the proxy created is valid only for a particular Web Service. If you need to consume other Web Services, you need to create a proxy for this service as well. VS .NET creates a proxy automatically for you when the reference for the Web Service is added. Create a proxy for the Web Service using the wsdl utility supplied with the .NET SDK. It will create FirstSevice.cs in the current directory. We need to compile it to create FirstService.dll (proxy) for the Web Service.

Windows Application-Based Web Service Consumer

Writing a Windows application-based Web Service consumer is the same as writing any other Windows application. The only work to be done is to create the proxy (which we have already done) and reference this proxy when compiling the application. Following is our Windows application that uses the Web Service. This application creates a Web Service object (of course, proxy) and calls the SayHello and Add methods on it.

23

Page 24: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

WinApp.cs

using System;

using System.IO;

namespace SvcConsumer{

class SvcEater

{

public static void Main(String[] args)

{

FirstService mySvc = new FirstService();

Console.WriteLine("Calling Hello World Service: " +

mySvc.SayHello());

Console.WriteLine("Calling Add(2, 3) Service: " +

mySvc.Add(2, 3).ToString());

}

}

}

Compile it using c:>csc /r:FirstService.dll WinApp.cs. It will create WinApp.exe. Run it to test the application and the Web Service.

Now, the question arises: How can I be sure that my application is actually calling the Web Service? It is simple to test. Stop your Web server so that the Web Service cannot be contacted. Now, run the WinApp application. It will fire a run-time exception. Now, start the Web server again. It should work.

24

Page 25: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

5)Write a program to implement the operation can receive request and will return a response in two ways :

a) one way operation

In this very simple message exchange pattern (see Figure 5), sometimes known as the "fire-and-forget"

method, messages are pushed in one direction only. The source does not care whether the destination

accepts the message (with or without error conditions). The service provider implements a Web service to

which the requestor can send messages.

---------------------

massage

//Execute call

var client = WCFClientFactory.CreateClient<si_empsave_async_outclient>(CredentialType.PI);

try

{

client.SI_EmpSave_Async_Out(empObj);

}

catch (System.ServiceModel.ProtocolException ex) //Just handle this specific exception.

//Otherwise bubble up

{

25

Service provider

(Destination)Service requestor

(source)

Page 26: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

if (!ex.Message.Equals("The one-way operation returned a non-null message with Action=''."))

throw;

}

</si_empsave_async_outclient> <endpoint address="http://ipv4.fiddler/test.aspx" binding="basicHttpBinding"

bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"

name="BasicHttpBinding_IService1" />

protected void Page_Load(object sender, EventArgs e)

{ Response.Clear();

Response.StatusCode = 200;

Response.ContentType = "text/xml";

Response.End();

}

26

Page 27: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

b) Request-Reply Operations

All the samples in the previous chapters included contracts whose operations are of the type known as request-reply. As the name implies, the client issues a request in the form of a message, and blocks until it get the reply message. If the service does not respond within a default timeout of one minute, the client will get a TimeoutException. Request-reply is the default operation mode. Programming against request-reply operations is simple enough and resembles programming using the classic client/server model. The returned response message containing the results or returned values is converted to normal method returned values. In addition, the proxy will throw an exception on the client side if there are any communication or service-side exceptions. With the exception of the NetPeerTcpBinding and NetMsmqBinding, all bindings support request-reply operations.

27

Page 28: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

6) write a program the service provider can be implement a single get price() , static bind() and get product operation

getprice()

package com.ecerami.soap.examples;

import java.util.Hashtable;

/**

* A Sample SOAP Service

* Provides Current Price for requested Stockkeeping Unit (SKU)

*/

public class PriceService {

protected Hashtable products;

/**

* Zero Argument Constructor

* Load product database with two sample products

*/

public PriceService ( ) {

products = new Hashtable( );

// Red Hat Linux

products.put("A358185", new Double (54.99));

// McAfee PGP Personal Privacy

products.put("A358565", new Double (19.99));

} /**

* Provides Current Price for requested SKU

* In a real-setup, this method would connect to

* a price database. If SKU is not found, method

28

Page 29: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

* will throw a PriceException.

*/

public double getPrice (String sku)

throws ProductNotFoundException {

Double price = (Double) products.get(sku);

if (price == null) {

throw new ProductNotFoundException ("SKU: "+sku+" not found");

}

return price.doubleValue( );

} }

To generate a WSDL file for this class, run the following command:

java2wsdl com.ecerami.soap.examples.PriceService -s -e http://localhost:

8080/soap/servlet/rpcrouter -n urn:examples:priceservice

The -s option directs GLUE to create a SOAP binding; the -e option specifies the address of

our service; and the -n option specifies the namespace URN for the service. GLUE will generate

a PriceService.wsdl file.

Getproduct()

<?xml version="1.0" encoding="UTF-8"?>

<definitions name="ProductService"

targetNamespace="http://www.ecerami.com/wsdl/ProductService.wsdl"

xmlns="http://schemas.xmlsoap.org/wsdl/"

xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"

xmlns:tns="http://www.ecerami.com/wsdl/ProductService.wsdl"

xmlns:xsd="http://www.w3.org/2001/XMLSchema"

xmlns:xsd1="http://www.ecerami.com/schema">

29

Page 30: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

<types>

<xsd:schema

targetNamespace="http://www.ecerami.com/schema"

xmlns="http://www.w3.org/2001/XMLSchema">

<xsd:complexType name="product">

<xsd:sequence>

<xsd:element name="name" type="xsd:string"/>

<xsd:element name="description" type="xsd:string"/>

<xsd:element name="price" type="xsd:double"/>

<xsd:element name="SKU" type="xsd:string"/>

</xsd:sequence>

</xsd:complexType>

</xsd:schema>

</types>

<message name="getProductRequest">

<part name="sku" type="xsd:string"/>

</message>

<message name="getProductResponse">

<part name="product" type="xsd1:product"/>

</message>

<portType name="Product_PortType">

<operation name="getProduct">

<input message="tns:getProductRequest"/>

<output message="tns:getProductResponse"/>

</operation>

</portType>

30

Page 31: Web Services Lab for CSE CS

I M.Tech II Sem Web Services lab DEPT. OF CSE ACTS

<binding name="Product_Binding" type="tns:Product_PortType">

<soap:binding style="rpc"

transport="http://schemas.xmlsoap.org/soap/http"/>

<operation name="getProduct">

<soap:operation soapAction="urn:examples:productservice"/>

<input>

<soap:body

encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"

namespace="urn:examples:productservice"

use="encoded"/>

</input>

<output>

<soap:body

encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"

namespace="urn:examples:productservice" use="encoded"/>

</output>

</operation>

</binding>

<service name="Product_Service">

<port name="Product_Port" binding="tns:Product_Binding">

<soap:address

location="http://localhost:8080/soap/servlet/rpcrouter"/>

</port>

</service>

</definitions>

31