Transcript Document 7250812
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 Client 2 Proxy of Interface 1 SOAP UDDI Registry 2 UDDI Registry 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://www.google.com/apps (usable applications).
Professional Web Service Examples
Microsoft Azure: https://azure.microsoft.com
Education: https://azure.microsoft.com/en-us/community/education/ Students: https://azure.microsoft.com/en-us/free/ Free Courses: https://mva.microsoft.com/product-training/microsoft-azure
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. Debugging on winserv1:
http://winserv1.cs.uakron.edu/xiaotest/calc.asmx
.
How does the test work?
Example: Calc.asmx
Users call http://winserv1.cs.uakron.edu/xiaotest/Calc.asmx up in a browser on the server . 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 BufferResponse CacheDuration Description EnableSession MessageName TransactionOption Description Enables and disables response buffering Caches responses, in seconds Adds a textual description to a Web method Enables and disables session state for this Web method (default: disabled) Specifies the Web method’s name 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 Which one can be converted to WS?
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 event handlers (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; (What is it?) operation elements that document the “operations,” or Web methods, that the service supports; (What it can do?) binding elements that document the protocols that the Web methods support; (How to use it?) 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
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
Consuming Web Services
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 return
a SOAP envelope containing the result, 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"
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
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
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
Writing Clients to Consume Web Services
Web Services
Client 1 Proxy of Interface 2 Client 2 Proxy of Interface 1 SOAP UDDI Registry 2 UDDI Registry 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/calc.asmx
(use V.S. Command Prompt on winsrev1) In the lab: Z: mkdir ws cd ws wsdl http://winserv1.cs.uakron.edu/xiaotest/calc/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
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.
2.
Use Wsdl.exe to create a proxy class for Calc.asmx.
wsdl http://winserv1.cs.uakron.edu
/
xiaotest/calc/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); } }
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: CalculatorWebService.cs wsdl http://winserv1.cs.uakron.edu/xiaotest/calc/calc.asmx
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" %>