Presentation is loading. Please wait.

Presentation is loading. Please wait.

Web Services Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz Dr. Dietrich Birngruber Software Architect TechTalk www.techtalk.at.

Similar presentations


Presentation on theme: "Web Services Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz Dr. Dietrich Birngruber Software Architect TechTalk www.techtalk.at."— Presentation transcript:

1 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

2 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

3 3 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/

4 4 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

5 5 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

6 6 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)

7 7 Web Services Scenario

8 8 Web Services in Comparison Java RMI.NET RemotingCORBAWeb services Programming language Java.NET languages (C#, VB.NET,..) independent Interface definition Java InterfacesC# InterfacesCORBA IDLWSDL (XML- based) Data structuresJava objects.NET objectsIDL-specified objects XML data Transport protocol RMI-IIOPbinary or OAPGIOP/IIOPHTTP, HTTPS, SMTP, FTP PackagingJava object serialisation.NET object serialisation ORB/CDRSOAP InfrastructureJava RMI infrastructure.NET remoting infrastructure ORBsWeb, Mail, FTP server

9 9 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)

10 10 Web Service Infrastructure

11 11 Web Service Architecture

12 12 Web Service Architecture (2)

13 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

14 14 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 )

15 15.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. SOAP- HTTP) System.Xml.Serialization –for XML serialization

16 16 Implementation of Web Services public class MyWebService : WebService { deriving from base class System.Web.Services.WebService [WebMethod(Description= comment ")] […] public Returntype MyWebMethod( …) { … Identification and settings by.NET attributes –identification of web service methods –definition of format and encoding –XML namespaces and element names to use –etc. in asmx -file with @WebService directive

17 17 Example: TimeService 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(); } TimeService.asmx WebService directive deriving from WebService Attribute [ WebMethod ] identifies web service method

18 18 Example: Simple.NET Client 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); } Client program creates TimeService object and calls GetTime > wsdl.exe /namespace:TimeClient /out:TimeServiceProxy.cs http://localhost/netsem-ws/MyFirstService.asmx wsdl.exe generated proxy for client ( TimeClient.TimeService )

19 19 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(); } }

20 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

21 21 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)

22 22 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, … 1: GetTime_Request 2: GetTime_Response ClientServer e.g.: request-response for RPC by 2 messages

23 23 SOAP Messages envelope ( ) as container letter head ( ) with meta information (Message Headers) letter ( ) with arbitrary XML data fault descriptions SOAP messages comparable to letters with

24 24 XML Structure (simplified, SOAP 1.2)... data (depends on encoding and format)...who is responsible?......textual description......more error details...

25 25 Data in 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

26 26 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

27 27 Example: HTTP-POST Call of GetTime(bool shortForm) of web service http://localhost/time/TimeService.asmx http://localhost/time/TimeService.asmx/GetTime?shortForm=true Call : HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length string HTTP response:

28 28 Example: SOAP over HTTP (1) 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 { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/816/1/slides/slide_27.jpg", "name": "28 Example: SOAP over HTTP (1) 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

29 29 Example: SOAP over HTTP (2) SOAP encoded response: HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length string Return value

30 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

31 31 SOAP and.NET.NET provides support for –defining message format and encoding –encoding of.NET data types –development of message headers –life cycle management

32 32 Message Format and Encoding (1) 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 [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) {... }

33 33 Message Format and Encoding (2) Attributes SoapDocumentService and SoapDocumentMethod for document format [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 {... }

34 34 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

35 35 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; } public struct TimeDesc { [SoapAttribute] public string TimeLong; [SoapAttribute] public string TimeShort; [SoapAttribute (AttributeName = "ZoneID")] public int TimeZone; } Encoding of TimeDesc adjusted by attribute [SoapAttribute] fields encoded as XML attributes

36 36 Example: Encoding of a Type (2)... { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/816/1/slides/slide_35.jpg", "name": "36 Example: Encoding of a Type (2)...", "description": "

37 37 Including Types SoapIncludeAttribute allows inclusion of types important for specializations Customer and Employee have to be included explicitly into web service description! Example: PersonService public class PersonService : WebService { [WebMethod]… public Person[ ] GetAll() {…} } Web method with return value of type Person[] Person CustomerEmployee Person has 2 specializations Customer and Employee

38 38 Example: PersonService (1) Classes Person, Customer and Employee public abstract class Person { …} public class Customer : Person { …} public class Employee : Person {…} 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; } PersonService defines web method GetAll with return type Person[] SoapInclude attribute includes Customer and Employee types

39 39 Example: PersonService (2) SOAP encoded response 1 Max Customer EMP-33 EMP-33 Tom Employee

40 40 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

41 41 Classes SoapHeader and SoapHeaderAttribute Recipient Header must be handled Header handled successfully public string Actor {get; set;} public bool DidUnderstand {get; set;} public bool MustUnderstand {get; set;} In -, Out -, InOut direction of headers Name of field of web service class for header entry public SoapHeaderDirection Direction {get; set;} public string MemberName {get; set;}

42 42 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... }

43 43 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); }

44 44 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()); aewt12348cvNNgrt55

45 45 Life Cycle Web service objects are stateless Are created for each call Data can be stored in properties of –Application state object or –Sesssion state object public HttpApplicationState Application {get;} public HttpApplicationState Session {get;} public sealed class HttpSessionState : ICollection, IEnumerable { public object this[ string name ] {get; set;} public object this[ int index ] {get; set;} … }

46 46 Example: StateDemo (1) using System.Web.Services; [WebService(Namespace="http://dotnet.jku.at/StateDemo/")] public class StateDemo : WebService { Web service StateDemo demonstrates storage of data 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; }

47 47 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; }

48 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

49 49 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)

50 50 concrete part abstract part Structure of WSDL 1.1 WSDL description of a web services types defined in simple messages parts of messages interface specification operations of an interface input message output message binding of interface to protocols and encoding description of the binding for each operation service description URI and binding to port

51 51 Example: WSDL for TimeService (1) WSDL description created by web container (IIS) http://localhost/WebProject1/TimeService.asmx?WSDL … abstract part

52 52 Example: WSDL for TimeService (2) … Simple web service for querying the time concrete part

53 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

54 54 Universal, Description, Discovery and Integration (UDDI) Standardized protocol for searching for and using web services Provides web services interface Directory (UDDI) 1.) register 2.) search 3.) connect 4.) call Client Web Service A Web Service B http://www.uddi.org

55 55 DISCO Microsofts 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

56 56 DISCO Descriptions Creation of DISCO descriptions: –by command tool disco.exe –by IIS http://localhost/WebProject1/TimeService.asmx?DISCO > disco.exe /out:WebProject1 WebProject1/TimeService.asmx

57 57 Example: TimeService Discovery (1) 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(); } } 2 variants of TimeService –TimeService1 –TimeService2 using System.Web.Services; [WebService(Namespace="http://dotnet.jku.at/time/", Name="TimeService")] public class TimeService2 : WebService { [WebMethod] public string GetTime() { return "I dont know the time!"; } }

58 58 Example: TimeService Discovery (2) using System; using System.Web.Services.Discovery; using System.Collections; public class DiscoSample { public static void Main(string[] args) { Disco client with discovery of DISCO file DiscoveryClientProtocol discoClient = new DiscoveryClientProtocol(); foreach (string uri in args) { discoClient.Discover(uri); } –loading the DISCO files discoClient.ResolveAll(); TimeService proxy = new TimeService(); foreach (object obj in discoClient.Documents.Values) { DiscoveryDocument dDoc = obj as DiscoveryDocument; –iterating over all DISCO descriptions

59 59 Example: TimeService Discovery (3) ContractReference contr = null; IEnumerator it = dDoc.References.GetEnumerator(); while (contr == null && it.MoveNext()) contr = it.Current as ContractReference; –iterating over all -elements and retrieve URLs –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); } }

60 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

61 61 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

62 62 Indigo Architecture

63 63 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

64 64 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(); } }

65 65 Indigo Web Service Example (3) Configuration of the server in file Server.exe.config soap.tcp://localhost:12345/TimeService/ true true

66 66 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

67 67 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

68 68 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 >

69 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

70 70 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

71 71 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


Download ppt "Web Services Dr. Herbert Praehofer Institute for System Software Johannes Kepler University Linz Dr. Dietrich Birngruber Software Architect TechTalk www.techtalk.at."

Similar presentations


Ads by Google