Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
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? Web Services 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 A Web service is an application that exposes Web methods over the Web. 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/) 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. 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. 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. 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. 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). 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) 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; } 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; } } 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. 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. 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. Inside Web Services 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. 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. The WebMethod Attribute The WebMethod attribute tags a method as a Web method and supports the following parameters: Parameter Name Description BufferResponse Enables and disables response buffering CacheDuration Caches responses, in seconds Description Adds a textual description to a Web method EnableSession Enables and disables session state for this Web method (default: disabled) MessageName Specifies the Web method’s name TransactionOption Specifies the transactional behavior of a Web method 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; } 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 Converting Congo to Web Service Level Two: Enabling Sessions (1) Export methods in ShoppingCart (Congo.cs) (2) Initialization of ShoppingCart (Congo.asax) (3) 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); } 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 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. 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). 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> 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 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. 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. 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. 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> 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> 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> 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> Writing Clients to Consume Web Services Web Services 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 A Web service is an application that exposes Web methods over the Web. 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. 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. 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 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 A Simple Web Service Client Write a console client (not a web client) for web service Calc.asmx. 1. 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. 2. 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); }} A Simple Web Service Client 3. Compile the CS files into a console application: csc CalcConsoleClient.cs CalculatorWebService.cs 4. Run CalcConsoleClient.exe. 5. The WS client program instantiates a Web service proxy, calls the service’s Add method, and displays the result. Write an ASP client for Calc.asmx 1. 2. 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 (); } 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> 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 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. 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 Web Services and More Code-Behind Asynchronous For-fee 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 (WSCalc). 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. 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); } For-Fee Web Services Authenticate Web Service Callers: Assign authorized callers an authentication key and require them to pass the key in each method call. Transmit user credentials in HTTP Authorization headers. Transmit user credentials in SOAP headers. System.Web.Services.Protocols.SoapHeader For-Fee Web Services Server Side: public class AuthHeader : SoapHeader { public string UserName; public string Password; } class SafeService { public AuthHeader header; [WebMethod] [SoapHeader ("header", Required="true")] public int Add (int a, int b) { if (header.UserName == "jeffpro" && header.Password == "imbatman") return a + b; else throw new HttpException (401, "Not authorized"); }} For-Fee Web Services Client Side: SafeService calc = new SafeService (); AuthHeader header = new AuthHeader (); header.UserName = "jeffpro"; header.Password = "imbatman"; calc.AuthHeaderValue = header; int sum = calc.Add (2, 2); For-Fee Web Services The outgoing SOAP envelope (generated by .NET): <?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:Header> <AuthHeader xmlns="http://tempuri.org/"> <UserName>jeffpro</UserName> <Password>imbatman</Password> </AuthHeader> </soap:Header> <soap:Body> <Add xmlns="http://tempuri.org/"> <a>2</a> <b>2</b> </Add> </soap:Body> </soap:Envelope> Web Services 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 A Web service is an application that exposes Web methods over the Web. Finding Web Services On a Server (DISCO) On the Internet (UDDI) Web Service Discovery—DISCO How do clients know that a Web service exists? DISCO (short for “discovery”) is a file-based protocol for local Web service discovery—that is, for getting a list of available Web services from DISCO files deployed on Web servers. Publish a DISCO file on your Web server that describes the Web services. Clients interrogate the DISCO file to find out what Web services are available and where the services’ WSDL contracts can be found. DISCO’s chief disadvantage is that you can’t read a DISCO file if you don’t have its URL. Web Service Discovery—DISCO As an example, to publish two Web services: http://www.wintellect.com/calc.asmx http://www.wintellect.com/locator.asmx Deploy the following DISCO file at a well-known URL on your server. The contractRef elements identify the URLs of the Web services’ WSDL contracts. <?xml version="1.0" ?> <discovery xmlns="http://schemas.xmlsoap.org/disco/" xmlns:scl="http://schemas.xmlsoap.org/disco/scl/"> <scl:contractRef ref="http://www.wintellect.com/calc.asmx?wsdl" docRef="http://www.wintellect.com/calc.asmx" /> <scl:contractRef ref="http://www.wintellect.com/locator.asmx?wsdl" docRef="http://www.wintellect.com/locator.asmx" /> </discovery> Web Service Discovery—DISCO Or deploy a VSDISCO file to enable dynamic discovery. The following VSDISCO file automatically exposes all ASMX and DISCO files in a host directory and its subdirectories, with the exception of those subdirectories noted with exclude elements: <?xml version="1.0" ?> <dynamicDiscovery xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17"> <exclude path="_vti_cnf" /> <exclude path="_vti_pvt" /> </dynamicDiscovery> Web Service Discovery—UDDI UDDI (Universal Description, Discovery, and Integration) is a global (Internet) Web service directory that is itself implemented as a Web service. Developed by IBM, Microsoft, and Ariba. A specification for building distributed databases that enable interested parties to “discover” each other’s Web services. No one company owns the databases; anyone is free to publish a UDDI-based business registry. Operator sites have already been established by IBM and Microsoft. Web Service Discovery—UDDI UDDI sites are themselves Web service sites. They publish a pair of SOAP-based APIs: an inquiry API for inquiring about companies and their Web services a publisher API for advertising a company’s Web services (operator sites typically limit the publisher API to registered members). Most developers will use high-level tools to query UDDI business registries and generate wrapper classes that allow them to place calls to the Web services. Referencing Web Services in Visual Studio .NET • Project->Add Service Reference->Advanced->Add Web Reference • URL: http://winserv1.cs.uakron.edu/xiaotest/ws/Calc.asmx?wsdl • Go (you should see the service description and methods) • Web reference name: CalcService (any name you want for the name space for the proxy) • Add Reference • View->Class View to explore the classes • In your forms1.cs file using your-project-name-space.CalcService CalculatorWebService calcws; calcws = new CalculatorWebService (); Dawn of a New Era True cross-platform distributed computing based on HTTP, XML, and SOAP. Summary: Web Services (Architecture), Web Methods, WSDL, SOAP, XML, DISCO, UDDI, Web Service Clients (Stand Alone, Web Based), Web Service Proxies, For-Fee Web Services.