1 / 63

Chapter 11 Web Services (Code Reuse over the Internet)

Chapter 11 Web Services (Code Reuse over the Internet). Yingcai Xiao. What is it? What it is for? Examples How to write one? What’s inside? How does it work?. Client 1. Proxy of Interface 2. UDDI Registry 2. SOAP. UDDI Registry 1. Client 2. Proxy of Interface 1. SOAP. Application 1.

marnin
Download Presentation

Chapter 11 Web Services (Code Reuse over the Internet)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 11Web Services(Code Reuse over the Internet) Yingcai Xiao

  2. What is it?What it is for?ExamplesHow to write one?What’s inside?How does it work?

  3. Client 1 Proxy of Interface 2 UDDI Registry 2 SOAP UDDI Registry 1 Client 2 Proxy of Interface 1 SOAP Application 1 WSDL Interface 1 Application 2 WSDL Interface 2 WEB Web Services A Web service is an application that exposes Web methods over the Web.

  4. Sharing Objects over the Internet: How? • Transmitting => HTTP (Hypertext Transport Ptotocol http://www.w3.org/Protocols/) • Sharing => Standard: SOAP (Simple Object Access Protocol) for objects “SOAP is a simple XML-based protocol to let applications exchange information over HTTP.”http://www.w3schools.com/soap http://www.w3.org/TR/SOAP WSDL (Web Service Definition Language) for services “WSDL (Web Services Description Language) is an XML-based language for describing Web services and how to access them.” http://www.w3schools.com/wsdl/default.asp • Defining => both are based on XML (Extensible Markup Language, http://www.xml.com/) .

  5. Web Services (XML Web Services) (Outside) • A Web service is a different kind of Web application. • It’s not designed to serve end users. • It’s designed to provide services to other applications through a highly programmable Internet. • It doesn’t have a user interface. • It exposes callable API functions, known as Web methods, over the Internet. • .NET Framework makes writing Web services and Web service clients easy. • Web services are not the property of Microsoft. They’re an industry standard built on open protocols such as HTTP and the Simple Object Access Protocol (SOAP). • You don’t need the .NET Framework to write Web services or Web service clients.

  6. Web Services (Inside) • A Web service is an application that: • Runs on a Web server • Exposes Web methods to interested callers • Listens for HTTP requests representing commands to invoke Web methods • Executes Web methods and returns the results • Most Web services expect SOAP messages.

  7. Web Service Examples Cloud Computing: “is location independent computing, whereby shared servers provide resources, software, and data to computers and other devices on demand” http://en.wikipedia.org/wiki/Cloud_computing In Cloud Computing, software is in the “cloud”. One of the main techniques for Cloud Computing is software as a service (SaaS), which is based on web services.

  8. Web Service Examples • Amazon Web Services (AWS): http://aws.amazon.com/ Web Services based Cloud Computing at Amazon Elastic Compute Cloud (Amazon EC2) provides scalable compute capacity http://aws.amazon.com/ec2/ Amazon CloudFront : for content delivery Discussion Forums: http://developer.amazonwebservices.com/connect/forumindex.jspa Eucalyptus (“Elastic Utility Computing Architecture for Linking Your Programs To Useful Systems”): http://www.eucalyptus.com/ software platform for implementing private cloud computing using AWS API.

  9. Professional Web Service Examples Google Apps/AppEngine: http://code.google.com/appengine/ (Google Cloud: run your web applications on Google's infrastructure.) developers.google.com : APIs and Tools for developers http://code.google.com/ (open source project hosting service) http://www.google.com/apps (usable applications).

  10. Ways to Write WS • There are many ways to write Web services • write Web services by hand; • use SOAP toolkits from Microsoft, IBM, and other companies; • use the .NET Framework (easy, managed). (need to install IIS and ASP.NET)

  11. Our First Web Service Using ASP.NET Calc.asmx <%@ WebService Language="C#" Class="CalcService" %> using System; using System.Web.Services; [WebService (Name="Calculator Web Service", Description="Performs simple math over the Web")] class CalcService { [WebMethod (Description="Computes the sum of two integers")] public int Add (int a, int b) { return a + b; }

  12. Our First Web Service Using ASP.NET [WebMethod (Description="Computes the difference between two integers")] public int Subtract (int a, int b) { return a - b; } }

  13. Our First Web Service Using ASP.NET • The ASMX file (calc.asmx) is a complete Web service. It implements two Web methods: Add and Subtract. Both take two integers as input and return an integer as well. • Calc.asmx implements two Web methods: Add and Subtract. • Deploying: copying it to a web app directory on your Web server that is URL-addressable (e.g. C:\inetpub\wwwroot\xiaotest). • Accessing: http://winserv1.cs.uakron.edu/xiaotest/calc.asmx.

  14. How a Web Service can be tested • Web services do not have user interface for regular users (even though they do have APIs for programmers.) • ASP.NET can generate forms to test web services on the fly from ASMX files. • Therefore, we don’t have to write special clients and GUI to test web services. • But the tests need to be done locally on the server.

  15. How does the test work? Example: Calc.asmx • Users call http://winserv1.cs.uakron.edu/xiaotest/Calc.asmx up in a browser. • IIS sends the request to ASP.NET on winserv1.cs.uakron.edu. • ASP.NET compiles Calc.asmx into a DLL. • ASP.NET displays a page that users can test the Add method. • Users Interact with it by clicking the “Add” button. • ASP.NET finds the method name and signature by reading them from the metadata in the DLL. • It generates an HTML form that users can use to call the Add method with choice of inputs. • When the users type 2 and 2 into the “a” and “b” boxes and click Invoke, the XML returned by the Web method appears in a separate browser window.

  16. Inside Web Services

  17. Inside ASP.NET based Web services • ASMX is a file name extension registered to ASP.NET in Machine.config. • ASMX files begin with @ WebService directives. • At a minimum, the directive must contain a Class attribute identifying the class that makes up the Web service. • Web service classes can be attributed with optional WebService attributes. • Web methods are declared by tagging public methods with WebMethod attributes. • Helper methods are not exposed by omitting the attribute. • HTTP, XML, and SOAP are hidden under the hood. • The Web methods can be invoked with SOAP, HTTP GET, and HTTP POST. • They can return output in SOAP responses or simple XML wrappers.

  18. The WebService Base Class • class CalcService : WebService • WebService belongs to the System.Web.Services namespace. • It contributes properties named Application, Session, Context, Server, and User to derived classes.

  19. The WebMethod Attribute • The WebMethod attribute tags a method as a Web method and supports the following parameters:

  20. The WebMethod Attribute [WebMethod (EnableSession="true", Description="Adds an item to a shopping cart")] public void AddToCart (Item item) { ShoppingCart cart = (ShoppingCart) Session["MyShoppingCart"]; cart.Add (item); } Web methods cannot be overloaded. (Why?) [WebMethod (MessageName="AddInts")] public int Add (int a, int b) { return a + b; } [WebMethod (MessageName="AddFloats")] public float Add (float a, float b) { return a + b; }

  21. Converting Congo to Web Service Congo.aspx : GUI + Event Handlers Congo.asax: Initialization Congo.cs: Web Service Level One: Export methods in ShoppingCart. [WebMethod (MessageName="AddOrder")] public void AddOrder (BookOrder Order) { … } Only Congo.cs code are reused

  22. Converting Congo to Web Service Level Two: Enabling Sessions • Export methods in ShoppingCart (Congo.cs) • Initialization of ShoppingCart (Congo.asax) • Create WS wrappers for some event handlers too (Congo.aspx) [WebMethod (EnableSession="true", Description="Adds an item to a shopping cart")] public void AddToCart (Item item) { ShoppingCart cart = (ShoppingCart) Session["MyShoppingCart"]; cart.Add (item); }

  23. The Web Services Description Language (WSDL) • A new standard for describing web services. • An XML vocabulary. • For machines to read. • Documented at http://www.w3.org/TR/wsdl. • Need to publish a WSDL contract when publishing a Web service. • Other developers can use the contract to write clients for your Web service. Wsdl.exe generates a wrapper class containing all the elements needed to talk to a Web service. • To generate a WSDL contract : http://winserv1.cs.uakron.edu/xiaotest/Calc.asmx?wsdl

  24. WSDL Contract • A WSDL contract which contains: • service element that describes the Web service; • operation elements that document the “operations,” or Web methods, that the service supports; • binding elements that document the protocols that the Web methods support; • other descriptive information.

  25. Web Services and Complex Data Types • Complex types are supported. • Represented in XML using SOAP. • A client obtains an XML schema describing the data type from the service’s WSDL contract. • Note: WSDL is for describing web services (special web applications) while SOAP is for describing web objects. Both use XML vocabulary. (books, chapters, paragraphs, English).

  26. Web Services and Complex Data Types C# Class public class Bookstore { public string Name; public string Address; public string City; public string State; … } SOAP in XML <s:complexType name="Bookstore"> <s:sequence> <s:element minOccurs="1" maxOccurs="1" name="Name" nillable="true" type="s:string" /> <s:element minOccurs="1" maxOccurs="1" name="Address" nillable="true" type="s:string" /> <s:element minOccurs="1" maxOccurs="1" name="City" nillable="true" type="s:string" /> <s:element minOccurs="1" maxOccurs="1" name="State" nillable="true" type="s:string" /> </s:sequence> </s:complexType>

  27. Web Services and Complex Data Types • You can’t pass complex types to a Web method using HTTP GET and POST. That’s not a limitation if you use SOAP to invoke Web methods. (ASP.NET generates test pages using HTTP GET). • Any fields or properties declared in a class or struct that’s passed to or from a Web method must be public if they’re to be serialized (transmitted or saved) when instances of the class or struct are serialized. That’s because the .NET Framework’s XML serializer will not serialize nonpublic members. • Examine a WSDL contract: http://winserv1.cs.uakron.edu/xiaotest/calc.asmx?wsdl

  28. How to Use/Consume Web Services (WS) • Internal (low-level) code for using web services. • HTTP commands for using web services through a web browser. • How to write a WS client using proxies. • A console-based WS client. • An ASP.NET-based WS client. • For-fee WSs. • Searching for WSs.

  29. WS Low-level Code • The Web service’s job for responding to each request is to • receive input from client, • parse the SOAP envelope containing the inputs, • compute, • formulate a SOAP envelope containing the result, • return it to the client in the body of the HTTP response. • The WSDL contract is published just once for each web service, not for each request. • http://winserv1.cs.uakron.edu/xiaotest/calc.asmx?wsdl • .NET Framework insulates developers from the low-level details of SOAP, HTTP, and XML and provides a high-level framework for writing Web services and Web service clients.

  30. WS Low-level Code • Example: a Web service that publishes Web methods named Add and Subtract at www.wintellect.com/calc.asmx. • Before sending a request to the web service, the client needs to know the services provided by the web service by reading its WSDL contract. • http://tempuri.org/ provides namespaces for XML Web Services under development.

  31. WS Low-level Code A client sent a request to add 2 and 2 to the “Add” Web method using SOAP. POST /calc.asmx HTTP/1.1 Host: www.wintellect.com Content-Type: text/xml; charset=utf-8 Content-Length: 338 SOAPAction: "http://tempuri.org/Add" <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd=http://www.w3.org/2001/XMLSchema xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <Add xmlns="http://tempuri.org/"> <a>2</a> <b>2</b> </Add> </soap:Body> </soap:Envelope>

  32. WS Low-level Code • And here’s how the Web service would respond using SOAP: HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content Length: 353 <?xml version="1.0" encoding="utf8"?> <soap:Envelope  xmlns:xsi=http://www.w3.org/2001/XMLSchemainstance  xmlns:xsd=http://www.w3.org/2001/XMLSchema   xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">   <soap:Body>     <AddResponse xmlns="http://tempuri.org/">       <AddResult>4</AddResult>     </AddResponse>   </soap:Body> </soap:Envelope>

  33. WS Using HTTP GET • .NET Framework also allows Web methods to be invoked using ordinary HTTP GET and POST commands instead of SOAP. This is a non-OO approach and can’t take care of ComplexType objects. Using Get: GET /calc.asmx/Add?a=2&b=2 HTTP/1.1 Host: www.wintellect.com The Web service responds as follows: HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: 80 <?xml version="1.0" encoding="utf-8"?> <int xmlns="http://tempuri.org/">4</int>

  34. WS Using HTTP POST Here’s a POST command that adds 2 and 2: POST /calc.asmx/Add HTTP/1.1 Host: www.wintellect.com Content-Type: application/x-www-form-urlencoded Content-Length: 7 a=2&b=2 And here’s the Web service’s response: HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: 80 <?xml version="1.0" encoding="utf-8"?> <int xmlns="http://tempuri.org/">4</int>

  35. Writing Clients to Consume Web Services

  36. Client 1 Proxy of Interface 2 UDDI Registry 2 SOAP UDDI Registry 1 Client 2 Proxy of Interface 1 SOAP Application 1 WSDL Interface 1 Application 2 WSDL Interface 2 WEB Web Services A Web service is an application that exposes Web methods over the Web.

  37. Web Service Clients & Proxies Web service clients—applications that use, or consume, Web methods. Web Service Proxies • A Web service proxy is an object that provides a local representation of a remote Web service. • A proxy is instantiated in the client’s own application domain, but calls to the proxy flow through the proxy and out to the Web service that the proxy represents.

  38. Web Service Clients & Proxies • Calling the corresponding Web service is a simple matter of calling methods on the proxy. CalculatorWebService calc = new CalculatorWebService (); int sum = calc.Add (2, 2); • When you call one of these methods, the proxy packages up the input parameters and invokes the Web method using the protocol encapsulated in the proxy (typically SOAP). • The proxy insulates you from the low-level details of the Web service and of the protocols that it uses. It even parses the XML that comes back and makes the result available as managed types.

  39. Generation of a Web Service Proxy • The wsdl.exe utility that comes with the .NET Framework SDK generates Web service proxy classes from WSDL contracts. http://msdn.microsoft.com/en-us/library/aa529578.aspx • For Web services written with .NET: All Programs->…-> Visual Studio Command Prompt cd to the directory you are going to write your client wsdl http://winserv1.cs.uakron.edu/xiaotest/calc.asmx (use V.S. 2008 Command Prompt on winsrev1) In the lab: Z: mkdir ws cd ws wsdl http://winserv1.cs.uakron.edu/xiaotest/calc.asmx • For Web services not written with .NET: find the WSDL contract (calc.wsdl), then wsdl calc.wsdl

  40. Generation of a Web service proxy • Wsdl.exe generates a CS file containing a class that represents the Web service proxy. • Use the class to invoke the Web service’s methods. • The proxy class’s name comes from the service name. Example: [WebService (Name="Calculator Web Service")] The resulting <service> tag in the WSDL contract looks like this: Name=Calculator_x0020_Web_x0020_Service The resulting proxy class is named CalculatorWebService. Wsdl.exe switches: /out:Calc.cs /language:vb /namespace:Calc /protocol:httpget /protocol:httppost /proxy:http://myproxy

  41. A Simple Web Service Client Write a console client (not a web client) for web service Calc.asmx. • Use Wsdl.exe to create a proxy class for Calc.asmx. wsdl http://winserv1.cs.uakron.edu/xiaotest/calc.asmx wsdl.exe responds by creating a file named CalculatorWebService.cs which contains the proxy class. • Create a new text file named CalcConsoleClient.cs to use the proxy class. using System; class MyApp { public static void Main () { CalculatorWebService calc = new CalculatorWebService (); int sum = calc.Add (2, 2); Console.WriteLine ("2 + 2 = " + sum); } }

  42. A Simple Web Service Client 3. Compile the CS files into a console application: csc CalcConsoleClient.cs CalculatorWebService.cs • Run CalcConsoleClient.exe. 5. The WS client program instantiates a Web service proxy, calls the service’s Add method, and displays the result.

  43. Write an ASP client for Calc.asmx • Create a proxy class for Calc.asmx the same way as above. • Create a new CS file named CalcASPClient.cs to use the proxy class. using System; using System.Web.UI; using System.Web.UI.WebControls; public class CalcASPClient : Page { protected Label Sum; protected TextBox op1, op2; public void OnAdd (Object sender, EventArgs e) { int a = Convert.ToInt32 (op1.Text); int b = Convert.ToInt32 (op2.Text); CalculatorWebService calc = new CalculatorWebService (); int c = calc.Add (a, b); Sum.Text = c.ToString (); }

  44. Write an ASP client for Calc.asmx 3. Compile the CS files into a dll for code behind: csc /target:library /out:bin\CalcASPClient.dll CalcASPClient.cs CalculatorWebService.cs 4. Create a new ASP file named CalcASPClient.aspx file to use the code behind. <%@ Page Inherits="CalcASPClient" %> <html> <body> <form runat="server"> <asp:TextBox ID="op1" RunAt="server" /> + <asp:TextBox ID="op2" RunAt="server" /> <asp:Button Text="=" OnClick="OnAdd" RunAt="server" /> <asp:Label ID="Sum" RunAt="server" /> </form> </body> </html>

  45. Write an ASP client for Calc.asmx 5. Create a web application directory: CalcClient. 6. Access the “client” through a browser. http://winserv1.cs.uakron.edu/xiaotest/CalcClient/CalcASPClient.aspx

  46. The event flow when the user clicks to add: User-> Web Client (a browser)-> Web Server (IIS) where Web app CalcASPClient.aspx is -> ASP.NET-> ASP Application (CalcASPClient.aspx and CalcASPClient::OnAdd)-> Web Service Proxy (CalculatorWebService::Add) -> Web Server (IIS) where Calc.asmx is-> ASP.NET-> Web Service (CalcService::Add)-> Web Service Client (Web Server (IIS) where CalcASPClient.aspx is) -> Web Client of Web Application CalcASPClient.aspx -> User.

  47. The CityView Application • A real Web application as a Web service client. • The Web service is the Microsoft TerraService (msrmaps.com/terraservice2.asmx). • It is a Web service front end to the Microsoft TerraServer database. • TerraServer (msrmaps.com) is one of the world’s largest online databases of photographs and maps of the Earth’s surface. • TerraService exposes TerraServer’s content via Web methods. Its WSDL contract is available at http://msrmaps.com/terraservice2.asmx?wsdl

  48. Web Services and More Code-Behind Asynchronous For-fee

  49. Web Services and Code-Behind • Coding: Calc2.asmx: <%@ WebService Class="CalcService" %> • Calc.cs: contains the class code and needs to be compiled into bin\Calc.dll. • Deploying: Root must be a web application directory (WS-Calc). http://localhost/calc2.asmx • Benefits: (a) Catches compilation errors before the service is deployed. (b) Enables to write Web services in languages that ASP.NET doesn’t natively support.

  50. Asynchronous Method Calls • An asynchronous call returns immediately, no matter how long the Web service requires to process the call. • To retrieve the results from an asynchronous call, you make a separate call later on by setting up a callback function. AsyncCallback cb = new AsyncCallback (AddCompleted); IAsyncResult res = calc.BeginAdd (2, 2, cb, null); public void AddCompleted (IAsyncResult res) { int sum = calc.EndAdd (res); }

More Related