370 likes | 553 Views
Distributed Programming Web Services. Purpose Examples of Web Services Architecture Web Services in .Net. Slides partly based on Joe Hummel. Why web services?. Applications operates over different platforms A Java app gets data from a .NET app
E N D
Distributed ProgrammingWeb Services • Purpose • Examples of Web Services • Architecture • Web Services in .Net Slides partly based on Joe Hummel
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 Application Y
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
DB Web server Web Service DT BT 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: • existing tiers should be used as they are, therefore no recoding ? Client Server Web Service Tier
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
Amazon.com web service • Amazon.com offers product information via web service • Why? • To raise the sale! More than 10% are sold via WS…
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/
Windows Live web service • Execute searches & returns results • Example from MSDN
A little live demo: Valuta conversion • There is a webservice here: • http://www.webservicex.net/CurrencyConvertor.asmx
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(); }
<Add> <x>20</x> <y>99</y> </Add> (1) XML (2) XML int Add(int x, int y) { return x + y; } <Add> <result>119</result> </Add> obj Basic architekture • Standard RPC, but with use of XML & web server: obj = new WebService(); result = obj.Add(20, 99); Web server Client Service Page
obj More details… • Proxy and stub objects supports RPC • Messages in SOAP format • SOAP = Simple Object Access Protocol Web server Client Service Page (stub) method call method call proxy SOAP msg (XML) HTTP request
obj 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 Web server Service.wsdl Service Page (stub)
Example • Get Windows Live’s WSDL dokumentation for the search web service • http://soap.search.msn.com/webservices.asmx?wsdl.
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);
google = new GoogleSearchService(); result = google.doGoogleSearch("4a8/TvZQFHID0WIWnL1CMmMx0sNqhG8H", txtSearch.Text, 0, 10, false, "", false, "", "", ""); foreach (ResultElement re in result.resultElements) ...; Beware of the architecture • Data-only marshalling! • Don't be mistaken: • It looks like objects is MBV (marshal by value) • That is not true! • No code is marshalled, only public data fields • Web service objects are really MBDO (marshal by data only)
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)
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.
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>
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>
WSDL • WSDL - Web Service Definition LanguageMetadata (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
Make a web service yourself • Live demo • But in practice, some knowledge of XML is needed
Exercise: • Lav den ene “følg-mig”-opgaverne i folderen RuteOpgaveWindows 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
Serialization • Serialization • Purpose • Standard serializers
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.
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
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.
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; .... }
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();
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);
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);
Serialization result: Xml Something strange here ?
Exercise • Exercise 1 • Construct a list of person objectsYou 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 idUse fstream.Position<fstream.Length to determine end_of_file