web services overviewdotnet.jku.at/buch/cd-de/dotnetdays/webfiles/dnrk/wso.doc · web viewthis...

84
Web Services Overview

Upload: hanguyet

Post on 14-Apr-2018

216 views

Category:

Documents


1 download

TRANSCRIPT

Web Services Overview

2 Web Services Overview

Overview

ObjectivesThis module will introduce you to Web Services. Web Services are a key concept in the Microsoft® .NET Framework to create and interconnect Web applications across the Internet.

While you don’t have to build Web Services using the Microsoft ASP.NET Web Services platform, it is recommended, because it provides several features that simplify developing Web Services.

What You Will Learn Overview of Web Services How to design, create, and use Web ServicesRelated Topics Covered in This Lesson How Web Services are built on the .NET Framework Why to use the ASP.NET Web Services platform

Web Services Overview 3

Overview

Section 1: OverviewWe start with an overview of distributed computing and Web development as it is today. Then the basics of Web Services are introduced. And you will see what the key benefits are that Web Services will bring to your distributed (Web) applications.

4 Web Services Overview

Overview

Looking back …Traditional distributed computingIf we are talking about distributed computing, we are talking about the client/server model. Today this term implicitly means three-tier architecture, where we have:

First tier: user interface. Second tier: business logic. Third tier: database.

Normally each of these tiers resides on a dedicated machine. The first tier is on a client, which could be a browser. The second tier is on a server, in this case the Web server. The last tier could be, for example, a Microsoft SQL Server™ database.

Distributed computing requires distributed object model or remoting architecture. With this you can develop distributed applications as you did with a local programming model, and even call services on remote systems. This is called remote method invocation.

Besides this we need the ability to interchange services—or components! Components are black boxes offering services or functionalities, and they provide for packaging and interoperability.

The most important object models today are:

COM: Component Object Model. CORBA: Common Object Request Broker

Architecture. Java RMI and EJB: Java Remote Method Invocation

and Enterprise JavaBeans.

Web Services Overview 5

Microsoft Windows® DNAMicrosoft subsumed all of its products related to distributed applications under the term Windows Distributed interNetwork Applications (DNA).

Windows DNA encompassed, for example, DHTML, COM, ASP, and Message Queuing (formerly known as MSMQ).

The interactive WebMany Web sites are like brochures, presenting static information about a person, a company, or a product. But if you want to collect information from the visitors to your site or let a user manipulate data on your server, you must build an interactive Web page. Most probably, you are going to need some or all of the following technologies to automate your site:

HTML forms: the standard mechanism to collect user input from Web sites.

Data handling: A comfortable way to work with data (on the server side) is a component accessing a database.

Validation: When working with databases it is important to validate a user’s entries, which can be done by using scripting code on the client side.

Security: You can protect your application and data against misuse or malicious attacks by using security mechanisms provided by, for example, HTML or the Web server, or you can implement your own security component. You can also make use of several protocols for secure communication between Web client and server.

State management and transactions: HTTP is a stateless protocol. But you can use different techniques to maintain state information between related or consecutive requests.

6 Web Services Overview

Overview

What’s Wrong with That?Distributed object models don’t scale to the InternetObject models like COM, CORBA, and RMI tightly couple a service and the consumer of this service.

This is a reason for the need of a homogeneous infrastructure. But there’s no guarantee that the service and the consumer use the same operating system, programming language, or object model.

Another problem arises with versioning: if the implementation changes on one side, the other side will fail.

Limited COM support on non-Windows platformsWhile COM is widely supported on the Windows platform, the support on non-Windows platforms like UNIX is limited.

The usage of COM within Java requires the Microsoft Java Virtual Machine. This is really an issue, because Microsoft JVM is not supported on non-Windows platforms.

CORBA is a remoting architectureFrom the beginning CORBA was designed to target the problem of inter-machine communication, providing for cross-language and cross-platform interoperability—between CORBA-compliant Object Request Brokers (ORBs). The CORBA architecture allows clients in one process to call methods in remote processes. That’s why it is not really a component architecture. Even so, CORBA is called the leading and most widely used remoting architecture.

Web Services Overview 7

To solve the programming problems with components in CORBA, the Object Management Group (OMG) presented object services. Most of these object services are additions to CORBA, and were designed by different committees. So, this is the point where CORBA starts getting messy.

In 1997 OMG published a “request for proposals” (RFP) on the CORBA Component Model (CCM). This seems to be a good (!) architecture, but until now there’s a lack of CCM implementations.

Since CORBA is a specification—not a product—implementations of CORBA are vendor specific. So, if you make use of vendor-specific features or services, your applications may not be portable.

EJB—Enterprise JavaBeansWith Enterprise JavaBeans you are tied to one language: Java!

The purely interactive WebEach of the aforementioned topics related to the interactive Web provides support up to a more or less satisfying level. But if you want to build real Web applications you need solutions that go over and above this level.

Data handling: The existing data access infrastructure was not designed for the Internet. It was built for tightly coupled and linked environments.

Security: One point we like to stress here is code identity. You must be able to protect your server from malicious mobile code and allow friendly mobile code to run safely.

State Management: Almost all state management solutions work with cookies, so that state management will only be maintained if the client browser permits cookies. But many users are afraid of enabling cookies, because of their bad reputation with respect to privacy.

Administration: If any changes are made to your Web application and you have to update one or more files, you have to bring your Web server offline. Otherwise it is like pulling the rug out from under your applications.

8 Web Services Overview

Overview

Web Services—BasicsToday there is a strong desire for easy-to-use and easy-to-create Web applications, and those applications are required to be language and platform independent. In response to this need, Microsoft’s .NET Framework provides Web Services.

Expose services to other processesWeb Services expose their functionality via standard Web protocols, like HTTP and XML, and enable you to interconnect Web applications. Broadly speaking, Web Services are URL-addressable resources that return requested information to a client or manipulate the data model behind the Web Service.

Black boxesLike components, Web Services are black boxes and can be reused without knowledge about how the service is implemented.

Based on the .NET FrameworkWhile you don’t have to build Web Services using the ASP.NET Web Services platform, it is recommended, because it provides several features that simplify developing Web Services. So ASP.NET and the .NET Framework plays an important role for Web Services.

Based on open standardsWeb Services are based on open standards like HTTP, XML, and SOAP. So, any application that supports these standards is able to support Web Services!

Web Services Overview 9

Overview

Web Services—BasicsInterconnectWith Web Services you can easily connect applications—even via the Internet.

Different clients can make use of Web Services. For example, a browser can make use of the functionality the service offers. Also Web Services themselves can communicate with each other or just call methods that are provided by other Web Services.

And many different devices can consume Web Services. For example, a WAP device such as a mobile phone can invoke a Web Service.

Distribution and integration of application logicA significant advantage of Web Services is that developers can program against a Web Service to import its functionality into their own Web applications. We now have the technology to not only distribute application logic, but also to integrate functionality that is provided by a “service” that resides “somewhere out there.”

Web Services are loosely coupledBecause Web Services are loosely coupled, you can change the implementation of a service without affecting the connected partner. The basic principle to achieve this is a homogeneous infrastructure that meets two requirements:

First, we need underlying protocols that are common to all communicating entities. This is covered, because Web Services are based on the aforementioned open

10 Web Services Overview

standards. One important point to stress is that XML plays a major role here (more on that later).

Second, we need to ensure that communication takes place asynchronously through messages.

Enable the “programmable Web”Because of these characteristics, Web Services enable the programmable Web. We are no longer restricted to a purely interactive Web.

Web Services Overview 11

Overview

Distributed Web ApplicationsThis architecture and set of features provide an infrastructure for building distributed Web applications.

ASP.NET defines a Web application as the sum of all files, handlers, modules, and executable code that can be invoked or run in the scope of a given virtual directory on a Web application server.

Distributed applicationsYou can create distributed applications where Web Forms build the presentation layer, the middle tier consists of the Internet and Web Services, and the third tier are databases implemented by Microsoft SQL Server.

For example, a user can access a Web application that resides on a dedicated Web server using a Web browser. The application can use services provided by the operating system of the application server, as well as Web Services exposed by the same server.

Additionally, the Web application can call Web Services provided by a different server. This second server can be accessed via the Internet. This could be a pure Web Service server, exposing Web Services whose functionality ranges from simple services for elementary computation to services that represent complex databases.

Web Services represent black-box functionality and can be reused without worrying about the service’s implementation.

12 Web Services Overview

Architecture

Section 2: ArchitectureIn this section you will get an overview of the .NET Framework architecture, the programming model, and the configuration system.

Web Services Overview 13

Architecture

The .NET Framework ArchitectureBefore we go into detail on Web Services, let’s have a look at the underlying architecture.

The .NET Framework architecture is built on top of the operating system services. This framework contains different layers.

In this picture there is the .NET Framework common language runtime, which resides on top of the operating system services. The common language runtime loads and executes code that targets the runtime. This code is therefore called managed code.

The runtime gives you, for example, the ability for cross-language integration. For that matter it provides the common type system, which defines a standard set of types and rules to create new types.

Another point is that information related to executable code is stored together as metadata. The metadata is generated from the source code. Executable code and metadata together are characterized as self-describing components.

Further on, a group of resources and types along with the corresponding metadata (manifest) are referred to as an assembly. The manifest contains the full definition of an assembly’s functionality, which makes the use of the assembly fairly simple.

A resource may be a dynamic-link library (DLL). Now you can use that resource—the DLL—by just copying the assembly to whatever location you want; no installation, no registration.

14 Web Services Overview

As mentioned earlier, the .NET Framework provides a rich set of class libraries. These include base classes, like networking and input/output classes, a data class library for data access, and classes for use by programming tools, such as debugging services. All of them are brought together by the Services Framework, which sits on top of the common language runtime.

The top layer of the .NET framework consists of the Windows application model and, in parallel, the Web application model.

Before focusing on the Web application model, let me tell you a few things about the Windows application model, or Windows Forms. Windows Forms make graphical behavior language-independent, because they are based on the .NET Framework. They provide an extensible set of object-oriented classes, which you can use to develop more traditional Windows applications and take advantage of new Windows 2000 features. You can configure your application to use versions of shared components your application was built and tested with. You can include existing COM components, but also make use of Web Services (which are explained later).

Now let us look at the Web application model, in the slide presented as ASP.NET, including Web Forms and Web Services.

ASP.NET comes with built-in Web Forms controls, which are responsible for generating the user interface. They mirror typical HTML widgets like text boxes or buttons. If these controls do not fit your needs, you are free to create your own user controls.

Web Services brings you a model to bind different applications over the Internet. A Web Service can be understood as a contract between server and client. Those contracts are described by the XML-based Web Services Description Language (WSDL). Doing so, Web Services are defined as ports that are endpoints that communicate via XML-based messages.

Web Services Overview 15

Architecture

Programming ModelProgramming Web Services is something similar to COM programming. But unlike COM, Web Services are based on simple, open standards and use XML-based communication instead of binary communication.

Compiling code in .NET means that the compiler emits Microsoft intermediate language (MSIL) and produces metadata—if you compile your source code to managed code. The code is called managed code, because it is managed by the common language runtime.

MSIL is code in an assembly language–like style and can be executed by the runtime. MSIL is CPU independent and can be efficiently converted to native code.

The conversion to native code in turn can be CPU-specific and optimized. The intermediate language provides a hardware abstraction layer.

Metadata is generated from the source code and contains information that is related to the executable code. This metadata and a collection of physical files are grouped into an assembly. Assemblies are essential to the common language runtime.

Metadata is sometimes referred to as an assembly’s manifest. A manifest can be stored as part of a DLL or as a stand-alone file.

Among other things, a manifest contains:

A list of all files in the assembly. Version information, including version and build

numbers. The assembly’s shared name information.

16 Web Services Overview

Type reference information. Optionally, a developer can store a description of the

assembly, configuration information, or product information.

The common language runtime has an Execution Engine creates the Virtual Execution System (VES). The VES is, among other things, responsible for loading managed code and converting MSIL to native code.

Loading the code means two things. First, the implementation is loaded into memory. Second, the code is prepared for execution using the information that is stored in the assembly. Preparation includes, for example, resolving type references and loading related class libraries.

Now that the code is loaded and prepared it has to be converted from MSIL into native code. This is done by a just-in-time (JIT) compiler that is also part of the runtime, on the same computer architecture that the code should run on.

Web Services Overview 17

Architecture

Configuration (1/2)ASP.NET ships with a rich and flexible configuration system for both developers and administrators.

Concepts and architectureAll configuration settings are stored in XML-based files named Web.Config. Those files are human readable and writeable. They are easy to edit by developers and administrators using text editors or, for example, Perl scripts. Configuration files are kept within the directory tree of your Web application.

You can store different Web.Config files on the server. Each configuration file affects the directory that it is placed in and all subdirectories. This is called hierarchical configuration architecture.

For example, assume that you stored a Web.Config file for your Web application in SubDir1 and none in the root directory. Then all configuration settings for the root directory are taken from the default Web.Config file (more about this on the next slide). The application subdirectories SubDir1 and SubDir2 are configured by the settings in the Web.Config file that is stored in SubDir1. SubDir2 will inherit all configuration settings of its parent directory.

Of course, you don’t have to write one configuration file for each directory of your application. It is possible to apply settings to specific directories using the <location> tag.

Be careful when using virtual directories, because there are some side effects of configuration inheritance, which can cause unexpected behavior or failures. For example,

18 Web Services Overview

if you access a file using a path that contains a virtual directory, configuration files in parent directories are ignored. If your virtual directory named AppDir1 is physically located in

C:\RootDir\SubDir1\SubDir2

and you use the URL

http://localhost/AppDir1/MyFile.aspx

the configuration information stored in SubDir1 is not loaded.

Nevertheless, this hierarchical configuration architecture is a simple way to customize your configuration. Additionally, all changes are automatically detected by the system. There is no need to register new configuration files or restart the application or the server.

One important thing to mention is that all configuration settings apply only to ASP.NET page files (.aspx), and not to .html or .asp files. Keep this in mind if you are thinking about security settings. This can become a typical security hole.

Web Services Overview 19

Architecture

Configuration (2/2)Web.Config fileAs mentioned before, the Web.Config file is an XML-based file. You use particular tags to specify the settings and to customize the configuration of your application. All configuration settings must reside between the starting <configuration> and ending </configuration> tags. Using the supported set of tags, you can easily build your own configuration file.

ASP.NET has a default configuration file machine.config located in the directory %windir%\Microsoft.NET\Framework\v1.0.2914\CONFIG. This file makes use of the standard set of configuration section handlers. Those section handlers are used to specify your settings within the Web.Config file.

But if all the standard section handlers do not meet your needs, you are free to extend the set of handlers by implementing your own. To do that you must create a class that implements the System.Web.Configuration. IConfigurationSectionHandler interface.

WebServicesConfiguration classFor Web Services, the WebServicesConfiguration class contains configuration information. This information is loaded from the <webServices> section in the Web.Config file.

20 Web Services Overview

Creating Web Services

Section 3: Creating Web ServicesSection 3 will introduce you to:

The basics of creating Web Services. The Web Services infrastructure. Code and syntax. The Web Services namespace. Publishing. Discovery.

Web Services Overview 21

Creating Web Services

Creating Web Services—Basics.asmx fileWeb Services normally have the extension .asmx. They are stored in the virtual path of your ASP.NET Web application. An .asmx file can be part of an existing solution or a stand-alone file.

Web Services infrastructureThe infrastructure of Web Services contains three main parts: discovery, description, and wire format.

Microsoft Visual Studio.NETMicrosoft Visual Studio.NET gives you support in developing single Web Services and complete Web applications. You can create Web Services using the templates:

Visual Basic.NET Web Service C# Web Service Managed C++ Web Service

22 Web Services Overview

Creating Web Services

Web Services InfrastructureWeb Services infrastructureThe three main parts of the infrastructure of Web Services are:

DiscoveryThis is the process of locating a Web Service and getting information about its capabilities. If you are to publish a Web Service, you can build an XML-based .vsdisco file, so that the Web Service can now be programmatically discovered.

DescriptionA Web Service can be described using Web Services Description Language (WSDL). WSDL is presented later in this module.

Wire FormatWeb Services work with protocols like HTTP-GET, HTTP-POST, SOAP, MIME, and more. With WSDL you can make use of any other transport protocol. More on this topic later.

All of the aforementioned requests lead to a response that consists of an XML-formatted document.

Web Services Overview 23

Creating Web Services

Code and SyntaxNow let’s see how to implement a Web Service:

WebService DirectiveFirst you have to specify the settings for ASP.NET Web Service compilers. Therefore the first line of your .asmx file must be the WebService directive, in which you specify the programming language and the class name of the Web Service.

WebMethod AttributeAll Web Services must inherit from the WebService base class. To make a single method of your Web Service class publicly available you assign the WebMethod attribute to it.

Code Declaration SyntaxThe implementation of the class can reside inline in the current .asmx file, or outline in another file.

OutlineIf the class does not reside within the current file, you use a directive similar to this. The corresponding Web Service class has to be stored within the /bin directory of your Web application.

InlineThis sample shows how to use the WebService directive and the WebMethod attribute when both the directive and the class reside in the same file.

24 Web Services Overview

Creating Web Services

Sample .asmx fileThe first line is the WebService directive, which defines the programming language and a reference class name. The specified class resides in the same file.

You must include namespaces if you want to use .NET class libraries.using System.Web.Services;must be included to build a Web Service.

The first method implemented in this class MathService is the method Subtract. The WebMethod attribute makes the method publicly available.

You can implement methods without using the WebMethod attribute, as in Subtract_vs. But those methods will not be published.

Web Services Overview 25

Creating Web Services

System.Web.Services Namespace (1/2)The namespace System.Web.Services consists of the following five classes:

System.Web.Services.WebServiceThis is the base class for all Web Services—all Web Services must inherit from this class.

It provides properties like the Session property, which gives you a reference to the HttpSessionState object, and methods like GetType() to get the object’s type.

System.Web.Services.WebServiceAttributeUse this class optionally to add additional information to the Web Service. This can be, for example, a string describing the Web Service’s functionality.

System.Web.Services.WebMethodAttributeYou’ve already learned about the WebMethod attribute and how it makes a class method a Web Service method.

26 Web Services Overview

Creating Web Services

System.Web.Services Namespace (2/2)System.Web.Services.WebServiceBindingAttributeWSDL describes a binding as a definition of a set of operations. With this attribute Web Methods can be bound to a class that implements a Web Service, which is not the default Web Service.

System.Web.Services.WebServicesConfigurationThis class contains configuration information that is loaded from the <webservices> section of the corresponding Web.Config file.

System.Web.Services.WebServicesConfigurationSectionHandlerA configuration section handler is responsible for interpreting and processing the configuration settings stated in the configuration sections of the Web.Config file.

Web Services Overview 27

Creating Web Services

Publishing a Web ServiceA Web Service must be published if you want a client to gain access to it.

Expose Web Service and Web Service methodsIf you want to expose your Web Service and make it publicly available, there are two main steps to follow:

Place the Web Service on a Web server. Publish the appropriate discovery mechanisms.

Now your Web Service can be accessed via URLs using, for example, a browser.

Create a Web Service proxyIf you want developers to program against your Web Service, you have to create a proxy and an assembly.

You can generate the proxy using the WSDL.exe command-line tool (described later in this module).

An assembly is a group of resources and types along with the corresponding metadata (manifest). A resource may be a DLL.

To create an assembly—a DLL—of your Web Service you use the appropriate compiler. Now you can use your service by just copying the assembly to whatever location you want to use it; no installation or registration is required.

Publish WSDL contract and HTML descriptionYou don’t have to implement additional code or configure your server to publish a description of your Web Service and its functionality.

28 Web Services Overview

If a client knows the base URL of your Web service, a simple HTML description of it can be received by entering the URL without any method names or parameters.

A more formal description is a WSDL contract, which can be obtained by sending a request via URL with the parameter “?WSDL” to it.

Web Service clientsA client to a Web Service can be, for example, a browser or another Web application.

Web Services Overview 29

Creating Web Services

Discovery of Web ServicesWhen publishing a Web Service, you have to create a discovery mechanism, so that a user can find and make use of your Web Service.

.vsdisco fileYou make your Web Service available to a user by creating a discovery file that has the extension .vsdisco. This is a XML-based document that contains information about a Web Service’s capabilities.

A discovery file contains links to other resources that describe Web Services. Usually those links are URLs of .asmx files. The URLs include the “?WSDL” parameter to retrieve the WSDL description of the Web Service.

.vsdisco files are stored in the root directory of an application server. A user can browse the directory to locate .vsdisco files and to find out what Web Services are available.

The dynamic discovery document is a special kind of discovery document that helps you to find all .disco files stored on a server.

Users can access discovery documents by using their URLs. Start discovering a given URL with the DISCO.exe tool. For example, you can find out what Web Services are provided on Microsoft’s TerraServer.

But, you don’t have to write a discovery file on your own. Visual Studio.NET automatically creates a discovery document for you when building a Web Service.

But you can also use Visual Studio.NET to easily add references to other existing Web Services to your project.

30 Web Services Overview

All you have to know is the URL of the dynamic discovery document.

Universal Discovery, Description, and Integration (UDDI)The Universal Discovery, Description, and Integration (UDDI) project provides a global directory of Web Services. For more information see http://www.uddi.org/.

Web Services Overview 31

Creating Web Services

DISCO.exeDiscovering Web ServicesThe command line tool disco.exe can be used to discover the Web Services provided by a server with a certain URL. It generates some files on your local hard drive, including the WSDL-description of the Web Service.

Command line sampleHere is a sample of how to use the disco.exe command line tool:disco /out:location /domain:domain /username:username /password:password http://localhost/WebService1/WebService1.vsdiscoIn this sample we want to discover the URL http://localhost/WebService1/WebService1.vsdisco. We can specify a username and a password that might be needed to access the .vsdisco file. With the /out option you can specify in which directory the tool should generate the output files.

32 Web Services Overview

Creating Web Services

WSDL.exeCreate client proxy classWith the WSDL.exe tool you can generate a proxy for a Web Service. Although Visual Studio.NET generates a proxy for your Web Service when you reference it, there might be situations where you want to use this command-line tool. The default language is C#.

InputAs an input for WSDL.exe you need the WSDL contract for the Web Service.

When generating a proxy you can specify, for example, the language (C#, Visual Basic®, or JScript.NET) or the protocol (HTTP-GET, HTTP-POST, or SOAP).

OutputThe output of the tool is a single source file containing the proxy class in the specified language. It also contains the appropriate network invocation and marshalling code. Additionally, you can use the tool to create a WSDL file in a local directory, if you know the URL of the Web Service:wsdl /c:proxy /l:C# /namespace:MathServiceSpace MathService.wsdlThe input file is MathService.wsdl. The command line options show that we want to create a proxy implemented in C#. The namespace option is added to create the namespace, which might be used by a Web Service client.

Web Services Overview 33

Using Web Services

Section 4: Using Web ServicesIn this section you will get an overview of the application model, and you will see how to invoke and consume Web Services. You will be introduced to the Web Services Description Language (WSDL).

34 Web Services Overview

Using Web Services

Application ModelA Web Service developer creates a Web Service and publishes it as part of a service application. This application resides on a Web server in an .asmx file—here Web Server 1.

The methods exposed by this Web Service can be invoked by sending HTTP requests to the URL of the .asmx file.

With the WebServiceUtil.exe tool you can generate a proxy class for a Web Service. This proxy hides the network and marshalling details from a Web application developer who, for example, creates an ASP.NET file.

This file contains a Web Form and resides as a part of a service application on another Web server—Web Server 2. Through the Web Forms and the proxy class the developer can programmatically access the Web Service on Web Server 1

Web Services Overview 35

Using Web Services

Invoking Web ServicesWeb Services are URL addressableWeb Services are URL addressable, which means that they can be invoked by using HTTP requests. The method and its arguments are included in the request.

ProtocolsWeb Services can be invoked using the following protocol schemes:

HTTP-GET HTTP-POST HTTP-SOAP

When using HTTP-GET, the method name and the arguments are part of the URL.

Using HTTP-POST, the method name is part of the URL, too. But the arguments are part of the POST body.

SOAP defines an XML grammar for identifying the method name, wrapping its arguments, and returning results!

36 Web Services Overview

Using Web Services

Invoking Web Services: HTTP-GET and POSTStandard HTTP-GETWith an URL like http://server/appl/service.asmx/method?param=value

you invoke a Web Service method. The method’s name is identified by the PATHINFO of the request. Arguments are passed as query string values, where the query string key specifies the parameter name. Multiple parameters of any primitive .NET runtime data type could be passed to the method.

The result returned from the runtime is an XML document. Any runtime types are supported as return values.

HTTP-POSTThe difference between GET and POST requests is that with HTTP-POST a method’s arguments are provided within the body of the POST request.

Web Services Overview 37

Using Web Services

Invoking Web Services: HTTP-SOAPSOAP is another protocol that can be used to invoke Web Services.

XML grammarSOAP provides an XML grammar for specifying the Web Service method, passing its parameters, and returning results.

Supports all standard .NET data types and value classesAll types that are supported by HTTP-GET and POST are also supported with SOAP. Additionally classes, structs, or datasets can be passed as arguments.

SOAP is the default protocol.

Class and struct marshallingAll public fields and properties of a class are serialized in XML format. This is how class and struct marshalling is provided.

38 Web Services Overview

Using Web Services

Consuming Web ServicesRequest without method name and parametersWhen you invoke the Web Service without specifying a method name or arguments, the runtime engine returns an HTML description of the Web Service.

It contains the capabilities of the Web Service, its methods, and protocols.

Web Service can return WSDLBut requests using HTTP-GET, -POST, or -SOAP can return WSDL.

Request with parameter “?WSDL”To retrieve WSDL you have to add the parameter “?WSDL” to the URL.

Now your browser will show you a formal WSDL description of Web Service in return. This is—as mentioned earlier—an XML-based document that can also be used as input for WebServiceUtil.exe tool to generate a proxy class.

Web Services Overview 39

Using Web Services

WSDL (1/2)But what is WSDL in more detail?

XML grammarWSDL is an XML grammar that defines services and ports that communicate with each other through messages.

It also defines binding extensions including SOAP 1.1, HTTP GET/POST, and MIME. Binding is used to specify a protocol or data format for a message, an operation, or a communication endpoint.

Public description of a Web Service and its contentA WSDL document, describing a Web Service and its content, is sometimes referred to as a WSDL contract.

Core ElementsThe core elements of a WSDL contract are:

service, port, and portType operations and message

Let’s go into more detail on these elements.

40 Web Services Overview

Using Web Services

WSDL (2/2)A service is a collection of related communication endpoints. A single endpoint is called port, and each port specifies an address and a binding.

Binding is used to declare a specific data format and protocol details.

Now we have ports as communication partners, and we know which protocol and format to use for communication. But we don’t know what is communicated or how ports should handle the exchanged data.

The data that is transmitted between the ports is called a message, and the portType defines an abstract set of operations that can be applied to messages.

WSDL describes four operations:

One-wayReceiving a message

Request-responseReceiving a message and sending a correlated message

Solicit-responseSending a message and receiving a correlated message

NotificationSending a message

So, a portType is like an interface declaration of a service, while the port gives you its location.

Web Services Overview 41

Using Web Services

Sample WSDL fileThis sample shows a part of a WSDL file and should give you an impression of how it is structured. We will concentrate on the portType and service sections.

All sections are enclosed by the <definitions> tag.

You can use the <import> tag to include external files. This allows you to split the code into different files for reuse.

The portType section defines one operation named opName. This port supports request-response operations, receiving a message (input) and sending a correlated message (output) as a response. The physical location of the Web Service method that is called is specified in the binding section.

In the service section you can group ports into one service specified by the service name. You can use, for example, the <soap:address> tag to give the port an address.

42 Web Services Overview

Advanced Web Services

Section 5: Advanced Web ServicesSection 5 introduces state management, security, transactions, and the execution model. You will see how to build distributed Web applications using these advanced solutions.

Web Services Overview 43

Advanced Web Services

State ManagementWeb Services are statelessOn each request, a Web Service class instance is instantiated and thrown away when it is no longer used. This means that Web Services are stateless. If you need to share data between different requests, you can use, for example, the ASP.NET built-in session state feature.

ASP.NET Session StateASP.NET provides simple and easy-to-use session state management. A session is restricted to a logical application and defines the context in which a user communicates with a server.

ASP.NET session state functionality includes:

Request identification and classification Store data across multiple requests Raise session events Automatic release of session data

All session state information in .NET is stored by default in a state server process. This process runs as a Windows service. The state can be serialized and stored as binary data in memory. Additionally you have the possibility to store the data in a SQL Server database.

The state service and the state information could reside on the same server as the application, but it can also be stored on an external state provider. This state provider is a dedicated machine managing the state information. With this arrangement, session state is still available after a crash of the application server.

44 Web Services Overview

Advanced Web Services

SecurityThere are several reasons why you should think of security when you want to expose a Web application to the public.

Reasons for SecurityOne reason is that you might want to prevent access to some areas of your Web server. Different groups of users might have different access rights to different areas or directories of your application or server.

You also need security when you have to record and store secure relevant user data. This data has to be protected against public and unwanted access.

Security ConfigurationThe Web.Config file has already been introduced. So it may be enough to mention that all security related configuration information in ASP.NET is contained in this file. You have the ability to configure three fundamental functions for ASP.NET security: authentication, authorization, and impersonation. Therefore your Web.Config will have three additional sequences enclosed in the parent <security> tag.

Authentication, Authorization, ImpersonationAll your Web clients communicate with your Web application through IIS. So you can use IIS authentication (Basic, Digest, and NTLM/Kerberos) in addition to the ASP.NET built-in authentication solutions.

The ASP.NET authentication providers are:

Passport authentication, which is a centralized authentication service provided by Microsoft.

Web Services Overview 45

Cookie authentication, which issues a cookie to the request/response that, contains the credentials for reacquiring the identity.

Windows authentication, which is used in conjunction with IIS authentication.

IIS authentication methods assume that the user is already known to the server, while ASP.NET methods do not. With Passport authentication your site has to support Microsoft Passport credentials, and Cookie authentication assigns an identity to an “unknown stranger” who complies with some rules.

Once a client request is authenticated and an identity is given, we have to determine whether this identity is allowed to have access to the requested resource.

ASP.NET distinguishes two modes of authorization: file and URL. File authorization is active when using Windows authentication. To determine if access should be granted or not, a check against an Access Control List (ACL) is done. In URL authorization, identities are mapped to pieces of the Uniform Resource Identifier (URI) namespace to selectively allow access to parts of the namespace.

When using impersonation, IIS and Windows file access security play a role here.

IIS authenticates the user using Basic, Digest, or Windows NTLM/Kerberos authentication. IIS then passes a token to ASP.NET; the token is either authenticated or unauthenticated.

ASP.NET now impersonates the given token, so that the ASP.NET application can operate with the identity of the requesting client. The access to the requested resource is permitted according to NTFS settings (obviously, the Web server file space must be formatted as NTFS).

Code Access SecurityBesides the ASP.NET built-in security features, a developer can make use of several security solutions of the .NET Framework. Here we focus on one of them: code access security.

With code access security you can admit code originating from one computer system to be executed safely on another system. Therefore the code’s identity and origin has to be verified.

To determine whether the code should be authorized or not, the runtime’s security system walks the call stack, checking for each caller whether access to a resource or performing an operation should be allowed.

46 Web Services Overview

In the .NET Framework you must specify the operations the code is allowed to perform. This can be done, for example, in the assembly of your Web application.

Web Services Overview 47

Advanced Web Services

Transactions (1/2)In some Web application scenarios you have a series of correlated operations corresponding to consecutive HTTP requests. You need to ensure that if one single operation fails, all related operations fail.

For example, a toolkit online shop sells electrical machines. If a customer orders a drill, it has to be assured that you have all information from the customer that you need, the drill is shippable, the order is saved to your database, and more. Transaction processing is the technology that enables you to control the whole process.

With Web Services built on the ASP.NET Web Services platform your code can be executed within automatic transactions.

Like ASP.NET Web FormsLike ASP.NET Web Forms, Web Services can interact with .NET resources in the context of COM+ transactions.

COM+ ServicesWindows 2000 provides COM+ Services including Events, Queuing, and Transaction services.

COM+ Automatic Transactions provides for the ACID directive, which means a transaction has to be atomic, consistent, isolated, and durable.

If a Web Service is running within a COM+ transaction context, this Web Service can interact with resources like a SQL Server or Message Queuing server maintaining the ACID properties.

48 Web Services Overview

Advanced Web Services

Transactions (2/2)TransactionOption Property on WebMethod AttributeYou have to declare each Web Service method to be executed within a transaction. Therefore specify the TransactionOption property on a WebMethod attribute.

Transaction ModesUsing the TransactionOption attribute you can choose between the following modes:

Disabled: disabled (!) Supported: If a transaction already exists, the method

will run in this existing transaction context. If no transaction exists, the method will not run within a transaction

NotSupported: Whether there still exists a transaction or not, the method will not run within a transaction.

Required: The method will run within a transaction. If no transaction exists, a new one will be started. If there already exists a transaction, the method will run within the existing transaction context.

RequiresNew: A new transaction will be started on each call.

Web Services Overview 49

Advanced Web Services

Execution ModelSynchronousSynchronous execution works like any other call to a class method, where after calling a method the calling application waits (and locks) for the reply.

AsynchronousIf you want to use asynchronous invocation you have to split the code implementing a method into two code blocks: a BeginMethodName and an EndMethodName block.

The Begin-block contains the code executed before an asynchronous operation is processed. Instead of blocking the whole Web Service, the .NET runtime determines when the operation has finished. Then the End-block is executed. How? The client is responsible for calling the End-block. There are two ways how the client gets to know when to do this: either the client passes a callback method to the Begin Method call or the client uses the WaitHandle class to actively check whether the Begin block is finished or not.

As indicated, the method names have to follow naming rules. For example, a method named Divide could be split into two async methods that must be named: BeginDivide and EndDivide.

Besides this splitting a developer does have to do only little additional programming to make use of asynchronous behavior. Of course, an asynchronous model must be well designed to address challenges like error handling and compensating actions.

50 Web Services Overview

Advanced Web Services

Using Web Services from UIWith ASP.NET you have the ability to completely separate layout and business logic.

Completely separate layout and processing logicThis means that you can split all inline code from the page and store both code and content in different files (with different file name extensions).

Thus you could have one or more .aspx and .css files specifying the design, and one or more .cs or .vb files (which are the file extensions for C# and Visual Basic.NET resource files) containing the business logic.

Files for designers and files for programmersNow your designers can work with nearly pure HTML files, while the programmers can implement the “working code.” This means easier maintainability of your application.

Web Services Overview 51

Advanced Web Services

SampleThis sample, taken from the ASP.NET QuickStart Tutorial, will give you an insight on how a Web Service is built.

.aspx fileThis code snippet from an .aspx file builds the user interface of the Web Service. The namespace MathServiceSpace is included to make use of the classes and methods it provides.

The <script> block contains the method Submit_Click, which is the event handler for the OnServerClick event. This event is raised when the Submit button is clicked. The name of the event handler method is specified by an attribute in the <input> tag.

.asmx fileThe method service.Add is implemented in the corresponding Web Service file whose file name extension is .asmx.

WSDL file returned by the ASP.NET runtimeA request to this file using the “?WSDL” parameter causes the ASP.NET runtime to return the WSDL description of the Web Service.

52 Web Services Overview

Advanced Web Services

SampleC# proxy class, generated by WebServiceUtil.exeThis file is used to generate the proxy class, which also implements the method Add (and the methods for asynchronous execution are generated). This single proxy file has to be stored within the /bin directory of the Web application.

Web Services Overview 53

Summary

SummaryIn this module we presented you an overview of Web Services. You learned what Web Services are and how to use them.

.NET architecture overviewThough here is not the place and the time to show you the full .NET architecture, we gave you an overview.

Web Services and ASP.NETWeb Services and ASP.NET are more or less coupled. The ASP.NET Web Services platform gives you rich support in designing and developing Web Services.

Create and Publish Web ServicesYou saw how to create and publish Web Services.

Invoke and Consume Web ServicesDifferent clients can invoke and consume Web Services. One way is to use a browser.

WSDL and Proxy ClassesAnother way is to program against Web Services. Therefore we introduced the Web Services Description Language (WSDL) and explained how to create proxy classes.

We've seen that most of all mentioned topics are based on or provide XML. Therefore, XML is the preferable format for data exchange and communication with Web Services.

54 Web Services Overview

Appendix A: A Simple Web Service

ASP.NET Quickstart TutorialThe ASP.NET QuickStart Tutorial is a samples collection introducing Microsoft .NET.

Web Services Overview 55

Appendix A: A Simple Web Service

ASP.NET QuickStartWhat is it?The ASP.NET QuickStart Tutorial is a collection of ASP.NET samples.

They introduce the syntax, architecture, and features of ASP.NET and the .NET Framework.

InstallationTo install this tutorial you have to install the Microsoft .NET Framework SDK. It is installed during the components update of the Visual Studio.NET Installation. After installation of the Framework SDK, open the .NET Framework SDK Overview and start the samples setup.

.NET Framework samplesNow that the samples are installed, open the .NET Framework SDK Overview again and click ASP.NET QuickStart in the samples block.

Then click ASP.NET Web Services under “Explore the samples.” A new window is opened, where you can click Writing a simple Web Service to get the MathService tutorial.

56 Web Services Overview

Appendix A: A Simple Web Service

Building a Simple Web ServiceThe MathService tutorial contains the complete code for a Web Service—including two versions written in C# and Visual Basic.NET.

But to understand why it was created, we will create our own MathService!

.asmxFirst we will implement the MathService class and its Web methods. We start by creating a new directory on the local machine and copying the MathService.asmx file to it. You will find this file in .NETframeworkSDK\ Samples\ Quickstart\ aspplus\ samples\ services\ MathService <language>Open the file with an editor. The first line is the webservice directive, which defines the programming language as C# and a reference class name.

You have to include using System.Web.Services; to build a Web Service.

There are four simple methods implemented. To make the methods publicly available you have to assign the [WebMethod] attribute to them.

Create a new virtual directory (e.g. “math”) within IIS that points to the directory where you copied the .asmx file to. Now you can request the file using a browser.

Web Services Overview 57

http://localhost/math/mathservice.asmxIn your browser you will see a list of all methods that are supported by the Web Service. Scroll down or click on a method name to see input fields, where you can enter values to make use of the MathService methods.

Create WSDL file (MathService.wsdl)But we want to build a client to the Web Service. Therefore the next step is to get the WSDL description of MathService.

To do this open a command line and change the directory to the directory where the .asmx file is stored. On the command line we call the disco.exe tool to generate the wsdl file.disco http://localhost/math/mathservice.asmxThe directory now should contain the following files:

mathservice.asmx

mathservice.disco

mathservice.wsdl

results.discomap

Generate C# proxy class (MathService.cs)Now we need the proxy class of the Web Service to program against it.

This is done with the WSDL.exe tool. On the console window (in the directory where you stored the Web Service files) enter:wsdl /l:c# /namespace:mathservice mathservice.wsdlWe use the namespace option to create the namespace, which will be used later in the Web Service client.

The proxy will be created and stored in the same directory, named MathService.cs. If you open the proxy class MathService.cs you see that the generated code looks different from the .asmx implementation.

You still have the class MathService and its methods Add, Subtract, Multiply, and Divide. But all of them have the SoapMethodAttribute attribute. And all of them are generated for the asynchronous programming model concepts.

Generate Assembly (MathService.dll)The last thing we have to do before implementing a client is to compile the proxy class to create the assembly (.dll).

We use the C# command-line compiler csc.csc /out:MathService.dll /target:library /reference:system.web.services.dll

58 Web Services Overview

/reference:system.xml.serialization.dll MathService.csThis will generate the MathService.dll library in the current directory. We use the reference options to reference the metadata of the specified assemblies. They are included because objects are serialized into XML formatted messages to send them to a message queue.

The generated DLL must be copied to the /bin directory, which has to be a subdirectory of your Web Service application directory.

Web Services Overview 59

Appendix A: A Simple Web Service

Consuming a Simple Web ServiceWe’ve seen how to create a Web Service—now we want to program against it.

If you first want to see how this can be done, open the file MathServiceClient.aspx in the same ASP.NET QuickStart directory from which you copied the MathService.asmx file.

But we want to implement our own MathService client.

ASP.NET UICreate a file called MathServiceClient.aspx, because we will use ASP.NET to create the user interface. What we need is a page where we can enter the required values, and where we have a choice of which method to call.

This means two input fields for the operands and four buttons to choose between add, subtract, multiply, and divide. Of course we have to display the result, which could be done by using an asp:label control.

First of all—and that’s a key point—import the namespace mathservice. Now we can make use of the methods exposed by the MathService.

We place two asp:TextBoxes on the page and assign the IDs Operand1 and Operand2 to them. Then we add four input buttons of type="submit"—one for each method. So the value has to be the name of the method.

The appropriate method will be called using the OnServerClick event. This event causes a roundtrip to the server and allows using exceptions.

60 Web Services Overview

Therefore we have to add the OnServerClick attribute to the input controls.

Event HandlerThe corresponding event handler could be implemented inline within the .aspx file. Using exceptions, we will try to get the values of the TextBoxes.

Then we have to create a new MathService. To call the service method we can use a switch statement using the values of the TextBoxes.

The result has to be assigned to the asp:label control.

Web Services Overview 61

Appendix B: TerraServer.Microsoft.net

TerraServer.Microsoft.netThis is a small tutorial showing how to make use of existing Web Services through another Web Service.

62 Web Services Overview

Appendix B: TerraServer.Microsoft.net

OverviewWhat is it?The Microsoft TerraServer .NET Web Service provides a set of Web methods. It is a programmable interface to the Microsoft TerraServer online database containing aerial imagery and topographical maps.

AssumptionsWe will use Visual Studio.NET to build our own Web Service. So VS.NET has to be installed on your machine.

You also need a working Internet connection—right from the start.

Web Services Overview 63

Appendix B: TerraServer.Microsoft.net

TutorialWe will develop a Windows application where you can enter a value and call the TerraService. The response will be a list of all names in the TerraServer database that match the entered value. For example, you can enter the name of a state in the United States and we will get a list of all places in that state.

Create a new projectFirst, start Visual Studio.NET.

To make navigation a bit easier and to allow us to more easily find what we want to show you, we are first going to identify some key tools in Visual Studio.NET that are used in this walkthrough.

On the upper right side of your Visual Studio.NET window you should see a number of tabbed, overlapped tool windows—try locating the Solution Explorer, the Class View, and the Toolbox windows.

If you can’t find them there, bring both up by clicking Solution Explorer, Class View, and Toolbox on the View menu.

Now we will create a new project by choosing File/New/Project and selecting Windows Application from Visual C# Projects.

Create application UIVisual Studio.NET then creates the project in the location you specified and the editor will show us a form called Form1.

In this form we need three things: an input field, a button, and another field that will show us the results.

64 Web Services Overview

The input field: Add a text box to Form1. You can drag one from the Toolbox (in the Win Forms section).

The button: Add a button to Form1 (also in the Toolbox, Win Forms section) and change the text to “Find.” To do this, right-click the button and then click Properties.

The result field: Add a ListView to Form1 (Toolbox, Win Forms). Change the View property to “Report.”

Add Web ReferenceNow we add the Web reference to the TerraServer: on the Project menu, click Add Web Reference. In the new opened window type the URL:http://terraservice.netand click Go.

On the left you can see the page content, and on the right there is a list of all references. On the left click “TerraService ASMX” – wait – and then click Add Reference.

In the Solution Explorer window you can see that there is a new subdirectory named Web References containing the TerraServer service.

Implement functionalityNow we have to implement the button1_Click() method. A sample of how to call the GetPlaceList method is shown on the TerraServer home page. There you can find the TerraService documentation.

First we need a TerraService object and a PlaceFacts list. Then we must call the GetPlaceList method and assign the outcome to our PlaceFacts list. Finally this result has to be inserted into the ListView Windows Form. That’s it!

If it won’t work, here’s the code of the button1_Click() method:

Web Services Overview 65

protected void button1_Click (object sender, System.EventArgs e){ namespace.net.terraservice.TerraService ts; namespace.net.terraservice.PlaceFacts[] plf;

ts = new namespace.net.terraservice. TerraService(); plf = ts.GetPlaceList( TextBox1.Text, 500, false );

listView1.Clear();

listView1.Columns.Add( "Place", 100, HorizontalAlignment.Left ); listView1.Columns.Add( "Country", 100, HorizontalAlignment.Left); listView1.Columns.Add( "State", 100, HorizontalAlignment.Left);

if (plf == null) { listView1.ListItems.Add( "Nothing", 0, new string[]{"found"}); } else { foreach( namespace.net.terraservice. PlaceFacts P in plf ) { listView1.ListItems.Add( P.Place.City, 0, new string[]{ P.Place.Country, P.Place.State } ); }; }}

66 Web Services Overview

Legal Notices

Unpublished work. © 2001 Microsoft Corporation. All rights reserved.

Microsoft, Visual Basic, Visual Studio, and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.