Web Services Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz Dr. Dietrich Birngruber Software Architect TechTalk www.techtalk.at © University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License Web Services Introduction Web Services in .NET SOAP SOAP and .NET Service Description with WSDL Discovery of Web Services: UDDI and DISCO Preview of Web Services .NET 2.0 Summary Motivation • Integration of heterogonous, distributed systems – globally distributed – different programming languages – different APIs • B2C and B2B applications • Usage of globally distributed services Example: Travel Agent Service taken from: Web Services Architecture Usage Scenarios, W3C Working Group Note, 11 February 2004, http://www.w3.org/TR/2004/NOTE-ws-arch-scenarios-20040211/ 3 What are Web Services? • Middleware for distributed applications • For remote procedure calls und data exchange • Open standard based on XML • For loosely coupled software services • Independent of programming languages and operating systems • Utilizing existing Internet protocols and server architectures 4 Definition Web Service (by W3C) • Software application identified by URI • interface description in XML • with interaction on the basis of XML encoded messages • and message exchange on the basis of Internet protocols 5 Independence and Integration through ... • SOAP – XML standard for message encoding – independent of transport protocol – independent of client and server implementations: Java, .NET, Python, … • Web Services Description Language - WSDL (1.1) – Interface description in XML • communication on the basis of existing protocols and server architectures – HTTP and Web server – SMTP and mail server – FTP and FTP server • Standardisation (W3C) – SOAP 1.2, WSDL 1.1 (1.2 und 2.0) – additional protocols based on SOAP and WSDL – protocol bindings (HTTP) 6 Web Services Scenario Web Service A script client SOAP HTTP Java client SOAP HTTP .NET client SOAP HTTP WebService C ... client SOAP protocol X web server + Java web service container Web Service B SOAP HTTP IIS (.NET web service container) SOAP SMTP Web Service D SOAP SMTP e-mail server + SOAP processor SOAP protocol remote procedure call 7 Web Services in Comparison Java RMI .NET Remoting CORBA Web services Programming language Java .NET languages (C#, VB.NET, ..) independent independent Interface definition Java Interfaces C# Interfaces CORBA IDL WSDL (XMLbased) Data structures Java objects .NET objects IDL-specified objects XML data Transport protocol RMI-IIOP binary or OAP GIOP/IIOP HTTP, HTTPS, SMTP, FTP Packaging Java object serialisation .NET object serialisation ORB/CDR SOAP Infrastructure Java RMI infrastructure .NET remoting infrastructure ORBs Web, Mail, FTP server 8 Pros and Cons • Pros – independent of programming language, run time environment and operating system – Built on existing Internet infrastructure – standardized – promoted from important players (Microsoft, IBM, SAP, Sun) • Cons – performance (XML) 9 Web Service Infrastructure Discover Services What services do exist? Where are they? (URL) E.g.: UDDI, DISCO client(s) Servide Description (in WSDL) What message does the service know and how are those called? Service Calls Using services via SOAP, HTTP, XML-RPC, ... Web Service + container 10 Web Service Architecture Discovery service WSD1 URL1 WSD2 URL2 ... ... sh se a bli rc h pu Web service container Client inquiry call Web Service 11 Web Service Architecture (2) Discovery service WSD1 URI1 WSD2 URI2 ... ... sh se a bli rc h pu service inquiry (URI) service description (WSD) Client service call (SOAP) result: SOAP service inquiry Web service container service description (WSD) Web service service call result 12 Web Services Introduction Web Services in .NET SOAP SOAP and .NET Service Description with WSDL Discovery of Web Services: UDDI and DISCO Preview of Web Services .NET 2.0 Summary Web Services in .NET • IIS and ASP.NET infrastructure support web services • .NET Framework provides several – base classes – attributes – protocols for the realization of web services • Visual Studio.NET provides powerful tools for developing web services – – – – implementation testing administration of IIS generation of proxy code (wsdl.exe) 14 .NET Namespaces • System.Web.Services – for developing web services (e.g.: WebService, WebMethod) • System.Web.Services.Configuration – for extending SOAP • System.Web.Services.Description – for creating and manipulating WSDL descriptions • System.Web.Services.Discovery – for using DISCO • System.Web.Services.Protocols – for implementation of communication protocols (e.g. SOAPHTTP) • System.Xml.Serialization – for XML serialization 15 Implementation of Web Services • in asmx-file with @WebService directive <%@ WebService Language="C#" Class="MyWebService" %> • deriving from base class System.Web.Services.WebService public class MyWebService : WebService { • Identification and settings by .NET attributes – – – – identification of web service methods definition of format and encoding XML namespaces and element names to use etc. [WebMethod(Description= “comment ")] […] public Returntype MyWebMethod( …) { … 16 Example: TimeService TimeService.asmx <%@ WebService Language="C#" Class="TimeService" %> WebService directive using System; using System.Web.Services; public class TimeService : WebService { [WebMethod(Description="Returns the current time")] public string GetTime(bool shortForm) { if (shortform) return DateTime.Now.ToShortTimeString(); else return DateTime.Now.ToLongTimeString(); } deriving from WebService Attribute [WebMethod] identifies web service method } 17 Example: Simple .NET Client • wsdl.exe generated proxy for client (TimeClient.TimeService) > wsdl.exe /namespace:TimeClient /out:TimeServiceProxy.cs http://localhost/netsem-ws/MyFirstService.asmx • Client program creates TimeService object and calls GetTime using System; using TimeClient; //Namespace des erzeugten Proxies public class NetClient { public static void Main(string[] args) { TimeService service = new TimeService(); Console.WriteLine("Die Zeit am Server ist: "); string time = service.GetTime(true); Console.WriteLine(time); } } 18 Example: Simple Java Client • Using GLUE tool + Java libraries: – wsdl2Java create Java interface (ITimeServiceSoap) and proxy (TimeServiceHelper) import Kapitel7.GLUEProxy.*; // import generated GLUE proxy classes /** Simple XML web service client in Java using GLUE */ public class JavaClientGLUE { public static void main(String[] args) { try { // Calling service using class and interface generated by wsdl2java ITimeServiceSoap service = TimeServiceHelper.bind(); String time = service.GetTime(true); System.out.println(“The time on the server is: \n" + time); } catch (Exception ex) { ex.printStackTrace(); } } } 19 Web Services Introduction Web Services in .NET SOAP SOAP and .NET Service Description with WSDL Discovery of Web Services: UDDI and DISCO Preview of Web Services .NET 2.0 Summary SOAP • Simple message protocol in XML – for packaging arbitrary application data – single messages only („one-way“) – asynchronous • Independent of transport protocol • SOAP does not define: – – – – distributed object model communication protocol distributed garbage collection distributed events (distributed callbacks) 21 Application of SOAP • SOAP is extendable – – – – method call protocol (RPC) security authentication etc. • Protocol realisation by combination of messages (message exchange patterns) – one-way, request-response, multicast, … e.g.: request-response for RPC by 2 messages Client 1: GetTime_Request 2: GetTime_Response Server 22 SOAP Messages SOAP messages comparable to letters with <Envelope> <Header> Message Header Message Header <Body> • envelope (<Envelope>) as container • letter head (<Header>) with meta information (Message Headers) • letter (<Body>) Data • with arbitrary XML data <Fault> Fault Descriptions • fault descriptions 23 XML Structure (simplified, SOAP 1.2) <?xml version="1.0" ?> <soap:Envelope xmlns:soap="..."> <soap:Header> <!-- (optional and extendable) --> <m:my xmlns:m="anURI" soap:mustUnderstand=“true" soap:role=“uri2" /> ... </soap:Header> <soap:Body> data (depends on encoding and format) <soap:Fault> <soap:Code>...who is responsible?... </Code> <soap:Reason>...textual description...</soap:Reason> <soap:Detail>...more error details...</soap:Detail> </soap:Fault> </soap:Body> </soap:Envelope> 24 Data in <Body> Part • Message format: – document structure defined by XML schema – rpc structure defined by SOAP for RPC • Data encoding: – literal encoding defined by XML schema – encoded encoding defined by SOAP encoding rules • Usual combinations: – document/literal standard in .NET – rpc/encoded often used by Java servers 25 HTTP Binding • HTTP-GET, HTTP-POST – call encoded in HTTP (URL encoded) – response encoded in XML Restricted to simple calls (no headers, no structured data) • SOAP over HTTP-POST – data part of POST request contains SOAP encoded call – response SOAP encoded No restrictions 26 Example: HTTP-POST Call of GetTime(bool shortForm) of web service http://localhost/time/TimeService.asmx • Call : http://localhost/time/TimeService.asmx/GetTime?shortForm=true • HTTP response: HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/">string</string> 27 Example: SOAP over HTTP (1) • SOAP over HTTP-POST: POST /time/TimeService.asmx HTTP/1.1 Content-type: text/xml; charset=utf-8 SOAPAction: http://dotnet.jku.at/GetTime Content-length: 198 User-Agent: Java1.4.0 Host: localhost Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2 Connection: keep-alive HTTP-header SOAPAction identifies SOAP-request <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <GetTime xmlns="http://tempuri.org/" <shortForm> true </shortForm> < /GetTime> </soap:Body> </soap:Envelope> Web method Parameter 28 Example: SOAP over HTTP (2) • SOAP encoded response: HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap=http://schemas.xmlsoap.org/soap/envelope/ xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd="http://www.w3.org/2001/XMLSchema"> Return <soap:Body> <GetTimeResponse xmlns="http://tempuri.org/"> value <GetTimeResult>string</GetTimeResult> </GetTimeResponse> </soap:Body> </soap:Envelope> 29 Web Services Introduction Web Services in .NET SOAP SOAP and .NET Service Description with WSDL Discovery of Web Services: UDDI and DISCO Preview of Web Services .NET 2.0 Summary SOAP and .NET .NET provides support for – defining message format and encoding – encoding of .NET data types – development of message headers – life cycle management 31 Message Format and Encoding (1) [SoapRpcMethod(Use=SoapBindingUse.Encoded Action="http://dotnet.jku.at/Sample/AddAddressRpc“, // SOAP action RequestNamespace="http://dotnet.jku.at/Sample/Request", RequestElementName="AddAddressRpcRequest", // SOAP element name ResponseNamespace="http://dotnet.jku.at/Sample/Response", ResponseElementName="AddAddressRpcResponse")] // SOAP element name [WebMethod(Description="Adds an address DataSet for the specified user")] public void AddAddressRpc(long userID, Address address) { ... } • Attributes SoapRpcService and SoapRpcMethod for rpc format • with parameters - Use: encoding (SoapBindingUse.Literal or SoapBindingUse.Encoded) Action: URI for SOAPAction-HTTP header RequestNamespace and RequestElementName: namespace and name of SOAP element for request ResponseNamespace and ResponseElementName: namespace and name of SOAP element for response 32 Message Format and Encoding (2) [SoapDocumentMethod(Use=SoapBindingUse.Literal, Action="http://dotnet.jku.at/Sample/AddAddressDocLit", // SOAPAction RequestNamespace="http://dotnet.jku.at/Sample/Request", RequestElementName="AddAddressDocLitRequest", // SOAP element name ResponseNamespace="http://dotnet.jku.at/Sample/Response", ResponseElementName="AddAddressDocLitResponse")] // SOAP element name [WebMethod(Description="Adds an address DataSet for the specified user")] public void AddAddressDocLit(long userID, Address address) { ... } [SoapDocumentService(Use=SoapBindingUse.Encoded)] public class TimeService : WebService { ... } • Attributes SoapDocumentService and SoapDocumentMethod for document format 33 SOAP Encoding of .NET Data Types • Serializing of .NET data types – on the basis of SOAP encoding rules http://schemas.xmlsoap.org/soap/encoding – adjusted by attributes (namespace System.Web.Serialization) SoapAttributeAttribute Serializing field as XML attribute SoapElementAttribute Serializing field as XML element SoapIgnoreAttribute No serialization of field SoapIncludeAttribute Including a type SoapEnumAttribute Adapting name of enumeration 34 Example: Encoding of a Type (1) • Web method GetTimeDesc uses type TimeDesc for return value [WebMethod(Description="Returns the time description of the server")] public TimeDesc GetTimeDesc() { TimeDesc td = new TimeDesc(); // ... return td; } • Encoding of TimeDesc adjusted by attribute [SoapAttribute] fields encoded as XML attributes public struct TimeDesc { [SoapAttribute] public string TimeLong; [SoapAttribute] public string TimeShort; [SoapAttribute (AttributeName = "ZoneID")] public int TimeZone; } 35 Example: Encoding of a Type (2) • SOAP encoded response ... <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ... <soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <types:GetTimeDescResponse> <GetTimeDescResult href="#id1" /> </types:GetTimeDescResponse> <types:TimeDesc id="id1" xsi:type="types:TimeDesc" types:TimeLong="10:00:25" types:TimeShort="10:00" types:ZoneID="1" /> </soap:Body> </soap:Envelope> 36 Including Types • SoapIncludeAttribute allows inclusion of types important for specializations Example: PersonService Web method with return value of type Person[] Person has 2 specializations Customer and Employee public class PersonService : WebService { Person [WebMethod]… public Person[ ] GetAll() {…} } Customer Employee Customer and Employee have to be included explicitly into web service description! 37 Example: PersonService (1) • Classes Person, Customer and Employee public abstract class Person { …} public class Customer : Person { …} public class Employee : Person {…} • PersonService defines web method GetAll with return type Person[] • SoapInclude attribute includes Customer and Employee types <%@ WebService Language="C#" Class="PersonService" %> using System; … using System.Xml.Serialization; public class PersonService : WebService { [WebMethod] [SoapRpcMethod] [SoapInclude(typeof(Customer)), SoapInclude(typeof(Employee))] public Person[] GetAll() { Person[] data = new Person[2]; data[0] = new Customer("1“, "Max Customer", "EMP-33"); data[1] = new Employee("EMP-33", "Tom Employee"); return data; } } 38 Example: PersonService (2) • SOAP encoded response <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ... > <soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <tns:GetAllResponse> <GetAllResult href="#id1" /> </tns:GetAllResponse> <soapenc:Array id="id1" soapenc:arrayType="types:Person[2]"> <Item href="#id2" /> <Item href="#id3" /> </soapenc:Array> <types:Customer id="id2" xsi:type="types:Customer"> <SSN xsi:type="xsd:string">1</SSN> <Name xsi:type="xsd:string">Max Customer</Name> <EmpSSN xsi:type="xsd:string">EMP-33</EmpSSN> </types:Customer> <types:Employee id="id3" xsi:type="types:Employee"> <SSN xsi:type="xsd:string">EMP-33</SSN> <Name xsi:type="xsd:string">Tom Employee</Name> </types:Employee> </soap:Body> </soap:Envelope> 39 SOAP Header Entries • SOAP header entries are used for metainfos in messages • Arbitrary header entries are possible • All header entries have attributes – recipient of entry (Actor) – if it must be handled by recipient (mustUnderstand) • .NET supports header entries by: – Class SoapHeader: development of header entry classes – Attribute SoapHeaderAttribute: Defining header entries for web methods 40 Classes SoapHeader and SoapHeaderAttribute SoapHeader //----- properties public string Actor { get; set; } public bool MustUnderstand { get; set; } public bool DidUnderstand { get; set; } ... • Recipient public string Actor {get; set;} • Header must be handled public bool MustUnderstand {get; set;} • Header handled successfully SoapHeaderAttribute //----- properties public SoapHeaderDirection Direction {get; set;} public string MemberName {get; set;} ... • In-, Out-, InOut direction of headers public SoapHeaderDirection Direction {get; set;} • Name of field of web service class for header entry public string MemberName {get; set;} public bool DidUnderstand {get; set;} 41 Example: AuthHeader (1) User indentification in TimeService – Login returns identification code (cookie) – GetTime sends back identification code in header entry • Header class AuthHeader defines public field cookie public class AuthHeader : SoapHeader { public string cookie; } • Web service class defines field curUser to store AuthHeader object [WebService(Namespace="http://dotnet.jku.at/time/")] public class HeaderTimeService : WebService { public AuthHeader curUser; • Login with user and password returns identification string [WebMethod (Description="Authenticates the user")] public string Login(string user, string pwd) { ... create cookie ... } bool ValidateCookie(string cookie) { ... validate cookie ... } 42 Example: AuthHeader (2) • • GetTime requires header entry of type AuthHeader which will be stored in field curUser Validates user based on login data [WebMethod(Description="Returns the current time")] [SoapHeader("curUser")] public string GetTime() { if (curUser != null && ValidateCookie(curUser.cookie)) return System.DateTime.Now.ToLongTimeString(); else throw new SoapHeaderException("Access denied!", SoapException.ClientFaultCode); } 43 Example: AuthHeader (3) • Client – creates service proxy and AutHeader object HeaderTimeService proxy = new HeaderTimeService(); AuthHeader entry = new AuthHeader(); – receives cookie from call to Login entry.cookie = proxy.Login(user, pwd); – sets the AuthorHeader in proxy – calls GetTime with AuthHeader header entry entry.cookie = proxy.Login(user, pwd); proxy.AuthHeaderValue = entry; Console.WriteLine(proxy.GetTime()); <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://..." ... > <soap:Header> <AuthHeader xmlns="http://dotnet.jku.at/time/"> <cookie>aewt12348cvNNgrt55</cookie> </AuthHeader> </soap:Header> <soap:Body> <GetTime xmlns="http://dotnet.jku.at/time/" /> </soap:Body> </soap:Envelope> 44 Life Cycle • Web service objects are stateless • Are created for each call • Data can be stored in properties of – Application state object or public HttpApplicationState Application {get;} – Sesssion state object public HttpApplicationState Session {get;} public sealed class HttpSessionState : ICollection, IEnumerable { public object this[ string name ] {get; set;} public object this[ int index ] {get; set;} … } 45 Example: StateDemo (1) Web service StateDemo demonstrates storage of data <%@ WebService Language="C#" Class="StateDemo" %> using System.Web.Services; [WebService(Namespace="http://dotnet.jku.at/StateDemo/")] public class StateDemo : WebService { • IncApplication increases property "Hit" of Application state object [WebMethod()] public int IncApplication() { int hit = (Application["Hit"] == null) ? 0 : (int) Application["Hit"]; hit++; Application["Hit"] = hit; return hit; } 46 Example: StateDemo (2) • Parameter EnableSession enables usage of Session object • IncSeesion increases property "Hit" of Session state object [WebMethod(EnableSession=true)] public int IncSession() { int hit = (Session["Hit"] == null) ? 0 : (int) Session["Hit"]; hit++; Session["Hit"] = hit; return hit; } } 47 Web Services Introduction Web Services in .NET SOAP SOAP and .NET Service Description with WSDL Discovery of Web Services: UDDI and DISCO Preview of Web Services .NET 2.0 Summary Web Service Description Language (WSDL) • • WSDL is an XML based IDL for web services a WSD describes: – – – – – used data types structure of messages operations (methods) protocols to call operations addresses of web service current version in .NET: WSDL 1.1 (http://schemas.xmlsoap.org/wsdl/) Working Draft: WSDL 2.0 (10/4/2004) 49 Structure of WSDL 1.1 <definitions> <types> </types> <message> <part> </part> </message> <portType> <operation> <input> <output> </operation> </portType> <binding> <operation> </binding> <service> <port> </service> </definitions> WSDL description of a web services types defined in <xsd:schema> simple messages parts of messages interface specification operations of an interface input message output message abstract part binding of interface to protocols and encoding description of the binding for each operation service description URI and binding to port concrete part 50 Example: WSDL for TimeService (1) • WSDL description created by web container (IIS) http://localhost/WebProject1/TimeService.asmx?WSDL <?xml version="1.0" encoding="utf-8"?> <definitions xmlns:soap=http://schemas.xmlsoap.org/wsdl/soap/ xmlns:tns="http://dotnet.jku.at/time/" xmlns:s="http://www.w3.org/2001/XMLSchema“ xmlns:http="http://schemas.xmlsoap.org/wsdl/http/“ xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/“ xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/“ targetNamespace="http://dotnet.jku.at/time/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <types /> <message name="GetTimeSoapIn" /> <message name="GetTimeSoapOut"> <part name="GetTimeResult" type="s:string" /> </message> <portType name="TimeServiceSoap"> <operation name="GetTime"> <input message="tns:GetTimeSoapIn" /> <output message="tns:GetTimeSoapOut" /> </operation> </portType> … abstract part 51 Example: WSDL for TimeService (2) … <binding name="TimeServiceSoap" type="tns:TimeServiceSoap"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc" /> <operation name="GetTime"> <soap:operation soapAction="http://dotnet.jku.at/time/GetTime" style="rpc" /> <input> <soap:body use="encoded" namespace="http://dotnet.jku.at/time/“ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" /> </input> <output> <soap:body use="encoded" namespace="http://dotnet.jku.at/time/“ concrete encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" /> part </output> </operation> </binding> <service name="TimeService"> <documentation>Simple web service for querying the time</documentation> <port name="TimeServiceSoap" binding="tns:TimeServiceSoap"> <soap:address location="http://localhost/time/TimeService.asmx" /> </port> </service> </definitions> 52 Web Services Introduction Web Services in .NET SOAP SOAP and .NET Service Description with WSDL Discovery of Web Services: UDDI and DISCO Preview of Web Services .NET 2.0 Summary Universal, Description, Discovery and Integration (UDDI) http://www.uddi.org • Standardized protocol for searching for and using web services • Provides web services interface 2.) search 1.) register Directory (UDDI) Client 3.) connect 4.) call Web Service A Web Service B 54 DISCO • Microsoft’s technique for dynamic usage of web services • DISCO file – contains XML document with URIs pointing to web services – can be the result to a UDDI inquiry • .NET support in namespace System.Web.Services.Discovery 55 DISCO Descriptions • Creation of DISCO descriptions: – by command tool disco.exe > disco.exe /out:WebProject1 WebProject1/TimeService.asmx – by IIS http://localhost/WebProject1/TimeService.asmx?DISCO <?xml version="1.0" encoding="utf-8" ?> <discovery xmlns:xsd="http://www.w3.org/2001/XMLSchema„ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance„ xmlns="http://schemas.xmlsoap.org/disco/"> <contractRef ref="http://localhost/WebProject1/TimeService.asmx?wsdl„ docRef="http://localhost/WebProject1/TimeService.asmx„ xmlns="http://schemas.xmlsoap.org/disco/scl/" /> <soap address="http://localhost/WebProject1/TimeService.asmx„ xmlns:q1="http://tempuri.org/" binding="q1:TimeServiceSoap„ xmlns="http://schemas.xmlsoap.org/disco/soap/" /> </discovery> 56 Example: TimeService Discovery (1) • 2 variants of TimeService – TimeService1 <%@ WebService Language="C#" Class="TimeService1" %> using System.Web.Services; [WebService(Namespace="http://dotnet.jku.at/time/", Name="TimeService")] public class TimeService1 : WebService { [WebMethod(Description="Returns the current server time")] public string GetTime() { return System.DateTime.Now.ToLongTimeString(); } } – TimeService2 <%@ WebService Language="C#" Class="TimeService2" %> using System.Web.Services; [WebService(Namespace="http://dotnet.jku.at/time/", Name="TimeService")] public class TimeService2 : WebService { [WebMethod] public string GetTime() { return "I don’t know the time!"; } } 57 Example: TimeService Discovery (2) • Disco client with discovery of DISCO file using System; using System.Web.Services.Discovery; using System.Collections; public class DiscoSample { public static void Main(string[] args) { – loading the DISCO files DiscoveryClientProtocol discoClient = new DiscoveryClientProtocol(); foreach (string uri in args) { discoClient.Discover(uri); } – iterating over all DISCO descriptions discoClient.ResolveAll(); TimeService proxy = new TimeService(); foreach (object obj in discoClient.Documents.Values) { DiscoveryDocument dDoc = obj as DiscoveryDocument; 58 Example: TimeService Discovery (3) – iterating over all <contactRef>-elements and retrieve URLs ContractReference contr = null; IEnumerator it = dDoc.References.GetEnumerator(); while (contr == null && it.MoveNext()) contr = it.Current as ContractReference; – given URL connect to web service and call web method if (contr != null) { proxy.Url = contr.DocRef; Print("Connecting proxy to " + proxy.Url); proxy.Discover(); Print("Result of GetTime: " + proxy.GetTime()); } } } } static void Print(string msg) { System.Console.WriteLine(msg); } } 59 Web Services Introduction Web Services in .NET SOAP SOAP and .NET Service Description with WSDL Discovery of Web Services: UDDI and DISCO Preview of Web Services .NET 2.0 Summary Indigo • Web services in .NET 2.0 are integrated in Indigo • Indigo unites – .NET remoting – Web services – .NET Enterprise Services in one uniform programming model • Indigo provides – – – – – – transactions reliable communication secure communication and authentication independence of transport protocols host independence message-based server activation 61 Indigo Architecture service message flow typed channel untyped channel port formatter transport to destination 62 Indigo Web Service Example (1) • Implementation of web service TimeService using System; using System.MessageBus.Services; [DatagramPortType(Name="TimeService", Namespace="http://dotnet.jku.at/WS")] public class TimeService { [ServiceMethod] public DateTime GetTime() { DateTime now = DateTime.Now; Console.WriteLine ("Time request at {0}", now); // output to monitor server return now; } } • Compiling and creation of assembly csc /target:library /reference:System.MessageBus.dll TimeService.cs • Creating the WSDL description wsdlgen TimeService.dll 63 Indigo Web Service Example (2) • Implementation of the server application using System; using System.MessageBus.Services; using System; using System.MessageBus; class Server { static void Main () { ServiceEnvironment se = null; try { se = ServiceEnvironment.Load(); se.Open(); Console.WriteLine("Press enter to stop the service ..."); Console.ReadLine(); } finally { if (se != null) se.Close(); } } } 64 Indigo Web Service Example (3) • Configuration of the server in file Server.exe.config <configuration> <system.messagebus> <serviceEnvironments> <serviceEnvironment name="main"> <port> <identityRole> soap.tcp://localhost:12345/TimeService/ </identityRole> </port> <remove name="securityManager"/> <!-- Security disabled!!! --> <policyManager> <areUntrustedPolicyAttachmentsAccepted> true </areUntrustedPolicyAttachmentsAccepted> <isPolicyReturned> true </isPolicyReturned> </policyManager> <serviceManager> <activatableServices> <add type="TimeService, TimeService" /> </activatableServices> </serviceManager> </serviceEnvironment> </serviceEnvironments> </system.messagebus> </configuration> 65 Indigo Web Service Example (4) • Compilation of the server application csc /reference:System.MessageBus.dll Server.cs • Creation of the proxy for the client wsdlgen dotnet_jku_at.WS.wsdl dotnet_jku_at.WS.xsd • Compilation of the proxy code csc /target:library /reference:System.MessageBus.dll dotnet_jku_at.WS.cs 66 Indigo Web Service Example (5) • Implementation of the client application using System; using System.MessageBus.Services; public class Client { public static void Main () { ServiceEnvironment se = null; try { se = ServiceEnvironment.Load(); ServiceManager sm = se[typeof(ServiceManager)] as ServiceManager; if (sm == null) throw new Exception("ServiceManager is not available."); se.Open(); Uri uri = new Uri("soap.tcp://localhost:12345/TimeService/"); // get a channel to the web service from the default service manager ITimeServiceChannel channel = (ITimeServiceChannel) sm.CreateChannel(typeof(ITimeServiceChannel), uri); Console.WriteLine(channel.GetTime());// invoke web service method } catch (Exception e) { Console.WriteLine(e); } finally { if (se != null) se.Close(); } } } • Configuration of the client (analogous to the server) and compilation csc /reference:System.MessageBus.dll,dotnet_jku_at.WS.dll Client.cs 67 Indigo Web Service Example (6) • Starting the server and the client //----- Server > Host.exe Press enter to stop the service ... Time request at 1/29/2004 3:35:51 PM > //----- Client > Client.exe Time request at 1/29/2004 3:35:51 PM > 68 Web Services Introduction Web Services in .NET SOAP SOAP and .NET Service Description with WSDL Discovery of Web Services: UDDI and DISCO Preview of Web Services .NET 2.0 Summary Summary • • • • Web services are a middleware technology on the basis of XM and Internet protocols independent of programming language and run time system for the integration of heterogeneous, distributed systems • .NET supports web services – development of web services – development of web service clients – discovery and dynamic connection to web services • In .NET 2.0 Indigo unites the different remoting technologies 70 Resources (apart from dotnet.jku.at) • UDDI & Co www.uddi.org: Homepage of UDDI initiative www-3.ibm.com/services/uddi: Discovery service from IBM uddi.microsoft.com: Discovery service from Microsoft www.xmethods.com: Catalogue with UDDI- und DISCO entries • For developers www.w3.org: Specifications www.webservices.org: Articles and tutorials about web services www.gotdotnet.com: Site for .NET technology, including web services groups.yahoo.com/group/soapbuilders: Discussion group for SOAP • Java implementations xml.apache.org/axis/: Web service server in Java based on Apache www.themindelectric.com: GLUE: web service server in Java 71