Anda di halaman 1dari 70

Web Services

Dr. Herbert Praehofer


Institute for System Software
Johannes Kepler University Linz

Dr. Dietrich Birngruber


Ecolog GmbH
Wels

© 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
Preview of MCF
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

SOAP Web- SOAP Web-


Script-Client
HTTP Service A HTTP Service B

SOAP
IIS (.NET-Web-Service-Container)
Java-Client HTTP SOAP
SMTP

SOAP Web- SOAP Web-


.NET-Client HTTP Service C SMTP Service D

Web-Server +
SOAP Java-Web-Service- Email-Server +
... Client Protokoll X
Container SOAP-Processor

SOAP
entfernter Aufruf
Protokoll
7
Web Services in Comparison
Java RMI .NET Remoting CORBA Web Services

Programming Java .NET languages independent independent


language (C#, VB.NET, ..)

Interface Java Interfaces .NET Interfaces CORBA IDL WSDL (XML-


definition based)

Data structures Java objects .NET objects IDL-specified XML data


objects

Transport RMI-IIOP binary or OAP GIOP/IIOP HTTP, HTTPS,


protocol SMTP, FTP

Packaging Java object .NET object ORB/CDR SOAP


serialisation serialisation

Infrastructure Java RMI .NET remoting ORBs Web, Mail, FTP


infrastructure infrastructure 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)
– Not really object oriented

9
Web Service Infrastructure

Discover Services
What services do exist?
Where are they? (URL)

E.g.: UDDI,
DISCO
client(s) Service 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
... ...

pu
h
rc

bli
a

sh
se

Web service
container

Client inquiry
Web
Service
call

11
Web Service Architecture (2)
Discovery service

WSD1 URI1
WSD2 URI2

... ...

pu
h
rc

bli
a

sh
se

service inquiry (URI) service inquiry

service description (WSD)


Web service service description (WSD) Web
Client
container service
service call (SOAP) service call

result: SOAP result

12
Web Services
Introduction
Web Services in .NET
SOAP
SOAP and .NET
Service Description with WSDL
Preview of MCF
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. SOAP-
HTTP)
• 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( …) {

asmx-File in a virtual directory in the16IIS


Example: TimeService
stored in virtual directory
time/TimeService.asmx
TimeService.asmx

<%@ WebService Language="C#" Class="TimeService" %> WebService directive


using System;
using System.Web.Services;

public class TimeService : WebService {


deriving from WebService
[WebMethod(Description="Returns the current time")]
public string GetTime(bool shortForm) {
Attribute [WebMethod]
if (shortform) return DateTime.Now.ToShortTimeString(); identifies Web service
else return DateTime.Now.ToLongTimeString(); method
}
}

17
WebService Description in IE

18
Example: Simple .NET Client
• wsdl.exe generates proxy for client (TimeClient.TimeService)
> wsdl.exe /namespace:TimeClient /out:TimeServiceProxy.cs
http://localhost/netsem-ws/TimeService.asmx

• Client program creates TimeService object and calls GetTime


using System;
using TimeClient; //Namespace of generated proxies

public class NetClient {


public static void Main(string[] args) {
TimeService service = new TimeService();
Console.WriteLine(“Time at the server is: ");
string time = service.GetTime(true);
Console.WriteLine(time);
}
}

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
Preview of MCF
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)

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, …

e.g.: request-response for RPC by 2 messages

1: GetTime_Request
Client 2: GetTime_Response Server

23
SOAP Messages

SOAP messages comparable to letters with


<Envelope> • envelope (<Envelope>) as container
<Header> • letter head (<Header>)
Message Header with meta information
Message Header (Message Headers)

<Body> • letter (<Body>)


Data
• with arbitrary XML data

<Fault> • fault descriptions


Fault Descriptions

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

25
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

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

28
Example: SOAP over HTTP (1)
• SOAP over HTTP-POST:
HTTP header SOAPAction
POST /time/TimeService.asmx HTTP/1.1
Content-type: text/xml; charset=utf-8 identifies SOAP request
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

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


<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
Web method
<GetTime xmlns="http://tempuri.org/"
<shortForm>
true Parameter
</shortForm>
< /GetTime>
</soap:Body>
</soap:Envelope>

29
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">
<soap:Body> Return
<GetTimeResponse xmlns="http://tempuri.org/"> value
<GetTimeResult>string</GetTimeResult>
</GetTimeResponse>
</soap:Body>
</soap:Envelope>

30
Web Services
Introduction
Web Services in .NET
SOAP
SOAP and .NET
Service Description with WSDL
Preview of MCF
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

Uses .NET attributes extensively

32
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

33
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

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

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

37
Including Types
• SoapIncludeAttribute allows inclusion of types
 important for specializations

Example: PersonService

Web method with return value of type Person has 2 specializations


Person[] 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!
38
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] Includes


[SoapInclude(typeof(Customer)), SoapInclude(typeof(Employee))] subtypes
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;
}
} 39
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> 40
SOAP Header Entries
• SOAP header entries are used for meta informations in messages
• Arbitrary header entries are possible, e.g. <Envelope>

<Header>
– e.g. authentication of clients Message Header

• All header entries have attributes Message Header


– recipient of entry (Actor)
<Body>
– if it must be handled by recipient (mustUnderstand)
Data

<Fault>
Fault Descriptions

• .NET supports header entries by:


– Class SoapHeader: Development of header entry classes
– Attribute SoapHeaderAttribute: Defining header entries for web methods

41
Classes SoapHeader
and SoapHeaderAttribute

SoapHeader SoapHeaderAttribute
//----- properties //----- properties
public string Actor { get; set; } public SoapHeaderDirection Direction {get; set;}
public bool MustUnderstand { get; set; } public string MemberName {get; set;}
public bool DidUnderstand { get; set; } ...
...

• Recipient • In-, Out-, InOut direction of headers


public string Actor {get; set;} public SoapHeaderDirection Direction
{get; set;}
• Header must be handled
public bool MustUnderstand {get; set;}
• Field of Web service for the header entry
• Header handled successfully public string MemberName {get; set;}
public bool DidUnderstand {get; set;}

42
Example: AuthHeader
• Identification of user 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;
}

[WebService(Namespace="http://dotnet.jku.at/time/")]
public class HeaderTimeService : WebService {

public AuthHeader curUser; "curUser" is a field for


[WebMethod(Description="Returns the current time")] AuthHeader
[SoapHeader("curUser")]
public string GetTime() {
….

43
Example: AuthHeader
• Identification of user in TimeService
– Login returns identification code (cookie)
– GetTime sends back identification code in header entry

:HeaderTimeService :HeaderTimeServiceProxy :Client

cookie = Login(user, pw)


<soap:Envelope>.. <Login> <…. </soap>
Login(..) <soap:Envelope>..<cookie>afah2..</cookie> </soap>"afah2320u799a8d"
entry =
AuthHeaderValue = entry new AuthHeader(cookie)
<soap:Envelope>
<Headers>
<AuthHeader>
<cookie>afah2320u799a8d</cookie>
GetTime()
</AuthHeader>
</Headers>
curUser=
<GetTime> … </GetTime>
GetTime </soap>
Validate
Cookie(..)
<soap:Envelope>..<GetTimeResponse>17:5s</… </soap>
17:52

44
Example: AuthHeader (1)
Identification of user 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 and return cookie }

bool ValidateCookie(string cookie) { ... validate cookie ... }


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

46
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 AuthHeader in proxy


– calls GetTime with AuthHeader header entry
proxy.AuthHeaderValue = entry;
<?xml version="1.0" encoding="utf­8"?>
Console.WriteLine(proxy.GetTime()); <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>
47
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;}
defined in base class
– Sesssion state object WebService !
public HttpSessionState Session {get;}

public sealed class HttpSessionState : ICollection, IEnumerable {


public object this[ string name ] {get; set;}
public object this[ int index ] {get; set;}

}

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

49
Example: StateDemo (2)

• Parameter EnableSession enables usage of Session object


• IncSession 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;
}
}

50
Web Services
Introduction
Web Services in .NET
SOAP
SOAP and .NET
Service Description with WSDL
Preview of MCF
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)

52
Structure of WSDL 1.1
<definitions> WSDL description of a Web services
<types> types defined in <xsd:schema>
</types>
<message> simple messages
<part> parts of messages
</part> abstract
</message>
part
<portType> interface specification
<operation> operations of an interface
<input> input message
<output> output message
</operation>
</portType>
<binding> binding of interface to protocols and encoding
<operation> description of the binding for each operation
</binding>
<service> service description concrete
<port> URI and binding to port part
</service>
</definitions>
53
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 /> abstract
<message name="GetTimeSoapIn" /> part
<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>
54

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/“
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
concrete
</output> part
</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>

55
Web Services
Introduction
Web Services in .NET
SOAP
SOAP and .NET
Service Description with WSDL
Preview of MCF
Summary
Microsoft Communication Foundation (MCF)
• MCF shall unite the different architectures for distributed systems
– .NET Remoting
– Web Services
– .NET Enterprise Services

in a unique programming model


• Abstraction from the communication layer
– independent implementation of services
– binding to specific protocols

57
Architecture

Service interface and implementation

Addressierung – Bindung – Contract (ABC)


Addressing – Binding – Contract (ABC)

Kommunikations-Infrastruktur
Communication infrastructure

58
Approach
• Definition of service interface

 .NET program
• Implementation of interface

 .NET program
• Definition of host

 .NET application
 IIS
…
• Mapping of service to host

 ABC: Addressing, Binding und Contract

59
MCF Attribute
• MCF uses .NET attributes for service contracts
[ServiceContract]: marking a service interface

[OperationContract]: marking a service method

[DataContract]: marking a data class of a contract

[DataMember]: marking a public access method of a data class

60
Example: TimeService with MFC (1)
Interface definition
using System;
using System.ServiceModel; • WCF namespace

namespace WCFTimeService {

[ServiceContract(Namespace = "http://dotnet.jku.at/time")] • service interface


public interface ITimeServiceContract {

[OperationContract] • service method


string GetTime();

[OperationContract] • service method


TimeDescDataContract GetTimeDesc();

61
Example: TimeService with MFC (2)
Interface definition (cont.)
[System.Runtime.Serialization.DataContract] • data part of contract
public class TimeDescDataContract {
private string timeLong;
private string timeShort;

public TimeDescDataContract() {
timeLong = DateTime.Now.ToLongDateString();
timeShort = DateTime.Now.ToShortDateString();
}

[System.Runtime.Serialization.DataMember] • public data member


public string TimeShort {
get { return timeShort; }
set { timeShort = value; }
}
• public data member
[System.Runtime.Serialization.DataMember]
public string TimeLong {
get { return timeLong; }
set { timeLong = value; }
}
}
} 62
Example: TimeService with MFC (3)
Service implementation

public class TimeServiceBehavior : ITimeServiceContract {

public string GetTime() {


return DateTime.Now.ToString();
}

public TimeDescDataContract GetTimeDesc() {


return new TimeDescDataContract();
}

}
}

63
Example: TimeService with MFC (3)
ServiceHost application
MCF class ServiceHost facilitates publishing
services under URI
using System;
using System.ServiceModel;

class MyServiceHost {
static ServiceHost myServiceHost = null;

static void StartService() {


Uri baseAddress = new Uri("http://localhost:8080/WCF/TimeService"); • URI of service
myServiceHost = new ServiceHost(typeof(TimeServiceBehavior), baseAddress); • instantiation and opening of
myServiceHost.Open(); ServiceHost component
}

static void StopService() {


if (myServiceHost.State != CommunicationState.Closed)
myServiceHost.Close();
}

static void Main() {


StartService(); • start ServiceHost
Console.WriteLine("Service gestartet... ");
Console.ReadLine();
StopService(); • stop ServiceHost
}
}
64
Example: TimeService with MFC (4)
ABC configuration

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


<configuration>
<system.serviceModel>
<services>
<service name="WCFTimeService.TimeServiceBehavior">
<endpoint Endpoint:
address="" • addressing
binding="basicHttpBinding" • binding on HTTP protocol
contract="WCFTimeService.ITimeServiceContract" • contract
/>
</service>
</services>
</system.serviceModel>
</configuration>

basicHttpBinding: HTTP and SOAP based communication


wsHttpBinding: HTTP-based WS-I conform communication
wsDualHttpBinding: wsHttpBinding with callbacks
netTcpBinding binary TCP/IP-based communication
netNamedPipeBinding: fast interprocess communication on a
single computer
65
Example: TimeService with MFC (5)
Web-Service realization and IIS hosting similar to asmx-file in a virtual
directory of IIS
File TimeService.svn with code behind directive
<% @ServiceHost Service="WCFTimeService.TimeServiceBehavior" %>

web.config with endpoint entry


<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="WCFTimeService.TimeServiceBehavior">
<endpoint
address=""
binding="basicHttpBinding"
contract="WCFTimeService.ITimeServiceContract"
/>
</service>
</services>
</system.serviceModel>
<system.web>
<!-- system.web spezifische Einträge -->
</system.web>
</configuration> 66
Web Services
Introduction
Web Services in .NET
SOAP
SOAP and .NET
Service Description with WSDL
Preview of MCF
Summary
Summary
• Web services are a middleware technology
• on the basis of XML 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
• MFC shall unite the different MS remoting technologies in
the future

68
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

69
Dates
Project
– topic can be selected by yourself
– must deal with ASP.NET | ADO.NET | WebServices
– at least 250 lines of code (or 500 lines if combined with C# project)
– deadline: Fr 12. 1. 2007 16:30 – 18:30, SSW Institute

Exam
– Fr. 12.01. 2007, 15:00 – 16:00

70

Anda mungkin juga menyukai