WebServicesAndSerialization

Download Report

Transcript WebServicesAndSerialization

Distributed Programming
Web Services
•
•
•
•
Purpose
Examples of Web Services
Architecture
Web Services in .Net
Slides partly based on Joe Hummel
Nordjyllands Erhvervakademi - 2009
1
Why web services?
• Applications operates over different platforms
– A Java app gets data from a .NET app
– A Windows server gets data from an IBM mainframe
– A Linux server gets data from a Windows server
Application X
Nordjyllands Erhvervakademi - 2009
Application Y
2
When to use web services?
• When interoperability between platforms is the important
demand. Else:
– remoting is more efficient
– remoting offers more features
– remoting offers better security
• But web services is…
– an easy way to exchange data between two organizations
– an easy way to exchange data between a organization’s
different systems, i.e. stock, invoicing and dispatching
– an easy way to provide a service worldwide
Nordjyllands Erhvervakademi - 2009
3
Web service design
• In the simple form a web service is a tier that wraps a
existing tier
– meaning a platform neutral interface to existing code:
?
Web
Service
Client
Web server
BT
DT
DB
Server
Web Service
Tier
– existing tiers should be used as they are, therefore no recoding
Nordjyllands Erhvervakademi - 2009
4
Examples of web services
• What is possible today?
• Theres is many different public services:
– Amazon.com client
– TerraServer satellite pictures
– Google* Windows Live search
– MapPoint maps & route planner
– .....
Search for webservices here: http://www.xmethods.net/
Or with your favorite search engine
*) Google does no longer provide new keys for the soap based web service
Nordjyllands Erhvervakademi - 2009
5
Amazon.com web service
• Amazon.com offers product information via web service
• Why?
– To raise the sale! More than 10% are sold via WS…
Nordjyllands Erhvervakademi - 2009
6
MapPoint web service
• Maps, route planning etc.
– Other providers too, i.e. Google Earth, MS Virtual Earth, Yahoo, etc.
– Sign up for MapPoint WebService: https://mappoint-css.live.com/mwssignup/
Nordjyllands Erhvervakademi - 2009
7
Windows Live web service
• Execute searches & returns results
• Example from MSDN
Nordjyllands Erhvervakademi - 2009
8
A little live demo: Valuta conversion
• There is a webservice here:
– http://www.webservicex.net/CurrencyConvertor.asmx
Nordjyllands Erhvervakademi - 2009
9
What happened…
•
•
•
•
Accessed systems on other places on the internet
Accessed systems running on other platforms
Went through a number of firewalls
Received non-trivial datatypes
• … all together programmed in traditional OO.
static void Main(string[] args)
{
WSCurrency.CurrencyConvertor cc = new WSCurrency.CurrencyConvertor();
Console.WriteLine("From EUR to DKK: {0}",cc.ConversionRate(WSCurrency.Currency.EUR
,WSCurrency.Currency.DKK));
Console.ReadLine();
}
Nordjyllands Erhvervakademi - 2009
10
Basic architekture
• Standard RPC, but with use of XML & web server:
<Add>
<x>20</x>
<y>99</y>
</Add>
obj = new WebService();
result = obj.Add(20, 99);
(1) XML
Service
Page
Client
obj
(2) XML
Web server
<Add>
<result>119</result>
</Add>
Nordjyllands Erhvervakademi - 2009
int Add(int x, int y)
{ return x + y; }
11
More details…
• Proxy and stub objects supports RPC
• Messages in SOAP format
– SOAP = Simple Object Access Protocol
Client
Service
Page
(stub)
method call
proxy
method call
obj
Web server
SOAP msg (XML)
HTTP request
Nordjyllands Erhvervakademi - 2009
12
WSDL
• WSDL = Web Service Description Language
• A formal, platform-neutral definition of a web service
– Provided by a web service as a WSDL document
– Used by clients to obtain information about a web service
Service.wsdl
Service
Page
(stub)
obj
Web server
Nordjyllands Erhvervakademi - 2009
13
Example
• Get Windows Live’s WSDL dokumentation for the search
web service
– http://soap.search.msn.com/webservices.asmx?wsdl.
Nordjyllands Erhvervakademi - 2009
14
The strength of formal techniques and
standardlisation
• Client-side tools can automatically handle WSDL!
• Example:
– make a “Web Reference” in Visual Studio .NET receive the WSDL
and enable IntelliSense, type-check, & proxy generation
google = new GoogleSearchService();
result = google.doGoogleSearch("4a8/TvZQFHID0WIWnL1CMmMx0sNqhG8H",
txtSearch.Text, 0, 10, false, "", false, "", "", "");
foreach (ResultElement re in result.resultElements)
lstURLs.Items.Add(re.URL);
Nordjyllands Erhvervakademi - 2009
15
Beware of the architecture
• Data-only marshalling!
• Don't be mistaken:
– It looks like objects is MBV (marshal by value)
google = new GoogleSearchService();
result = google.doGoogleSearch("4a8/TvZQFHID0WIWnL1CMmMx0sNqhG8H",
txtSearch.Text, 0, 10, false, "", false, "", "", "");
foreach (ResultElement re in result.resultElements)
...;
– That is not true!
– No code is marshalled, only public data fields
– Web service objects are really MBDO (marshal by data only)
Nordjyllands Erhvervakademi - 2009
16
SOAP, WSDL and UDDI
• SOAP - Simple Object Access Protocol
– Used when the webservice is called
• WSDL - Web Service Definition Language
– Metadata (description) for the webservice
• UDDI - Universal Description, Discovery and Integration
– Used for registration and searching for webservices
(Is not widely used, use google or xmethods.net instead)
Nordjyllands Erhvervakademi - 2009
17
SOAP
• SOAP - Simple Object Access Protocol
– Used for request and response when the application is runnning.
– Contains information about the method, that is called
– Parameters for the method
– And return values from the method.
Nordjyllands Erhvervakademi - 2009
18
SOAP request
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
:q0="http://tempuri.org/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<q0:BuyDKK>
<q0:cur>eur</q0:cur>
</q0:BuyDKK>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Nordjyllands Erhvervakademi - 2009
19
SOAP Response
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
:xsd="http://www.w3.org/2001/XMLSchema"
:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap:Body>
<BuyDKKResponse xmlns="http://tempuri.org/">
<BuyDKKResult>0.13437067494390023</BuyDKKResult>
</BuyDKKResponse>
</soap:Body>
</soap:Envelope>
Nordjyllands Erhvervakademi - 2009
20
WSDL
• WSDL - Web Service Definition Language
Metadata (description) of the webservice
– Can be used by developement tools for generation of proxy
(stub/skeleton)
– Name of the WebService
– Parameters – number, type and order
– Return type
– How to interact with the Web Service using HTTP/SOAP
Nordjyllands Erhvervakademi - 2009
21
Make a web service yourself
• Live demo
• But in practice, some knowledge of XML is needed
Nordjyllands Erhvervakademi - 2009
22
Exercise:
• Lav den ene “følg-mig”-opgaverne i folderen RuteOpgave
Windows udgaven er lidt lettere end web udgaven.
• Make and deploy a webservice, that returns the server time.
• There is a weather web service here:
http://iistest.noea.dk/weather/Weather.asmx
– Find the weather in Aalborg.
• First use SearchLocation to find the location id.
It returns an array of results. Use the id property
• Then get a WeatherData object by GetWeatherData
– The service is an encapsulation of the service at weather.com
– If you want to the result weather.com returns, then use GetWeather
instead of GetWeatherData
– It returns XML that you can do brute force with String.IndexOf
Nordjyllands Erhvervakademi - 2009
23
Seriliazation
Nordjyllands Erhvervakademi - 2009
24
Serialization
• Serialization
– Purpose
– Standard serializers
Nordjyllands Erhvervakademi - 2009
25
Stream
• A stream is an abstraction for data flowing between a
source and a destination
• Stream provides a common way to transfer a sequence of
data (e.g. an array) regardless of the device
• The device could be a file, the keyboard, a network
connection, a printer, the memory etc.
Nordjyllands Erhvervakademi - 2009
26
Serialization – Send objects by a stream
• A object have to be serialized before it can be send by a
stream
• In C#, it is done simply by setting the attribute [Serializable]
before the class token.
• 3 methods to serialize:
– BinaryFormatter
– SoapFormatter
– XmlSerializer
Nordjyllands Erhvervakademi - 2009
27
Serilization - continued....
• What is serialized?
– By BinaryFormatter is public/private fields and properties
serialized.
A remake of the object shall be possible in another place
– By SoapFormatter and XmlFormatter is only public fields and
properties serialized.
• If [NonSerialized] is stated before a field/property, then it
will not be serialized.
• Note that methods are never serialized.
Nordjyllands Erhvervakademi - 2009
28
Example
• Please note that field should be private, and assigned by
properties (but in this way, they can be within the slide ;-))
[Serializable]
class Person
{
public String FirstName;
public String LastName;
public DateTime Birthday;
public float Height;
[NonSerialized]
public int Id;
....
}
Nordjyllands Erhvervakademi - 2009
29
Serialize to binary format
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
...
Person p = new Person(23, "Donald", "Duck", DateTime.Now, 0.4f);
Stream bs = new FileStream(@"c:\temp\bp.dat",
FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(bs, p);
bs.Close();
Nordjyllands Erhvervakademi - 2009
30
Deserialize
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
....
Stream fstream = File.OpenRead (@"c:\temp\bp.dat”)
Person bp = (Person)bf.Deserialize(fstream);
Console.WriteLine("{0} {1}", bp.FirstName, bp.BirthDay);
Nordjyllands Erhvervakademi - 2009
31
Send by the socket
string server = "localhost";
int serverPort = 5432;
client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint serverEndPoint = new IPEndPoint(
Dns.Resolve(server).AddressList[0], serverPort);
client.Connect(serverEndPoint);
Stream netStream = new NetworkStream(client);
Stream bufStream = new BufferedStream(netStream, BUFSIZE);
Nordjyllands Erhvervakademi - 2009
32
Serialization result: Binary
Nordjyllands Erhvervakademi - 2009
33
Serialization result: Soap
Nordjyllands Erhvervakademi - 2009
34
Serialization result: Xml
Something strange
here ?
Nordjyllands Erhvervakademi - 2009
35
Exercise
• Exercise 1
– Construct a list of person objects
You are free to use the Person class from the slides
– Serialize the objects and save the objects to a binary file
– Read from the file and reconstruct the list
• Exercise 2
– Make a web service that searches the file for a person with a
specified id and returns it to the client.
– The interface could be:
Person GetPerson(int id);
– Hints:
Remove [NonSerialized] on id
Use fstream.Position<fstream.Length to determine end_of_file
Nordjyllands Erhvervakademi - 2009
36