You are on page 1of 29

Unit IV Building Web Services Introduction to web services Web services Infrastructure SOAP Building a web service Deploying

ying and publishing web services Finding web services Consuming web services. 1. Define Web service Web service is a programmable URL. It is an application component that is remotely callable using standard Internet protocols such as HTTP and XML. Web services on the Internet, does not depend on a specific OS, object model or programming language. Web services solve a basic, but pervasive problem experienced by many of us with todays Internet. Web services are all about delivering distributed applications via programmable components that are accessible over the web. As an example, many ecommerce sites need to calculate shipping charges based on a variety of shipping options. Typically, such a site might maintain a set of database tables that describe the shipping options and charges for each shipping company in its web site. By utilizing screen scraping (essentially a process of analyzing the data in a page for certain patterns in order to extract the data for processing), a program can examine the web page and extract the shipping information from that page. Consider the e-commerce site programmatically calling a web service provided by the shipping company on its web site that automatically calculate shipping costs based on the shipping method and package weight that you specify in your request and returns the resulting charge to you in real time. The potential valuable applications of web services are: Extend the capabilities of classic distributed applications and services to the heterogeneous platform that is the Internet Services that is either too difficult or too expensive to implement yourself. Example credit card validation, financial account management, stock quotes etc., Services that provide commonly needed functionality for other services. Example: User authentication, usage billing, usage auditing and so on. Services that aggregate distributed, discrete services into an orchestrated whole. A good example of this type of service would be travel booking. Services that integrate your business systems with your partners

2. Fundamental elements of web services: Microsoft provides an excellent platform for building and consuming web services with .Net framework, which virtually eliminates the need to learn about the plumbing that is a part of building and consuming web services. It is the foundation built on Internet standards that does not rely on any platform specific technology. This foundation supplies standards-based services that provide the following capabilities to web services:

3. XML

A standard, portable method for describing data A standard, extensible message format for communicating requests and responses A standard, extensible method for describing the capabilities of web services A method to discover what web services are available at any particular site A method to discover what sites provide web services

What is XML? XML (eXtensible Markup Language) provides a standards-based method for describing data. XML has the ability to describe data using a simple grammar that is highly interoperable among the many heterogeneous systems that are connected to the Internet. XML has a several key strengths that have helped it to become the de facto method for describing data: XML is a text-based language, which makes it easily readable and more portable than binary data format XML give the ability to define your own tags to describe data and its relationships to other data XML strictly enforces its language syntax, unlike HTML. Parsers are widely available to accurately parse and validate XML structure that you define, which means you dont have to do it yourself.

XML syntax: Though XML and HTML are derived from SGML, XML uses a set of human-readable tags and declarations to create a document. HTML is describing how to format information page, XML is concerned with describing data and its relationship to other data. XML document structure: An XML consists of a prolog, document elements and optional attributes that model a logically related set of data. The prolog contains information that applies to the document as a whole and appears at the top of document before the first document tag. The prolog usually contains information about the character encoding and document structure as well as other possible information. XML parsers use the prolog to correctly interpret the contents of XML document.

XML document examplae: <?XML version=1.0 encoding=UTF-8?> <weather> <location city=Chennai, Tamil Nadu> <forecast date=2006-06-08> <temperature units=F>80temperature> <humidity units=%>55</humidity> <skies> cloudy, 40% chance of showers</skies> </forecast> </location> </weather> The three basic rules to be followed while creating XML document: All elements must have an end tag All elements must be cleanly nested All attribute values must be enclosed in quotation marks Each document must have a unique first element (document root)

XML namespace: When developing xml documents, it is common to refer to element and attribute names that share a common context as vocabulary. The possibility arises that an element or attribute in that vocabulary may have a name that is identical to an element or attribute used by someone else in a different vocabulary. XML namespace solve this ambiguity problem by associating explicit namespace (or vocabulary) with elements and attributes in XML document. Thus a namespace is essentially a set of names in which all the elements and attribute names can be guaranteed to be unique. Slightly change the xml document example as follows: <?XML version=1.0 encoding=UTF-8?> <weather xmlns=http://mydomain.com/xml/weather> <location city=Chennai, Tamil Nadu> <forecast date=2006-06-08> <temperature units=F>80temperature> <humidity units=%>55</humidity> <skies> cloudy, 40% chance of showers</skies> </forecast> </location> </weather> In this example, the weather elements include a namespace declaration specified by the standard xmlns attribute. It is worth pointing out here that the URL used to define the

namespaces does not to point at anything. However, while using XSD (xml schema definition) language, this URI can point to XSD file. Default declaration defines a namespace whose scope includes all elements contained within the element where the declaration was specified. Explicit namespace declaration defines a shorthand reference to an existing namespace. XML Schemas: XML parser uses strict rules to ensure that the XML document is well formed. However, this does not address the issue of validating that an XML document contains the proper assortment of elements and in valid combinations. What is needed is a language that will allow a generic XML parser to determine that the document conforms to these additional, user defined rules. The XSD language defines rules for describing the valid combinations and relationships of elements, attributes, and data types that can appear in XML document. This enables authors as well as consumers to validate that the document is formed correctly according to the schema definition. XSD syntax: An XSD schema document contains a top-level schema element. The schema element must define the XML schema namespace, as in the following: <xsd:schema xmlns:xsd=http://www.w3.org/2001/SMLSchema> The element and attribute type is declared as: <xsd:element name=skies type=xsd:string /> <xsd:attribute name=city type=xsd:string /> The complex type: <xsd:complextype> <xsd:attribute ref=units/> </xsd:complextype> 4. Exchange message: Web service communicates in the form of messages. A request message delivers the information about an operation to be executed and any data required to carry out that operation. Request messages flow from clients to web services. A response message delivers information about results of operation execution. Response message flow from web services to clients.

Message exchange with soap: The simple object access protocol is an industry-standard message format that enables message-based communication for web services. SOAP implements a message format based on XML to exchange function requests and responses. Using xml as the basis for soap messages makes it possible for these messages to be understandable and transportable by any system that implements basic Internet communication services. SOAP use the term binding to transport a message with referring to a specific protocol. Message exchange with HTTP-Get and Http-post: Web services can also exchange messages using Http-get and Http-post. These verbs are standard messages of http protocol that enable the exchange of information as name/value pairs. Http-get passes name/value pairs as Uuencoded text and appended to url of request. Httppost also passes name/value pairs as Uuencoded text, except that parameters are passed within the actual http request header rather than as a query string appended to url. 5. Describe web service capabilities: A web service description is an xml document that defines the capabilities that a web service offers. This document provides essential information in a structured form that enables a consumer to understand how to interact with a web service. The web service description language (WSDL) defines a standard, extensible XML grammar that is used to define these web service descriptions in the form of XML document. The WSDL elements are: Type: a container for data type definitions using some type system Message: an abstract typed definition of the data being communicated Operation: an abstract description of an action supported by web 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 6. Publishing and finding web services: Publishing: Given a standard means to describe the capabilities of web service via the WSDL document, we must consider how a potential consumer of a web service will locate a wsdl document on a target web server. Web service authors use a discover document (DISCO) to publish their web service. The DISCO document is an xml document that

contains pointers to such things as the wsdl file for the web service. The process takes place By providing url on a target web server to discovery tool. The Microsoft.Net framework provides a tool named disco.exe to enable web service discovery. In addition, VS.net has integrated support for web service discovery using the concept of web references. The structure of DISCO document: <?xml version=1.0?> <disco:discovery xmlns:disco=http://schemas.xmlsoap.org/disco xmlns:wsdl=http://schemas.xmlsoap.org/disco/wsdl> <wsdl:ContractRef ref=http://jdc72000cte/services/ctemp/ctem.asmx?wsdl /> </disco:discovery> It is possible to distribute DISCO documents to centralized web service directories, which can be used to more easily locate web services. Enabling discovery of web service is optional. Finding web services: As more and more web services are created and deployed by numerous organization on the Internet, it will become increasingly more difficult for consumers to find these services. Similar to search engine approach that is used to query and locate web pages, the Universal description, discovery, and integration (UDDI) specification defines a logically centralized but physically distributed, xml-based registry database and API for companies to find each other and the web services that they offer. The UDDI is located at http://www.uddi.org. It provides a browser-based interface for registering your company and services as well as the capability to lookup potential business partners. UDDI defines, classifies and stores three basic types of information: White pages: describe address, contact, and other standard business demographic information Yellow pages: describe industrial categorizations for businesses based on standard categories Green pages: describes the technical specification for web services

Microsoft is uddi as a core building block in the .net platform. Finding web services with DISCO tool: The .net framework provides a tool named disco.exe to locate web services at a given url and copy web service descriptions that it finds to local hard drive. The output of disco tool is typically used as input to wsdl tool to create a proxy class with which to consume the web services. The location of disco tool is: Program files\microsoft.net\frameworksdk\bin

The disco tool supports the command line options: /d[omain]:domain :specify user credentials to proxy server that requires authentication /nosave: do not save and throw the result /nologo: elimintate Microsoft startup banner /o[ut]:directoryname: specifies the folder where the discovered documents will be saved /p[assword]:password: specifies the password to use when connecting with proxy server /proxy:URL specifies the url of proxy server to use for http requests. Files created by disco tool: .wsdl, and .disco and .discomap Microsoft Hailstorm: Major software vendors are planning to deliver a horizontal set of useful web services that will be needed by many next-generation web-based applications. The Microsfot Hailstorm collect and store personal information that can be shared with other applications and services based entirely on consent and control. Hailstorm promises to eliminate the frustration of having multiuser names and passwords and lack of control over personal information and replace with a single source for these data. 7. state management Http is a stateless protocol. This means that http does not retain any information or knowledge from one request to the next even though those requests may come from the same user session and may even be related to each other. Asp.net provides both application state and session state management capabilities for web applications. Application state is used to store data that applies to the applications as a whole and is available to all sessions using the application. Session state is used to store data that is specific to each browser session using the application. Session state is not visible across different sessions. Both application and session state information is stored in key/value dictionary objects. For application state, memory used by application variables are not released between requests. They have concurrency and synchronization issues. It is not shared across a web farm (where an application is hosted on multiple servers) or web garden ( where an application is hosted on multiple processes on a single server) For session state, it can survive IIS and worker-process restarts without losing session state information. It can be used in both web farm and web garden configuration. It can be used even if the client browser does not support cookies. 8. Web service infrastructure:

Web services are built on the foundation of xml, http, and soap. Using these technologies web services enable the creation of distributed applications that can easily leverage the size and diversity of the Internet. Some of the .Net web service namespaces are: System.web.services (build and consume web services) System.web.Services.Description (describe via wsdl) System.web.services.discovery (implement discovery process to locate services) System.web.services.protocols (implement protocols to exchange web service messages) Web service infrastructure: The primary infrastructures of web services are: Web service directories (to locate providers of web services) Web service dictionary ( to locate web services) Web service description ( to describe web service capabilities) Web service wire formats ( to exchange data and messages)

Web service directories provide a centralized, Internet accessible location that consumers can use to find web services that have been offered for use by other companies or organization. You can search for web services using a variety of structured criteria such as business type, industry, type of goods produced, services offered and so on UDDI specification is the defector for cataloging and finding web services

Web service discovery: It is the process of locating one or more related documents that describe a specific web service. These capabilities are described in wsdl, which is an xml grammar specifically designed for this purpose. Before you can submit requests to a web service, you must know how to format requests for a particular service in the form of a message that encodes the operation required. It permits a consumer to search for and locate the wsdl document for web service. The disco specification defines an xml-based grammar and algorithm for discovering the existence of web services and locating their wsdl document. The <contractRef> element is used to link web service wsdl document and <discoveryRef> element is used to link to other discovery documents.

Web service description: A web service description is an xml document that defines the capabilities of a web service. Using wsdl xml grammar, you can clearly and unambiguously define webaddressable entry points in terms of the request messages that a web service will accept as well as the response messages a web service can return. ASP.net supports the dynamic generation of wsdl documents from web service assembly when it is required. This eliminates the issues related to keeping a separate wsdl document in sync with the web service assembly that implements the service. In a nutshell the process works as follows: 1. the client requests the wsdl document using a url of the form http://server/webservicepath/entrypoint.asmx?wsdl 2. the web server maps the request for the asmx file to asp.net runtime 3. the asp.net runtime uses an instance of the webservicehandlerfactory class to process the url 4. the webservicehandlerfactory class obtains the query string and uses classes from the system.reflection namespace to obtain the web service assembly metadata 5. the metadata is then used with classes from the system.web.services. Description namespace to generate and return the wsdl document to the client The process makes it simple for a web service to describe its capabilities to a requesting or potential consumer. The standard method of interacting with a web service is through the use of proxy class. VS and asp.net provides a tool to generate web service proxy class. Web service wire formats: Wire formats define the method by which web service request and response messages are encoded and transported between the web service and any consumer. Http-get: This protocol encodes web service operation requests and arguments in the url to the web service. The operation is coded as part of url string and any arguments are coded as query string parameters appended to base url. http://localhost/ctemp/ctemp.asmx/ctemp?temperature=32&fromunits=f&tounits=c Http-post: this protocol encodes the web service requests and arguments within the payload area of the http-post request as name/value pairs. It is identical with http-get operation except in the way in which the web service call arguments are passed to the server. http-soap: It is the default asp.net web service wire format. It is based on the soap specification and supports the widest range of simple and complex data types. Web service request and response messages are encoded into the soap messages that are included in the payload area of http-post message. Soap messages are encoded in xml using the soap vocabulary defined in specification.

9. Leveraging asp.net features in web services: Supporting transactions: asp.net web services are capable of supporting transactions, just like the automatic transaction support provided for classic com+ components. The asp.net transactions cannot be started by another application and then flow into web service method. That is web services only support transactions that are started by the web service method itself. To enable transaction support you must add transactionoption method. In Vb.net <webmethod(ttransactionoption:=transactionoption.required)> public function ctemp.. In c# [webmethod(transactionoption=transactionoption.required)] public string ctemp

The property options are: Disabled (does not participate in transactions) Notsupported(does not run within the scope of transaction ,even if one is currently pending) Supported(participates in any pending transaction. If a transaction is not pending, the method will execute without one) Required ( if a transaction is pending, the method participates in the transaction, if a transaction is not pending, a new transaction is started) Requiresnew( regardless of the current transaction state, a new transaction is started for the method) The default property is required. Enabling session state: Session state allows web service methods to maintain contextual information between calls. To use the built-in session state support provided for asp.net web services, the webservice class must inherit from either the webservice base class or use the httpcontext class. Session state support for web service is bound to http protocol because it relies on cookie feature. It is disabled by default because it incurs additional overhead that you may not wish or need to use. To enable session support, you must add enablesession property to

10

the webmethod attribute that is used to identify web-callable methods in web service class. Example: In vb.net <webmethod(enablesession:=true)> public function ctemp In c#: [webmethod(enablesession=true)] public string ctemp Web service caching: Asp.net web services support output caching. This permits the result of previous method request to be saved in a memory cahce, to be recalled on subsequent requests without having to re-execute the logic of the method. Output caching is convenient and useful in situations where the data being returned does not change often. This results in potentially large performance gains for the web service when many consumers make requests for the same information. To enable output caching, In VB.net : <webmethod(cacheduration:=120)> public function ctemp In VB.net : [webmethod(cacheduration=120)] public function ctemp Buffering server responses: Response buffering allows the web server to return the response to the consumer all at once, after the response has been completely generated, rather than transmitting it in multiple chunks. It may be beneficial for long-running methods to transmit the response as it is generated. To enable response buffering for web services, In vb.net: <webmethod(bufferresponse:=true)> public function ctemp In c#: [webmethod(bufferresponse=true)] public function ctemp 10. Soap Soap is a lightweight, xml-based protocol for exchanging information in decentralized, distributed environment, such as that offered by the Internet. Soap enables two processes to communicate with each other regardless of hardware and software platforms on which they are running. It has been created and adopted as part of an open process, which has been embraced at an unprecedented level by most of major hardware and software vendors. The soap specification is an open technology that provides the basis for application-to-application integration, known as web services.

11

The fundamental building block of soap is xml. Soap defines a specialized, yet flexible xml grammar that standardizes the format and structure of messages. The benefits of xml in soap are: Xml is human readable, making it easier to understand and debug Xml parsers and related technologies are widely available Xml is open standard Xml includes many related technologies that can be leveraged in soap

The capabilities of soap are: Enables interoperability between systems using standard, widely available protocols such as xml and http Allows systems to communicate with each other through firewalls, without having to open additional, potentially unsafe ports Soap fully describes each data element in the message, making it easier to understand and troubleshoot problems that may occur

Soap does not do the following: Attempt to define how objects are created or destroyed Impose any specific security mechanism or implementation Define an authentication scheme Soap messages can be exchanged over secure socket layer (ssl) which is a standard web protocol that provides a secure, encrypted http connection between the client and server. Soap specification: The soap protocol specification is a w3c submitted note that is now under the umbrella of xml protocols working group. The specification consists of four primary parts: A definition for a mandatory, extensible message envelope that encapsulates all soap data. It is fundamental message carrier A set of data-encoding rules for presenting application-defined data types and a model for serializing data that appears within soap envelope A definition for rpc-style (request/response) message exchange patter. Soap does not require two way message exchanges A definition for a protocol binding between soap and http to describe transmission using http protocol.

Soap message elements: Envelope: servers as a container for remaining soap message elements Header: contains optional data a consumer may or may not be required to understand to process the message properly. This is the primary extensibility mechanism of soap.

12

Body: contains the actual encoding of a method call and any input arguments or an encoded response that contains the results of the method call. Soap envelope: It is a required part of soap message. It servers as a container for all remaining soap messages. Typically, it includes soap header and body elements. Also it defines namespaces used by these elements. Soap header: It is an optional part of soap message. It defines additional information that can be related to method request in the body element. It does not contain specific semantics. Soap body: It is required part of a soap message that contains the data specific to a particular method call, such as the method name and any input/output arguments or the return values produced by the method. Soap envelope
Soap header Soap body

Coding example: <soap:envelope xmlns:xsi=http://www.w3.org/2001/smlschema-instance xmlns:xsd=http://www.w3.org/2001/xmlschema xmlns.soap=http://schemas.xmlsoap.org/soap/envelope/> <soap:header> <authentication xmlns=http://tempuri.org> <username>srm</username> <password>mca</password> </authentication> </soap:header> <soap:body > <ctempresponse xmlns=http://tempuri.org /> <ctempresult>0</ctempresult> </ctempresponse> </soap:body> </soap:envelope> Soap Data type support:

13

It supports in terms of xsd, the xml schema specification. This specification defines standards for describing primitive data types as well as complex, hierarchical structures. In addition to primitive types, user-defined structures can be represented. The .net clr data type can be mapped with xsd data types. Xsd schema definition boolean byte double unisignedShort clr Boolean N/A Dobule UInt16

.net framework and asp.net automatically serialize and deserialize these data structures into xml-encoded element hierarchies that can be carried in the soap message body. Soap exceptions: Soap exceptions are used to return error or exception information to the consumer of a web service as the result of a failed method cal. The soap specification uses the term faults rather than exceptions. Soap exceptions can occur at various stages of processing a web service request. For example, an error may occur at http level before the method call can actually be delivered to web service. In this http response must be returned, using standard http status code numbering conventions. Soap fault codes: 100: version mismatch 200: must understand 300: invalid request 400: application faulted The faultString element contains a string description of the error that occurred. Http as a soap transport: To deliver messages encoded as soap requests, or responses, we need a transport protocol. This transport protocol must be widely available in order to maximize the reach of our web services. The obvious choice of http as the transport protocol makes soap a highly available message format. http is primary transport protocol that is human readable. The structure of soap message contained within http post request: Post/objectURL http/1.1 Soapmethod name Soap envelope Soap header Header1

14

Header2 Soap body Call element Soap in .net framework: Asp.net and .net framework automatically generate and process soap messages for your web service application using a familiar object oriented design approach. Te customization is also possible. Using soap headers: Soap headers are the chief extensibility mechanism offered by soap specification. This feature enables to piggyback metadata along with a method request or response message that can be used by receiver to control, or add additional context to, the method call. User credentials are often added as a soap header to enable a web service method to authenticate a user before allowing the method call to be executed.

.net soap header class in vb.net: imports system.web.services.protocols public class authenticationsoapheader inherits soapheader public username as string public password as string end class in c#: using system.web.services.protocols public class authenticationsosapheader : soapheader { public string username; public string password; } .net soap header attribute:

15

It is used to enable support for soap headers on specific web service methods that are declared with the webmethod attribute. The attributes are membername, direction and required. Example: In vb.net: <soapheader(authsoapheader, direction:=soapheaderdirection.out> In c#: [soapheader(authsoapheader, direction:=soapheaderdirection.out] Using soap extensions: One of the more advanced features of soap within the .net framework is the soap extension technology. Using this technology, you can inspect or modify a soap message at specific stages in message processing on either the client or server. Soap extensions are a powerful features, because they enable you to implement some very interesting applications that can be leveraged by web services and/or their clients in a completely transparent manner. For example, you can create extensions that do the following: Encrypt messages to protect the contents while in transit Compress messages to reduce the size of the transmission stream Log messages for auditing or tracing message activity (for debugging) Process soap attachments

.net framework exposes this functionality through the following base classes that you can derive from to create custom soap extensions: System.web.services.protocols.soapextension System.web.services.protocols.soapextensionattribute

Handling soap exceptions: In vb.net: Dim div as new mywebservice Dim z as integer Try Z=div.divide(1,0) Catch err as soapexception Strerror=web method caused an exception End try In C#: Public mywebservice div = new mywebservice; Int z; Try{ Z=div.divide(1,0); } 16

Catch(exception e) { strerror=web method caused an exception; } Microsoft Toolkit features: The Microsoft soap toolkit supplies the technologies and tools needed to build and deploy web services using Visual Studio 6.0 as the development environment along with the familiar com programming model. The toolkit is free and fully supported sdk that you can down from msdn web site. Toolkit features: Contain both client and server side com components and development tools Server side component that maps web service request to com object method calls described by wsdl and web service meta language documents Client side component that enables a consumer to call web services described by wsdl document Components that generate, transport and process soap messages A wsdl/wsml document generator tool A vb add-in that simplifies the processing of xml documents contained in soap messages Additional APIs utilities and sample applications that illustrate how to use the soap toolkit to build web service and consumer applications. Soap tool kit provides two choices for providing a soap listener for the Internet information server (IIS) : ISAPI and ASP listener. The advantages of ISAPI listener are that it is faster than the asp listener and does not require implementing any code. If you need to parse or validate input arguments, perform security checks or execute similar actions on an incoming request, you must use asp listener. 11. Building web service: Asp.net web service development requirements: Personal workstation with .net framework sdk installed Development web server that is configured to host and run development version of web service Production web server that is configured to host the final run-time version of web service

Creating web service application: 1. Create a directory under web server root directory named ctemp 2. From windows 2000 start menu, choose settings control panel 3. double click the administrative tools icon 17

4. Within administrative tools group, double click the internet services manager icon. This will display Internet Information Services window. 5. In the Internet Information services window, drill down to the default web site on local computer. You should see a list of virtual directories. 6. From the action menu, choose newvirtual directory. This display the virtual directory creation wizard. 7. Click the next button to continue. This displays the virtual directory alias panel. 8. Enter ctemp as the name of your vitual directory in the text box, 9. click next button to continue. This displays the website content directory panel 10. Enter in the text box the physical path to the ctemp directory you created earlier. 11. Click the next button to continue. This displays the access permissions panel. 12. This panel controls the type of access permitted to users of files referenced by the virtual directory. You can enable one or a combination of choices from the list by toggling the checkbox next to each option. The choices are: a. Read b. Run scripts (such as asp) c. Execute (such as isapi/cgi) d. Write e. Browse Keep the default settings as shown in the permissions panel and click next to continue. This displays the completion panel 13. click the finish button to complete the virtual directory creation wizard. Declare the web service: Add an asp.net webservice directive at the top of ctemp.asmx file, specifying the class implementing the web service and the programming language used for implementation code. The web service declarations In vb.net: <%@ webservice language=vb codebehind=ctemp.vb class=temconverter %> In c#: <%@ webservice language =c# codebehind=ctemp.cs class=tempconverter %> Web service files: The simplest of asp.net web services can be built using only an asmx file in a web application directory. More sophisticated and flexible web services can be built by leveraging features of asp.net and .net framework. Asp.net web service files are: Service name.asmx

18

Service name.asmx.vb Service name.asmx.cs Web.config Global.asax Global.asax.vb Service name.vsdisco Bin\service name.dll Implementing web services: Write code to implement web service. Web service declaration and class definition in ctemp.asmx file: Vb.net: <%@ webservice language=vb class=tempconverter %> imports system imports system.web.services public class tempconverter . End class

C#: <%@ webservice language=c# class tempconverter %> using system; using system.web.services; public class tempconverter : webservice {..} Web service attribute: The web service attribute is optional attribute that can be added to web service class declaration to configure various properties for the class. The webservice attribute can be added to the front of the class declaration as follows: <webService()> public class tempconverter The attributes are: Description : about the functionality Namespace: provide unique xml namespace for wsdl document Name: overrides the web service name, normally taken from class name Creating web methods:

19

In vb.net <webmethod()> public function ctemp(byval temperature as decimal, byval fromunits as string, byval tounits as string) as decimal . End function In c#: [webmethod] public decimal ctemp(decimal temperature, string fromunits, string to units) {.} Webmethod attributes are: Description: describe the functionality Enablesession: enables session state so that the state can be maintained between method calls message name: used to provide an alias name for web methods. This is typically required when implementing polymorphic methods in a class. Transaction option: allows the web method to support transactions Cacheduration: enables output caching so that the results of particular method call Can be saved to a cache and reused, rather than regenerated Bufferresponse: permits the server to buffer the response and transmit it only After the response has been completely generated. Handling errors: .net framework via clr, provides an excellent support for handling errors via exceptions. Applications built on .net framework can throw and catch exceptions to handle all types of run time errors. This support is also available to web services. Building web services: Asp.net will build web service and cache the application code for future reference. Each subsequent request for web service will then be handled by cached executables. If asp.net runtime is restarted, the cache is lost and next request for web service will result in build and cache process being repeated. The automatic build capability of asp.net is flexible and another example of asp.net features. 12. Testing and debugging web service: The .net framework provides a quick and simple method to test the web service. Specifically you can test the web service using web browser and http-get protocol.

20

Testing with http-get: Using a web browser to test web service with http-get protocol does not require to develop a consumer application. Therefore, this is a quick and easy way to perform some initial testing of web service. The http-get protocol encodes data as query string parameters when posting to the server. This encoding method is used to pass the proper method input arguments as query string arguments. Two way exists to invoke the http-get protocol using web browser to test web service. You can use built-in test page offered by asp.net runtime or you can encode the complete url to web service using location, method, name and any input arguments as query string parameters in address bar of browser. Using web service test page: The asp.net runtime provides excellent support for interactive viewing of web service information and capabilities, as well as basic html forms for performing interactive tests using http-get protocol support built into browser. The web service help file template named defaultwsdlhelpgenerator.aspx is located in \winnt\microsoft.net\framework\version\config folder. To view the help page of ctemp web service, type the following url: http://localhost/ctemp/ctemp.asmx This page shows us the name of web service, the methods that it supports and a link to web service wsdl document. The second part of this page includes a warning regarding the use of temporary namespace uri http://tempuri.org/ for our service. Viewing wsdl service contract: To view wsdl service contract, simply click the service description hot link on web service help page. This will display the wsdl xml file contents. Note that the url in address bar of browser window as http://jdc72000cte\ctemp\ctemp.asmx?wsdl The query string instructs the asp.net to generate and display the wsdl service contract for specified web service. This type of feature is called reflection, which basically menas that a .net class can be queried to obtain information about properties, methods, events and other features it offers via its programmatic interfaces.

21

Viewing web method help: Click the ctemp method hot link. This display a browser page. Note the url that appears in address bar of browser windown http://jdc7200cte/ctemp/ctemp.asmx?op=ctemp This query string instructs the iis web server to display a page that contains detailed information about web service method specified as the value part of query string argument. The first part of the web method help page contains a hot link that will return you to the main web service documentation page. Underneath this link is a simple form that permits to invoke the web service method. The second part of web method documentation page contains sample soap http-get and http-post request and response message definitions. To invoke manually: http://localhost/ctemp/ctemp.asmx/ctemp?temperature=78&fromunits=f&tounits=c Testing with http-post: It is similar to http-get protocol. It encodes data as name/value pairs within the body of http request when posting to server, rather than encoding data in the form of query string, as does http-get.The steps are: 1. copy winnt\microsfot.net\framework\version\config\defaultwsdlhelpgenerator.aspx to ctemp web service virtual directory 2. rename file as ctemp.aspx 3. edit ctemp.aspx with text editor 4. change showpost flag to true 5. save changes to file 6. create text file name web.config in ctemp virtual directory with text editor 7. add the following text to web.config file <?xml version =1.0 encoding=utf-8 ?> <configuration> <system.web> <webservices> <wsdlhelpgenerator href=ctemp.aspx /> </webservices> </system.web> </configuration>

22

8. save the changes to the file You can test ctemp method using http-post protocol: http://localhost/ctemp/ctemp.asmx Debugging the web service: The .net sdk debugger, named dbgclr.exe, is located in the .net sdk installation folder, which is typically found at programfiles\microsoft.ent\frameworksdk\guidebug. Enabling debug mode for asp.net web services: It is required to instruct asp.net runtime to compile the application with additional information <?xml version =1.0 encoding=utf-8 ?> <configuration> <system.web> <compilation debug=true /> </system.web> </configuration> Starting asp.net runtime: Open IE and type: http://localhost/ctemp/ctemp.asmx Debug ctemp web service: The .net sdk debugger is gui debugging tool, that can be found at programfiles\microsfot.net\frameworksdk\guidebug\dbgclr.exe. Starting the .net debugger application displays the window as: 1. Select file open file. This displays the open file dialog box 2. navigate to inetpub\wwwroot\ctemp folder. Select ctemp.asxm file and click open button. This loads the ctemp web service code into the main debugger window. 3. Select toolsdebug processes. This displays the processes dialog box. 4. Check the box labeled show system processes, if it is not already checked. 5. Select aspnet_wp.exe entry from list of processes and click attach button 6. click close button to close processes dialog box The .net debugger is now configure to debug web service To set a breakpoint in web service code, simply point mouse to the left margin of code window in the .net debugger application and click the line on which you would like to set

23

a breakpoint. It is represented by red circle in the code margin adjacent to appropriate line of code. Examine program variables by ? temperature Resume method execution by choosing debug continue .net debugger window. 13. Deploying and publishing web services: Before deployment, you must make sure that the web service specifies a unique xml namespace. This namespace is used within the web service wsdl document to uniquely identify the callable entry points of service. Web service namespaces: The namespace that you choose to identify web service must be unique. Typically, using your Internet domain name as part of web service namespace will guarantee uniqueness and also more readily identify the owner of web service. Asp.net web services support a namespace property as part of web service attribute used to identify the class that implements the functionality of web service. Vb.net: <%@ webservice language=vb class=tempconverter %> imports system imports system.web.services <webservice(namespace:=http://mydomain.com/ctemp/)> public class tempconverter . End class C#: <%@ webservice language=c# class tempconverter %> using system; using system.web.services; [webservice(namespace:=http://mydomain.com/ctemp/)] public class tempconverter : webservice {..} Deploying web services: It enables the web service to execute on a target web server. The deployment process invovlves copying web service entry point file (asmx file), web service assembly along with any dependent assemblies and supported files. Files deployed with web service:

24

\inteput\wwwroot\projectname\servicename.asmx global.asax web.config \inetpub\wwwroot\projectname\bin\servicename.dll Web service deployment tools: Visual studio web setup project, visual studio project copy and dos xcopy command Deployment using web setup project: Advantages is that the installation package automatically handles any registration and configuration issues that web service may depend upon, relieving you of this burden: 1. 2. 3. 4. create a web setup project using web setup project template in visual studio build the project copy the installation package to target web server run the installation package on target web server

The user has opportunity to specify alternate virtual directory target and setup creates new virtual directory and configures it. Deployment using project copy: It is simpler deployment method, but does not perform virtual directory configuration or registrations that may be necessary for web service. The feature is available by choosing Project copy project in visual studio.net. The following are the three options available for copying files: Only files needed to run application All project files All files in the source project folder Deployment using xcopy: The DOS xcopy command is the simplest method for deploying a web service to a target web server. It does not create or configure virtual directories, nor does it register or configure any dependent assemblies outside of .net framework. Publishing web services: Publishing web services enables potential consumers to locate interrogate service descriptions that instruct the consumer on how to interact with web service. The process

25

of locating and interrogating web service descriptions is referred as discover process. The two methods for enabling discovery process are: DISCO and UDDI. If consumer population is fairly small and simply point them to target web server then deploy disco file on server. The consumer will invoke the discovery process against url of target server and locate web service description. If consumer population is relatively large or unknown then you will need to provide a mechanism for consumers to find where your disco and web service descriptions are located just as web users utilize search engines to find web pages. 14. Consume web applications: Web service consumer overview: A web service consumer is any application that references and uses a web service. A web service consumer can take many forms: client application, server application, component or event another web service. The type of consumer does not matter as long as it has the capability to communicate with web services using http and soap. To consume a web service, do the following: Find web service Obtain its wsdl service contract Generate proxy class with which to call web service Create an instance of proxy class Call the methods exposed by proxy

Web service proxies: The proxy class mimics the interface of actual web service and takes care of formatting appropriate soap messages to actual web service to deliver requests to web service as well as process the responses that come back By generating and using a proxy class, we can reach web service via http and soap. The benefit of proxy class is that we can create an instance of the class and call its methods just like native .net assembly. The http and soap plumbing required to call web service methods is completely hidden from us within the proxy class. This greatly broadens the reach of component to many different platforms, not just windows platforms alone. Creating the consumer application: To create a consumer application, first create the virtual directory on local web server. After that begin the process of building first web service consumer application.

26

Obain wsdl document: Either use .net disco tool or IE web browser to obtain wsdl document. The .net disco tools is good choice if you know atleast the url of target web server and web service directory has been enabled through the use of one or more disco documents on target web server. IE is good choic if you know the exact url of web service entry point, the web service is an asp.net web service or web service directory via disco is not possible because on disco documents are available for the service. Generate proxy class: The .net framework sdk includes wsdl tool to generate proxy classes from wsdl documents. The web service proxy class with .net supported languages are created. The proxy class can then be used by consumer application to make request against web service using a local class that hides all low-level details of communication that takes place using http and soap. Open command window, and type > cd c:\inetpub\wwwroot\ctempclient Also type wsdl/l:vb /o:ctempproxy.vb /n:ctemproxyctemp.wsdl Build web form: For asp.net web forms application, use text boxes, radio buttons and command buttons to input temperature and conversion requisition. Create instance of proxy class: To call methods of proxy class that represents the web service, create an instance of proxy class. It is done by simply referring the class definition in declaration. Add the following line at top of ctempclient.aspx file: <% @ import namespace=ctempproxy %> Add code that will handle onclik event of btncovert server control. In vb.net: <script language=vb runat=server> sub btnconvert_click(sender as object, e as eventargs) dim tc as new tempconverter() txtoutputtemp.text = format(tc.ctemp(ctype(txtinputtemp.text, decimal) optfromunits.selecteditem.value, optotunits.selecteditem.value), fixed) end sub </script>

27

Calling ctemp proxy method To call a web service method on proxy class, specify the name of the method to call using the reference to the instance of proxy that we declared. In vb.net Txtoutputemp.text = format(tc.ctemp(ctype(txtinputtemp.text, optfromunits.selecteditem.value, opttounits.selecteditem.value), fixed) Testing the consumer application: To test the application, simply start an instance of IE web browser and type the following URL into the address bar: http://localhost/ctempclient/ctempclient.aspx To test the application, enter temperature value in the first text box, select source units, select target units and then click the converts to button. The web form is submitted to server, where the click event code of button is executed. This code creates an instance of ctemp proxy class, calls the ctemp method, and outputs the conversion results to the target temperature text box. 15. Application Execution Model: The consumer application is started when a user requests the main form of application. 1. a user requests the main form of ctempclient application, such as http://localhost/ctempclient/ctempcleint.aspx 2. the IIS web server on localhost receives the request and hands it off to the asp.net runtime for execution of page. 3. The asp.net runtime creates an instance of page class that represents the web form and executes the page 4. The page class generates the html and sends it to the browser, causing the form to be rendered in users browser window. 5. The page class is then destroyed by asp.net runtime along with any other necessary request cleanup processing. 6. The user enters information into the form and presses the convert to button. This causes the form to be posted back to the web server. 7. Again, the web server hands off the request to asp.net runtime, which creates a new instance of page class that implements the web form and executes the page. 8. This time the server-side button controls click event code is now executed. Recall that this is where we added our code to create and call the ctemp web service. decimal),

28

9. The click event code creates an instance of ctemp web service proxy class. This class inherits from sytem.web.services.protocols.sopahttpclientprotocol class. This provides the foundation for communicating the method request and response via soap messages over the http transport. 10. The click event code now calls the synchronous ctemp method on the proxy object, passing the input arguments obtained from the postback data of the form. 11. The web service proxy calls the invoke method, passing along the input arguments. This method serializes ctemp method call into soap message that matches the method signature defined in wsdl document. 12. The IIS web server that hosts the ctemp web service receives the request and hands it off to the asp.net runtime to execute the requested page. 13. The asp.net runtime deserializes the soap payload from the request, creates an instance of ctemp web service implementation class, and executes the ctemp method, passing the input arguments. 14. Next, the asp.net runtime takes the result of ctemp method call and serializes it into soap response message. This message is then added to payload of http response and delivered back to client. 15. The invoke method of proxy class deserializes the result from soap response message into generic .net object type. This type is then explicityly cast to the return data type expected by caller and returned to consumer application 16. The click event code in our consumer application takes the result, converts it to the string data type, and assigns the result to output text box in web form, formatted to two decimal places. The event code processing is now completed and page execution continues. 17. The page now executes through its rendering phase to generate html that is returned to users browser. The page class is then torn down by asp.net runtime and any other cleanup processing that is necessary is executed.

29