Document 7250812

Download Report

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"

2 2

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 4

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 4

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 4

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 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.

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" %>

+

Write an ASP client for Calc.asmx

5.

6.

Create a web application directory: CalcClient. 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.

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 (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.

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): jeffpro imbatman 2 2

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.

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 local

(short for “discovery”) is a file-based protocol for 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.

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:

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 ();

Cloud Computing

Cloud Computing

• Computing technology and infrastructure offered by vendors

on demand

. •

Based on virtualization

techniques, hence offers the benefits of virtualization • Services consumed based on

pay per use

model

– No up-front cost – No commitment

Cloud Computing

• • Services offered as – Software as a Service (

SaaS, Applications

) • Web services, Google Apps – Platform as a Service (

PaaS, Operating Systems

) • Microsoft Azure, Google App Engine – Infrastructure as a Service (

IaaS, Hardware

) • Amazon’s Elastic Compute Cloud, Microsoft Azure VM role instance

http://en.wikipedia.org/wiki/File:Cloud_computi ng.svg

Why Cloud Computing?

• Virtualization benefits – Cost-effective, reliable, flexible and portable • No hardware requirements • Cloud vendor worry about software upgrades and hardware failures – Highly available • Application installed in the cloud - data centers • Access via internet browser • Large-capacity storage and high performance computing • Add resources on-demand, scalable

Cloud Vendors

• Microsoft Azure Platform – Windows Azure Compute and Storage – SQL Azure – Windows Azure AppFabric – https://windows.azure.com/default.aspx

• Amazon – Elastic Compute Cloud – Simple Storage Service – Relational Database Service – Elastic Load Balancing – https://console.aws.amazon.com/ec2/home?region=us-east-1

Cloud Computing

http://

www.windowsazure.com

http

://aws.amazon.com/ec2/ http://www.ibm.com/cloud-computing http://www.google.com/apps/intl/en/business/ Salesforce.com

www.

rackspace

.com/Cloud

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

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.