UNIT I

INTRODUCTION WEB SERVICES

WEB SERVICES INTRODUCTION

Before understanding why web services are popular or so important,
you should first assess ‘What is Web Services, what’s its use and
how does it work?’ The nature and functionality of web services have made
it very popular. Nowadays, our business systems have matured, transparent and
more logical and high tech, and all for these are because of web services.

Definition

Web services are the amalgamation of eXtensible Markup Language
(XML) and HyperText Transfer Protocol HTTP that can convert your application
into a Web-application, which publish its function or message to the rest of
the world. In other words, we can say, web services are just Internet
Application Programming Interfaces (API) that can be accessed over a network,
such as Internet and intranet, and executed on a remote system hosting the
requested services.

Web-applications are simple applications that run on the web. Web
services are browsers and operating system independent service, which means it
can run on any browser without the need of making any changes. Web Services
take Web-applications to the Next Level.

The World Wide Web Consortium (W3C) has defined the web services.
According to W3C, “Web Services are the message-based design frequently
found on the Web and in enterprise software. The Web of Services is based on
technologies such as HTTP, XML, SOAP, WSDL, SPARQL, and others.”

The Elements of Web Services

Web services use XML to code and to decode data, and SOAP to
transport it (using open protocols). Besides these, HTTP, Web Services
Description Language (WSDL), Universal Description, Discovery and Integration
(UDDI), and SPARQL are the elements of Web Services.  To understand clearly about Web Services,
it is mandatory to have some brief knowledge of web services elements.

HTTP

HyperText Transfer Protocol in short HTTP is the most widely used
protocol by World Wide Web. It defines how messages are formatted and
transmitted, and what actions Web servers and browsers should take in response
to various commands.

One of the shortcomings of HTTP is that it is a stateless
protocol, which means each command is executed independently, without any
knowledge of the commands that came before it. This shortcoming has been
resolved in new technologies includes ActiveX, Java, JavaScript and cookies.

Simple Object Access Protocol (SOAP)

SOAP is a simple XML-based protocol that allows to communicate
applications information over HTTP without the dependency of OS platform. SOAP
uses HTTP and XML as the mechanisms for information exchange.

Universal Description, Discovery and Integration (UDDI)

Universal Description, Discovery and Integration in short UDDI is
a web based distributed directory like traditional phone book's yellow and
white pages that enables businesses to list themselves on the Internet and
discover each other. It defines a registry service – a Web service that
manages information about service providers, service implementations, and
service metadata – for Web services and for other electronic and
non-electronic services. The service providers can use UDDI to advertise the
services they offer while service consumers can use UDDI to discover services.

Web Services Description Language (WSDL)

The WSDL refers to Web Services Description Language, is an XML
based protocol used for sending and receiving the information through
decentralized and distributed environments. WSDL is an integral part of UDDI
that was developed jointly by Microsoft and IBM.

It defines what services are available in its Web service and also
defines the methods, parameter names, parameter data types, and return data
types for the Web service. The WSDL document is quite reliable and applications
that use web services accept it

SPARQL

SPARQL refers to SPARQL Protocol and RDF Query Language is an RDF
query language that defines a standard query language and data access protocol
for use with the Resource Description Framework (RDF) data model. It works for
any data source that can be mapped to RDF. SPARQL allows a query to be
consisted of triple patterns, conjunctions, disjunctions, and optional
patterns.

It is standardized by the RDF Data Access Working Group (DAWG) of
the W3C, and is considered a key semantic web technology.

Uses of Web Services

Web services are a set of tools that can be used in a number of
ways most commonly in three styles:

Remote Procedure
Calls

Service-oriented
architecture

Representational
state transfer

Moreover, it is also used as Reusable application-components
and Connect existing software.

Remote procedure calls (RPC)

The Remote procedure calls Web services present a distributed
function call interface, which is familiar to many developers. Typically, the
basic unit of RPC Web services is the WSDL operation.

Service-oriented architecture (SOA)

Under Service-oriented architecture (SOA) Web services is used to
implement an architecture in which the basic unit of communication is a
message, rather than an operation. This is often referred to as
"message-oriented" services. Major software vendors and industry
analysts support the SOA Web Services.

Representational state transfer (REST)

The Representational State Transfer (REST) Web Services attempts
to describe architectures based on REST can use WSDL to describe SOAP messaging
over HTTP, which defines the operations. REST describes operations, can be
implemented as an abstraction purely on top of SOAP or can be created without
using SOAP at all.

In Reusable application-components uses Web Services offers most
frequently used services like currency conversion, weather reports, language
translation and much more.

In Connect existing software, Web Services offers you to exchange
data between different applications and different platforms. In this type of
uses, you can solve the interoperability problem by giving different
applications a way to link their data.

1 WEB SERVICES
ARCHITECTURE

Basic Architecture

The Web services
architecture places into relationship various components and technologies that
comprise a Web services "stack" or completely functional
implementation. Valid implementations include subsets or parts of the stack,
but must at least provide the components within the basic architecture.
Components and technologies that extend the basic architecture are represented
within the extended architecture.

The basic
architecture includes Web services technologies capable of:

Exchanging messages

Describing Web services

Publishing and discovering
Web service descriptions

The basic Web
services architecture defines an interaction between software agents as an
exchange of messages between service requesters and service providers.
Requesters are software agents that request the execution of a service.
Providers are software agents that provide a service. Agents can be both
service requesters and providers. Providers are responsible for publishing a
description of the service(s) they provide. Requesters must be able to find the
description(s) of the services.

The basic Web
service architecture models the interactions between three roles: the service
provider, service discovery agency, and service requestor. The interactions
involve the publish, find, and bind operations. These roles and operations act
upon the web service artifacts: the web service software module and its description.
In a typical scenario a service provider hosts a network accessible software
module (an implementation of a web service). The service provider defines a
service description for the web service and publishes it to a requestor or
service discovery agency. The service requestor uses a find operation to
retrieve the service description locally or from the discovery agency (i.e. a
registry or respository) and uses the service description to bind with the
service provider and invoke or interact with the web service implementation.
Service provider and service requestor roles are logical constructs and a
service may exhibit characteristics of both.

Requesters and
providers interact using one or more message exchange patterns (MEPs) that
define the sequence of one or more messages exchanged between them. A service
description is hosted by a discovery service, to which a provider publishes the
description, and from which the requester discovers the description. The
description includes data type and structure information, identifies the MEP,
and contains the address of the service provider.

The extended
architecture describes Web services support for MEPs that group basic messages
into higher-level interactions, details how support for features such as security,
transactions, orchestration, privace and others may be represented in messages
(SOAP modules), and describes how additional features can be added to support
business level interactions. The extended architecture builds on the basic
architecture using the extensibility mechanisms inherent in the basic
technologies.

Software agents in
the basic architecture can take on one or all of the following roles:

Service requester --
requests the execution of a Web service

Service provider --
processes a Web service request

Discovery agency -- agency
through which a Web service description is published and made discoverable

A software agent in
the Web services architecture can act in one or multiple roles, acting as
requester or provider only, both requester and provider, or as requester,
provider, and discovery agency. A service is invoked after the description is
found, since the service description is required to establish a binding.

The figure above
illustrates the basic Web services architecture, in which a service requestor
and service provider interact based on the service's description information
published by the provider and discovered by the requester through some form of
discovery agency. Service requesters and providers interact by exchanging
messages, which may be aggregated to form MEPs.

In the diagram
above, the nodes of the triangle represent roles and the edges represent
operations.

One or more intermediaries
may exist in a message path between requester and provider. Intermediaries,
where present, cannot interfere with the MEP. Intermediaries may perform
certain functions associated with the message such as routing, security,
management, or other operations. Examples of MEPs include one-way,
request/response, publish/subscribe, and broadcast.

Basic Web services
architecture components are typically defined using XML applications, use XML
infoset definitions for message data typing and structuring, and use HTTP for
transport. Extended Web services architecture components are typically defined
using extensions to the core XML applications and transports, including
alternatives to HTTP.

A message is
defined as a construct that can include zero or more headers in addition to
data. The header part of a message can include information pertinent to
extended Web services functionality, such as security, transaction context,
orchestration information, or message routing information. The data part of a
message contains the message content or data.

A web service is
described using a standard, formal XML notion, called its service description,
that provides all of the details necessary to interact with the service,
including message formats (that detail the operations), transport protocols,
and location. The nature of the interface hides the implementation details of
the service so that it can be used independently of the hardware or software
platform on which it is implemented and independently of the programming
language in which it is written.

Web services can be
used alone or in conjunction with other web services to carry out a complex
aggregation or a business transaction.

The figure above
illustrates the relationships between requesters, providers, services,
descriptions, and discovery services in the case where agents take on both
requester and provider roles. For example, XML messages compliant with the SOAP
specification are exchanged between the requester and provider. The provider
publishes a WSDL file that contains a description of the message and endpoint
information to allow the requester to generate the SOAP message and send it to
the correct destination.

To support the
common MEP of request/response, for example, a Web services implementation
provides software agents that function as both requesters and providers, as
shown in Figure 2. The service requester sends a message in the form of a
request for information, or to perform an operation, and receives a message
from the service provder that contains the result of the request or operation.
The service provider receives the request, processed the message and sends a
response. The technologies typically used for this type of Web services
interaction include SOAP, WSDL, and HTTP.

Purpose of the Web Service Architecture

Web services provide a standard means of interoperating between
different software applications, running on a variety of platforms and/or
frameworks. This document (WSA) is intended to provide a common definition of a
Web service, and define its place within a larger Web services framework to
guide the community. The WSA provides a conceptual model and a context for
understanding Web services and the relationships between the components of this
model. The architecture does not attempt to specify how Web services are
implemented, and imposes no restriction on how Web services might be combined.
The WSA describes both the minimal characteristics that are common to all Web
services, and a number of characteristics that are needed by many, but not all,
Web services. The Web services architecture is an interoperability architecture:
it identifies those global elements of the global Web services network that are
required in order to ensure interoperability between Web services.

Architecture

The server-side infrastructure is based on ASP.NET and uses XML
serialization.

Figure: ASP.NET Web services architecture and request flow

The Marriage of the Web Services Architecture with Building
Automation Information Models

Since BACnet and EIB objects and LonMark functional profiles are
information models, and XML is a modeling language, we could express these high
level information models in XML and in so doing make them compatible with the
emerging Web services architecture.

Figure: Web Services Architecture

Because of the flexibility of XML and the web services
architecture, these high level models could be expanded to include other types
of facility-related (but not necessarily building automation-related)
information. If each building automation protocol developed its own XML model,
however, we would have similar but incompatible system models. Today's problems
of translating from one protocol to another at the building controller level
would become tomorrow's translation problems at the Web services level. What's
needed is a unified system model, in XML, that can be used by any building
automation protocol.

It should also be mentioned that this push toward Web services
architecture should not be interpreted as an end to standard protocols. Web
Services are useful as a computer-to-computer or
software-application-to-software-application interface, but they are
"overkill" as a device-to-device interface. While it might be
possible to expose information as XML at a building-controller level, it would
not be practical to do so at a zone or unitary-controller level. Web services
should be viewed more as a successor to OPC than a replacement for BACnet, EIB,
or LON.

Two aspects:
internal and external

Internal: how do
we connect a Web service to a company's information systems

External: how do
we connect a client with a Web service

With respect to
the internal architecture, Web services are viewed as wrappers of existing
information systems. We need a middleware layer that can connect Web
services to a company's existing middleware platform.

With respect to
the external architecture, Web services assume the existence of a
third-party directory service that is used for service discovery. Once
such a service is in place, then the external architecture looks like
this:

Since it would
be difficult to scale this approach (assuming the existence of a
third-party manager) for other middleware characteristics (such as support
for transactions), it is assumed that in the future, individual Web
services will each provide these managers (in some fashion) and that these
individual managers will coordinate in a peer-to-peer fashion to achieve
the desired effects.

The Web services architecture is based upon
the interactions between three primary roles: service provider, service registry,
and service requestor. These roles interact using publish, find, and bind
operations. The service provider is the business that provides access to the
Web service and publishes the service description in a service registry. The
service requestor finds the service description in a service registry and uses
the information in the description to bind to a service. A logical view of the
Web services architecture is shown in Figure. In this view of the Web services
architecture, the service registry provides a centralized location for storing
service descriptions. A UDDI registry is an example of this type of service
registry.

Figure 1: Web services architecture

Although it is important, the centralized
service registry is not the only model for Web service discovery. The simplest
form of service discovery is to request a copy of the service description from
the service provider. After receiving the request, the service provider can
simply e-mail the service description as an attachment or provide it to the
service requestor on a transferable media, such as a diskette. Although this
type of service discovery is simple, it is not very efficient since it requires
prior knowledge of the Web service, as well as the contact information for the
service provider.

Between these two extremes, there is a need
for a distributed service discovery method that provides references to service
descriptions at the service provider's point-of-offering. The Web Services
Inspection Language provides this type of distributed discovery method, by
specifying how to inspect a Web site for available Web services. The
WS-Inspection specification defines the locations on a Web site where you could
look for Web service descriptions.

Since the Web Services Inspection Language
focuses on distributed service discovery, the WS-Inspection specification
complements UDDI by facilitating the discovery of services available on Web
sites, but which may not be listed yet in a UDDI registry.

2 OVERVIEW OF WEB
SERVICES

Web services overview

A Web service is a set of related application functions that can
be programmatically invoked over the Internet. Businesses can dynamically mix
and match Web services to perform complex transactions with minimal
programming. Web services allow buyers and sellers all over the world to
discover each other, connect dynamically, and execute transactions in real time
with minimal human interaction.

Web services are self-contained, self-describing modular
applications that can be published, located, and invoked across the Web.

Web services are self-contained.
On the client side, no additional software is required.  A programming
language with XML and HTTP client support is enough to get you started.
On the server side, a Web server and servlet engine are required.  The
client and server can be implemented in different environments.  It is
possible to Web service enable an existing application without writing a single
line of code.

Web services are self-describing. The client and server need to recognize only the format and
content of request and response messages.  The definition of the message
format travels with the message; no external metadata repositories or code
generation tools are required.

Web services are modular. Simple
Web services can be aggregated to form more complex Web services either by
using workflow techniques or by calling lower layer Web services from a Web
service implementation.

Web Services are platform independent. Web services are based on a concise set of open, XML-based
standards designed to promote interoperability between a Web service and
clients across a variety of computing platforms and programming languages.

Web services might be anything, for example, theatre review
articles, weather reports, credit checks, stock quotations, travel advisories,
or airline travel reservation processes. Each of these self-contained business
services is an application that can easily integrate with other services, from
the same or different companies, to create a complete business process. This
interoperability allows businesses to dynamically publish, discover, and bind a
range of Web services through the Internet.

Categories of Web services

Web services can be grouped into three categories:

Business information. A
business shares information with consumers or other businesses. In this case,
the business is using Web services to expand its scope. Examples of business
informational Web services are news streams, weather reports, or stock
quotations.

Business integration. A
business provides transactional, "for fee" services to its customers.
In this case, the business becomes part of a global network of value-added
suppliers that can be used to conduct commerce. Examples of business
integration Web services include bid and auction e-marketplaces, reservation
systems, and credit checking.

Business process externalization. A business differentiates itself from its competition through the
creation of a global value chain. In this case, the business uses Web services
to dynamically integrate its processes. An example of business process
externalization Web services is the associations between different companies to
combine manufacturing, assembly, wholesale distribution, and retail sales of a
particular product.

Service roles and interactions

A network component in a Web Services architecture can play one or
more fundamental roles: service provider, service broker, and service client.

Service
providers create and deploy their Web services and can publish the
availability of their WSDL-described services through a service registry,
such as a UDDI Business Registry.

Service
brokers register and categorize published services and provide search
services. For example, UDDI acts as a service broker for WSDL-described
Web services.

Service
clients use broker services such as the UDDI Business Registry to discover
a needed WSDL-described service and then bind to and call the service
provider.

Binding involves establishing all environmental prerequisites that
are necessary to successfully complete the services. Examples of environmental
prerequisites include security, transaction monitoring, and HTTP availability.
The relationships between these roles are described in Figure 1.

Figure 1. Service roles and interactions.

Overview of Web Services, SOAP and WSDL

The ADFs take full advantage of using webservices to
communicate with ArcGIs Server services. As a developer using the ADFs or
ArcGIS Server directly it is important you understand using SOAP and its
relationship to the WSDL files provided with ArcGIS. This article will discuss
some of the basic concepts of working with Web Services, SOAP, and WSDL
provided with ArcGIS Server. Following this article you should read more
particular documents that explain how to apply the ideas explained here in
relation to a specific ADF.

Web services provide the ability for applications to communicate
using messaging over many different protocols. Because web services provide a
means to communicate between applications that are written both in the same
programming language as well as in different programming languages, a language
neutral means of communication was needed. XML is the format used to hold the
information carried between the applications. The XML message is carried using
SOAP (Simple Object Access Protocol). SOAP defines the headers and the valid
means for passing messages. That passing of messages usually takes place over
HTTP but it can actually be over any well know protocol, such as SMTP, FTP, or
DCOM. SOAP takes the xml message and wraps it so that it can be routed to the
receiving application and appropriaptely processed.

WSDL, on the other hand, describes what a web service does, what
methods it contains, what parameters and types it knows how to use, and which
ports it is using for communication. The WSDL defines the valid contents of the
XML messages to be passed over SOAP. The WSDL acts as a specification, like
IDL, to describe the interfaces and parameters on a web service. The methods
available are usually grouped together in a "port", which can be
thought of as a view to web services where different operations are exposed. A
WSDL can contain one or more ports. The WSDLs provided by ESRI have only one
port per WSDL. For example, all the methods exposed for the MapServer WSDL will
be listed as being part of MapServerPort. Another property of the web service
documented in the WSDL is the protocol over which to send messages and,
optionally, the URL for the associated server. The WSDL specification does all
of this work in a very generic manner, thereby allowing toolkits in different
languages, such as AXIS in Java,
to generate code from a WSDL description.

WSDLs and ArcGIS Server

If you look in your installation folder under XmlSchema you will
find eight WSDL files. Each one corresponds to a description of a web service
that ArcGIS Server is capable of publishing. Each WSDL roughly corresponds to
an ArcObject class, for example the MapServer.wsdl corresponds to the MapServer
object and the GeoDataServer.wsdl corresponds to the GeoDataServer object.
Because web services usually only send text messages (XML) between
applications, there are differences in method signatures and data types between
the WSDL and the corresponding ArcObject. When you open the GeocodeServer.wsdl
there are two important sections you need to understand. The first section is
inside the <types> element and the second section is inside the
<portType> element.

Value Objects

The <types> elements contains all the definition of the data
types for the WSDL, also called value objects. In this section you will find
the definition for all the elements that will be passed in as parameters to the
methods for the web service. The value objects can be composed of other value
objects but in the end the "final" types must be valid XML Schema
data types, such as String, Long, Int or Date. When the Java toolkit converts
from WSDL to Java classes all of the type elements will be Java value objects,
much like plain old java objects (POJOs). For example, if you look at PointN in
the WSDL, this is a XML representation of a Arcobject Point that is sufficient
for web service operations:

<xs:complexType
name="PointN">

<xs:complexContent>

<xs:extension
base="Point">

<xs:sequence>

<xs:element
name="X" type="xs:double"/>

<xs:element
name="Y" type="xs:double"/>

<xs:element
name="M" type="xs:double" minOccurs="0"/>

<xs:element
name="Z" type="xs:double" minOccurs="0"/>

<xs:element
name="ID" type="xs:int" minOccurs="0"/>

<xs:element
name="SpatialReference" type="SpatialReference"
minOccurs="0"/>

</xs:sequence>

</xs:extension>

</xs:complexContent>

</xs:complexType>

The Javadoc
for the class generated using the AXIS toolkit, shows a Java class which is
very similar to a POJO. From the WSDL definition we can see that M, Z, ID, and
SpatialReference are not required properties since their minOccurs attribute is
equal to 0. Therefore when you need to use a PointN value object you can create
it using the default construct, set the X and Y, and then pass it as a
parameter. There is no need to create the object on the Server Context, it is
created on the local machine. When you are setting the object's properties
since they are set locally no remote call is made to the ArcGIS serverl.

Port Usage

Inside the <portType> element is the listing of all the
methods that can be called on the web service. For example, one of the calls
you can make is ReverseGeocode, which takes a point and figures out the closest
address.

<operation
name="ReverseGeocode">

<input message="e:ReverseGeocodeIn"/>

<output message="e:ReverseGeocodeOut"/>

</operation>

There is a definition for the input message (the input parameters)
and the output message (the returned values) in another section of the WSDL. In
this case they are defined earlier in the file as <message> elements,
which are then mapped to <types>. Through this mapping you can see that a
ReverseGeocode input message contains a location, which is a point, a boolean
to indicate if intersections should be returned, and some properties in a PropertySet

<xs:element
name="ReverseGeocode">

<xs:complexType>

<xs:sequence>

<xs:element name="Location"
type="Point"/>

<xs:element
name="ReturnIntersection" type="xs:boolean"/>

<xs:element name="PropMods"
type="PropertySet"/>

</xs:sequence>

</xs:complexType>

</xs:element>

When the WSDL is used to generate Java proxies through AXIS a
class will be generated named GeocodeServerPort
which contains all the methods you can call on the ArcGIS Server GeocodeServer
object using web services. The GeocodeServerPort object is instantiated in the
local JVM but any method call on this class will execute a remote call to the
server. Any object returned from the server will be a value object and
therefore accessing its properties will not require calls to the server.
Therefore, the only methods in the Java classes generated from the WSDL which
make remote calls will be those methods exposed on a *Port object.

Implications for ArcGIS Server Developer

Using SOAP has several advantages for ArcGIS Server developers.
The greatest advantage is that the value objects are Java objects in the local
JVM. Because they reside in the local JVM and they are pure Java they are
easier to debug and work with in general. Another serious advantage is that the
only remote calls are those on the *Port objects. When using ArcGIS Server with
the server API, each call to set a variable or execute a GIS operation is a
remote call. Because the value objects are in the local JVM all calls to their
mutators are local calls. When you call one of the methods on a *Port object
you pass the value object as a parameter. The returned objects are also value
objects, so retrieving values from this object are local calls as well. This
overall reduction in remote calls greatly increases the performance of your
application.

Here is an example which comes from the example below. It uses
Value objects and the MapServerPort to query the count of features in a layer
in the map. Using the server API every method call, from creating the envelope
to the query feature count call would be a remote method call.

// The
envelope is a value object so this constructor is not a remote call

EnvelopeN env = new EnvelopeN(webExtent.getMinX(), webExtent.getMinY(),
webExtent.getMaxX(), webExtent.getMaxY(),

null, null, null, null, null);

// make a spatialfilter value object with the required parameters - none of
these method calls are remote

SpatialFilter spatialFilter = new SpatialFilter();

spatialFilter.setFilterGeometry(env);

spatialFilter.setSpatialRel(EsriSpatialRelEnum.esriSpatialRelIntersects);

spatialFilter.setWhereClause("");

spatialFilter.setSearchOrder(EsriSearchOrder.esriSearchOrderSpatial);

spatialFilter.setSpatialRelDescription("");

spatialFilter.setGeometryFieldName("");

int layerId = layer.getId();

//because queryFeatureCount is found on the MapServerPort the call to
queryFeatureCount goes back

//to the server which can throw an RemoteException

try {

numberOfFeatures =
mapServer.queryFeatureCount(mapServer.getDefaultMapName(), layerId,
spatialFilter);

} catch (RemoteException e){}

There are also some drawbacks, especially for current ArcGIS
Server programmers. Because of the requirements of the WSDL using simple types
and the way different toolkits generate default values, some of the generated
objects need more properties set before the methods will work. For example,
using an Element for custom graphics needs to have its color set when using
SOAP but not using the Server API. The implications of this for current ArcGIS
Server developers is that your code will not translate directly and that you
may have to set more values before the method call.

3 SERVICE ORIENTED ROLES AND ARCHITECTURE

1
Introduction

Service Oriented Architecture (SOA) is very topical paradigm in
enterprise architectures and IT systems nowadays. As people are still debating
the actual meaning and definition of SOA, more and more companies and IT organizations
are at the moment heading for a SOA implementation. It is a real “we
are also doing SOA”-craze, as companies after companies are putting
up their own SOA-solutions.

Although the name Service Oriented Architecture refers to the
world of technology and architectures, SOA is actually a lot more than just a
new set of tools or technology systems. In a way, SOA can be seen more about
organization and people than about technology: in SOA it is the IT organization
and governance that matters.

In this report we discuss the question, how the SOA implementation
will actually change the roles in a traditional IT organization. Here, we
define a role as a work role in an organization: a role is a set of work
tasks and responsibilities that can be collected under a single job
description, such as CIO, developer or architect. It is also worth noting for,
that in this report we do not make difference between the roles in an external
project organization that is actually implementing SOA for somebody else, and the
roles in an internal IT organization. With the notion IT organization we
refer at the same time to both of these concepts.

Thus, our research problem is: How does Service Oriented
Architecture change the roles in an IT organization?

1.1
Research Methods

The research is done based on a literature analysis. Our main
sources of information are books, articles and WWW-pages about Service Oriented
Architecture and the organization of a SOA project.

Our literature analysis is based on the methodology described by
Webster and Watson. We tried to follow the structured approach given in their
paper and followed citations backward and forward as Webster and Watson
suggested.

We gathered knowledge about the topic in many ways. Originally we
tried to use only scientific articles and search those only with Google
Scholar. During this process we found out, that the topic is not covered very
well in the scientific literature and the results we found with Google Scholar
were few. We extended our search to cover also a few basic books about SOA and
we also used Google to find more material. We included also trade journals such
as CIO Magazine in our sources of information, although we are aware that they
have not gone through any scientific validation.

We planned an initial set of key words that was the base for our
search. Following citations backward and forward was also a good approach to
find more material. The books and WWW-pages recommended by the lecturer were
also good and we found some relevant articles there.

1.2 Scope
of the Report

There are many possible ways to organize an information technology
development in a company. In this paper we scope our research to cover only the
roles of a traditional project oriented information system development and how
Service Oriented Architecture affects on these roles.

1.3
Structure of the Report This report consists
of 4 sections:

- In section 1 the research subject is introduced, research method
described and scope of the report defined.

- Section 2 is an introduction to Service Oriented architecture
(SOA).

- Section 3 discusses the traditional project roles in an IT
organization.

- Section 4 discusses how SOA changes the IT organization and its
roles.

2 Introduction to SOA

Service Oriented Architecture is an IT buzz word with multiple
interpretations but a successful SOA can also deliver real value to business.
In this section the basics of SOA are introduced to be able to understand the
principles affecting the role division of a SOA project.

2.1 Why SOA is needed?

The emerging need of business agility and flexibility has driven
organizations to seek new approaches for information system development. SOA is
a new paradigm to organize end-to-end enterprise integration. A successful SOA
provides the agility and flexibility of information systems that are needed to
fulfill the fast changing business needs.

2.2 The concept of a service

Service Oriented Architecture is based on the concept of a
service. In SOA world information systems are decomposed into services. Every
service should perform a meaningful unit of work from the business point of
view. Services are composed to form the enterprise information systems.

2.3 Benefits of applying SOA

The main benefit of applying SOA is the possibility to reuse of
the services. The loose coupling between services and service consumers enables
the enterprise wide use of services. When services are well designed and they
execute real business functions they are useful in several business units.

When a company has a comprehensive portfolio of services new
business processes based on these services can be implemented quicker than if
the development should every time be started from scratch. Modifying the
existing business processes is also easier and faster because existing services
can be reused and only the composition of the services should be changed.

The enterprise departments have traditionally ordered their
information systems from the IT department. The same kinds of systems are
implemented for multiple departments and the integration of these systems has
been the problem of the IT staff. SOA is an enterprise-wide approach. It
provides a change for IT and business people from various departments to meet
in the middle. Both business and IT people are also integrated into teams when
SOA is planned and implemented.

3 Traditional IT organization, skills and roles

3.1 Organization

A traditional service-based IT organization has evolved more than
twenty years and it is common in large and medium sized organizations. All
large enterprises have their own internal IT organizations leaded by Chief
Information Officer. Internal IT organizations serve mainly employees and
departments within the company providing e.g. application development,
maintenance and support services.

3.2 Skills

In a traditional IT organization the needed skills depend on the
applications that are developed and later maintained. A lot of application
specialists are needed in IT department to know both the technical and the
functional aspects of the applications. There might be separate staff that
takes care of the application development projects and after the implementation
phase ends the maintenance is taken care of by different staff.

3.3 Roles

There is not a single definition of traditional IT organization
roles. There are many aspects which affect the division of the roles e.g. the
structure of the organization and whether the development is project or process
based. Table 1 lists some IT project roles presented in literature.

Our literature study revealed that there are four basic roles that
are present in almost all IT projects. The size of the project does not affect
so much on these roles because the same person can have multiple roles or a
team can take care of a single role.

Table 1. Traditional IT
project roles.

Project manager, Business analyst, Architect and Developer were
proposed to be the basic roles of an IT project in all three articles we
reviewed to get an idea about the traditional roles. There can also be many
other roles depending on the project. As our literature study shows database
and infrastructure support can be very important when enterprise software is
developed. UI expert is needed e.g. when high level of usability is needed.

4 SOA Changes Old Roles and Brings New Roles

SOA will change many things in an IT Organization. As the
fundamental way of building IT systems changes in the form of service oriented
architecture, the organizations building these architectures will also change.
It is no wonder, that SOA organization and governance is said to be one of the
biggest determinants for success in SOA projects. It is up to the IT
organization to evolve into the needs of service oriented architecture.

Achieving the right organization structure is one key element of
implementing SOA. But it is not all. Also cultural aspects of an organization
are important. When organization changes, also the organization’s culture
changes. According to Schein, the organization’s culture is the first
thing to be altered, when changes in the organization structure is needed. But
changing the organization and its culture is nothing but easy.

The changes in the structures of an organization that is
implementing SOA can be divided in two categories: changes in organizational
level structures such as technical architecture boards or review
boards and changes in lower level and more individual structures such as project
level roles in the IT organization [also 2]. Here we will discuss solely
the changes that will happen to the roles in an IT organization.

4.1 New Skills and Roles Needed

SOA changes the work in an IT organization and in the process the
roles that operate in these organizations. Before SOA, IT organizations used to
be building applications. In the new SOA paradigm they are more likely
to be “assembling” applications from previously made services. In
addition to this shift, the whole SOA environment requires a new set of skills
and most importantly new mindset from the implementers: when earlier it was
sufficient to understand just specific functionality of an IT system, now even
the developers need to understand the cross organizational business aspects of
a new application or, preferably, a new service.

Many new skills are needed from the participants in a SOA project.
For one, software developers will have to be trained some new web service
technologies and tools, if

they are not known beforehand. Understanding the underlying
technologies and standards such as XML, SOAP, WSDL etc. is important, but as
mentioned earlier, the biggest challenge is to change the view of the whole
development process: now it is all about larger architectural issues, business
issues, business processes, services and most importantly reuse of these
services.

In a SOA project there will be many roles that resemble the
traditional IT project roles. These include, for example, CIO, project manager,
architect, business analyst and developer etc. But in the SOA paradigm, these
roles might have a somewhat different meaning in comparison to the traditional
ones. Numerous authors also stress, that when a company is implementing SOA many
totally new roles are needed. Unfortunately, only a few papers actually name
and discuss these roles thoroughly. Instead, many of our sources settle for
just giving a few examples such as service librarian or service developer. In
the table 2 below we give some new SOA roles mentioned in different sources.

Table 2. New SOA project
roles.

Here we go shortly trough the new roles according to Bieberstein
et al. and Zimmermann & Mueller to give some insight, what kinds of new
project roles may be needed. The more technology specific UDDI roles are
excluded here for simplicity.

SOA Architect

One of the most important new roles is a SOA architect that will
replace the role of a traditional architect. A SOA architect is a mediator
between the technology and business worlds of SOA and is responsible for
end-to-end service requestor and provider design. In another words SOA
architects need to negotiate the whole big picture of a given application
between technology and business needs.

Service Designer

The job of a service designer is to model services according to
data and functionality modeling techniques. They define, for example, service
interface contracts and messaging schemas between the services.

Process Flow Designer

This is, as the original paper says, an optional role. The process
flow designer tries to map a given business process to an explicit and
declarative service orchestration. In another words, process flow designer
designs the technical side of a business process.

Service Developer

Service developer is in charge of the actual development of the
services. They develop the service interfaces and implementations on the side
of the provider and also the service invocation code on the requestor side.

Integration Specialist

Integration Specialists act as a link between the service designer
and process flow designer and their work. Integration specialists have to have
a broad technical experience in the integration field and understanding of the
SOA systems.

Interoperability Tester

Interoperability tester ensures the implementations conformance to
used standards and that any given service request-respond implementation works
correctly.

Service Governor

Service governor is a cross-divisional role that validates and
selects the right and most suitable business services for a given organization.
Service governor also tries to find out who actually owns these services.

As one can conclude from the vague descriptions and table given
above, the new roles in a SOA organization are not yet as finalized as they
could be: different sources give different new roles to the IT organization. It
also seems that new roles are invented when the need for them arises. In this
situation it is not quite clear, if all the roles given in different sources
are actually needed. In some organizations the role of the service governor,
for example, could be handled by service architect instead etc. On the whole,
it is not an easy task to define, what new roles an SOA implementing IT
organization will need. Therefore, instead of debating of the defined new
roles, it might be more useful to discuss, how do the old roles of the IT
organization change.

4.2 How Will the Roles in an IT Organization Evolve?

Here we discuss, how the most important and existing roles in IT
organization and IT projects will evolve when the organization is moving
towards SOA. Many articles that tried to give and define new SOA roles actually
concentrated more on the subject how existing project roles are extended and
evolved in SOA paradigm.

Also, in many articles the line between old, extended and new
roles was not quite clear. Also, with the novel understanding how these
existing roles will change, the other, maybe new, roles can more easily be
adjusted into the IT organization [also 11]. The roles that we handle are CIO,
project manager, architect, developer and business analyst.

CIO

Here we discuss the new role of the CIO in the organization.
Although, the CIO is not an actual work role of a SOA project we
decided to handle it none the less. This is because in many of our articles it
was the role of the CIO that seemed to face the biggest evolution. These
changes are due to the previously stated facts that the success of SOA depends
strongly on the IT organization and governance. And who other deals more
intimately with these matters than CIO?

According to Graham, strong IT governance is the key to success.
SOA will be a failure with a CIO that is not embracing strong SOA governance.
Firstly, CIO needs to get strongly and personally involved with SOA as early as
possible: there is really nothing better for a SOA success than a CIO as a SOA
champion. CIOs need to get hands dirty with SOA both at the low and high level
SOA decisions. Further, CIO will have to be more concentrated to the role
division and organization of their IT departments: it is the job of the CIO now
to define and negotiate the new SOA roles. In the process, the SOA CIO must now
be master of the change of organizations culture also: they should know how to
change the organization effectively.

The role of the CIO changes also on a bigger level. Because SOA
brings more and more together the business and technology sides of the IT, also
CIO must better comprehend both of these worlds. At the same time CIO has to
handle matters ranging from business value, cross-organizational business
processes and their implementation, and on the other hand low level application
implementation and maintenance. Holmes even suggests that the role of CIO will
be therefore divided in two: there would be the strategic CIO handling the
business related big picture and then there would be the tactical CIO executing
the day to day IT Organization. Worthen, on the other hand, sees that this
brings the roles of CEO and CIO more closely linked.

Project Manager

The role of the Project Manager in a SOA team is also changing.
The biggest change will probably be the fact, that with SOA the development
cycles will definitely be shorter in any chosen development process (from agile
to waterfall). So, project manager needs to be able to plan shorter delivery
times for services. Project Managers will also have to be able to more and more
understand both the business and technical world of SOA paradigm. Their work is
integrated with the business users and customers but in the same time with the
traditional IT implementation team. Also, when the SOA implementation goes
further, the project manager will be gradually more responsible of coordinating
and tracking running services instead of implementing new services.

Architect

The role of an architect (or SOA architect) is discussed here,
although the role of SOA architect was previously defined in the section 4.1.
This is because, unlike some authors, we think that SOA architect can be
fundamentally seen as an evolution of an old role, instead of a totally new
role. Although, all the matters said about SOA architect are also valid here.

According to Mittal the role of a SOA architect is also seen as a
SOA champion, just like the CIO. Naturally, SOA architects need to be fluent
with the SOA concepts. It is important that they really get the big
cross-organizational picture of the business processes that are implemented.
They also have to make sure, that implemented services are really needed and
most importantly reused. They are the key decision makers concerning service
management and orchestration.

As said before, an architect in the SOA paradigm is a mediator
between the technology and business worlds of SOA and is responsible for
end-to-end service requestor and provider design. She makes sure that all
implementation is done in the principles of service orientation. Importantly,
SOA architect is the person to design the granularity of the services, a
totally new concept when moving into the SOA world.

Developer

As with the architect role, we see also the service developer or
SOA developer role more as an evolution from the original developer, instead of
a totally new role. The developers in the SOA world need to, as said before,
really understand both business processes and the implemented functionality.
When they build and compose new services, good design principles for error
handling, data translation and security etc. are more important than ever. The
developers will also have to change their preferences from building to more and
more reusing, because in the end, the reuse is one of the biggest things in SOA
that changes developers work.

Business Analyst

The role of the business analyst can be seen one of the most
crucial in the new SOA team. Traditionally business analysts have been
communicating with executives and users at a strategic level to extract their
requirements for a given application.

4 ARCHITECTURAL
PROCESS

How The Process Works

The architectural design process is organized to ensure that objectives
are reached in order of priority; the highest priorities are addressed and the
largest design solutions are arrived at first, then the details fall in place
in concert with the larger issues and ideas.  Without this approach, the
resulting building is just a random collection of unrelated decisions.

The Classic Steps to the Process

The
process is typically broken down into the following steps:

1. Pre-Design Phase (PD)

2. Schematic Design Phase (SD)

3. Design Development Phase (DD)

4. Construction Documents Phase (CD)

5. Bidding & Negotiation Phase (BN)

6. Construction Observation/Contract Administration Phase (CA)

7. Supplemental Services (SS)

Every project is unique, and not all projects follow this process
exactly.

Architectural Processes: How an Architecture Team Gets Work Done

Architectural processes are important in establishing a successful
architecture program. A process is a repeatable way of doing something. A good
process establishes the roles and responsibilities, sets expectations around communication
with other teams and aids in defining deliverables for the team.

Win up to £1000 at The Cloud Hack – Free developer event
in London 11th June

Visual Studio Team Foundation Server 2010 Training

It cannot be understated how much processes also show people how
to interact with the architecture group and what the architecture group does.
Before you start drawing pictures or designing solutions, you need to think
about what processes you are going to use to do architecture. Questions like
when does the architecture team interact with the business requirements process
and how does an architecture review work can be answered and your teams value
be measured through process, much like any other part of the business. Once you
have a process you can work at making it more efficient and showing value
through metrics and successful interactions with other business and IT
processes.

The key in creating a successful process is ensuring that it works
within your organization. For example, if you work in a business that has
adopted an agile methodology, you will need to make sure that the architecture
processes align properly with the way the business has chosen to work. You
would not want to go through the entire backlog and create detail drawings for
every item because the agile methodologies are focused on solution delivery and
not documentation. You will need a process that will focus on solution delivery
and not documentation. Creating the right process for your organization’s
style is not easy,

A good process will teach and grow people and can really make your
architecture team shine. It is not a substitute for competent architects,
although it can be used to develop people. It can decrease bureaucracy, improve
deliverable quality and improve productivity. A good process needs to be
created with a balance of managerial skills and architecture skills to
generally get it right.

Regardless of the processes you invent or borrow, a good
architectural process will generally need to cover the following areas:

Championing/Initialization

What is the process for introducing new architectures? How do you
get buy in for the new architecture or major design decisions? How do you gain
management, development and infrastructure buy-in for the architecture? How is
the architecture team going to support the developers in implementing the
architecture?

Requirements

How does the architecture team interact with the requirements
gathering process? What level of review and input does the architecture team
need over the requirements process?

For example, the architecture team needs to have a process for
getting the requirements from an architecture point of view. The architecture
team will need to be integrated into the process to review the functional and
non-functional requirements to make decisions around technology reuse and how
the performance and security non-functional requirements will be met before the
business requirements document is approved ideally, so it can incorporate
changes from the architecture team.

Design

What framework is used for design if any? What artifacts are due
and when can they be expected in relation to each other and other processes? A
key point is to remember that artifacts should support decision-making, so they
will need to be available to support key decision points in business processes.

Review/Validation

What is the architecture review process? How do you validate or
vet architecture? How do changes get addressed in the architecture?

Deployment

Does the deployed architecture match what was designed? How is the
deployment of an architecture supported by the architecture team? How do
changes get implemented into the architecture?

Governance

How are technology standards introduced and approved? How do the
standards get publicized? What happens if the standards aren’t or
can’t be followed? What does the governance organization look like? What
needs to be reviewed by the architecture team or does not need review?

An Example of Swim Lanes to Diagram a Process

You will need to document the processes you create and make them
widely known. A process does not require complex tools to document. You can use
PowerPoint with bullets to represent simpler or high level processes or you can
create swim lane diagrams with Visio to represent a more detailed or complex
process.

The following are some resources about software development
processes and architectural frameworks to get you started with creating an
architectural process.

Waterfall/Spiral

These methodologies will require that the architectural process
focus on the architecture as a whole early and planning up front including
proof of concepts. You will need processes to handle reviews of the
architecture during formal change requests. You will need an Architectural
Control Board to review and approve complete architecture before the overall
process can move to the next step or phase. A waterfall approach will require a
solid software architecture up front and controls over changing it through the
process.

Rational Unified Process (RUP)

The creators of RUP looked at why software projects failed and
created a process that addresses these issues. It is a software process that
focuses on documentation to aid communication in a software development process
and created the commonly use modeling language called the Universal Modeling
Language (UML).

Click here for
more information on RUP.

Agile Software Development and Agile Architecture

Agile architecture
processes would focus on managing change, complexity, solution
delivery over documentation (documentation is still important, just not the
focus like in RUP) and enabling the delivery of the next cycle.

Frameworks

Frameworks represent different views that various stakeholders of
the system will find informative and useful. These frameworks generally represent
the design phase of your processes and can help you decide and discover the
information that you may need to create the appropriate architecture.
Generally, they make it easier to think through the scope of the architecture
process and should be incorporated where appropriate. There are many
frameworks, but the following are the most common.

Zachmann EAD

The Zachmann
Enterprise Architecture Framework defines layers from the most
conceptual called scope, down to the finest detail of the physical
implementation.

Across each of the layers you need to pay attention to data,
function, network, people, time, and motivation. This framework was the first
and established much of the terminology we use in architecture today. I think
of the Zachmann framework as more of a tool to think through architecture, than
a process to do architecture. See a detailed
picture of the Zachman Framework.

TOGAF Enterprise
Architecture Description

This is the Open Group’s popular framework for application and infrastructure
architecture that is designed to work within your processes.

Enterprise Architecture Body of Knowledge (EABOK)

The EABOK framework
focuses more on the process of architecture and showing the value of Enterprise
Architecture. This is an interesting read as it compares various frameworks
like Zachmann and TOGAF, but it is on the complex side.

Gartner states that 40% of all architecture programs will fail by
the year 2010 because they don’t show value. This is because many new
architects tackle the design and documentation aspects of architecture first,
before establishing it as a part of the business processes. While documentation
is an important part of architecture and communication, it will not make your
architectural program a success. You need to focus on the processes which will
define your interactions with the rest of the business, establish roles and
responsibilities, gain management buy in, facilitate communication and
establish architecture as an intricate part of the processes.

How is Software Architecture Created?

The Visual Architecting Process™ (VAP) integrates
what we have learned from great architects, and good as well as failed
architectures, to help you create a software architecture that is:

good—it
is technically sound and clearly represented

right—it
meets the needs and objectives of key stakeholders, and

successful—it
is actually used in developing systems that deliver strategic advantage.

The Visual Architecting Process™ (VAP) covers the
techniques, including architecture modeling and architecture trade-off
analysis, used in creating a technically sound architecture. It covers
architectural requirements and prioritization to create the right architecture,
together with architecture validation to ensure that the architects and key
stakeholders agree that it is indeed the right architecture. And it covers the
organizational process steps that help ensure that the architecture is embraced
and used informedly so that, ultimately, the architecture is successful.

The Technical Process

Overview

The focal deliverable of the architecting process is the architecture
document (set), motivating and describing the structure of the
system through various views. However, though system structuring is at the
heart of the architecting process, it is just one of several activities
critical to the creation of a good architecture (Figure P1). Architectural
requirements are needed to focus the structuring activities.

Figure P1. The Visual Architecting Process™ (VAP)

Different architectural approaches tend to yield differing degrees
of fit to various system requirements, and modeling
and evaluating alternatives, and analyzing tradeoffs among them, are an
important part of the structuring phase. Lastly, a validation phase provides
early indicators of, and hence an opportunity to resolve, problems with the
architecture.

Architectural Requirements

Architectural
requirements are a subset of the system requirements, determined by
architectural relevance. The business objectives for the system, and the
architecture in particular, are important to ensure that the architecture is
aligned with the business agenda. The system context helps determine what is in
scope and what is out of scope, what the system interface is, and what factors
impinge on the architecture. The system value proposition helps establish how the system will
fit the users’ agenda and top-level, high-priority goals.
These goals are translated into a set of use cases, which are used
to document functional requirements. The system structure fails if it does not
support the services or functionality that users value, or if the qualities
associated with this functionality inhibit user performance or are otherwise
unsatisfactory. System qualities that have architectural significance (e.g.,
performance and security, but not usability at the user interface level) are
therefore also important in directing architectural choices during structuring.

Of course, requirements may already have been collected by product
teams. In that case, the architecture team needs to review those requirements for
architectural relevance and completeness (especially with respect to
non-functional requirements), and be concerned with requirements for future
products that the architecture will need to support.

Lastly, for the architecture of a product line or family,
architectural requirements that are unique to each product and those that are
common across the product set need to be distinguished so that the structure
can be designed to support both the commonality and the uniqueness in each
product.

Architecture Specification

The architecture is created and documented in the system
structuring phase. The architecture
decision model guides early decision-making, and helps us to
organize the architecture artifacts. These artifacts document (sets of)
decisions in terms of models and views, descriptions, explanations, rationale,
implications, alternatives considered but not chosen, white papers, etc.

Meta-Architecture

First, the architectural vision is formulated, to act as a beacon
guiding decisions during the rest of system structuring. It is a good practice
to explicitly allocate time for research—or scavenging for ideas—in
documented architectural styles, patterns, dominant designs and reference
architectures, other architectures your organization, competitors, partners, or
suppliers have created or you find documented in the literature, etc. Based on
this study, and your and the team’s past experience, the
meta-architecture is formulated. This includes the architectural style,
concepts, mechanisms and principles
that will guide the architecture team during the next steps of structuring.

Conceptual
Architecture

The system is decomposed into components (structural elements) and
the responsibilities of each component, and interconnections between components
are identified. The intent of the conceptual architecture is to direct
attention at an appropriate decomposition of the system without delving into
the details of interface specification and type information. Moreover, it
provides a useful vehicle for communicating the architecture to non-technical
audiences, such as management, marketing, and many users.

Logical Architecture

The logical architecture is the detailed architecture
specification, precisely defining the component interfaces and connection
mechanisms and protocols. It also provides contextual information about the
components and how they should be used in assembling systems.

The logical architecture is used by the component designers
and developers, as well as component users (i.e., those that assemble
components into systems).

The conceptual architecture forms the starting point for the
logical architecture, and is likely to be modified as well as refined during
the course of the creation of the logical architecture. Modeling the dynamic
behavior of the system (at the architectural—or component—level) is
a useful way to think through and refine the responsibilities and interfaces
of the components. Component specifications make the architecture concrete.
These should include a summary description of services the component provides,
the component owner’s name, IID and version names, message signatures
(IDL), a description of the operations, constraints or pre-post conditions for
each operation (these may be represented in a state diagram), the concurrency
model, constraints on component composition, a lifecycle model, how the
component is instantiated, how it is named, a typical use scenario, a
programming example, exceptions, and a test or performance suite.

Execution Architecture

An execution architecture is created for distributed or concurrent
systems. It is formed by mapping the components onto the processes of the
physical system. Different possible configurations are evaluated against
requirements such as performance and scaling.

Architecture Tradeoff Analysis

At each step in structuring, it is worthwhile challenging the
team’s creativity to expand the solution set under consideration, and
then evaluating the different architecture alternatives against the prioritized
architectural requirements. This is known as architecture tradeoff analysis
(Barbacci et. al., 1998), and it recognizes that different approaches yield
differing degrees of fit to the requirements. Selection of the best solution generally involves some compromise, but it is best to
make this explicit.

Architecture
Validation

During structuring, the architects obviously make their best
effort to meet the requirements on the architecture. The architecture
validation phase involves additional people from outside the architecting team
to help provide an objective assessment of the architecture. In addition to
enhancing confidence that the architecture will meet the demands placed on it,
including the right participants in this phase can help create buy-in to the
architecture. Architecture assessment involves "thought experiments",
modeling and walking-through scenarios that exemplify requirements, as well as
assessment by experts who look for gaps and weaknesses in the architecture
based on their experience. Another important part of validation is the
development of prototypes or proofs-of-concept. Taking a skeletal version of
the architecture all the way through to implementation, for example, is a
really good way to prove out aspects of the architecture.

Iterations

Though described sequentially above, the architecting process is
best conducted iteratively, with multiple cycles through requirements,
structuring and validation. One approach is to have at least one cycle devoted
to each of Meta, Conceptual, Logical, and Execution architecture phases and
cycles for developing the architectural guidelines and any other materials to
help in deploying the architecture (such as tutorials). At each cycle, just
enough requirements are collected to proceed with the next structuring step,
and validation concentrates on the architecture in its current phase of
maturity and depth.

Moreover, a number of architecture teams that we have worked with
have stopped at different points, leaving more detailed architecting to the
product and component teams. At one end of the spectrum, a very small team of
architects created the meta-architecture, and each of the product teams created
their own architectures within the guidelines and constraints of the
meta-architecture. Other architecture teams created the meta- and conceptual
architectures, and a broader team of component owners developed the logical
architecture. At the other end of the spectrum, the architecture team developed
the entire architecture, all the way to its detailed logical architecture
specification. This approach yields the most control over the architecture
specification, but is typically fraught with organizational issues (e.g., the
"NIH syndrome") that slow or even completely inhibit the use of the
architecture.

The Organizational
Process

Overview

Architecture projects are susceptible to three major
organizational sources of failure—the project is under-resourced or
cancelled prematurely by an uncommitted management; it is stalled with endless
infighting or a lack of leadership; or the architecture is ignored or resisted
by product developers. The organizational process helps address these pitfalls.
Two phases—namely Init/Commit and Deployment—bookend the technical
process. However, the principal activities in these phases, namely championing
the architecture and leading/teaming in Init/Commit, and consulting in
Deployment, also overlap with the technical process activities.

Init/Commit

The Init/Commit phase focuses on initiating the architecture
project on a sound footing, and gaining strong commitment from upper
management. The creation of the architecture vision is central both to aligning
the architecture team and gaining management sponsorship. A communication plan
is also helpful in sensitizing the team to the need for frequent communication
with others in the organization. A heads-down, hidden skunkworks architecture
project may make quick progress—as long as it is well-led and its members
act as a team. However, not listening to the needs of the management,
developers, marketing, manufacturing and user communities and not paying
attention to gaining and sustaining sponsorship in the management and technical
leadership of the organization, or buy-in from the developer community, will
lead to failure. The communication plan places attention on balancing the need
for communication and isolation, as well as planning what to communicate when,
and to whom.

Deployment

The Deployment phase follows the technical process, and addresses
the needs of the developers who are meant to use the architecture to design and
implement products. These range from understanding the architecture and its
rationale, to responding to the need for changes to the architecture. This
entails consulting, and perhaps tutorials and demos, as well as the architects'
involvement in design reviews.

Championing

It is important that at least the senior architect and the
architecture project manager (if there is one) champion the architecture and
gain the support of all levels of management affected by the architecture.
Championing the architecture starts early, and continues throughout the life of
the architecture, though attention to championing tapers off as the
architecture comes to be embraced by the management and developer communities.

Leading/Teaming

For the architecture team to be successful, there must be a leader
and the team members must collaborate to bring their creativity and experience
to bear on creating an architecture that will best serve the organization. This
would seem so obvious as to not warrant being said, but unfortunately this is
easier said than done. Explicit attention to developing the designated lead
architect’s leadership skills, in the same way one would attend to
developing these skills in management, is a worthy investment. Likewise,
investing in activities aimed at developing the team as a team also has great
payoff in the team’s efficacy.

Communicating
and Consulting

Consulting with and assisting the developer community in their use
of the architecture is important in facilitating its successful adoption and
appropriate use. These activities are most intense during deployment. However,
earlier communication and consulting helps create buy-in the developer
community through participation and understanding. This allows the architecture
team to understand the developers’ needs and the developers to understand
the architecture (and its rationale) as it evolves through the cycles of the
technical process.

Tailoring the Process To Your Project

We worked with and studied dozens of architecting projects, and
distilled what we believe to be the best practices and pitfalls
that would help architects successfully create and deploy their architectures.
Based on this experience, we synthesized the Visual Architecting
Process™ (VAP). Though this architecting process lays out the
activities and guidelines that we have derived from real-world experience, no
project that we studied followed exactly this process. Also, every project that
we have consulted with or coached, has adapted the process. This has been true
of other software development methods, such as SA/SD, OMT and Fusion (Malan,
Coleman and Letsinger, 1995). It would appear that a method is not fully
embraced by a project team until they have adapted it to their particular
project needs. In this regard, methods are somewhat like architectures!

We do encourage architects to use the process, and to work quickly
and iteratively, not getting stuck on any model or aspect of the architecture
but always keeping to the discipline of moving forward quickly and coming back
soon to revise, rework and mature the architecture. Early on, your cycles are
through different models (with descriptions, explanations and rationale). Later
on you will start to cycle through models and contained code experiments. As
soon as the architecture is mature enough to begin construction, you will need
to work with project managers and key developers to create the right balance
between addressing technical risk and getting architectural elements in place,
and launching teams focused on building feature sets or storylines so that
users can be involved in construction feedback loops.

But remember, the visual architecting process is very much about
bringing stakeholders into the process from the start, and about iterating and
maturing the architecture. The point where construction begins and and the
point where the architecture is considered stable and under change control are not
necessarily the same point, and where they are set is a project-by-project
decision. It depends on factors like scope of the architecture, co-location or
geographical distribution of the team(s), maturity of the problem domain and
experience with this kind of system, etc. There is no tablet of commandments in
RUP or agile or anything else that can effectively prescribe where this point
should be set for every project, regardless of its context. What your strategy
is and internal capabilities are, how the organization is structured, what
goals you are trying to address and what resources you have to go after those
goals, all matter! Context matters, and experience and good judgment matter.

Scaling Agile with VAP

The VAP is all about being agile even when the complexity of the
system, and the organizational unit(s) building it, demands just enough
upfront design—for example, to launch concurrent agile teams. What VAP
emphasizes and enables is parallelizing the requirements and architecture
iterations, with intensive stakeholder involvement as pertinent to the quick cycles.
VAP can also be applied on traditionally small agile projects, with just enough
design work during each iteration. For larger, complex systems, early VAP
cycles use the cheapest possible artifacts (models, prototypes, etc.) for
learning quickly about stakeholder value and architectural challenge.

5 THREE TIER WEB BASED ARCHITECTURE

3-Tier Client/Server Architecture 3-Tier client-server architectures have 3 essential components:

1. A
Client PC

2. An
Application Server

3. A
Database Server

3-Tier Architecture Considerations:

•
Client program contains presentation logic only

o Less
resources needed for client workstation

o No
client modification if database location changes

o Less
code to distribute to client workstations

•
One server handles many client requests

o More
resources available for server program

o Reduces
data traffic on the network

Application Architecture

2 - Tier or 3 - Tier?

This is clearly not a  new subject and is clearly a
subject that is well discussed.  Yet, in my experience I have seen many a
systems designed the wrong way.  In the industry I have come across die
hard believers in one versus the other approach.  What is rare to come
across is some who evaluated the needs of the customer or the requirements for the
application to actually determine which of the two architectures (or others) is
best.  Also, I find that at times I too tend to forget all the factors
that must be evaluated.  So I figured I might as well write these down for
future reference.

Having said that, let me define 3 vs 2 tier.  A 3 tier
application typically has a web server, an application server, and a database
server (as in at least 3 different physical machines).  Clealry for a 3
tier system to work the code required will have to be different from the code
needed to make a 2 tier system to work.  The reason being, in a 3 tier
system, the web server will have to make requests to code that resides on a
physically different machine, i.e., the application server.

Nearly all existing technologies (java/J2EE, .Net, etc) offer
the ability to develop 2 and 3 tier applications.  I will use .Net as an
example but I believe the concepts remain the same no matter what technology
you use.

Before we discuss architecture, a quick note on code.  The
.Net technology has made most aspects of coding very simple.  Using the
new technologies to their max is always a good idea.  Irrespective of what
your current needs are, designing your application and therefore code it
to be flexible enough to handle multiple tiers and SOA principals is
always a good idea.

It is entirely possible to write code that is loosely coupled to
your middle tier.  It is also possible to design your middle tier such
that a consumer of it can use tight coupling, remoting or web services to
access it.  You do not need any fancy frameworks to do this.  The
.Net framework makes this very easy.  But more about that later.
Perhaps another article.  For now let's just stick to identifying reasons
for having a 2 vs 3 tier application architecture.

2 Tier vs. 3 Tier

Without going into too much detail let me start by laying out the
advnatages of using a 2 tier architecture.  I will then followup with all
its limitations, hence the need for 3 tier systems.  To conclude I will
present a simple table taht will assist in making the 2 vs 3 tier decision.

Performance.  Because of
tight coupling a 2 tiered application will run fatser.  Though it is not
necessary to have tight coupling in 2 tiered application in most cases tight
coupling is used..  Also, the absence of a network hop from the web to
application server helps improve performance.

Potentially easier deployment and configuration management issues.  In a 2 tier environment there is not as much configuration
required thereby making code deployment and server maintenance slightly easier.

Why 3 Tier?

So one would argue, hey! I have better speed and
possibly easier maintenance, why would I ever consider doing anything but
a 2 Tier system.  Ah! so lets look into this a little deeper.

Back to Performance.
Imagine you are developing a application where the user logs on, enters some
data and hits submit.  Upon submitting imagine if the application server
now uses the input from the user to conduct some CPU and RAM intensive
calculations for the next 5 minutes.  After which it will enter some
results into the database and the user can come back and view these results
(clearly we do no want this to be a synchronous process where the user will
wait for 5 minutes on the browser).

Now imagine additional users hitting this site during these 5
minutes.  Uh oh! we have a problem.  They are getting poor response
times.  The number crunching process seems to have brought down the web
site.  So now the performance advantage of the 2 Tier world is suddenly
lost. A 3 tier architecture offers you the ability to scale your system
according to how it will be used.  It gives you the ability to setup
servers based on functionality and scale accordingly.

Security .  Additonally, a
web server is often placed in the least protected part of your network and is
exposed to the outside world.  In most sytems security is key and a large
part of security is to protect your database and file storage systems.  In
a 2 Tiered system, the web server communicates with the database server and
other resources on your network directly.  The threat here is that if
someone attacks your web server there is now a direct gateway to all your
network resources.

However, in a 3 tiered architecture, you limit communications from
your web server to just to the application servers.  In fact you can
confirgure the application server to accept instructions only from the web
servers.  this way an intrusion into your network, i.e., someone walking
in and connecting his laptop to your network, will still not give them access
to the system in question.

2 Tier

3 Tier

Number of Users

Large

X

Small

X

Domain/Security

Intranet

X

Internet

X

Processing

High

X

Low

X

Load and throughput.  In
a 2 tiered system if you have a huge increase in your user base you will need
to buy servers that will need to be powerful enough to run both the web and the
application.  However in the 3 tiered system, you can scale your
architecture based on what your system does and on where your choke point is.
For example, if you have a processor heavy system, then you can add additional
application servers and leave the web servers as is.  If the system does
not require much processing, then you can handle additional load by adding more
web servers (very cheap machines to handle throughput rather than processing)
and leave the application servers as is.

So how do I choose 2 or 3 tier?  Below is a table that can
assist in making the decision.  A 2 Tiered system can be beneficial when
you have a small number of users, low security or intranet application, and low
level of processing requirements.  The moment any of these conditions fail
you must consider a move to a 3 tier architecture.

UNIT II

XML

1 INTRODUCTION TO XML

XML was designed to transport and store data.

HTML was designed to display data.

What You Should
Already Know

Before you continue you should have a basic understanding of the
following:

HTML

JavaScript

What is XML?

XML
stands for EXtensible Markup Language

XML is a
markup language much like HTML

XML was
designed to carry data, not to display data

XML tags
are not predefined. You must define your own tags

XML is
designed to be self-descriptive

XML is a
W3C Recommendation

The Difference
Between XML and HTML

XML is not a replacement for HTML.

XML and HTML were designed with different goals:

XML was
designed to transport and store data, with focus on what data is

HTML was
designed to display data, with focus on how data looks

HTML is about displaying information, while XML is about carrying
information.

XML Does Not DO
Anything

Maybe it is a little hard to understand, but XML does not DO
anything. XML was created to structure, store, and transport information.

The following example is a note to Tove, from Jani, stored as XML:

<note>

<to>Tove</to>

<from>Jani</from>

<heading>Reminder</heading>

<body>Don't forget me this weekend!</body>

</note>

The note above is quite self descriptive. It has sender and
receiver information, it also has a heading and a message body.

But still, this XML document does not DO anything. It is just
information wrapped in tags. Someone must write a piece of software to send,
receive or display it.

With XML You Invent
Your Own Tags

The tags in the example above (like <to> and <from>)
are not defined in any XML standard. These tags are "invented" by the
author of the XML document.

That is because the XML language has no predefined tags.

The tags used in HTML are predefined. HTML documents can only use
tags defined in the HTML standard (like <p>, <h1>, etc.).

XML allows the author to define his/her own tags and his/her own
document structure.

XML is Not a
Replacement for HTML

XML is a complement to HTML.

It is important to understand that XML is not a replacement for
HTML. In most web applications, XML is used to transport data, while HTML is
used to format and display the data.

My best description of XML is this:

XML is a software- and
hardware-independent tool for carrying information.

XML is a W3C
Recommendation

XML became a W3C Recommendation February 10, 1998.

To read more about the XML activities at W3C, please read our W3C Tutorial.

XML is Everywhere

XML is now as important for the Web as HTML was to the foundation
of the Web.

XML is the most common tool for data transmissions between all
sorts of applications.

XML

Please note that the descriptions given below are simplified and
only meant to give an impression of XML. They leave out a lot of the standards and are (for reasons of readability) a little inaccurate.
Also note that these standards are not finalized yet, so that they may change
before they're officially accepted. As a first introduction, however, this
document should be useful.

XML itself

There already exists a standard for defining markup languages like
HTML, which is called SGML. HTML is actually defined in SGML. SGML could have
been used as this new standard, and browsers could have been extended with SGML
parsers. However, SGML is quite complex to implement and contains a lot of
features that are very rarely used. Its support for different character sets is
also a bit weak, which is something that can cause problems on the web where
people use many different kinds of computers and languages. It's also difficult
to interpret an SGML document without having the definition of the markup
language (the DTD) available. Because of this, the XWG decided to develop a
simplified version of SGML, which they called XML. (As they like to say, XML is
more like SGML light, than HTML++.)

The main point of XML is that you, by defining your own markup
language, can encode the information of your documents much more precisely than
is possible with HTML. This means that programs processing these documents can
"understand" them much better and therefore process the information
in ways that are impossible with HTML (or ordinary text processor documents).
Imagine that you marked up recipes (for, say, soups and sea food dishes etc)
according to a DTD tailored for recipes where you entered the amounts of each
ingredient and alternatives for some ingredients. You could then easily make a
program that, given a list of the contents of your fridge, would go through the
entire list of recipes and make a list of the dishes you could make with them.
Given nutritional information about the ingredients (x calories per ounce of
this, y calories per once of that etc) the program could sort the suggestions
by the amount of calories in each dish. Or by how long they'd take to prepare,
or the price (given price information for the ingredients), or... The
possibilites are almost endless, because the information is encoded in a way
that the computer can "understand".

Defining your own markup language with XML is actually
surprisingly simple. If you wanted to make a markup language for FAQs you might
want it to be used like this: (note that this example is really too simple to
be very useful)

<?xml version="1.0" encoding="UTF-8"
standalone="yes"?>

<!DOCTYPE FAQ SYSTEM "FAQ.DTD">

<FAQ>

<INFO>

<SUBJECT>   XML    </SUBJECT>

<AUTHOR>
Lars Marius Garshol</AUTHOR>

<EMAIL>
[email-masked]
</EMAIL>

<VERSION>
1.0   </VERSION>

<DATE>      20.jun.97
</DATE>

</INFO>

<PART
NO="1">

<Q
NO="1">

<QTEXT>What is XML?</QTEXT>

<A>SGML light.</A>

</Q>

<Q
NO="2">

<QTEXT>What can I use it for?</QTEXT>

<A>Anything.</A>

</Q>

</PART>

</FAQ>

In XML, the markup language shown above (let's call it FAQML) had
a DTD like this:

<!ELEMENT FAQ     (INFO, PART+)>

<!ELEMENT INFO
(SUBJECT, AUTHOR, EMAIL?, VERSION?, DATE?)>

<!ELEMENT SUBJECT (#PCDATA)>

<!ELEMENT AUTHOR
(#PCDATA)>

<!ELEMENT EMAIL
(#PCDATA)>

<!ELEMENT VERSION (#PCDATA)>

<!ELEMENT DATE
(#PCDATA)>

<!ELEMENT PART
(Q+)>

<!ELEMENT Q       (QTEXT,
A)>

<!ELEMENT QTEXT
(#PCDATA)>

<!ELEMENT A
(#PCDATA)>

<!ATTLIST PART
NO    CDATA
#IMPLIED

TITLE CDATA #IMPLIED>

<!ATTLIST Q       NO    CDATA #IMPLIED>

<!ELEMENT> is used to define elements like this:
<!ELEMENT NAME CONTENTS>. NAME gives the name of the element, and
CONTENTS describes which elements that are allowed where inside the element
we've defined. A,B means that you must have an A first, followed by a B. ?
after an element means that it can be skipped, + means that it must be included
one or more times and * means that it can be skipped or included one or more
times. #PCDATA means ordinary text without markup (more or less).

An important difference between XML and SMGL is that elements in
XML which do not have any contents (like IMG and BR of HTML) are written like
this in XML: <IMG SRC="pamela.gif"/>. Note the slash before the
final >. This means that a program can read the document without knowing the
DTD (which is where it says that IMG does not have any contents) and still know
that IMG does not have an end tag and that what comes after IMG is not inside
the element.

<!ATTLIST> defines the attributes of an element. In the DTD
given above it's used to give PART and Q an attribute called NO, which contains
ordinary text and which can be skipped. As you can see, PART has two
attributes, and the last one is called TITLE, contains text and can be skipped.

Linking in XML

HyTime is a standard for adding linking attributes and elements to
SGML DTDs. It is far more advanced than what's possible with HTML and
contains a lot of stuff not useful on the web. The XWG is therefore currently
making a similar standard for XML which borrows a lot from HyTime (and similar
standards) and simplifies it.

To make it possible to use this linking standard in any DTD (regardless
of which elements the DTD has) there aren't defined any particular elements for
linking. Instead, linking elements use special attributes that identify them as
linking elements. All elements that have an attribute called XML-LINK will be
considered linking. The value of XML-LINK specifies what kind of link the
element specifies.

XML links can be between two or more resources, and resources can
be either files (and not necessarily XML or HTML files) or elements in files.
Links can be specified with the ACTUATE-attribute to be followed either (if the
value is USER) when the user explicitly requests this (for instance by
clicking) or (value AUTO) automatically (ie: when the system reads the linking
element). What happens when you follow the link is specified with SHOW, which
can take the following values:

EMBED

This means that the resource the link points to is to be inserted
into the document the link comes from. This will happen either during the
displaying of the document or during processing of the document. This can be
useful for including text from other files (with ACTUATE=AUTO) or to include a
picture in a page. It can also be used to insert footnotes into the text and
ACTUATE will then specify if the user has to click on the footnotes to include
them or whether all footnotes will be inserted automatically.

REPLACE

This means that the resource the link points to is to replace the
linking element. If you have two different versions of a paragraph you can link
them in such a way that one can see the other version in the same context by
following the link.

NEW

In this case, following the link will not affect the resource the
link came from. Instead, the linked resource will be processed/displayed in a
new context. Ordinary HTML links are of type NEW, as the new page is displayed
in place of the previous one.

XML is even more advanced than this. Links can be between more
than one resource, they can be specified outside the actual documents
themselves and the linked-to element inside a resource can be specified in very
powerful ways. The element can be identified with an ID-attribute, position in
the element structure and one can even specify that the link goes to things
like "fourth LI inside the first UL inside BODY".

In FAQML this could have been used both for specifying links to
relevant information outside the FAQ as well as specifying internal
relationships between different answers. It could also have been used for
footnotes etc.

XML and layout

There is actually already an SGML standard for this as well, and
it's called DSSSL, and isn't very simple, either. The XWG has therefore decided
to make a simplified version of DSSSL as well and call it XSL. So far, not much
has been done about this. One proposal (see references)
has been submitted, but it hasn't been accepted yet, and it's uncertain if it
will be. So, I'm going to describe DSSSL instead of XSL, at least until the
future shape of XSL becomes clearer.

DSSSL is actually a full programming language, based on Scheme (a
LISP dialect), and is very powerful. It can be used both as a stylesheet
specifying fonts and positioning for the different elements and as a
transformational language that can be used to transform documents from one DTD
to another.

The most common use of DSSSL is to convert SGML documents to other
formats better suited for presentation, like PDF (also known as Acrobat),
PostScript, LaTeX, HTML or RTF. What the XWG is planning is to use XSL to
specify how XML documents are to be displayed on screen.

Below I try to show how we could make a stylesheet for FAQML, but
without explaining very much of what really happens. I've split the DSSSL file
into several parts in order to be able to comment it as it's written, but it is
meant to be a single file.

DSSSL consists of several different parts, and the most basic one
is the expression language which is quite simply a subset of Scheme. This means
that DSSSL-stylesheets are really one large Scheme expression that is
calculated by the DSSSL engine, with a file as the result of the calculation.
Another important part (which is built on the expression language) is the style
language, which I've used almost exclusively in this example. A third part is
the query language, which can be used to find any element you want in your
document. I've used it in this example to find the number of a FAQ question
from inside the QTEXT element. This was necessary because NO is an attribute of
the surrounding Q element, and not QTEXT itself.

All formatting in DSSSL is done with so-called flow objects. In
the code below you'll se a lot of (element X (make Y-expressions which indicate
that when element X shows up the DSSSL engine is to create a flow object of type
Y. Then style rules for Y and then the contents of Y are specified. There's
much more to DSSSL than this, but the rest is considered to be outside the
scope of this document.

<!doctype style-sheet PUBLIC "-//James Clark//DTD DSSSL
Style Sheet//EN">

;--- DSSSL stylesheet for FAQML

;---Constants

(define *font-size*          12pt)

(define *font*                 "Times
New Roman")

The first line tells the SGML parser that this document follows
the DTD for DSSSL. (Yes, DSSSL is an SGML application.) The next two lines are
comments (after ; the rest of the line is ignored). Then I define two constants
that I use below in the styles themselves. This is done to make it easy to
change the font size of the entire document without having to adjust sizes for
all kinds of headers etc. Instead, I just change the value of *font-size*.

;---Element styles

(element FAQ

(make
simple-page-sequence

font-family-name:           *font*

font-size:
*font-size*

input-whitespace-treatment:
'collapse

line-spacing:                  (*
*font-size* 1.2)

(process-children)))

This part creates a flow object for the FAQ element, ie: the whole
document. The flow object is "simple-page-sequence", which I assume
is meant for small articles. I then specify what font to use, font size, that
whitespace is to be considered insignificant (like in HTML) and then I give the
line height. The line height is set to be 1.2 times the font size.

(element INFO

(make paragraph

quadding:                      'center

space-after:                   (*
*font-size* 1.5)

(process-children)))

This indicates that the element INFO (from start-tag to end-tag)
is to be laid out as a paragraph that is centered and has a blank space as high
as 1.5 lines after it. After creating the paragraph flow object the DSSSL
engine is to go on to process the child elements of INFO.

(element SUBJECT

(make paragraph

font-size:                       (*
*font-size* 2)

line-spacing:                  (*
*font-size* 2)

space-after:                   (*
*font-size* 2)

(process-children)))

The subject element gets its own paragraph and is displayed in
double font size. AUTHOR and EMAIL are simpler versions of this, so I skip
them. (You can find them in the complete DSSSL file linked to below.)

(element VERSION

(make paragraph

(make
sequence

(literal "Version: "))

(process-children)))

The VERSION element is given its own paragraph, which contains
sequence flow objects. I insert one containing the text "Version: "
before the actual contents of VERSION are processed. This means that the text
"Version: " will be inserted in front of the actual version number.
DATE is similar, so I skip that.

(element PART

(make paragraph

font-size:                       (*
*font-size* 1.5)

line-spacing:                  (*
*font-size* 2)

(make
sequence

(literal (attribute-string
"NO" (current-node)))

(literal ". ")

(literal (attribute-string
"TITLE" (current-node)))

)

(process-children)))

I wanted PART to have a large font size and contain both number
and title. We've already seen how to do this with sequence, but the problem of
getting hold of the number and title is new. They are only given as attributes,
and thus will be ignored by (process-children). The function attribute-string
gives us what we want. (attribute-string "NO" (current-node)) returns
the value of the attribute NO in the current element. The rest of this style
sheet is so simple that I'll just skip it without comments.

In case anyone's interested, they can find the entire DSSSL file here,
together with the results in RTF and
PostScript formats.
The RTF file is produced by Jade and the Postscript file is produced from this.
Note that the RTF and Postscript files are from the Norwegian version. This should
make no difference, though.

The difference between XSL and DSSSL

At this point it doesn't seem like XSL will be based on Scheme,
since Microsoft and Netscape already have implemented JavaScript in their
browsers. So XSL will probably be defined as an XML DTD that uses JavaScript
for programming. That's a pity, since DSSSL has such a nice syntax and Scheme
is such a great programming language, but Netscape Navigator and MSIE are of
course large enough as it is.

What will XML be used for?

Please note that what follows is only my personal views on the
future of the web and should as such be regarded with a pinch of salt.

The layout problem

The first thing I hope XML can put right is the problem of making
web pages with decent layout that are still accessible to anyone, regardless of
browser. Considering that XSL will be a complete standard to be supported one
should, after a while, expect a stable standard to write against. XSL also lets
you check whether optional features are present or not and if not you can
supply alternative code to take care of those cases.

A FAQ-maintainer will also be rid of the problems with maintaining
the FAQ in HTML, .txt and PDF versions (or whatever). Instead s/he can make one
(or more) DSSSL stylesheets to be run each time the original has been updated
to create new versions of the distribution files. (Just like I produced .RTF
and .PS files for my FAQ above.)

Considering that neither Microsoft nor Netscape has been able to
implement CSS (or even HTML) properly one can wonder what will happen when they
try to implement XML and XSL. My hope is that they'll decide they have to make
a real effort and do it properly and that if they don't somebody who does will
take over the market. They've now promised to support XML, so there's room for
hope, but no hope.

More versatile ways of displaying data

An API to be supported by all XML and HTML processors (that is
browsers and other tools) is under development under the name Document Object
Model (or DOM). This happens a little on the side of the XWGs work, but is
still well under way. This API will make it possible to make Java applets (or
JavaScript snippets) that can be used to change the display of XML-encoded
information in web browsers. (The members of XWG like to call this "giving
Java something to work with.")

This can be used in a nearly infinite number of ways, but examples
of what the developers have in mind are footnotes that are invisible until you
click the footnote number in the text, that you can start from the table of
contents in a document and descend through the levels by clicking (like in
Windows Explorer). You can also make things like tables that can be sorted by
any column by clicking on it. The possibilities are nearly unlimited, and this
is only the tip of the iceberg.

This can be made significantly much more advanced. One could
imagine that VRML (a language for coding 3D worlds) was redefined in XML and
VRML viewers were written as Java applets using DOM. This would mean that VRML
could be used together with HTML with no need for extra software on the client
side. (Well, there would be the applets, but they both install and remove
themselves.)

The major vendors of electronic components (so-called chips) have
joined forces to make a DTD that can be used to describe components. Together
with the right Java applets this could be used to download any descriptions of
chips and then model how these work together.

Searching and agents

The applications described here are currently not feasible, but I
hope that in time they may be.

That the information in XML documents is so precisely described by
the markup means that one can search them in much better ways than the
primitive text searches currently available from search engines like Excite and
Altavista today. There are already SGML query languages that are similar to SQL
in power and this field is still under research.

With standardized DTDs for different applications one could
retrieve information much more accurately than today. One could envision things
like a central search engine for chip vendors where you could do very precise
searches for components by specification, almost as if they were in an ordinary
relational database. Similar services would be possible for all documents with
a common DTD.

Exploiting this for global search engines like Excite and
Altavista is going to be a lot more difficult becaouse of the number of
different DTDs. With an overview of the most important ones and a little
artificial intelligence in the search engines this could perhaps be handled,
but for now this is pure science fiction.

Jon Bosak writes about using this sort of technique with
intelligent agents, which are personal robots that search the web (and possibly
other services as well) for information for you based on your preferences. This
might be easier, as you could list the DTDs and your preferences privately, but
it's still science fiction.

Exchanging information between different systems

Because a DTD gives a standard format for information related to a
specific subject it can be used to simplify the exchange of information between
different sources. Many kinds of applications have or will have standard DTDs.
I've already mentioned chip manufacturers, and many other industries already
have standard DTDs and more will follow. This means that systems can use these
common DTDs to exchange information with each other, regardless of their
internal format. The main applications of this will probably be the exchange of
data between companies in the same industry or researchers within an academic
field, although many other applications for ordinary users are imaginable.

2 XML FUNDAMENTALS

What is XML?

What is XML good for?

Why did Sun invest in XML?

XML and users

What is XML?

XML is a
document format

XML is a
data format

XML is an
activity of the World Wide Web Consortium (W3C) organized and led by Sun
Microsystems

Objective:
move the Web to its next stage of evolution by adapting existing
international standards for markup, linking, and formatting

What is XML good for?

Internationalized electronic
publishing

Platform-independent

Language-independent

Media-independent

Data-centric Web applications

Database exchange

Distribution of processing to
clients

Client-side manipulation of
views into the data

Customization of information
by intelligent agents

Management of document
collections

Business transactions

Why did Sun invest in
XML?

Sun organized and led the XML activity, beginning in 1996. Sun
continues to lead the XML activity today. Why?

HTML was
not enough for publishing on the Web.

HTML was
not enough for distributed applications.

Without
XML, HTML would have been replaced by a more powerful binary proprietary
format.

XML and users

Big
open-standards victory for users

Freely
extensible

Human-readable

Machine-comprehensible

Easy to
implement

Completely
internationalized

"Data
the way you want it" (Microsoft)

User
control of views into data

Interoperability
of content, style, and behavior

Contents:

XML Documents and
XML Files

Elements, Tags,
and Character Data

Attributes

XML Names

Entity References

CDATA Sections

Comments

Processing
Instructions

The XML
Declaration

Checking Documents
for Well-Formedness

·
This chapter shows you how to write simple XML documents. You'll
see that an XML document is built from text content marked up with text tags
such as <SKU>, <Record_ID>, and <author> that look
superficially like HTML tags. However, in HTML you're limited to about a
hundred predefined tags that describe web-page formatting. In XML you can
create as many tags as you need. Furthermore, these tags will mostly describe
the type of content they contain rather than formatting or layout information.
In XML you don't say that something is italicized or indented or bold; you say
that it's a book or a biography or a calendar.

·
Although XML is looser than HTML in regards to which tags it
allows, it is much stricter about where those tags are placed and how they're
written. In particular, all XML documents must be well-formed. Well-formedness rules specify constraints such as "Every
start-tag must have a matching end-tag" and "Attribute values must be
quoted." These rules are unbreakable, which makes parsing XML documents
easy and writing them a little harder, but they still allow an almost unlimited
flexibility of expression.

2.1. XML Documents and XML
Files

An XML document contains
text, never binary data. It can be opened with any program that knows how to
read a text file. Example 2-1
is close to the simplest XML document imaginable. Nonetheless, t is a
well-formed XML document. XML parsers can read it and understand it (at least
as far as a computer program can be said to understand anything).

Example 2-1. A very simple yet complete XML document

<person> Alan Turing
</person>

In the most common scenario, this document would be the entire
contents of a file named person.xml,
or perhaps 2-1.xml.
However, XML is not picky about the filename. As far as the parser is
concerned, this file could be called person.txt,
person,
or Hey you, there's
some XML in this here file! Your operating system may or may not
like these names, but an XML parser won't care. The document might not even be
in a file at all. It could be a record or a field in a database. It could be
generated on the fly by a CGI program in response to a browser query. It could
even be stored in more than one file, though that's unlikely for such a simple
document. If it is served by a web server, it will probably be assigned the
MIME media type application/xml or text/xml. However, specific XML applications may use more specific MIME
media types such as application/mathml+xml, application/XSLT+xml, image/svg+xml, text/vnd.wap.wml, or even text/html (in very special
cases).

WARNING: For generic XML
documents, application/xml should be preferred to text/xml, although most web servers use text/xml by default. text/xml uses the ASCII
character set as a default, which is incorrect for most XML documents.

2.2. Elements, Tags, and Character Data

The document in Example 2-1
is composed of a single element named person. The
element is delimited by the start-tag
<person> and the end-tag </person>.
Everything between the start-tag and the end-tag of the element (exclusive) is
called the element's content. The content of this element is the text
string:

Alan Turing

The whitespace is part of the content, though many applications will
choose to ignore it. <person> and </person> are markup. The string "Alan Turing" and its surrounding
whitespace are character
data. The tag is the most common form of markup in an XML document,
but there are other kinds we'll discuss later.

2.2.1. Tag Syntax

XML tags look superficially like HTML
tags. Start-tags begin with < and end-tags begin with </. Both of these
are followed by the name of the element and are closed by >. However, unlike
HTML tags, you are allowed to make up new XML tags as you go along. To describe
a person, use <person> and </person> tags. To describe a calendar,
use <calendar> and </calendar> tags. The names of the tags
generally reflect the type of content inside the element, not how that content
will be formatted.

2.2.1.1. Empty
elements

There's
also a special syntax for empty
elements, i.e., elements that have no content. Such an element can be
represented by a single empty-element tag that begins with < but ends
with />. For instance, in XHTML, an XMLized reformulation of standard HTML,
the line-break and horizontal-rule elements are written as <br /> and
<hr /> instead of <br> and <hr>. These are exactly equivalent
to <br></br> and <hr></hr>, however. Which form you use
for empty elements is completely up to you. However, what you cannot do in XML
and XHTML (unlike HTML) is use only the start-tag--for instance <br> or
<hr>--without using the matching the end-tag. That would be a
well-formedness error.

2.2.1.2. Case
sensitivity

XML, unlike HTML, is case sensitive. <Person> is not the same as
<PERSON> is not the same as <person>. If you open an element with a
<person> tag, you can't close it with a </PERSON> tag. You're free
to use upper- or lowercase or both as you choose. You just have to be
consistent within any one element.

2.2.2. XML Trees

Let's look at a slightly more
complicated XML document. Example 2-2
is a person element that contains more information suitably marked up to show
its meaning.

Example
2-2. A more complex XML document describing a person

<person>
<name> <first_name>Alan</first_name>
<last_name>Turing</last_name> </name>
<profession>computer scientist</profession>
<profession>mathematician</profession>
<profession>cryptographer</profession> </person>

2.2.2.1. Parents and
children

This XML document is still composed of one person element. However, now
this element doesn't merely contain undifferentiated character data. It
contains four child elements: a name element and three profession
elements. The name element contains two child elements of its own, first_name
and last_name.

The person element is called the parent of the name element and
the three profession elements. The name element is the parent of the first_name
and last_name elements. The name element and the three profession elements are
sometimes called each other's siblings. The first_name and
last_name elements are also siblings.

As in human society,
any one parent may have multiple children. However, unlike human society, XML
gives each child exactly one parent, not two or more. Each element (with one
exception I'll note shortly) has exactly one parent element. That is, it is
completely enclosed by another element. If an element's start-tag is inside
some element, then its end-tag must also be inside that element. Overlapping tags, as in <strong><em>this common example from
HTML</strong></em>, are prohibited in XML. Since the em element
begins inside the strong element, it must also finish inside the strong
element.

2.2.2.2. The root
element

Every XML
document has one element that does not have a parent. This is the first element
in the document and the element that contains all other elements. In Example 2-1
and Example 2-2,
the person element filled this role. It is called the root element of
the document . It is also
sometimes called the document element. Every well-formed XML document
has exactly one root element. Since elements may not overlap, and since all
elements except the root have exactly one parent, XML documents form a data
structure programmers call a tree. Figure 2-1
diagrams this relationship for Example 2-2.
Each gray box represents an element. Each black box represents character data.
Each arrow represents a containment relationship.

Figure 2-1. A tree diagram for Example 2-2

2.2.3. Mixed Content

In Example 2-2,
the contents of the first_name, last_name, and profession elements
were character data, that is, text that does not contain any tags. The contents
of the person and name elements were child elements and some whitespace that
most applications will ignore. This dichotomy between elements that contain
only character data and elements that contain only child elements (and possibly
a little whitespace) is common in documents that are data oriented. However,
XML can also be used for more free-form, narrative documents such as business
reports, magazine articles, student essays, short stories, web pages, and so
forth, as shown by Example 2-3.

Example
2-3. A narrative-organized XML document

<biography>
<name><first_name>Alan</first_name>
<last_name>Turing</last_name> </name> was one of the first
people to truly deserve the name <emphasize>computer
scientist</emphasize>. Although his contributions to the field are too
numerous to list, his best-known are the eponymous <emphasize>Turing
Test</emphasize> and <emphasize>Turing Machine</emphasize>.
<definition>The <term>Turing Test</term> is to this day the
standard test for determining whether a computer is truly intelligent. This
test has yet to be passed. </definition> <definition>The
<term>Turing Machine</term> is an abstract finite state automaton
with infinite memory that can be proven equivalent to any any other finite
state automaton with arbitrarily large memory. Thus what is true for a Turing
machine is true for all equivalent machines no matter how implemented.
</definition> <name><last_name>Turing</last_name></name>
was also an accomplished <profession>mathematician</profession> and
<profession>cryptographer</profession>. His assistance was crucial
in helping the Allies decode the German Enigma machine. He committed suicide on
<date><month>June</month> <day>7</day>,
<year>1954</year></date> after being convicted of
homosexuality and forced to take female hormone injections. </biography>

The root
element of this document is biography. The biography contains name, definition,
profession, and emphasize child elements. It also contains a lot of raw
character data. Some of these elements such as last_name and profession only
contain character data. Others such as name contain only child elements. Still
others such as definition contain both character data and child
elements. These elements are said to contain mixed content. Mixed
content is common in XML documents containing articles, essays, stories, books,
novels, reports, web pages, and anything else that's organized as a written
narrative. Mixed content is less common and harder to work with in
computer-generated and processed XML documents used for purposes such as
database exchange, object serialization, persistent file formats, and so on.
One of the strengths of XML is the ease with which it can be adapted to the
very different requirements of human-authored and computer-generated documents.

2.3. Attributes

XML elements can have attributes. An attribute is
a name-value pair attached to the element's start-tag. Names are separated from values by an equals sign
and optional whitespace. Values are enclosed in single or double quotation
marks. For example, this person element has a born attribute with the value
1912-06-23 and a died attribute with the value 1954-06-07:

<person
born="1912-06-23" died="1954-06-07"> Alan Turing
</person>

This next element is
exactly the same as far an XML parser is concerned. It simply uses single
quotes instead of double quotes, puts some extra whitespace around the equals
signs, and reorders the attributes.

<person died =
'1954-06-07' born = '1912-06-23' > Alan Turing </person>

The whitespace around
the equals signs is purely a matter of personal aesthetics. The single quotes
may be useful in cases where the attribute value itself contains a double quote.
Attribute order is not significant.

Example
2-4 shows how attributes might be used to encode much of the same
information given in the data-oriented document of Example
2-2.

Example
2-4. An XML document that describes a person using attributes

<person> <name first="Alan"
last="Turing"/> <profession value="computer scientist"/>
<profession value="mathematician"/> <profession
value="cryptographer"/> </person>

This
raises the question of when and whether one should use child elements or attributes to hold information. This is a
subject of heated debate. Some informaticians maintain that attributes are for
metadata about the element while elements are for the information itself.
Others point out that it's not always so obvious what's data and what's
metadata. Indeed, the answer may depend on where the information is put to use.

What's undisputed is
that each element may have no more than one attribute with a given name. That's
unlikely to be a problem for a birth date or a death date; it would be an issue
for a profession, name, address, or anything else of which an element might
plausibly have more than one. Furthermore, attributes are quite limited in
structure. The value of the attribute is simply a text string. The division of
a date into a year, month, and day with hyphens in the previous example is at
the limits of the substructure that can reasonably be encoded in an attribute.
Consequently, an element-based structure is a lot more flexible and extensible.
Nonetheless, attributes are certainly more convenient in some applications.
Ultimately, if you're designing your own XML vocabulary, it's up to you to
decide when to use which.

Attributes are also
useful in narrative documents, as Example
2-5 demonstrates. Here it's perhaps a little more obvious what belongs to
elements and what to attributes. The raw text of the narrative is presented as
character data inside elements. Additional information annotating that data is
presented as attributes. This includes source references, image URLs,
hyperlinks, and birth and death dates. Even here, however, there's more than
one way to do it. For instance, the footnote numbers could be attributes of the
footnote element rather than character data.

Example
2-5. A narrative XML document that uses attributes

<biography
xmlns:xlink="http://www.w3.org/1999/xlink/namespace/"> <image
source="http://www.turing.org.uk/turing/pi1/bus.jpg"
width="152" height="345"/> <person born='1912-06-23'
died='1954-06-07'><first_name>Alan</first_name>
<last_name>Turing</last_name> </person> was one of the first
people to truly deserve the name <emphasize>computer
scientist</emphasize>. Although his contributions to the field were too
numerous to list, his best-known are the eponymous <emphasize
xlink:type="simple" xlink:href="http://cogsci.ucsd.edu/~asaygin/tt/ttest.html">Turing
Test</emphasize> and <emphasize xlink:type="simple"
xlink:href="http://mathworld.wolfram.com/TuringMachine.html">Turing
Machine</emphasize>. <last_name>Turing</last_name> was also
an accomplished <profession>mathematician</profession> and
<profession>cryptographer</profession>. His assistance was crucial
in helping the Allies decode the German Enigma machine.<footnote
source="The Ultra Secret, F.W. Winterbotham,
1974">1</footnote> He committed suicide on
<date><month>June</month> <day>7</day>,
<year>1954</year></date> after being convicted of
homosexuality and forced to take female hormone injections.<footnote
source="Alan Turing: the Enigma, Andrew Hodges,
1983">2</footnote> </biography>

2.4. XML Names

The XML specification can
be quite legalistic and picky at times. Nonetheless, it tries to be efficient
where possible. One way it does that is by reusing the same rules for different
items where possible. For example, the rules for XML element names are also the
rules for XML attribute names, as well as for the names of several less common
constructs. Generally, these are referred to simply as XML names.

Element and other XML
names may contain essentially any alphanumeric character. This includes the
standard English letters A through Z and a through z
as well as the digits 0 through 9. XML names may also include
non-English letters, numbers, and ideograms such as ö, ç,
,
and.They may also include these three punctuation characters:

the underscore

the hyphen

the period

XML names may not contain
other punctuation characters such as quotation marks, apostrophes, dollar
signs, carets, percent symbols, and semicolons. The colon is allowed, but its
use is reserved for namespaces as discussed in Chapter
4. XML names may not contain whitespace of any kind,
whether a space, a carriage return, a line feed, a nonbreaking space, and so
forth. Finally, all names beginning with the string XML (in any combination of
case) are reserved for standardization in W3C XML-related specifications.

XML names may only
start with letters, ideograms, and the underscore character. They may not start
with a number, hyphen, or period. There is no limit to the length of an element
or other XML name. Thus these are all well-formed elements:

<Drivers_License_Number>98 NY
32</Drivers_License_Number>

<month-day-year>7/23/2001</month-day-year>

<first_name>Alan</first_name>

<_4-lane>I-610</_4-lane>

<téléphone>011 33 91 55
27 55 27</téléphone>

These are not
acceptable elements:

<Driver's_License_Number>98 NY
32</Driver's_License_Number>

<month/day/year>7/23/2001</month/day/year>

<first name>Alan</first name>

<4-lane>I-610</4-lane>

2.5. Entity References

The character data inside an element may not contain a raw unescaped opening angle bracket
(<). This character is
always interpreted as beginning a tag. If you need to use this character in
your text, you can escape it using the &lt; entity reference. When a parser reads the document, it
will replace the &lt; entity reference with the actual < character. However, it will not confuse &lt; with the start of a tag. For example:

<SCRIPT
LANGUAGE="JavaScript"> if (location.host.toLowerCase(
).indexOf("cafeconleche") &lt; 0) {
location.href="http://www.cafeconleche.org/"; } </SCRIPT>

The character data
inside an element may not contain a raw unescaped ampersand (&) either. This is always interpreted as beginning an entity or
character reference. However, the ampersand may be escaped using the &amp; entity reference like this:

<publisher>O'Reilly
&amp; Associates</publisher>

Entity references such
as &amp; and &lt; are considered to be markup. When an application parses an XML
document, it replaces this particular markup with the actual characters to which the
entity reference refers.

XML predefines exactly
five entity references. These are:

&lt;

The less-than sign; a.k.a. the opening angle bracket (<)

&amp;

The ampersand (&)

&gt;

The greater-than sign; a.k.a. the closing angle bracket (>)

&quot;

The straight, double quotation marks (")

&apos;

The apostrophe; a.k.a. the straight single quote (')

Only &lt; and &amp; must be used instead of the literal characters in element
content. The others are optional. &quot; and &apos; are useful inside attribute values where a raw " or ' might be misconstrued as ending the attribute value. For example,
this image tag uses the &apos; entity reference to fill in the apostrophe in O'Reilly:

<image
source='oreilly_koala3.gif' width='122' height='66' alt='Powered by
O&apos;Reilly Books' />

Although there's no
possibility of an unescaped greater-than sign (>) being misinterpreted as closing a tag it wasn't meant to close, &gt; is allowed mostly for symmetry with &lt;.

2.6. CDATA Sections

When an XML document includes samples of XML or HTML source code, the < and & characters in those samples
must be encoded as &lt; and &amp;. The more sections of literal code a
document includes and the longer they are, the more tedious this encoding
becomes. Instead you can enclose each sample of
literal code in a CDATA section. A CDATA section is set off by a <![CDATA[ and ]]>.
Everything between the <![CDATA[ and the ]]> is treated as raw character
data. Less-than signs don't begin. Ampersands don't start entity references.
Everything is simply character data, not markup.

For example, in a
Scalable Vector Graphics (SVG) tutorial written in XHTML, you might see
something like this:

<p>You can use
a default <code>xmlns</code> attribute to avoid having to add the
svg prefix to all your elements:</p> <![CDATA[ <svg
xmlns="http://www.w3.org/2000/svg" width="12cm"
height="10cm"> <ellipse rx="110" ry="130"
/> <rect x="4cm" y="1cm" width="3cm"
height="6cm" /> </svg> ]]>

The SVG source code
has been included directly in the XHTML file without carefully replacing each
< with &lt;. The result will be a sample SVG document, not an embedded
SVG picture, as might happen if this example were not placed inside a CDATA
section.

The only thing that
can not appear in a CDATA section is the CDATA section end delimiter ]]>.

CDATA sections exist
for the convenience of human authors, not for programs. Parsers are not
required to tell you whether a particular block of text came from a CDATA
section, from normal character data, or from character data that contained
entity references such as &lt; and &amp;. By the time you get access to
the data, these differences will have been washed away.

2.7. Comments

XML documents can be commented so that coauthors
can leave notes for each other and themselves, documenting why they've done
what they've done or items that remain to be done. XML comments are
syntactically similar to HTML comments. Just as in HTML, they begin with
<!-- and end with the first occurrence of -->. For example:

<!-- I need to
verify and update these links when I get a chance. -->

The double hyphen --
should not appear anywhere inside the comment until the closing -->. In
particular, a three hyphen close like ---> is specifically forbidden.

Comments may appear
anywhere in the character data of a document. They may also appear
before or after the root element. (Comments are not elements, so this does not
violate the tree structure or the one-root element rules for XML.) However,
comments may not appear inside a tag or inside another comment.

Applications that
read and process XML documents may or may not pass along information included
in comments. They are certainly free to drop them out if they choose. Do not
write documents or applications that depend on the contents of comments being
available. Comments are strictly for making the raw source code of an XML
document more legible to human readers. They are not intended for computer
programs. For this purpose you should use a processing instruction
instead.

2.8. Processing Instructions

In HTML, comments are sometimes abused to
support nonstandard extensions. For instance, the contents of the script
element are sometimes enclosed in a comment to protect it from display by a
nonscript-aware browser. The Apache web server parses comments in .shtml
files to recognize server side includes. Unfortunately, these documents may not
survive being passed through various HTML editors and processors with their
comments and associated semantics intact. Worse yet, it's possible for an
innocent comment to be misconstrued as input to the application.

XML provides the processing
instruction as an alternative means of passing information to particular
applications that may read the document. A processing instruction begins with
<? and ends with ?>. Immediately following the <? is an XML
name called the target, possibly the name of the application for which
this processing instruction is intended or possibly just an identifier for this
particular processing instruction. The rest of the processing instruction
contains text in a format appropriate for the applications for which the
instruction is intended.

For example, in HTML
a robots META tag is used to tell
search-engine and other robots whether and how they should index a page. The
following processing instruction has been proposed as an equivalent for XML
documents:

<?robots
index="yes" follow="no"?>

The target of this
processing instruction is robots. The syntax of this particular processing
instruction is two pseudoattributes, one named index and one named follow,
whose values are either yes or no. The semantics of this particular processing
instruction are that if the index attribute has the value yes, then
search-engine robots should index this page. If index has the value no, then it
won't be. Similarly, if follow has the value yes, then links from this document
will be followed.

Other processing
instructions may have totally different syntaxes and semantics. For instance,
processing instructions can contain an effectively unlimited amount of text.
PHP includes large programs in processing instructions. For example:

<?php
mysql_connect("database.unc.edu", "clerk",
"password"); $result = mysql("HR", "SELECT LastName,
FirstName FROM Employees ORDER BY LastName, FirstName"); $i = 0; while ($i
< mysql_numrows ($result)) { $fields = mysql_fetch_row($result); echo
"<person>$fields[1] $fields[0] </person>\r\n"; $i++; }
mysql_close( ); ?>

Processing
instructions are markup, but they're not elements. Consequently, like comments,
processing instructions may appear anywhere in an XML document outside of a
tag, including before or after the root element. The most common processing
instruction, xml-stylesheet, is used to attach stylesheets to documents. It
always appears before the root element, as Example
2-6 demonstrates. In this example, the xml-stylesheet processing
instruction tells browsers to apply the CSS stylesheet person.css to
this document before showing it to the reader.

Example
2-6. A very simple yet complete XML document

<?xml-stylesheet href="person.css"
type="text/css"?> <person> Alan Turing </person>

The
processing instruction names xml, XML, XmL, etc., in any combination of case,
are forbidden to avoid confusion with the XML declaration. Otherwise, you're
free to pick any legal XML name for your processing instructions.

2.9. The XML Declaration

XML documents should (but do not have to)
begin with an XML declaration. The XML
declaration looks like a processing instruction with the name xml and version,
standalone, and encoding attributes. Technically, it's not a processing
instruction though, just the XML declaration; nothing more, nothing less. Example
2-7 demonstrates.

Example
2-7. A very simple XML document with an XML declaration

<?xml version="1.0"
encoding="ASCII" standalone="yes"?>
<person> Alan Turing </person>

XML
documents do not have to have an XML declaration. However, if an XML document
does have an XML declaration, then that declaration must be the first thing in
the document. It must not be preceded by any comments, whitespace, processing
instructions, and so forth. The reason is that an XML parser uses the first
five characters (<?xml) to make some reasonable guesses about the encoding,
such as whether the document uses a single byte or multibyte character set. The
only thing that may precede the XML declaration is an invisible Unicode
byte-order mark. We'll discuss this further in Chapter
5.

2.9.1. encoding

So far we've been a little cavalier about encodings. We've said that
XML documents are composed of pure text, but we haven't said what encoding that
text uses. Is it ASCII? Latin-1? Unicode? Something else?

The short answer to
this question is "Yes." The long answer is that by default XML
documents are assumed to be encoded in the UTF-8 variable-length
encoding of the Unicode character set. This is a strict superset of ASCII, so pure
ASCII text files are also UTF-8 documents. However, most XML processors,
especially those written in Java, can handle a much broader range of character
sets. All you have to do is tell the parser which character encoding the
document uses. Preferably this is done through metainformation, stored in the
filesystem or provided by the server. However, not all systems provide
character-set metadata so XML also allows documents to specify their own
character set with an encoding declaration inside the XML declaration. Example
2-8 shows how you'd indicate that a document was written in the ISO-8859-1
(Latin-1) character set that includes letters like ö and ç needed
for many non-English Western European languages.

Example 2-8. An XML
document encoded in Latin-1

<?xml version="1.0"
encoding="ISO-8859-1" standalone="yes"?>
<person> Erwin Schrödinger </person>

The
encoding attribute is optional in an XML declaration. If it is omitted and no
metadata is available, then the Unicode character set is assumed. The parser
may use the first several bytes of the file to try to guess which encoding of
Unicode is in use. If metadata is available and it conflicts with the encoding
declaration, then the encoding specified by the metadata wins. For example, if
an HTTP header says a document is encoded in ASCII but the encoding declaration
says it's encoded in UTF-8, then the parser will pick ASCII.

The
different encodings and the proper handling of non-English XML documents will
be discussed in greater detail in Chapter 5.

2.9.2. standalone

If the standalone attribute has the value no, then an application may
be required to read an external DTD (that is a DTD in
a file other than the one it's reading now) to determine the proper values for
parts of the document. For instance, a DTD may provide default values for
attributes that a parser is required to report even though they aren't actually
present in the document.

Documents that do not
have DTDs, like all the documents in this chapter, can have the value yes for
the standalone attribute. Documents that do have DTDs can also have the value
yes for the standalone attribute if the DTD doesn't in any way change the
content of the document or if the DTD is purely internal. Details for documents
with DTDs are covered in Chapter 3.

The standalone attribute is optional in an XML declaration. If it
is omitted, then the value no is assumed.

2.10. Checking Documents for Well-Formedness

Every XML document, without exception, must be well-formed. This means it must
adhere to a number of rules, including the following:

Every start-tag must have a matching end-tag.

Elements may nest, but may not overlap.

There must be exactly one root element.

Attribute values must be quoted.

An element may not have two attributes with
the same name.

Comments and processing instructions may not
appear inside tags.

No unescaped < or & signs may occur in
the character data of an element or attribute.

This is not an
exhaustive list. There are many, many ways a document can be malformed. You'll
find a complete list in Chapter 20.
Some of these involve constructs that we have not yet discussed such as DTDs.
Others are extremely unlikely to occur if you follow the examples in this
chapter (for example, including whitespace between the opening < and the
element name in a tag).

Whether the error is small or large, likely or unlikely, an XML
parser reading a document is required to report it. It may or may not report
multiple well-formedness errors it detects in the document. However, the parser
is not allowed to try to fix the document and make a best-faith effort of
providing what it thinks the author really meant. It can't fill in missing
quotes around attribute values, insert an omitted end-tag, or ignore the
comment that's inside a start-tag. The parser is required to return an error.
The objective here is to avoid the bug-for-bug compatibility wars that plagued
early web browsers and continue to this day. Consequently, before you publish
an XML document, whether that document is a web page, input to a database, or
something else, you'll want to check it for well-formedness.

The simplest way to do this is by loading the document into a web
browser that understands XML documents such as Mozilla. If the document is
well-formed, the browser will display it. If it isn't, then it will show an
error message.

Instead of loading the document into a web browser, you can use an
XML parser directly. Most XML parsers are not intended for end users. They are
class libraries designed to be embedded into an easier-to-use program such as
Mozilla. They provide a minimal command-line interface, if that; that interface
is often not particularly well documented. Nonetheless, it can sometimes be
quicker to run a batch of files through a command-line interface than loading
each of them into a web browser. Furthermore, once you learn about DTDs and
schemas, you can use the same tools to validate documents, which most web
browsers won't do.

There are many XML parsers available in a variety of languages.
Here, we'll demonstrate checking for well-formedness with the Apache
XML Project's Xerces-J 1.4, which you can download from http://xml.apache.org/xerces-j.
This open source package is written in pure Java so it should run across all major
platforms. The procedure should be similar for other parsers, though details
will vary.

To use this parser, you'll first need a Java 1.1 or later
compatible virtual machine. Virtual machines for Windows, Solaris, and Linux
are available from http://java.sun.com/. To install Xerces-J 1.4.4, just add xerces.jar
and xercesSamples.jar files to your Java class path. In Java 2 you can
simply put those .jar files into your jre/lib/ext directory.

The class that actually checks files for well-formedness is called
sax.SAXCount. It's run from a Unix shell or DOS prompt
like any other standalone Java program. The command-line arguments are the URLs
to or filenames of the documents you want to check. Here's the result of
running SAXCount against an early version of Example
2-5. The very first line of output tells you where the first problem in the
file is. The rest of the output is a more or less irrelevant stack trace.

D:\xian\examples\02>java sax.SAXCount 2-5.xml [Fatal Error] 2-5.xml:3:30: The value of
attribute "height" must not contain the '<' character.
Stopping after fatal error: The value of attribute "height" must not
contain the '<' character. at org.apache.xerces.framework.XMLParser.reportError(XMLParser.java:
1282) at org.apache.xerces.framework.XMLDocumentScanner.reportFatalXMLError(
XMLDocumentScanner.java:644) at
org.apache.xerces.framework.XMLDocumentScanner.scanAttValue(
XMLDocumentScanner.java:519) at org.apache.xerces.framework.XMLParser.scanAttValue(
XMLParser.java:1932) at
org.apache.xerces.framework.XMLDocumentScanner.scanElement(
XMLDocumentScanner.java:1800) at
org.apache.xerces.framework.XMLDocumentScanner$ContentDispatcher.
dispatch(XMLDocumentScanner.java:1223) at
org.apache.xerces.framework.XMLDocumentScanner.parseSome(
XMLDocumentScanner.java:381) at
org.apache.xerces.framework.XMLParser.parse(XMLParser.java:1138) at
org.apache.xerces.framework.XMLParser.parse(XMLParser.java:1177) at sax.SAXCount.print(SAXCount.java:135)
at sax.SAXCount.main(SAXCount.java:331)

As you can see, it found an error. In this case the error message
wasn't particularly helpful. The actual problem wasn't that an attribute value
contained a < character. It was that the closing quote was missing from the
height attribute value. Still, that was enough for us to locate and fix the
problem. Despite the long list of output, SAXCount only reports the
first error in the document, so you may have to run it multiple times until all
the mistakes are found and fixed. Once we fixed Example
2-5 to make it well-formed, SAXCount simply reported how long it
took to parse the document and what it saw when it did:

D:\xian\examples\02>java
sax.SAXCount 2-5.xml 2-5.xml: 140 ms (17 elems, 12 attrs, 0 spaces, 564
chars)

3 WELL FORMED XML
DOCUMENTS

Well-Formed XML

This tutorial is designed as a walkthrough of well-formed XML
document creation, teaching basic XML. You will learn about XML, understand its
purpose and write a well-formed XML document. Use the following steps and the
examples that accompany them to achieve the goals of this tutorial. If you do
get confused, look to the examples, which illustrate the concepts and
simplicity behind XML.

Well-formed documents are well-formed because they do not have to
be created in a structured environment, against a pre-defined set of structural
rules, but merely have to comply with XML well-formedness constraints. These
constraints require that elements, which are named content containers, properly
nest within each other and use other markup syntax correctly. Well-formed XML
elements are defined by their use, not by a rigid structural definition, allowing
authors to create elements in response to their development. This flexibility
offers authors greater control over document processing and design than in
traditional SGML environments, in which structure must be formally defined in a
DTD before any documents can be written.

Well-formed XML frees Web authors from the fixed nature of HTML,
allowing imaginations to prevail over restraint. HTML is a fixed document type,
meaning that it cannot be expanded or altered to improve its description power.
For example, authors can describe documents in XML using elements of their own
naming, such as ESSAY, SECTION, PARAGRAPH, NOTE and IMPORTANT. After writing
the document, the author might change an instance of the PARAGRAPH element to
TAKENOTICE to signify that that instance differed from and served a contrasting
purpose to the rest. This level of flexibility is indicative of well-formed XML
and allows authors to describe documents as they see fit. Authors can publish
XML documents with XSL, CSS or DSSSL stylesheets, which provide Web browsers
and conversion tools with styling information for each element, to express
documents appropriately.

Well formed XML documents simply markup pages with descriptive
tags. You don't need to describe or explain what these tags mean. In other
words a well formed XML document does not need a DTD, but is must conform to
the XML syntax rules. If all tags in a document are correctly formed and follow
XML guidelines, then a document is considered as well formed.

Syntax is the Grammar of a language. For a document in XML to be
well formed, it must obey the following most important rules:

           XML
documents must contain at least one element. In this example
"Tootsie" is not well formed, because it is not marked up as an
element within angle brackets.

Well Formed    Not Well Formed

<title>Tootsie</title>

"Tootsie"

XML documents must
contain a unique opening and closing tag that contains the whole document,
forming what is called a root element. In this example, the second column is
not well formed because it lacks a root element as in the first column:

<videocollection>...</videocollection>

Well Formed    Not Well Formed

<videocollection>

<title>Tootsie</title>

<title>Jurassic
Park</title>

<title>Mission Impossible</title>

</videocollection>>

<title>Tootsie</title>

<title>Jurassic
Park</title>

<title>Mission Impossible</title>

•           All
other tags must be nested properly, i.e. there must be an opening and a closing
tag and the tags cannot overlap. The tags that in HTML would normally stand
alone, such as <img> or <br> Tag are called "empty Tags"
when used in an XML document In XML empty Tags look like this: e.g.:
<BR/>.

</title... has no closing angle bracket, therfore the tag is
not complete!

</title)...has a wrong closing bracket, therfore the tag is not
complete!

In the second example the tags are not properly nested.

Well Formed    Not Well Formed

<videocollection>

<title>Tootsie</title>

<title>Jurassic
Park</title>

<title>Mission Impossible</title>

</videocollection>

<videocollection>

<title>Tootsie</title>

</videocollection>

<videocollection>

<title>Tootsie</title

<title>Jurassic
Park</title)

<title>Mission Impossible</title>

</videocollection >

<videocollection>

<title>Tootsie

</videocollection></title>

•           Tags
in XML are case sensitive, that means that <CREW>, <Crew> and
<crew> are not the same. The XML processing instruction must be all
lowercase. But keywords in DTDs must be all UPPERCASE, such as ELEMENT,
ATTLIST, #REQUIRED, #IMPLIED, NMTOKEN,
ID, etc. However, your own
elements and attributes may be any case you choose, as long as you are
consistent.

Well Formed      Not
Well Formed

<crew>Sydney Pollak</crew>

<CREW>Sydney Pollak</crew>

<crew>Sydney Pollak</Crew>

Attribute values must
always be quoted (as opposed to HTML).

Well Formed    Not Well Formed

<title id="1">Tootsie</title>

<title id="1>Tootsie</title>

<title id=1>Tootsie</title>

These are just some
examples to for the above mentioned well formdness constraints, which are only
the most important, but by far not complete. Please check the XML
Specifications for a complete knowledge.

To check whether a document is well-formed or not you should  only checked whether the document is
properly marked up according to XML syntax rules(well-formed or not).

In our example the following section of XML data is Well Formed.

<?xml version="1.0"?>

<videocollection>

<title
id="1">Tootsie</title>

<genre>comedy</genre>

<year>1982</year>

<language>English</language>

<cast>Dustin Hoffman</cast>

<cast>Jessica Lang</cast>

<cast>Teri
Gar</cast>

<cast>Sydney Pollak</cast>

<crew>

<director>Sydney Pollak</director>

</crew>

<title
id="2">Jurassic
Park</title>

<genre>science fiction</genre>

<year>1993</year>

<language>English</language>

<cast>Sam Neil</cast>

<cast>Laura Dern</cast>

<cast>Jeff Goldblum</cast>

<crew>

<director>Steven Spielberg</director>

</crew>

<title
id="3">Mission Impossible</title>

<genre>action</genre>

<year>1996</year>

<language>English</language>

<cast>Tom Cruise</cast>

<cast>Jon Voight</cast>

<cast>Emmanuelle Beart</cast>

<cast>Jean Reno</cast>

<crew>

<director>Brian de Palma</director>

</crew>

</videocollection>

In the chapter on Parser you can check whether this document is
really well-formed, using a parser.

4 COMPONENTS OF XML
DOCUMENT

XML
enables you to store structured data such that different types of devices can
recognize it. You need to organize data before storing it in an XML document.
This involves arranging the data in a hierarchy. The various components of an
XML documents that can be used for representing data in a hierarchical order
are:

Processing Instructions:

An XML
Documents usually begins with the XML declaration statement called the
Processing Instructions (PI). The PI statement provides information on how the
XML file should be processed. The PI statement can be written as:

<B> <?xml version =”1.0”
encoding=”UTF-8”?>  </B>

The preceding statements indicate that XML version 1.0 is use. The PI statement
is optional. However, as new versions of XML are released, this tag becomes
important as it explicitly declares the version of XML being used in the file.
This statement enables forward compatibility. The PI statement must be written
using lowercase letters.

The PI statement uses the encoding property to specify the encoding scheme used
to create the XML file. The encoding scheme is the standard character set for
language. The UTF-8 standard character set is use to create pages in English.
UTF stands for UCS (Universal Character Set ) Transformation format. This
character set used eight bits of information to represent each character.

Tags:

Tags are used to specify a name for a given piece of information. It is a
means of identifying data. Data is marked up using tags. A tag consists of
opening and closing angular brackets (<>) that encloses the name of the
tag. Tags usually occur in pairs. Each pair consists of a start tag and an end
tag.

The start tag contains the name of the tag and the end tag includes a forward
slash (/) before the name of the tag, as given in the following example:

<P> Suderson </P>

In the preceding code snippet, <P> and </P> is a predefined HTML
tag or mark up enclosing the name. Here, <P> is the start tag and
</P> is the end tag. As XML allows you to create your own tags, the same
information can be stored as:

<EMP_NAME> Suderson </EMP_NAME>

In the code snippet, <EMP_NAME> is a new tag created in XML, to store the
name of the employee.

Elements:

Elements are the basic units used to identify and describe the data in XML.
They are the building blocks of an XML document. Elements are represented using
tags. XML allows you to give meaningful names to elements. This helps improve
the readability of the code and enables easy identification of the element
content. An XML document always has a root element. A root element contains all
other elements in the document. Consider the following example:

<? Xml version=”1.0”>

<AUTHORS>

<AUTHOR>

<FIRSTNAME>SUDERSON</FIRSTNAME>

<LASTNAME>SARATHY</LASTNAME>

</AUTHOR>

</AUTHORS>

In the preceding example, the AUTHORS element contains all other elements I the
XML document, and is the root element. An XML document can contain only one
root element. All other elements must be embedded within the opening and
closing tags of the root element.

Content:

Content refers to the information represented by the elements of an XML
document. Consider the following example:

<BOOKNAME> The Painted House </BOOKNAME>

In the preceding example, the name of the book, The Painted House, is the
content of the <BOOKNAME> element.

XML enables you to declare and use elements that can contain different types of
information. An element can contain:

I) Character or data Content -
Elements can contain only textual information. Consider the following example:

<BOOKNAME> The Painted House </BOOKNAME>

In the preceding example, the BOOKNAME element contain only textual
information, and is, therefore, said to have character or data content.

II) Element Content - Elements
can contain other elements. The element contained in another elements are
called child content, and the containing element is called the parent element.
A parent element can contain many child elements. All the child element of the
parent element is siblings and are related to one another. Consider the
following example.

<AUTHOR>

<FIRSTNAME>SUDERSON</FIRSTNAME>

<LASTNAME>SARATHY</LASTNAME>

</AUTHOR>

In the
preceding example, the AUTHOR element has two child elements, FIRSTNAME and
LASTNAME. Therefore, it is said to have element content.

III) Combination or Mixed content - Elements can contain textual information as well as other
elements, as illustrated in the following example:

<AUTHORS>

This Author has written a book called, the National Treaure

<AUTHOR>

<FIRSTNAME>SUDERSON</FIRSTNAME>

<LASTNAME>SARATHY</LASTNAME>

</AUTHOR>

</AUTHORS>

In the preceding example, the AUTHORS element contains textual
information as well as the FIRSTNAME and LASTNAME element. Therefore, it is
said to have combination or mixed content.

Attributes:

Attributes provide additional information about the elements for which they
are declared. An attribute consists of a name-value pair. Consider the
following example:

<PRODUCTNAME PRODID = “P001”>SUDERSON DOLL
</PRODUCTNAME>

In the preceding example, the PRODUCTNAME element has an attribute called
PRODID, whose value is set to P001. The attribute name and value are specified
within the opening tag of the PRODUCTNAME element.

Elements
can have one or more attributes. You must decide whether a specific piece or
information is represented as an element or an attribute when you create the
structure or an XML document. In general, an element is used to represent a
definable unit and an attribute is used to represent data that further
qualifies the element. For example, an element called FONT can have an
attribute called COLOR to specify the font color. In this case, the COLOR attribute
further qualifies the FONT element. Therefore, COLOR is represented as an
attribute and not as an element.

You may decide to represent information using elements or attributes. There are
no rules governing this decision. However, you can consider the following
guidelines while deciding whether to represent information by using an element
or an attribute:

If the data must be displayed, you can represent it as an element. In general,
element attributes are used for intangible, abstract properties, such as ID. If
the data must be frequently updated, it is better represented as an element
because it is easier to edit elements than attributes with XML editing tools.
For example, if the quantity on hand of the product needs to be frequently
updated, you can represent the quantity on hand by using an element.

If the value of the piece of information must be frequently checked, it can be
represented as an attribute. This is because an XML processor can check the
content of an attribute value more easily than it can check the content of an
element. For example, you can represent PRODUCT ID and CATEGORY as attributes
if you often retrieve details about products based on their IDs and Categories.

Entities:

An entity is a name that is associated with a block of data, such as chunk
of text or a reference to an external file that contains textual or binary
information. It is a set of information that can be specifying a single name.

Certain characters such as < and & cannot be used in XML documents
because they have a special meaning. For example, the < symbol is used as a
delimiter for tags. XML provides predefined entities, called internal entities,
to enable you to express such characters in an XML document.

An internal entity consists of a name that is associated with a block of
information. The name of the internal entity is always preceded by an ampersand
(&) and terminated with a semicolon. Some of the predefined internal
entities that form a part of the XML specification are listed below:

< - used to display Less Than symbol.

> - used to display Greater Than symbol.

& - used to display Ampersand symbol.

" - used to display double quotes symbol.

Internal entities are replaced by the symbols that they represent, when used in
an XML document. Consider the following Code snippet.

<DISPLAY> My age is > 23 </DISPLAY>

In the preceding code snippet, when the XML file is opened in the browser, the
internal entity is replaced with the greater than (>) symbol.

Comments:

Comments are statements used to explain the XML code. They are
used to provide documentation information about the XML file or the application
to which the file belongs. The parser ignores comments entries during code
execution. Comments are not essential in an XML file. However, it is good
programming practice to include comments along with the code. This helps you
easily understand the code.

Comments are created using an opening angular bracket followed by an
exclamation mark and two hyphens (!--). This is followed by the text that comprises
the comment. Comments are closed using two hyphens followed by a closing
angular brackets (-->). The following example illustrates the use of a
comment in an XML document.

<!--> This is an example of Comment Statement -->

The text contained within a comment entry cannot have two consecutive hyphens,
as given in the following example.

<!--> This is an example of --  Comment Statement -->

5 XML TOOLS

xmltools:
command-line tools for XML

This is a set of
command-line tools for handling XML. Each of the tools performs a particular
function to edit XML files, and they all work with locators, which are
effectively URLs which identify specific pieces of an XML file. A locator
consists of a series of element specifications separated by periods; each element
specification either has a round-parenthetical numeric location or a
square-bracketed ID location. So, for instance, if we have some XML of the
form:

<thingy>

<item id="first"/>

<item id="second"/>

</thingy>

Then the locators
thingy.item(1) and thingy.item[second] would each refer to the second item. If
the items hadn't been empty, we could build a locator such as
thingy.item(1).stuff, which would refer to the first "stuff" elements
in the second item. (The default location is (0).)

So the following
program embodies four actions: snip, replace, set, and insert. "Snip"
simply returns the contents of the location named. "Replace" replaces
the location with whatever's on stdin (no guarantee of well-formedness!)
"Set" is used to set an attribute on the named elements, and
"insert" inserts the content of stdin either before or after the
named element, or before or after the named element's content.

A word of apology:
although the four actions end up in four different executables, I have all four
being generated from the same source code, with #defines to determine which of
the four actions is to be taken. This makes for somewhat confusing code, but I
hope that the literate programming presentation will make up for it.

The program uses
James Clark's expat XML
parser, which I highly recommend. It is documented in these pages in
a literate style, which I
highly recommend. The actual tool I'm using to generate the documentation pages
is my tool LPML,
which I can only recommend if you're really brave. It's working for me, but
then I'm writing it myself.

The motivation
for the development is the open-source
workflow toolkit, which relies heavily on XML and expat. These tools
will be used in the datasheet manipulation portion of the whole system.

1 INTRODUCTION

This
review of XML tools is focused on the requirements for creating a Validating
Web Feature Server. This product will be tightly integrated with the existing
GeoServer project. The Validating Web Feature Server will require XML
processing for:

·
Configuration of geo-spatial validation plug-ins

· Web Feature
Server Update requests

· Web Feature
Server Update response

· Validation
of XML Schema

The XML Processing
tools, currently in use by the GeoServer project, meet these requirements and
no change is recommended. Spatial constraint expression is featured in the
OpenGIS Web Feature Server specification. Constraints are expressed in XML and
open source parsing code is

available as part of
the GeoServer and Geotool2 codebase.

2 XML PROCESSING

There are several
common approaches to parsing XML documents.

· Push Model:

XML
parser is configured with a series of callbacks, defined as functions or events,
which are invoked as the parser encounters elements of the XML document.
Although efficient the  difficulty
of tracking state is placed on the application programmer.

· Tree Model:

An
in memory tree based data structure is produced from the XML document, an API
is provided to allow navigation between nodes of the tree. Keeping XML documents
in memory is prohibitive given the volume of data in a geospatial

application.

· Pull Model:

An
effective compromise between the previous two approaches. A pull-based parser
is queried for the next response, allowing the application programmer the use
of stack to track parser state. A variety of query and transformation languages
exist that make use of, or define, hierarchical based operations. In addition
there have been several attempts to provide direct data mapping of XML
documents to Java Objects.

2.1 XML Processing
Standards

XML processing tools
are based on the following standards:

· Document
Object Model (DOM) - W3C standard for tree based XML parsing

· Simple API
for XML (SAX) - de-facto standard for push based XML parsing

· XSL
Transformations (XSLT) - W3C standard for XML to XML transformations

· Data Type
Definition – defines an XML documents validity using a text file

· XMLSchema
– defines an XML documents validity using an XML file

Many smaller
standards are used to fill out the XML landscape:

· XQuery
– a query language similar in spirit to SQL

· XPath
– used to query hierarchical data structure

· XPointer
– used to provided links between XML documents

In addition Java XML
processing tools reference the following:

·
Java API for XML Processing (JAXP) - allows the use of different XML processing
implementations to be used without source code changes.

3 REVIEW OF EXISTING
TOOLS

This
review is limited to open source tools, given the level of cooperation required
with the GeoServer and geotools2 projects.

3.1 XML Processing
Tools

XML Processing Tools
used by the GeoServer project:

· Xerces

§ Validating XML
parser

§ SAX support
(used by GeoServer)

§ DOM support

§ XML Schema
support

§ JAXP support

· Xalan

§ XSLT engine

§ XPath support

· JDOM

§ Java interface
to SAX or DOM based parsers

Other popular XML
Processing Tools:

· Saxon
– popular XSLT engine

Java XML Data Binding
Tools:

· Castor
– open source, although lacks complete schema support

· JAXB –
Java Community Process based, provides schema support

3.2 DTD Validation

The
WFS Specification mandates the use of XML Schema as a minimum for all operations.
Other output formats for GetFeature, such as DTD, are possible if specified by DescribeFeatureType
and GetCapabilities.

DTD Validation Tools:

·
XSDValid – contains dtdvalid DTD validation tool The GeoServer project
does not currently uses DTD schema definitions.

3.3 XML Schema
Validation

GeoServer
services make use of the Geographic Markup Language (GML) as an XML based
transportation encoding. GML is validated against a series of XML Schemas
customized with application schema definitions.

The following tools
were found for XML Schema validation:

· XSV –
web based user interface

· SQC –
IBM XML Schema Quality Checker

· XSDValid
– contains csdvalid XML Schema validation tool

·
Decisionsoft XML validation - http://tools.decisionsoft.com/schemaValidate.html

·
GML4J – open source GML Schema Parser SQC in particular is well suited to
QA integration.

3.4 XML SPY

XML
Spy is a wonderful tool produced by Altova.

3.5
OpenGIS Literature

It
is an XML development environment for designing and editing XML, XML Schema,
XSL/XSLT, SOAP, WSDL and Web Service technologies. It has proved to be very
useful in our development of XML and XML schemas.

OpenGIS
describes in detail how to specify spatial constrains for the WFS GetFeature
Operation. Spatial Constraints are specified as part of a Filter on a Query
operation, however a short cut exists for filtering based on a Bounding Box:

<QuerytypeName="myns:HYDROGRAPHY">

<ogc:PropertyName>myns:GEOTEMP</ogc:PropertyName>

<ogc:PropertyName>myns:DEPTH</ogc:PropertyName>

<ogc:Filter><ogc:Not><ogc:Disjoint>

<ogc:PropertyName>myns:GEOTEMP</ogc:PropertyName>

<gml:Box>

<gml:coordinates>-57.9118,46.2023-46.6873,51.8145</gml:coordinates>

</gml:Box>

</ogc:Disjoint></ogc:Not></ogc:Filter>

</Query>

The
Filter Encoding Implementation Specification defines spatial operations using
the following DTD fragment:

<!ENTITY %
spatial_ops "( Equals |

Disjoint |

Intersects |

Touches |

Crosses |

Within |

Contains |

Overlaps |

Beyond |

BBOX)">

<!ELEMENT Equals
(PropertyName,%GeometryClasses;)>

<!ELEMENT Disjoint
(PropertyName,%GeometryClasses;)>

<!ELEMENT
Intersects (PropertyName,%GeometryClasses;)>

<!ELEMENT Touches
(PropertyName,%GeometryClasses;)>

<!ELEMENT Crosses
(PropertyName,%GeometryClasses;)>

<!ELEMENT Within
(PropertyName,%GeometryClasses;,Distance)>

<!ELEMENT Contains
(PropertyName,%GeometryClasses;)>

<!ELEMENT Overlaps
(PropertyName,%GeometryClasses;)>

<!ELEMENT Beyond
(PropertyName,%GeometryClasses;,Distance)>

<!ELEMENT BBOX
(PropertyName,gml:Box)>

<!ELEMENT Distance
(#PCDATA)>

<!ATTLIST Distance
units CDATA #REQUIRED>

3.6 Open Source
Examples

The
current GeoServer 0.96 implementation relies on geoltools2 for parsing spatial
constraints.

4.1
Open GIS Consortium, Inc.

An
international industry consortium developing publicly available geoprocessing
specifications Open GIS Consortium Www.opengis.org
WFS Specification Www.opengis.org/techno/specs/02-058.pdf

Filter
Encoding Implementation

Specification

Www.opengis.org/techno/RFC13a.pdf

4.2
The GeoServer Project

A
Java implementation of the Web Feature Server specification: GeoServer
Geoserver.sourceforge.net

4.3
XML Tools

4.3.1
The Apache XML Project

XML
Schema and DTD Validation:

The
Apache XML Project Xml.apache.org

Xerces
Xml.apache.org/xerces2-j

Xalan
Xml.apache.org/xalan-j

4.3.2
Other

XML
Spy www.xmlspy.com

JAXP
java.sun.com/xml/jaxp

Crimson
gump.cocoondev.org/xml-crimson.html

JDOM

KXML

XML
Schema Validation Resources

The
W3C XML Schema web site (http://www.w3.org/XML/Schema) has a list of validation
tools.

EXAMPLE
XML SCHEMA FILE GeoServer featureType.xsd (XML schema
file)

<?xml
version="1.0" encoding="UTF-8"?>

<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"

elementFormDefault="qualified"
attributeFormDefault="unqualified">

<xs:complexType
name="LatLonBoundingBoxType">

<xs:attribute
name="minx"

type="xs:string"
use="required"/>

<xs:attribute
name="miny"

type="xs:string"
use="required"/>

<xs:attribute
name="maxx"

type="xs:string"
use="required"/>

<xs:attribute
name="maxy"

type="xs:string"
use="required"/>

</xs:complexType>

<xs:complexType
name="MetadataURLType">

<xs:sequence>

<xs:element
name="url" type="xs:string"/>

<xs:element
name="type" type="xs:string"/>

<xs:element
name="format" type="xs:string"/>

</xs:sequence>

</xs:complexType>

<xs:complexType
name="featureTypeType">

<xs:sequence>

<xs:element
name="Name" type="xs:string"/>

<xs:element
name="Title" type="xs:string"/>

<xs:element
name="Abstract" type="xs:string"/>

<xs:element
name="Keywords" type="xs:string"/>

<xs:element
name="SRS" type="xs:string"/>

<xs:element
name="Operations" type="xs:string"/>

<xs:element
name="LatLonBoundingBox"

type="LatLonBoundingBoxType"/>

<xs:element
name="MetadataURL"

type="MetadataURLType"/>

<xs:element
name="Host" type="xs:string"/>

<xs:element
name="Port" type="xs:string"/>

<xs:element
name="DatabaseName"

type="xs:string"/>

<xs:element
name="User" type="xs:string"/>

<xs:element
name="Password" type="xs:string"/>

</xs:sequence>

</xs:complexType>

<xs:element
name="featureType"

type="featureTypeType"/>

</xs:schema>

6 XML STYLESHEETS

XML Style Sheet (XSL) Syntax

XSL
is used to define, how the XML file should be converted so that it can seen in
the required format in the Browser. For Example say in the XML file we declare
a Tag called

<showbold>This
is The Heading Text </showbold> ,

and
you want to show the Text inside these tags in a different Font and Color ,
then in your XSL file you would declare it as

<xsl:template
match="showbold">

<b><font color="#FF0000" face="Arial"
size="3">

<xsl:apply-templates/>

</font></b>

</xsl:template>

Here
as soon as the Tag "showbold" is encountered in the XML file, then
automatically the Text is replaced with Different Font size and color in bold.
This is just an example. In real time, some tags, will be creating Table and
show the Data in a well formatted way. Also note that tag "showbold"
is not part of the standard HTML and here you have defined a Custom Tag.

Declaring Sequences in XSL File

Sequences
are useful if you want to show the same kind of tags, declared multiple times
in the XML file in a more suitable format like, using Tables. Let's consider
the Following Example XML File.

<?xml
version="1.0" encoding="ISO8859-1" ?>

<?xml-stylesheet
type="text/xsl" href="Library_Catalog.xsl"?>

<LIBRARY>

<BOOK>

<TITLE>Professional JINI</TITLE>

<AUTHOR>Sing Li</AUTHOR>

<PUBLISHER>Wrox Publications</PUBLISHER>

</BOOK>

....

......

The
above XML file has a Parent Tag called LIBRARY which has lots of Sub Tags
called BOOK. Now while Displaying this XML file, say we want to Display it in
the Form of a Table. Here's how we will be generating Sequence in the XSL file,

<?xml
version='1.0'?>

<xsl:stylesheet
xmlns:xsl="http://www.w3.org/TR/WD-xsl">

<xsl:template
match="/">

<html>

<body>

<table
border="2" bgcolor="blue">

<tr>

<th>Title</th>

<th>Author</th>

<th>Publisher</th>

</tr>

<xsl:for-each
select="LIBRARY/BOOK">

<tr>

<td><xsl:value-of select="TITLE"/></td>

<td><xsl:value-of select="AUTHOR"/></td>

<td><xsl:value-of
select="PUBLISHER"/></td>

</tr>

</xsl:for-each>

</table>

</body>

</html>

</xsl:template>

</xsl:stylesheet>

As you can see in the above Example, we
consider each BOOK Tag under Main Tag LIBRARY and in a Sequence we display the
List of all Books. The Main difference is made by tag "xsl:for-each"
which helps in iterating through all the BOOK tags.

Also
note that when we say xsl:value-of select="PUBLISHER , then it retrieves
the Value given inside the Tags </PUBLISHER> within the current Tag
<BOOK>.

Displaying XML with CSS

With
CSS (Cascading Style Sheets) you can add display information to an XML
document.

Displaying your XML Files with
CSS?

It
is possible to use CSS to format an XML document. Below is an example of how to
use a CSS style sheet to format an XML document:

Take
a look at this XML file: The CD catalog

Then
look at this style sheet: The CSS file

Finally,
view: The CD catalog formatted with the CSS file

Below
is a fraction of the XML file. The second line links the XML file to the CSS
file:

<?xml
version="1.0" encoding="ISO-8859-1"?>

<?xml-stylesheet
type="text/css" href="cd_catalog.css"?>

<CATALOG>

<CD>

<TITLE>Empire
Burlesque</TITLE>

<ARTIST>Bob
Dylan</ARTIST>

<COUNTRY>USA</COUNTRY>

<COMPANY>Columbia</COMPANY>

<PRICE>10.90</PRICE>

<YEAR>1985</YEAR>

</CD>

<CD>

<TITLE>Hide your
heart</TITLE>

<ARTIST>Bonnie
Tyler</ARTIST>

<COUNTRY>UK</COUNTRY>

<COMPANY>CBS
Records</COMPANY>

<PRICE>9.90</PRICE>

<YEAR>1988</YEAR>

</CD>

.

.

.

</CATALOG>

Formatting
XML with CSS is not the most common method.

W3C
recommend using XSLT instead.

Displaying XML with XSLT

With
XSLT you can transform an XML document into HTML.

XSLT
is the recommended style sheet language of XML.

XSLT
(eXtensible Stylesheet Language Transformations) is far more sophisticated than
CSS.

XSLT
can be used to transform XML into HTML, before it is displayed by a browser:

Transforming XML with XSLT on the
Server

In
the example above, the XSLT transformation is done by the browser, when the
browser reads the XML file.

Different
browsers may produce different result when transforming XML with XSLT. To
reduce this problem the XSLT transformation can be done on the server.

The xml-stylesheet processing instruction

[Definition: A processing instruction information item is said to be a potential
xml-stylesheet processing instruction if it has the [target] property
xml-stylesheet and it either is in the [children] property of a document
information item and appears before the element information item of the
document information item's [children] property, or it appears in the
[children] property of a document type declaration information item.]

For potential xml-stylesheet
processing instructions that are in the [children] property of a
document information item, xml-stylesheet processors must report to
the application the parsing result of invoking the rules for
parsing pseudo-attributes from a string, using the processing
instruction information item's [content] property as the string.

For potential xml-stylesheet
processing instructions that are in the [children] property of a
document type declaration information item, xml-stylesheet processors may report to
the application the parsing result of invoking the rules for
parsing pseudo-attributes from a string, using the processing
instruction information item's [content] property as the string. [Definition: If it is not reported to the application, the processing instruction
information item is said to be ignored.]

Note:

Since non-validating XML processors are not required to
read parameter entities or the external subset, it is possible that processing
instructions that appear in parameter entities or the external subset will not
be present in the document type declaration information item's [children]
property. [XML]

[Definition: A potential xml-stylesheet
processing instruction is said to be an xml-stylesheet processing
instruction if the parsing result is not an error when invoking
the rules for
parsing pseudo-attributes from a string, using the processing
instruction information item's [content] property as the string.]

Documents must not use processing instruction
information items with the [target] property xml-stylesheet if they are not xml-stylesheet processing
instructions.

Documents should not use xml-stylesheet processing
instructions that are in the [children] property of a document type
declaration information item.

An xml-stylesheet processing instruction
will match the following production:

Production for xml-stylesheet processing instruction

[1]

StyleSheetPI

::=

"<?xml-stylesheet"
( (S PseudoAtts)?
- (Char* "?>" Char*) )
"?>"

Documents may specify the following pseudo-attributes on xml-stylesheet processing
instructions, unless otherwise stated:

href

Gives the
address of the referenced style sheet. Documents must specify this pseudo-attribute. Documents must set the
value
to a string that matches the grammar for <IRI-reference> given in RFC
3987. [RFC3987]

Note:

It is possible to associate a style sheet that is in the
same document as the xml-stylesheet processing instruction
by using just a fragment identifier in the href pseudo-attribute.

For details on how this is managed in XSLT, see 3.11 Embedded Stylesheet Modules
in [XSLT].

type

Gives an
advisory media type for the referenced style sheet. If specified, documents must
set the value
to a string that matches the media-type production defined in section 3.7
"Media Types" of RFC 2616. [RFC2616]

Note:

Syntactic conformance to the production in RFC 2616 is all that is required by the
above. This specification imposes no requirements with respect to the status of
the types used. Some unregistered (as of the publication of this specification)
media types, such as text/xsl, are well-supported by existing implementations,
whereas some registered media types, such as application/xslt+xml, are not.

The value
is advisory in that it is intended to be used by an application only when no
other source of media type information becomes available during retrieval of
the stylesheet itself.

title

Gives the
title of the referenced style sheet in a style sheet set. No constraints beyond
those of the PseudoAttValue
production are placed on the value.

media

Gives the
media for which the referenced style sheet applies. If specified, documents must
set the value
to a string that matches the media_query_list production of the Media Queries
specification. [MQ]

charset

Gives an advisory character encoding for the referenced style sheet. If
specified, documents must set the value
to a valid character encoding name, which must be the name or alias
labeled as "preferred MIME name" in the IANA Character Sets registry,
if there is one, or the encoding's name, if none of the aliases are so labeled.
[IANACHARSET]

The value
is advisory in that it is intended to be used by an application only when no
other source of encoding information becomes available during retrieval of the
stylesheet itself, either explicitly via an HTTP header, or implicitly via its
media type, as in the case of XML documents.

alternate

If the value
is "yes", it indicates that the referenced style sheet is an
alternative style sheet, and documents must also specify the title pseudo-attribute with a non-empty value.
If specified, documents must set the value
to either "yes" or "no".

Documents must not specify other pseudo-attributes on xml-stylesheet processing
instructions.

Any links to style sheets that are specified externally
to the document (e.g. Link headers in some versions of HTTP [RFC2068])
are considered to create associations that occur before the associations
specified by the xml-stylesheet processing
instructions. The application is responsible for taking all
associations and determining how, if at all, their order affects its
processing.

7 XSL

In
computing, the term Extensible Stylesheet Language (XSL) is used to refer to a
family of languages used to transform and render XML documents. Historically,
the XSL Working Group in W3C produced a draft specification under the name XSL,
which eventually split into three parts:

XSL
Transformation (XSLT): is an XML language for transforming XML documents

XSL
Formatting Objects (XSL-FO): an XML language for specifying the visual
formatting of an XML document

XML
Path Language (XPath): a non-XML language used by XSLT, and also available for
use in non-XSLT contexts, for addressing the parts of an XML document.

As
a result, the term XSL is now used with a number of different meanings:

Sometimes
it refers to XSLT: this usage is best avoided. However, "xsl" is used
both as the conventional namespace prefix for the XSLT namespace, and as the
conventional filename suffix for files containing XSLT stylesheet modules

Sometimes
it refers to XSL-FO: this usage can be justified by the fact that the XSL-FO
specification carries the title Extensible Stylesheet Language (XSL); however,
the term XSL-FO is less likely to be misunderstood

Sometimes
it refers to both languages considered together, or to the working group that
develops both languages

Sometimes,
especially in the Microsoft world, it refers to a now-obsolete variant of XSLT
developed and shipped by Microsoft as part of MSXML before the W3C
specification was finalized XSL Languages

It
started with XSL and ended up with XSLT, XPath, and XSL-FO.

XSL
stands for EXtensible Stylesheet Language.

The
World Wide Web Consortium (W3C) started to develop XSL because there was a need
for an XML-based Stylesheet Language.

CSS
= Style Sheets for HTML

HTML
uses predefined tags, and the meaning of each tag is well understood.

The
<table> tag in HTML defines a table - and a browser knows how to display
it. Adding styles to HTML elements are simple. Telling a browser to display an
element in a special font or color, is easy with CSS.

XSL
= Style Sheets for XML

XML
does not use predefined tags (we can use any tag-names we like), and therefore
the meaning of each tag is not well understood.

A
<table> tag could mean an HTML table, a piece of furniture, or something
else - and a browser does not know how to display it.

XSL
- More Than a Style Sheet Language

XSL
consists of three parts:

XSLT
- a language for transforming XML documents

XPath
- a language for navigating in XML documents

XSL-FO
- a language for formatting XML documents

XSLT
- the language for transforming XML documents.

XSLT
Tutorial

XSL stands for EXtensible Stylesheet
Language, and is a style sheet language for XML documents.

XSLT
stands for XSL Transformations. In this tutorial you will learn how to use XSLT
to transform XML documents into other formats, like XHTML.

Online XSLT Editor

With
our online editor, you can edit the XML and the XSL source code, and click on a
button to view the result.

XSLT Example

<?xml
version="1.0"?>

<xsl:stylesheet
version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template
match="/">

<html>

<body>

<h2>My CD
Collection</h2>

<table
border="1">

<tr
bgcolor="#9acd32">

<th>Title</th>

<th>Artist</th>

</tr>

<xsl:for-each
select="catalog/cd">

<tr>

<td><xsl:value-of select="title"/></td>

<td><xsl:value-of select="artist"/></td>

</tr>

</xsl:for-each>

</table>

</body>

</html>

</xsl:template>

</xsl:stylesheet>

Benefits of XSL

Unlike the case of HTML, element names in XML have no
intrinsic presentation semantics. Absent a stylesheet, a processor could not
possibly know how to render the content of an XML document other than as an
undifferentiated string of characters. XSL provides a comprehensive model and a
vocabulary for writing such stylesheets using XML syntax.

This document is intended for implementors of such XSL
processors. Although it can be used as a reference manual for writers of XSL
stylesheets, it is not tutorial in nature.

XSL builds on the prior work on Cascading Style Sheets [CSS2] and the Document
Style Semantics and Specification Language [DSSSL]. While many of
XSL's formatting objects and properties correspond to the common set of
properties, this would not be sufficient by itself to accomplish all the goals
of XSL. In particular, XSL introduces a model for pagination and layout that
extends what is currently available and that can in turn be extended, in a
straightforward way, to page structures beyond the simple page models described
in this specification.

1 Paging and Scrolling

Doing both scrollable document windows and pagination
introduces new complexities to the styling (and pagination) of XML content.
Because pagination introduces arbitrary boundaries (pages or regions on pages)
on the content, concepts such as the control of spacing at page, region, and
block boundaries become extremely important. There are also concepts related to
adjusting the spaces between lines (to adjust the page vertically) and between
words and letters (to justify the lines of text). These do not always arise
with simple scrollable document windows, such as those found in today's
browsers. However, there is a correspondence between a page with multiple
regions, such as a body, header, footer, and left and right sidebars, and a Web
presentation using "frames". The distribution of content into the
regions is basically the same in both cases, and XSL handles both cases in an
analogous fashion.

XSL was developed to give designers control over the
features needed when documents are paginated as well as to provide an
equivalent "frame" based structure for browsing on the Web. To
achieve this control, XSL has extended the set of formatting objects and
formatting properties beyond those available in either CSS2 or DSSSL. In
addition, the selection of XML source components that can be styled (elements,
attributes, text nodes, comments, and processing instructions) is based on XSLT
and XPath [XPath],
thus providing the user with an extremely powerful selection mechanism.

The design of the formatting objects and properties
extensions was first inspired by DSSSL. The actual extensions, however, do not
always look like the DSSSL constructs on which they were based. To either
conform more closely with the CSS2 specification or to handle cases more simply
than in DSSSL, some extensions have diverged from DSSSL.

There are several ways in which extensions were made. In
some cases, it sufficed to add new values, as in the case of those added to
reflect a variety of writing-modes, such as top-to-bottom and bottom-to-top,
rather than just left-to-right and right-to-left.

In other cases, common properties that are expressed in
CSS2 as one property with multiple simultaneous values, were split into several
new properties to provide independent control over independent aspects of the
property. For example, the "white-space" property was split into four
properties: a "white-space-treatment" property that controls how
white space is processed, a "linefeed-treatment" property that
controls how line feeds are processed, a "white-space-collapse"
property that controls how multiple consecutive spaces are collapsed, and a
"wrap-option" property that controls whether lines are automatically
wrapped when they encounter a boundary, such as the edge of a column. The
effect of splitting a property into two or more (sub-)properties is to make the
equivalent existing CSS2 property a "shorthand" for the set of sub-properties
it subsumes.

In still other cases, it was necessary to create new
properties. For example, there are a number of new properties that control how
hyphenation is done. These include identifying the script and country the text
is from as well as such properties as "hyphenation-character" (which
varies from script to script).

Some of the formatting objects and many of the properties
in XSL come from the CSS2 specification, ensuring compatibility between the
two.

There are four classes of XSL properties that can be
identified as:

CSS
properties by copy (unchanged from their CSS2 semantics)

CSS
properties with extended values

CSS
properties broken apart and/or extended

XSL-only
properties

2 Selectors and Tree Construction

As mentioned above, XSL uses XSLT and XPath for tree
construction and pattern selection, thus providing a high degree of control
over how portions of the source content are presented, and what properties are
associated with those content portions, even where mixed namespaces are
involved.

For example, the patterns of XPath allow the selection of
a portion of a string or the Nth text node in a paragraph. This allows users to
have a rule that makes all third paragraphs in procedural steps appear in bold,
for instance. In addition, properties can be associated with a content portion
based on the numeric value of that content portion or attributes on the
containing element. This allows one to have a style rule that makes negative
values appear in "red" and positive values appear in "black".
Also, text can be generated depending on a particular context in the source
tree, or portions of the source tree may be presented multiple times with
different styles.

3 An Extended Page Layout Model

There is a set of formatting objects in XSL to describe
both the layout structure of a page or "frame" (how big is the body;
are there multiple columns; are there headers, footers, or sidebars; how big
are these) and the rules by which the XML source content is placed into these
"containers".

The layout structure is defined in terms of one or more
instances of a "simple-page-master" formatting object. This
formatting object allows one to define independently filled regions for the
body (with multiple columns), a header, a footer, and sidebars on a page. These
simple-page-masters can be used in page sequences that specify in which order
the various simple-page-masters shall be used. The page sequence also specifies
how styled content is to fill those pages. This model allows one to specify a
sequence of simple-page-masters for a book chapter where the page instances are
automatically generated by the formatter or an explicit sequence of pages such
as used in a magazine layout. Styled content is assigned to the various regions
on a page by associating the name of the region with names attached to styled
content in the result tree.

In addition to these layout formatting objects and
properties, there are properties designed to provide the level of control over
formatting that is typical of paginated documents. This includes control over
hyphenation, and expanding the control over text that is kept with other text
in the same line, column, or on the same page.

4 A Comprehensive Area Model

The extension of the properties and formatting objects,
particularly in the area on control over the spacing of blocks, lines, and page
regions and within lines, necessitated an extension of the CSS2 box formatting
model. This extended model is described in 4 Area Model
of this specification. The CSS2 box model is a subset of this model. See the
mapping of the CSS2 box model terminology to the XSL Area Model terminology in 7.2 XSL Areas and the CSS Box Model.
The area model provides a vocabulary for describing the relationships and
space-adjustment between letters, words, lines, and blocks.

5 Internationalization and Writing-Modes

There are some scripts, in particular in the Far East, that are typically set with words proceeding
from top-to-bottom and lines proceeding either from right-to-left (most common)
or from left-to-right. Other directions are also used. Properties expressed in
terms of a fixed, absolute frame of reference (using top, bottom, left, and right)
and which apply only to a notion of words proceeding from left to right or
right to left do not generalize well to text written in those scripts.

For this reason XSL (and before it DSSSL) uses a relative
frame of reference for the formatting object and property descriptions. Just as
the CSS2 frame of reference has four directions (top, bottom, left and right),
so does the XSL relative frame of reference have four directions (before,
after, start, and end), but these are relative to the "writing-mode".
The "writing-mode" property is a way of controlling the directions
needed by a formatter to correctly place glyphs, words, lines, blocks, etc. on
the page or screen. The "writing-mode" expresses the basic directions
noted above. There are writing-modes for "left-to-right -
top-to-bottom" (denoted as "lr-tb"), "right-to-left -
top-to-bottom" (denoted as "rl-tb"), "top-to-bottom -
right-to-left" (denoted as "tb-rl") and more. See 7.29.7 writing-mode
for the description of the "writing-mode" property. Typically, the
writing-mode value specifies two directions: the first is the
inline-progression-direction which determines the direction in which words will
be placed and the second is the block-progression-direction which determines
the direction in which blocks (and lines) are placed one after another. In
addition, the inline-progression-direction for a sequence of characters may be
implicitly determined using bidirectional character types for those characters
from the Unicode Character Database [UNICODE Character Database]
for those characters and the Unicode bidirectional (BIDI) algorithm [UNICODE UAX
#9].

Besides the directions that are explicit in the name of
the value of the "writing-mode" property, the writing-mode determines
other directions needed by the formatter, such as the shift-direction (used for
subscripts and superscripts), etc.

6 Linking

Because XML, unlike HTML, has no built-in semantics,
there is no built-in notion of a hypertext link. In this context,
"link" refers to "hypertext link" as defined in http://www.w3.org/TR/html401/struct/links.html#h-12.1
as well as some of the aspects of "link" as defined in http://www.w3.org/TR/xlink/#intro,
where "link is a relationship between two or more resources or portions of
resources, made explicit by an XLink linking element". Therefore, XSL has
a formatting object that expresses the dual semantics of formatting the content
of the link reference and the semantics of following the link.

XSL provides a few mechanisms for changing the
presentation of a link target that is being visited. One of these mechanisms
permits indicating the link target as such; another allows for control over the
placement of the link target in the viewing area; still another permits some
degree of control over the way the link target is displayed in relationship to
the originating link anchor.

XSL also provides a general mechanism for changing the
way elements are formatted depending on their active state. This is
particularly useful in relation to links, to indicate whether a given link
reference has already been visited, or to apply a given style depending on
whether the mouse, for instance, is hovering over the link reference or not.

XSL Transformation

1 Tree Construction

The
Tree Construction is described in "XSL Transformations" [XSLT]. The
data model in XSLT is capable of representing either an XML 1.0 document
(conforming to [XML] and [XML Names]) or an XML 1.1 document (conforming to
[XML 1.1] and [XML Names 1.1]), and it makes no distinction between the two. In
principle, therefore, XSL 1.1 can be used with either of these XML versions;
the only differences arise outside the boundary of the transformation proper,
while creating the data model from textual XML (parsing).

The
provisions in "XSL Transformations" form an integral part of this
Recommendation and are considered normative. Because the data model is the same
whether the original document was XML 1.0 or XML 1.1, the semantics of XSLT processing
do not depend on the version of XML used by the original document. There is no
reason in principle why all the documents used in a single transformation must
conform to the same version of XML.

2 XSL Namespace

The
XSL namespace has the URI http://www.w3.org/1999/XSL/Format.

The
1999 in the URI indicates the year in which the URI was allocated by the W3C.
It does not indicate the version of XSL being used. XSL processors must use the
XML namespaces mechanism ([XML Names] or [XML Names 1.1]) to recognize elements
and attributes from this namespace. Elements from the XSL namespace are
recognized only in the stylesheet, not in the source document. Implementors
must not extend the XSL namespace with additional elements or attributes.
Instead, any extension must be in a separate namespace. The expanded-name of
extension elements must have a non-null namespace URI.

This
specification uses the prefix fo: for referring to elements in the XSL
namespace. However, XSL stylesheets are free to use any prefix, provided that
there is a namespace declaration that binds the prefix to the URI of the XSL
namespace. An element from the XSL namespace may have any attribute not from
the XSL namespace, provided that the expanded-name of the attribute has a
non-null namespace URI. The presence of such attributes must not change the
behavior of XSL elements and functions defined in this document. This means
that an extension attribute may change the processing of an FO, but only
provided that the constraints specified by XSL on that FO remain satisfied.
Thus, an XSL processor is always free to ignore such attributes, and must
ignore such attributes without giving an error if it does not recognize the
namespace URI. Such attributes can provide, for example, unique identifiers, optimization
hints, or documentation. It is an error for an element from the XSL namespace
to have attributes with expanded-names that have null namespace URIs (i.e.,
attributes with unprefixed names) other than attributes defined in this
document.

The
conventions used for the names of XSL elements, attributes, and functions are
as follows: names are all lowercase, hyphens are used to separate words, dots
are used to separate names for the components of complex datatypes, and
abbreviations are used only if they already appear in the syntax of a related
language such as XML or HTML.

8 CSS

CSS Introduction

What is CSS?

CSS
stands for Cascading Style Sheets

Styles
define how to display HTML elements

Styles
were added to HTML 4.0 to solve a problem

External
Style Sheets can save a lot of work

External
Style Sheets are stored in CSS files

CSS Demo

An
HTML document can be displayed with different styles.

Styles Solved a Big Problem

HTML
was never intended to contain tags for formatting a document.

HTML
was intended to define the content of a document, like:

<h1>This
is a heading</h1>

<p>This
is a paragraph.</p>

When
tags like <font>, and color attributes were added to the HTML 3.2
specification, it started a nightmare for web developers. Development of large
web sites, where fonts and color information were added to every single page,
became a long and expensive process.

To
solve this problem, the World Wide Web Consortium (W3C) created CSS.

In
HTML 4.0, all formatting could be removed from the HTML document, and stored in
a separate CSS file.

All
browsers support CSS today.

CSS Saves a Lot
of Work!

CSS
defines HOW HTML elements are to be displayed.

Styles
are normally saved in external .css files. External style sheets enable you to
change the appearance and layout of all the pages in a Web site, just by
editing one single file!

CSS Example

body

{

background-color:#d0e4fe;

}

h1

{

color:orange;

text-align:center;

}

p

{

font-family:"Times
New Roman";

font-size:20px;

}

Cascading Style Sheets

Cascading Style Sheets (CSS) is a style sheet language used to describe the presentation semantics (the look and
formatting) of a document written in a markup
language. Its most common application is to style web pages
written in HTML
and XHTML,
but the language can also be applied to any kind of XML document, including plain XML,
SVG and XUL.

CSS is designed primarily to enable the separation of
document content (written in HTML or a similar markup language) from document
presentation, including elements such as the layout,
colors,
and fonts.[1]
This separation can improve content accessibility,
provide more flexibility and control in the specification of presentation characteristics,
enable multiple pages to share formatting, and reduce complexity and repetition
in the structural content (such as by allowing for tableless web design). CSS can also allow
the same markup page to be presented in different styles for different
rendering methods, such as on-screen, in print, by voice (when read out by a
speech-based browser or screen reader) and on Braille-based,
tactile
devices. While the author of a document typically links that document to a CSS
style sheet, readers can use a different style sheet, perhaps one on their own
computer, to override the one the author has specified.

CSS specifies a priority scheme to determine which style
rules apply if more than one rule matches against a particular element. In this
so-called cascade, priorities or weights are calculated and
assigned to rules, so that the results are predictable.

The CSS specifications are maintained by the World Wide Web Consortium (W3C). Internet
media type (MIME type) text/css is registered for use with
CSS by RFC 2318 (March 1998).

Syntax

CSS has a simple syntax and uses
a number of English keywords to specify the names of various style properties.

A style sheet consists of a list of rules. Each
rule or rule-set consists of one or more selectors and a declaration
block. A declaration-block consists of a list of declarations in
braces. Each declaration itself consists of a property, a colon (:), a value.
If there are multiple declarations in a block, a semi-colon (;) must be
inserted to separate each declaration.[2]

In CSS, selectors are used to declare which of the
markup elements a style applies to, a kind of match expression. Selectors may
apply to all elements of a specific type, or only those elements that match a
certain attribute; elements may be matched depending on how they are placed
relative to each other in the markup code, or on how they are nested within the
Document Object Model.

Pseudo-classes are another form of specification used in CSS to identify markup elements,
and in some cases, specific user actions to which a particular declaration
block applies. An often-used example is the :hover pseudo-class that applies a
style only when the user 'points to' the visible element, usually by holding
the mouse cursor over it. It is appended to a selector as in a:hover or
#elementid:hover. Other pseudo-classes and pseudo-elements are, for
example, :first-line, :visited or :before. A special pseudo-class is :lang(c),
"c".[clarification needed]

A pseudo-class selects entire elements, such as
:link or :visited, whereas a pseudo-element makes a selection that may
consist of partial elements, such as :first-line or :first-letter.

Selectors may be combined in other ways too, especially
in CSS 2.1, to achieve greater specificity and flexibility.[3]

Here is an example summing up the rules above:

selector [, selector2, ...][:pseudo-class] {

property:
value;

[property2:
value2;

...]

}

/* comment */

Use

Prior to CSS, nearly all of the presentational attributes
of HTML documents were contained within the HTML markup; all font colors,
background styles, element alignments, borders and sizes had to be explicitly
described, often repeatedly, within the HTML. CSS allows authors to move much
of that information to a separate style sheet resulting in considerably simpler
HTML markup.

Headings (h1 elements), sub-headings (h2),
sub-sub-headings (h3), etc., are defined structurally using HTML. In print and
on the screen, choice of font, size, color and emphasis for these elements is presentational.

Prior to CSS, document authors who wanted to assign such typographic
characteristics to, say, all h2 headings had to use the HTML font and other
presentational elements for each occurrence of that heading type. The
additional presentational markup in the HTML made documents more complex, and
generally more difficult to maintain. In CSS, presentation is separated from
structure. In print, CSS can define color, font, text alignment, size, borders,
spacing, layout and many other typographic characteristics. It can do so
independently for on-screen and printed views. CSS also defines non-visual
styles such as the speed and emphasis with which text is read out by aural text
readers. The W3C
now considers the advantages of CSS for defining all aspects of the
presentation of HTML pages to be superior to other methods. It has therefore deprecated
the use of all the original presentational HTML markup.

CSS files are inserted into HTML documents using the
following syntax:

<link rel="stylesheet"
href="http://example.com/css/style.css" type="text/css"
/>

Sources

CSS information can be provided by various sources. CSS
style information can be either attached as a separate document or embedded in
the HTML document. Multiple style sheets can be imported. Different styles can
be applied depending on the output device being used; for example, the screen
version can be quite different from the printed version, so that authors can
tailor the presentation appropriately for each medium.

Priority scheme for CSS sources (from highest to lowest
priority):

Author
styles (provided by the web page author), in the form of:

Inline styles, inside the HTML document, style information on a single element,
specified using the "style" attribute

Embedded style, blocks of CSS information inside the HTML itself

External style sheets, i.e., a separate CSS file referenced from the document

User
style:

A
local CSS file the user specifies with a browser option, which acts as an
override applied to all documents

User
agent style

Default
styles applied by the user agent, i.e., the browser's default settings
for element presentation

The style sheet with the highest priority controls the
content display. Declarations not set in the highest priority source are passed
on by a source of lower priority such as the user agent style. This process is
called cascading.

One of the goals of CSS is also to allow users
greater control over presentation. Someone who finds red italic headings
difficult to read may apply a different style sheet. Depending on their browser
and the web site, a user may choose from various style sheets provided by the
designers, may remove all added style and view the site using the browser's
default styling, or may override just the red italic heading style without
altering other attributes.

File highlightheaders.css containing:

h1 { color: white; background-color: orange !important; }

h2 { color: white; background-color: green !important; }

Such a file is stored locally and is applicable if that
has been specified in the browser options. "!important" means that it
prevails over the author specifications.

History

Style sheets have existed in one form or another since
the beginnings of SGML
in the 1970s. Cascading Style Sheets were developed as a means for creating a
consistent approach to providing style information for web documents.

As HTML grew, it came to encompass a wider variety of stylistic
capabilities to meet the demands of web
developers. This evolution gave the designer more control over site
appearance but at the cost of HTML becoming more complex to write and maintain.
Variations in web browser implementations i.e. ViolaWWW
and WorldWideWeb[4]
made consistent site appearance difficult, and users had less control over how
web content was displayed. Robert
Cailliau wanted to separate the structure from the presentation.[4]
The ideal way would be to give the user different options and transferring
three different kinds of style sheets: one for printing, one for the
presentation on the screen and one for the editor feature.[4]

To improve web presentation capabilities, nine different
style sheet languages were proposed to the World Wide Web Consortium's (W3C)
www-style mailing list. Of the nine proposals, two were chosen as the
foundation for what became CSS: Cascading HTML Style Sheets (CHSS) and Stream-based
Style Sheet Proposal (SSP). CHSS, a language that has some
resemblance to today's CSS, was proposed by Håkon
Wium Lie in October 1994. Bert Bos
was working on a browser called Argo, which used its own style sheet language
called SSP.[5]
Lie and Yves Lafon joined Dave Raggett to expand the Arena browser for supporting CSS as a testbed
application for the W3C.[6][7][8]
Lie and Bos worked together to develop the CSS standard (the 'H' was removed
from the name because these style sheets could also be applied to other markup
languages besides HTML).[9]

Unlike existing style languages like DSSSL
and FOSI, CSS allowed a
document's style to be influenced by multiple style sheets. One style sheet
could inherit or
"cascade" from another, permitting a mixture of stylistic preferences
controlled equally by the site designer and user.

Lie's proposal was presented at the "Mosaic and the Web"
conference (later called WWW2) in Chicago,
Illinois in 1994, and again with Bert Bos in 1995.[9]
Around this time the W3C was already being established, and took an interest in
the development of CSS. It organized a workshop toward that end chaired by Steven
Pemberton. This resulted in W3C adding work on CSS to the
deliverables of the HTML editorial review board (ERB). Lie and Bos were the
primary technical staff on this aspect of the project, with additional members,
including Thomas Reardon of Microsoft, participating as well. In August 1996 Netscape
Communication Corporation presented an alternative style sheet language
called JavaScript Style Sheets (JSSS).[9]
The spec was never finished and is deprecated.[10]
By the end of 1996, CSS was ready to become official, and the CSS level 1
Recommendation was published in December.

Development of HTML, CSS, and the DOM had all been taking place in one
group, the HTML Editorial Review Board (ERB). Early in 1997, the ERB was split
into three working groups: HTML Working group, chaired by Dan Connolly
of W3C; DOM Working group, chaired by Lauren Wood of SoftQuad;
and CSS Working group, chaired by Chris Lilley of W3C.

The CSS Working Group began tackling issues that had not
been addressed with CSS level 1, resulting in the creation of CSS level 2 on
November 4, 1997. It was published as a W3C Recommendation on May 12, 1998. CSS
level 3, which was started in 1998, is still under development as of 2009.

In 2005 the CSS Working Groups decided to enforce the
requirements for standards more strictly. This meant that already published
standards like CSS 2.1, CSS 3 Selectors and CSS 3 Text were pulled back from
Candidate Recommendation to Working Draft level.

Difficulty with adoption

Although the CSS1 specification was completed in 1996 and
Microsoft's Internet Explorer 3[9]
was released in that year featuring some limited support for CSS, it was more
than three years before any web browser achieved near-full implementation of
the specification. Internet Explorer 5.0 for the Macintosh,
shipped in March 2000, was the first browser to have full (better than 99
percent) CSS1 support,[11]
surpassing Opera, which had been the leader since its
introduction of CSS support 15 months earlier. Other browsers followed soon
afterwards, and many of them additionally implemented parts of CSS2. As of
August 2010[update],
no (finished) browser has fully implemented CSS2, with implementation levels
varying (see Comparison of layout engines (CSS)).

Even though early browsers such as Internet Explorer 3[9]
and 4, and Netscape 4.x had support for CSS, it was
typically incomplete and afflicted with serious bugs.
This was a serious obstacle for the adoption of CSS.

When later 'version 5' browsers began to offer a fairly
full implementation of CSS, they were still incorrect in certain areas and were
fraught with inconsistencies, bugs and other quirks.
The proliferation of such CSS-related inconsistencies and even the variation in
feature support has made it difficult for designers to achieve a consistent
appearance across platforms. Some authors resorted to workarounds
such as CSS hacks
and CSS filters
to obtain consistent results across web browsers and platforms.

Problems with browsers' patchy adoption of CSS along with
errata in the original specification led the W3C to revise the CSS2 standard
into CSS2.1, which moved nearer to a working snapshot of current CSS support in
HTML browsers. Some CSS2 properties that no browser successfully implemented
were dropped, and in a few cases, defined behaviors were changed to bring the
standard into line with the predominant existing implementations. CSS2.1 became
a Candidate Recommendation on February 25, 2004, but CSS2.1 was pulled back to
Working Draft status on June 13, 2005,[12]
and only returned to Candidate Recommendation status on July 19, 2007.[13]

In the past, some web servers were configured to serve
all documents with the filename extension .css[14]
as mime type application/x-pointplus[15]
rather than text/css. At the time, the Net-Scene company was selling PointPlus
Maker to convert PowerPoint files into Compact Slide Show
files (using a .css extension).[16]

Variations

CSS has various levels and profiles. Each level of CSS
builds upon the last, typically adding new features and typically denoted as
CSS1, CSS2, and CSS3. Profiles are typically a subset of one or more levels of
CSS built for a particular device or user interface. Currently there are
profiles for mobile devices, printers, and television sets. Profiles should not
be confused with media types, which were added in CSS2.

CSS 1

The first CSS specification to become an official W3C
Recommendation is CSS level 1, published in December 1996.[17]
Among its capabilities are support for:

Font
properties such as typeface and emphasis

Color
of text, backgrounds, and other elements

Text
attributes such as spacing between words, letters, and lines of text

Alignment of text, images, tables
and other elements

Margin,
border, padding, and positioning for most elements

Unique
identification and generic classification of groups of attributes

The W3C no longer maintains the CSS1 Recommendation.[18]

CSS 2

CSS level 2 specification was developed by the W3C and
published as a Recommendation in May 1998. A superset of CSS1, CSS2 includes a
number of new capabilities like absolute, relative, and fixed positioning of
elements and z-index,
the concept of media types, support for aural style sheets and bidirectional
text, and new font properties such as shadows. The W3C no longer maintains the
CSS2 Recommendation.[19]

CSS level 2 revision 1 or CSS 2.1 fixes errors in CSS2,
removes poorly-supported or not fully interoperable features and adds
already-implemented browser extensions to the specification. In order to comply
with the W3C Process for standardizing technical specifications, CSS 2.1 goes
back and forth between Working Draft status and Candidate Recommendation
status. CSS 2.1 first became a Candidate Recommendation,
but it was reverted to a Working Draft on June 13, 2005 for further review. It
was returned to Candidate Recommendation status on 19 July 2007 and was updated
twice in 2009. However, since changes and clarifications were made to the prose
it went back to Last Call Working Draft on 7 December 2010. Later it went into
Proposed Recommendation on 12 April 2011.[20]

CSS 3

Instead of defining all features in a single, large
specification like CSS2, CSS3 is divided into several separate documents called
"modules". Each module adds new capability or extends features
defined in CSS2, over preserving backward compatibility. Work on CSS level 3
started around the time of publication of the original CSS2 Recommendation. The
earliest CSS3 drafts were published in June 1999.[21]

Due to the modularization, different modules have
different stability and are in different status.[22]
As of March 2011, there are over 40 CSS modules published from the CSS Working
Group.[23]
Some modules such as Selectors, Namespaces, Color and Media Queries are
considered stable and are either in Candidate Recommendation or Proposed
Recommendation status.[24]
Once CSS 2.1 is finalized and published as Recommendation, they are likely to
go to Recommendation as well.[25]

Browser support

Further information: Comparison of
layout engines (Cascading Style Sheets)

Because not all browsers correctly parse CSS code, developed
coding techniques known as CSS hacks can either filter specific browsers or
target specific browsers (generally both are known as CSS filters).
The former can be defined as CSS filtering hacks and the latter can be defined
as CSS targeting hacks and both of which can be used to hide or show parts of
the CSS to different browsers. This is achieved either by exploiting CSS-handling
quirks or bugs in the browser, or by taking advantage of lack of support for
parts of the CSS specifications.[26]
Using CSS filters, some designers have gone as far as delivering different CSS
to certain browsers to ensure designs render as expected. Because very early
web browsers were either completely incapable of handling CSS, or render CSS
very poorly, designers today often routinely use CSS filters that completely
prevent these browsers from accessing any of the CSS. Internet
Explorer support for CSS began with IE 3.0 and increased progressively with each
version. By 2008, the first Beta of Internet Explorer 8 offered support for CSS 2.1
in its best web standards mode.

An example of a well-known CSS browser bug is the Internet Explorer box model bug,
where box widths are interpreted incorrectly in several versions of the
browser, resulting in blocks that are too narrow when viewed in Internet
Explorer, but correct in standards-compliant browsers. The bug can be avoided
in Internet Explorer 6 by using the correct doctype
in (X)HTML documents. CSS hacks and CSS filters
are used to compensate for bugs such as this, just one of hundreds of CSS bugs
that have been documented in various versions of Netscape, Mozilla
Firefox, Opera, and Internet Explorer (including Internet Explorer 7).[27][28]

Even when the availability of CSS-capable browsers made
CSS a viable technology, the adoption of CSS was still held back by designers'
struggles with browsers' incorrect CSS implementation and patchy CSS support.
Even today, these problems continue to make the business of CSS design more
complex and costly than it was intended to be, and cross-browser testing
remains a necessity. Other reasons for continuing non-adoption of CSS are: its
perceived complexity, authors' lack of familiarity with CSS syntax and required
techniques, poor support from authoring tools, the risks posed by inconsistency
between browsers and the increased costs of testing.

Currently there is strong competition between Mozilla's
Gecko layout engine used in Firefox,
the WebKit
layout engine used in Apple Safari and Google Chrome,
the similar KHTML
engine used in KDE's
Konqueror
browser, and Opera's Presto layout engine—each of them is
leading in different aspects of CSS. As of August 2009, Internet Explorer 8,
Firefox 2 and 3 have reasonably complete levels of implementation of CSS 2.1.[29]

Limitations

Some noted limitations of the current capabilities of CSS
include:

Poor controls for flexible layouts

While new additions to CSS3 provide a stronger, more
robust feature-set for layout, CSS is still at heart a styling language (for
fonts, colours, borders and other decoration), not a layout language (for
blocks with positions, sizes, margins, and so on). These limitations mean that
creating fluid layouts generally requires hand-coding of CSS, and has held back
the development of a standards-based WYSIWYG
editor.[citation needed].

Selectors are unable to ascend

CSS offers no way to select a parent or ancestor of an
element that satisfies certain criteria. A more advanced selector scheme (such
as XPath)
would enable more sophisticated style sheets. However, the major reasons for
the CSS Working Group rejecting proposals for parent selectors are related to
browser performance and incremental rendering issues.[citation needed]

Vertical control limitations

While horizontal placement of elements is generally easy
to control, vertical placement is frequently unintuitive, convoluted, or
impossible. Simple tasks, such as centering an element vertically or getting a
footer to be placed no higher than bottom of viewport, either require
complicated and unintuitive style rules, or simple but widely unsupported
rules.[clarification needed]

Absence of expressions

There is currently no ability to specify property values
as simple expressions (such as margin-left: 10% - 3em + 4px;). This would be
useful in a variety of cases, such as calculating the size of columns subject
to a constraint on the sum of all columns. However, a working draft with a calc() value to address
this limitation has been published by the CSS WG.[30]
Internet Explorer versions 5 to 7 support a proprietary expression() statement,[31]
with similar functionality. This proprietary expression() statement is no
longer supported from Internet Explorer 8 onwards, except in compatibility
modes. This decision was taken for "standards compliance, browser
performance, and security reasons".[31]

Lack of column declaration

While possible in current CSS 3 (using the column-count
module)[32],
layouts with multiple columns can be complex to implement in CSS2.1. With CSS
2.1, the process is often done using floating elements, which are often
rendered differently by different browsers, different computer screen shapes,
and different screen ratios set on standard monitors.

Cannot explicitly declare new scope independently of position

Scoping rules for properties such as z-index look for the
closest parent element with a position:absolute or position:relative attribute.
This odd coupling has undesired effects such as it is impossible to avoid
declaring a new scope when one is forced to adjust an element's position,
preventing one from using the desired scope of a parent element.

Pseudo-class dynamic behavior not controllable

CSS implements pseudo-classes that allow a degree of user
feedback by conditional application of alternate styles. One CSS pseudo-class,
":hover", is dynamic (equivalent of javascript
"onmouseover") and has potential for abuse (e.g., implementing
cursor-proximity popups),[33]
but CSS has no ability for a client to disable it (no "disable"-like
property) or limit its effects (no "nochange"-like values for each
property).

Advantages

Flexibility

By combining CSS with the functionality of a Content Management System, a considerable
amount of flexibility can be programmed into content submission forms. This
allows a contributor, who may not be familiar or able to understand or edit CSS
or HTML code to select the layout of an article or other page they are
submitting on-the-fly, in the same form. For instance, a contributor, editor or
author of an article or page might be able to select the number of columns and
whether or not the page or article carries an image. This information is then
passed to the Content Management System, and the program logic evaluates the
information and determines, based on a certain number of combinations, how to
apply classes and IDs to the HTML elements, therefore styling and positioning
them according to the pre-defined CSS for that particular layout type. When
working with large-scale, complex sites, with many contributors such as news
and informational sites, this advantage weighs heavily on the feasibility and
maintenance of the project.

Separation of content from presentation

CSS facilitates publication of content in multiple
presentation formats based on nominal parameters. Nominal parameters include
explicit user preferences, different web browsers, the type of device being used
to view the content (a desktop computer or mobile Internet device), the
geographic location of the user and many other variables.

Site-wide consistency

Main articles: Separation of presentation and
content and Style sheet (web development)

When CSS is used effectively, in terms of inheritance and
"cascading," a global style sheet can be used to affect and style
elements site-wide. If the situation arises that the styling of the elements
should need to be changed or adjusted, these changes can be made by editing
rules in the global style sheet. Before CSS, this sort of maintenance was more
difficult, expensive and time-consuming.

Bandwidth

A stylesheet, whether internal to the source document or
separate, will specify the style once for a range of HTML elements selected by
class, type or relationship to others. This is much more efficient than
repeating style information inline for each occurrence of the element. An
external stylesheet is usually stored in the browser cache, and can therefore
be used on multiple pages without being reloaded, further reducing data
transfer over a network.

Page reformatting

Main article: Progressive enhancement

With a simple change of one line, a different style sheet
can be used for the same page. This has advantages for accessibility, as well
as providing the ability to tailor a page or site to different target devices.
Furthermore, devices not able to understand the styling still display the
content.

CSS frameworks

CSS frameworks are pre-prepared libraries that are meant to allow for easier,
more standards-compliant styling of web pages
using the Cascading Style Sheets language. Layout-grid related CSS frameworks
include Blueprint, 960 grid, and YUI CSS grids. Like programming and scripting
language libraries, CSS frameworks are usually incorporated as external .css
sheets referenced in the HTML <head>. They provide a number of ready-made
options for designing and laying out the web page. While many of these
frameworks have been published, some authors use them mostly for rapid
prototyping, or for learning from, and prefer to 'handcraft' CSS that is
appropriate to each published site without the design, maintenance and download
overhead of having many unused features in the site's styling.[34]

Positioning

CSS 2.1 defines three positioning schemes:

Normal flow

Inline items are laid out in the same way as the letters in words in text, one
after the other across the available space until there is no more room, then
starting a new line below. Block items stack vertically, like paragraphs
and like the items in a bulleted list. Normal flow also includes relative
positioning of block or inline items, and run-in boxes.

Floats

A floated item is taken out of the normal flow and
shifted to the left or right as far as possible in the space available. Other
content then flows alongside the floated item.

Absolute positioning

An absolutely positioned item has no place in, and no
effect on, the normal flow of other items. It occupies its assigned position in
its container independently of other items.[35]

Position: top, bottom, left, and right

There are four possible values of the position property.
If an item is positioned in any way other than static, then the further
properties top, bottom, left, and right are used to specify offsets and
positions.

Static

The default value places the item in the normal flow

Relative

The item is placed in the normal flow, and then
shifted or offset from that position. Subsequent flow items are laid out as if
the item had not been moved.

Absolute

Specifies absolute positioning

Fixed

The item is absolutely positioned in a fixed
position on the screen even as the rest of the document is scrolled[35]

Float and clear

The float property may have one of three values. Absolutely
positioned or fixed items cannot be floated. Other elements normally
flow around floated items, unless they are prevented from doing so by their
clear property.

left

Floats to the left of the line that it would have appeared in; other items may
flow around its right side

right

Floats to the right of the line that it would have appeared in; other items may
flow around its left side

none

Removes the float property from an item.

9 XML NAMESPACES

XML Namespaces

1 Basic Concepts

[Definition:
An XML namespace is identified by a URI reference [RFC3986]; element and
attribute names may be placed in an XML namespace using the mechanisms
described in this specification.]

[Definition:
An expanded name is a pair consisting of a namespace name and a local name. ]
[Definition: For a name N in a namespace identified by a URI I, the namespace
name is I. For a name N that is not in a namespace, the namespace name has no
value. ] [Definition: In either case the local name is N. ] It is this
combination of the universally managed URI namespace with the vocabulary's
local names that is effective in avoiding name clashes.

URI
references can contain characters not allowed in names, and are often
inconveniently long, so expanded names are not used directly to name elements
and attributes in XML documents. Instead qualified names are used. [Definition:
A qualified name is a name subject to namespace interpretation.] In documents
conforming to this specification, element and attribute names appear as
qualified names. Syntactically, they are either prefixed names or unprefixed
names. Attribute-based declaration syntax is provided to bind prefixes to namespace
names and to bind a default namespace that applies to unprefixed element names;
these declarations are scoped by the elements on which they appear so that
different bindings may apply in different parts of a document. Processors
conforming to this specification MUST recognize and act on these declarations
and prefixes.

2 Use of URIs as Namespace Names

The
empty string, though it is a legal URI reference, cannot be used as a namespace
name.

The
use of relative URI references, including same-document references, in
namespace declarations is deprecated.

Note:This
deprecation of relative URI references was decided on by a W3C XML Plenary
Ballot [Relative URI deprecation]. It also declares that "later
specifications such as DOM, XPath, etc. will define no interpretation for
them".

3 Comparing URI References

URI
references identifying namespaces are compared when determining whether a name
belongs to a given namespace, and whether two names belong to the same
namespace. [Definition: The two URIs are treated as strings, and they are
identical if and only if the strings are identical, that is, if they are the
same sequence of characters. ] The comparison is case-sensitive, and no
%-escaping is done or undone.

A
consequence of this is that URI references which are not identical in this
sense may resolve to the same resource. Examples include URI references which
differ only in case or %-escaping, or which are in external entities which have
different base URIs (but note that relative URIs are deprecated as namespace
names).

In
a namespace declaration, the URI reference is the normalized value of the
attribute, so replacement of XML character and entity references has already
been done before any comparison.

Examples:The
URI references below are all different for the purposes of identifying
namespaces, since they differ in case:

http://www.example.org/wine

http://www.Example.org/wine

http://www.example.org/Wine

The
URI references below are also all different for the purposes of identifying
namespaces:

http://www.example.org/~wilbur

http://www.example.org/%7ewilbur

http://www.example.org/%7Ewilbur

Because
of the risk of confusion between URIs that would be equivalent if dereferenced,
the use of %-escaped characters in namespace names is strongly discouraged.

4 Declaring Namespaces

[Definition:
A namespace (or more precisely, a namespace binding) is declared using a family
of reserved attributes. Such an attribute's name must either be xmlns or begin
xmlns:. These attributes, like any other XML attributes, may be provided
directly or by default. ]

Attribute
Names for Namespace Declaration

[1]    NSAttName    ::=    PrefixedAttName   | DefaultAttName

[2]    PrefixedAttName    ::=    'xmlns:' NCName [NSC:
Reserved Prefixes and Namespace Names]

[3]    DefaultAttName    ::=    'xmlns'

[4]    NCName    ::=    Name - (Char* ':' Char*) /*
An XML Name, minus the ":" */

The
attribute's normalized value MUST be either a URI reference — the
namespace name identifying the namespace — or an empty string. The namespace
name, to serve its intended purpose, SHOULD have the characteristics of
uniqueness and persistence. It is not a goal that it be directly usable for
retrieval of a schema (if any exists). Uniform Resource Names [RFC2141] is an
example of a syntax that is designed with these goals in mind. However, it
should be noted that ordinary URLs can be managed in such a way as to achieve
these same goals.

[Definition:
If the attribute name matches PrefixedAttName, then the NCName gives the
namespace prefix, used to associate element and attribute names with the
namespace name in the attribute value in the scope of the element to which the
declaration is attached. ]

[Definition:
If the attribute name matches DefaultAttName, then the namespace name in the
attribute value is that of the default namespace in the scope of the element to
which the declaration is attached.] Default namespaces and overriding of
declarations are discussed in 6 Applying Namespaces to Elements and Attributes.

An
example namespace declaration, which associates the namespace prefix edi with
the namespace name http://ecommerce.example.org/schema:

<x
xmlns:edi='http://ecommerce.example.org/schema'>

<!-- the "edi" prefix is
bound to http://ecommerce.example.org/schema

for the
"x" element and contents -->

</x>

Namespace
constraint: Reserved Prefixes and Namespace Names

The
prefix xml is by definition bound to the namespace name
http://www.w3.org/XML/1998/namespace. It MAY, but need not, be declared, and
MUST NOT be bound to any other namespace name. Other prefixes MUST NOT be bound
to this namespace name, and it MUST NOT be declared as the default namespace.

The
prefix xmlns is used only to declare namespace bindings and is by definition
bound to the namespace name http://www.w3.org/2000/xmlns/. It MUST NOT be
declared . Other prefixes MUST NOT be bound to this namespace name, and it MUST
NOT be declared as the default namespace. Element names MUST NOT have the
prefix xmlns.

All
other prefixes beginning with the three-letter sequence x, m, l, in any case
combination, are reserved. This means that:

users
SHOULD NOT use them except as defined by later specifications

processors
MUST NOT treat them as fatal errors.

Though
they are not themselves reserved, it is inadvisable to use prefixed names whose
LocalPart begins with the letters x, m, l, in any case combination, as these
names would be reserved if used without a prefix.

5 Qualified Names

In
XML documents conforming to this specification, some names (constructs
corresponding to the nonterminal Name) MUST be given as qualified names,
defined as follows:

Qualified
Name

[7]    QName    ::=    PrefixedName

| UnprefixedName

[8]    PrefixedName    ::=    Prefix ':' LocalPart

[9]    UnprefixedName    ::=    LocalPart

[10]    Prefix    ::=    NCName

[11]    LocalPart    ::=    NCName

The
Prefix provides the namespace prefix part of the qualified name, and MUST be
associated with a namespace URI reference in a namespace declaration.
[Definition: The LocalPart provides the local part of the qualified name.]

Note
that the prefix functions only as a placeholder for a namespace name.
Applications SHOULD use the namespace name, not the prefix, in constructing
names whose scope extends beyond the containing document.

6 Using Qualified Names

In
XML documents conforming to this specification, element names are given as
qualified names, as follows:

Element
Names

[12]    STag    ::=    '<' QName (S Attribute)*
S? '>'  [NSC: Prefix Declared]

[13]    ETag    ::=    '</' QName S? '>'
[NSC: Prefix Declared]

[14]    EmptyElemTag    ::=    '<' QName (S Attribute)*
S? '/>' [NSC: Prefix Declared]

An
example of a qualified name serving as an element name:

<!-- the 'price' element's namespace
is http://ecommerce.example.org/schema -->

<edi:price xmlns:edi='http://ecommerce.example.org/schema'
units='Euro'>32.18</edi:price>

Attributes
are either namespace declarations or their names are given as qualified names:

Attribute

[15]    Attribute    ::=    NSAttName Eq AttValue

| QName Eq AttValue [NSC: Prefix
Declared]

[NSC: No Prefix Undeclaring]

[NSC: Attributes Unique]

An
example of a qualified name serving as an attribute name:

<x
xmlns:edi='http://ecommerce.example.org/schema'>

<!-- the 'taxClass' attribute's
namespace is http://ecommerce.example.org/schema -->

<lineItem
edi:taxClass="exempt">Baby food</lineItem>

</x>

Namespace
constraint: Prefix Declared

The
namespace prefix, unless it is xml or xmlns, MUST have been declared in a
namespace declaration attribute in either the start-tag of the element where
the prefix is used or in an ancestor element (i.e., an element in whose content
the prefixed markup occurs).

Namespace
constraint: No Prefix Undeclaring

In
a namespace declaration for a prefix (i.e., where the NSAttName is a PrefixedAttName),
the attribute value MUST NOT be empty.

This
constraint may lead to operational difficulties in the case where the namespace
declaration attribute is provided, not directly in the XML document entity, but
via a default attribute declared in an external entity. Such declarations may
not be read by software which is based on a non-validating XML processor. Many
XML applications, presumably including namespace-sensitive ones, fail to
require validating processors. If correct operation with such applications is
required, namespace declarations MUST be provided either directly or via
default attributes declared in the internal subset of the DTD.

Element
names and attribute names are also given as qualified names when they appear in
declarations in the DTD:

Qualified
Names in Declarations

[16]    doctypedecl    ::=    '<!DOCTYPE' S QName (S ExternalID)? S? ('[' (markupdecl | PEReference | S)*
']' S?)? '>'

[17]    elementdecl    ::=    '<!ELEMENT' S QName S
contentspec S? '>'

[18]    cp    ::=    (QName | choice | seq) ('?'
| '*' | '+')?

[19]    Mixed    ::=    '(' S? '#PCDATA' (S? '|' S?
QName)* S? ')*'

| '(' S? '#PCDATA' S? ')'

[20]    AttlistDecl    ::=    '<!ATTLIST' S QName
AttDef* S? '>'

[21]    AttDef    ::=    S (QName | NSAttName) S
AttType S DefaultDecl

Note
that DTD-based validation is not namespace-aware in the following sense: a DTD
constrains the elements and attributes that may appear in a document by their
uninterpreted names, not by (namespace name, local name) pairs. To validate a
document that uses namespaces against a DTD, the same prefixes must be used in
the DTD as in the instance. A DTD may however indirectly constrain the
namespaces used in a valid document by providing #FIXED values for attributes
that declare namespaces.

7 Applying Namespaces to Elements
and Attributes

7.1
Namespace Scoping

The
scope of a namespace declaration declaring a prefix extends from the beginning
of the start-tag in which it appears to the end of the corresponding end-tag,
excluding the scope of any inner declarations with the same NSAttName part. In
the case of an empty tag, the scope is the tag itself.

Such
a namespace declaration applies to all element and attribute names within its
scope whose prefix matches that specified in the declaration.

The
expanded name corresponding to a prefixed element or attribute name has the URI
to which the prefix is bound as its namespace name, and the local part as its
local name.

<?xml
version="1.0"?>

<html:html
xmlns:html='http://www.w3.org/1999/xhtml'>

<html:head><html:title>Frobnostication</html:title></html:head>

<html:body><html:p>Moved to

<html:a
href='http://frob.example.com'>here.</html:a></html:p></html:body>

</html:html>

Multiple
namespace prefixes can be declared as attributes of a single element, as shown
in this example:

<?xml
version="1.0"?>

<!--
both namespace prefixes are available throughout -->

<bk:book
xmlns:bk='urn:loc.gov:books'

xmlns:isbn='urn:ISBN:0-395-36341-6'>

<bk:title>Cheaper by
the Dozen</bk:title>

<isbn:number>1568491379</isbn:number>

</bk:book>

Declaring Namespaces

[Definition:]
A namespace is declared using a family of reserved attributes. Such an
attribute's name must either be xmlns or have xmlns: as a prefix. These
attributes, like any other XML attributes, may be provided directly or by
default.

Attribute
Names for Namespace Declaration

[1]  NSAttName ::=  PrefixedAttName

| DefaultAttName

[2]  PrefixedAttName ::=  'xmlns:' NCName [  NSC: Leading "XML" ]

[3]  DefaultAttName ::=  'xmlns'

[4]  NCName ::=  (Letter | '_') (NCNameChar)* /*  An XML Name, minus the ":" */

[5]  NCNameChar ::=  Letter | Digit | '.' | '-' | '_' |
CombiningChar | Extender

[Definition:] The attribute's value, a
URI reference, is the namespace name identifying the namespace. The namespace
name, to serve its intended purpose, should have the characteristics of
uniqueness and persistence. It is not a goal that it be directly usable for
retrieval of a schema (if any exists). An example of a syntax that is designed with
these goals in mind is that for Uniform Resource Names [RFC2141]. However, it
should be noted that ordinary URLs can be managed in such a way as to achieve
these same goals.

[Definition:]
If the attribute name matches PrefixedAttName, then the NCName gives the
namespace prefix, used to associate element and attribute names with the
namespace name in the attribute value in the scope of the element to which the
declaration is attached. In such declarations, the namespace name may not be
empty.

[Definition:]
If the attribute name matches DefaultAttName, then the namespace name in the
attribute value is that of the default namespace in the scope of the element to
which the declaration is attached. In such a default declaration, the attribute
value may be empty. Default namespaces and overriding of declarations are
discussed in "5. Applying Namespaces to Elements and Attributes".

An
example namespace declaration, which associates the namespace prefix edi with
the namespace name http://ecommerce.org/schema:

<x
xmlns:edi='http://ecommerce.org/schema'>

<!-- the "edi" prefix is
bound to http://ecommerce.org/schema

for the
"x" element and contents -->

</x>

Namespace
Constraint: Leading "XML"

Prefixes
beginning with the three-letter sequence x, m, l, in any case combination, are
reserved for use by XML and XML-related specifications.

Qualified Names

[Definition:]
In XML documents conforming to this specification, some names (constructs
corresponding to the nonterminal Name) may be given as qualified names, defined
as follows:

Qualified Name

[6]  QName ::=  (Prefix ':')? LocalPart

[7]  Prefix ::=  NCName

[8]  LocalPart ::=  NCName

The Prefix provides the namespace prefix
part of the qualified name, and must be associated with a namespace URI
reference in a namespace declaration. [Definition:] The LocalPart provides the
local part of the qualified name.

Note
that the prefix functions only as a placeholder for a namespace name.
Applications should use the namespace name, not the prefix, in constructing names
whose scope extends beyond the containing document.

Using Qualified Names

In
XML documents conforming to this specification, element types are given as
qualified names, as follows:

Element Types

[9]  STag ::=  '<' QName (S Attribute)* S?
'>'  [  NSC: Prefix Declared ]

[10]  ETag ::=  '</' QName S? '>' [  NSC: Prefix Declared ]

[11]  EmptyElemTag ::=  '<' QName (S Attribute)* S? '/>'
[  NSC: Prefix Declared ]

An example of a qualified name serving as
an element type:

<x
xmlns:edi='http://ecommerce.org/schema'>

<!-- the 'price' element's namespace
is http://ecommerce.org/schema -->

<edi:price
units='Euro'>32.18</edi:price>

</x>

Attributes
are either namespace declarations or their names are given as qualified names:

Attribute

[12]  Attribute ::=  NSAttName Eq AttValue

| QName Eq AttValue [  NSC: Prefix Declared ]

An example of a qualified name serving as
an attribute name:

<x
xmlns:edi='http://ecommerce.org/schema'>

<!-- the 'taxClass' attribute's
namespace is http://ecommerce.org/schema -->

<lineItem
edi:taxClass="exempt">Baby food</lineItem>

</x>

Namespace Constraint: Prefix
Declared

The
namespace prefix, unless it is xml or xmlns, must have been declared in a
namespace declaration attribute in either the start-tag of the element where
the prefix is used or in an an ancestor element (i.e. an element in whose
content the prefixed markup occurs). The prefix xml is by definition bound to
the namespace name http://www.w3.org/XML/1998/namespace. The prefix xmlns is
used only for namespace bindings and is not itself bound to any namespace name.

This
constraint may lead to operational difficulties in the case where the namespace
declaration attribute is provided, not directly in the XML document entity, but
via a default attribute declared in an external entity. Such declarations may
not be read by software which is based on a non-validating XML processor. Many
XML applications, presumably including namespace-sensitive ones, fail to
require validating processors. For correct operation with such applications,
namespace declarations must be provided either directly or via default
attributes declared in the internal subset of the DTD. Element names and
attribute types are also given as qualified names when they appear in
declarations in the DTD:

Qualified Names in Declarations

[13]  doctypedecl ::=  '<!DOCTYPE' S QName (S ExternalID)? S? ('[' (markupdecl | PEReference | S)*
']' S?)? '>'

[14]  elementdecl ::=  '<!ELEMENT' S QName S contentspec S?
'>'

[15]  cp ::=  (QName | choice | seq) ('?' | '*' |
'+')?

[16]  Mixed ::=  '(' S? '#PCDATA' (S? '|' S? QName)* S?
')*'

| '(' S? '#PCDATA' S? ')'

[17]  AttlistDecl ::=  '<!ATTLIST' S QName AttDef* S? '>'

[18]  AttDef ::=  S (QName | NSAttName) S AttType S DefaultDecl

5. Applying Namespaces to
Elements and Attributes

5.1 Namespace Scoping

The
namespace declaration is considered to apply to the element where it is
specified and to all elements within the content of that element, unless
overridden by another namespace declaration with the same NSAttName part:

<?xml
version="1.0"?>

<!--
all elements here are explicitly in the HTML namespace -->

<html:html
xmlns:html='http://www.w3.org/TR/REC-html40'>

<html:head><html:title>Frobnostication</html:title></html:head>

<html:body><html:p>Moved to

<html:a
href='http://frob.com'>here.</html:a></html:p></html:body>

</html:html>

Multiple
namespace prefixes can be declared as attributes of a single element, as shown
in this example:

<?xml
version="1.0"?>

<!--
both namespace prefixes are available throughout -->

<bk:book
xmlns:bk='urn:loc.gov:books'

xmlns:isbn='urn:ISBN:0-395-36341-6'>

<bk:title>Cheaper by
the Dozen</bk:title>

<isbn:number>1568491379</isbn:number>

</bk:book>

5.2 Namespace Defaulting

A
default namespace is considered to apply to the element where it is declared
(if that element has no namespace prefix), and to all elements with no prefix
within the content of that element. If the URI reference in a default namespace
declaration is empty, then unprefixed elements in the scope of the declaration
are not considered to be in any namespace. Note that default namespaces do not
apply directly to attributes.

<?xml
version="1.0"?>

<!--
elements are in the HTML namespace, in this case by default -->

<html
xmlns='http://www.w3.org/TR/REC-html40'>

<head><title>Frobnostication</title></head>

<body><p>Moved to

<a
href='http://frob.com'>here</a>.</p></body>

</html>

<?xml
version="1.0"?>

<!--
unprefixed element types are from "books" -->

<book
xmlns='urn:loc.gov:books'

xmlns:isbn='urn:ISBN:0-395-36341-6'>

<title>Cheaper by the
Dozen</title>

<isbn:number>1568491379</isbn:number>

</book>

A
larger example of namespace scoping:

<?xml
version="1.0"?>

<!--
initially, the default namespace is "books" -->

<book
xmlns='urn:loc.gov:books'

xmlns:isbn='urn:ISBN:0-395-36341-6'>

<title>Cheaper by the
Dozen</title>

<isbn:number>1568491379</isbn:number>

<notes>

<!-- make
HTML the default namespace for some commentary -->

<p
xmlns='urn:w3-org-ns:HTML'>

This is a <i>funny</i> book!

</p>

</notes>

</book>

The
default namespace can be set to the empty string. This has the same effect,
within the scope of the declaration, of there being no default namespace.

<?xml
version='1.0'?>

<Beers>

<!-- the default namespace is now
that of HTML -->

<table
xmlns='http://www.w3.org/TR/REC-html40'>

<th><td>Name</td><td>Origin</td><td>Description</td></th>

<tr>

<!-- no default
namespace inside table cells -->

<td><brandName
xmlns="">Huntsman</brandName></td>

<td><origin
xmlns="">Bath,
UK</origin></td>

<td>

<details
xmlns=""><class>Bitter</class><hop>Fuggles</hop>

<pro>Wonderful hop, light alcohol, good summer beer</pro>

<con>Fragile; excessive variance pub to pub</con>

</details>

</td>

</tr>

</table>

</Beers>

5.3 Uniqueness of Attributes

In
XML documents conforming to this specification, no tag may contain two
attributes which: have identical names, or  have qualified names with the same local
part and with prefixes which have been bound to namespace names that are
identical.

For
example, each of the bad start-tags is illegal in the following:

<!--
http://www.w3.org is bound to n1 and n2 -->

<x
xmlns:n1="http://www.w3.org"

xmlns:n2="http://www.w3.org" >

<bad a="1"     a="2" />

<bad n1:a="1"  n2:a="2" />

</x>

However,
each of the following is legal, the second because the default namespace does
not apply to attribute names:

<!--
http://www.w3.org is bound to n1 and is the default -->

<x
xmlns:n1="http://www.w3.org"

xmlns="http://www.w3.org" >

<good a="1"     b="2" />

<good a="1"     n1:a="2"
/>

</x>

Conformance of Documents

In
XML documents which conform to this specification, element types and attribute
names must match the production for QName and must satisfy the "Namespace
Constraints". An XML document conforms to this specification if all other
tokens in the document which are required, for XML conformance, to match the
XML production for Name, match this specification's production for NCName. The
effect of conformance is that in such a document:

All
element types and attribute names contain either zero or one colon.

No
entity names, PI targets, or notation names contain any colons.

Strictly
speaking, attribute values declared to be of types ID, IDREF(S), ENTITY(IES),
and NOTATION are also Names, and thus should be colon-free. However, the
declared type of attribute values is only available to processors which read
markup declarations, for example validating processors. Thus, unless the use of
a validating processor has been specified, there can be no assurance that the
contents of attribute values have been checked for conformance to this
specification.

XML Namespaces provide a method
to avoid element name conflicts.

Name Conflicts

In
XML, element names are defined by the developer. This often results in a
conflict when trying to mix XML documents from different XML applications.

This
XML carries HTML table information:

<table>

<tr>

<td>Apples</td>

<td>Bananas</td>

</tr>

</table>

This
XML carries information about a table (a piece of furniture):

<table>

<name>African Coffee
Table</name>

<width>80</width>

<length>120</length>

</table>

If
these XML fragments were added together, there would be a name conflict. Both
contain a <table> element, but the elements have different content and
meaning.

An
XML parser will not know how to handle these differences.

Solving the Name Conflict Using a
Prefix

Name
conflicts in XML can easily be avoided using a name prefix.

This
XML carries information about an HTML table, and a piece of furniture:

<h:table>

<h:tr>

<h:td>Apples</h:td>

<h:td>Bananas</h:td>

</h:tr>

</h:table>

<f:table>

<f:name>African Coffee
Table</f:name>

<f:width>80</f:width>

<f:length>120</f:length>

</f:table>

In
the example above, there will be no conflict because the two <table>
elements have different names.

XML
Namespaces - The xmlns Attribute

When
using prefixes in XML, a so-called namespace for the prefix must be defined.

The
namespace is defined by the xmlns attribute in the start tag of an element.

The
namespace declaration has the following syntax. xmlns:prefix="URI".

<root>

<h:table
xmlns:h="http://www.w3.org/TR/html4/">

<h:tr>

<h:td>Apples</h:td>

<h:td>Bananas</h:td>

</h:tr>

</h:table>

<f:table
xmlns:f="http://www.w3schools.com/furniture">

<f:name>African Coffee
Table</f:name>

<f:width>80</f:width>

<f:length>120</f:length>

</f:table>

</root>

In
the example above, the xmlns attribute in the <table> tag give the h: and
f: prefixes a qualified namespace. When a namespace is defined for an element,
all child elements with the same prefix are associated with the same namespace.
Namespaces can be declared in the elements where they are used or in the XML
root element:

<root

xmlns:h="http://www.w3.org/TR/html4/"

xmlns:f="http://www.w3schools.com/furniture">

<h:table>

<h:tr>

<h:td>Apples</h:td>

<h:td>Bananas</h:td>

</h:tr>

</h:table>

<f:table>

<f:name>African Coffee Table</f:name>

<f:width>80</f:width>

<f:length>120</f:length>

</f:table>

</root>

Note:
The namespace URI is not used by the parser to look up information.

The
purpose is to give the namespace a unique name. However, often companies use
the namespace as a pointer to a web page containing namespace information.

Try
to go to http://www.w3.org/TR/html4/.

Uniform Resource Identifier (URI)

A
Uniform Resource Identifier (URI) is a string of characters which identifies an
Internet Resource. The most common URI is the Uniform Resource Locator (URL)
which identifies an Internet domain address. Another, not so common type of URI
is the Universal Resource Name (URN). In our examples we will only use URLs.

Default Namespaces

Defining
a default namespace for an element saves us from using prefixes in all the
child elements. It has the following syntax:

xmlns="namespaceURI"

This
XML carries HTML table information:

<table
xmlns="http://www.w3.org/TR/html4/">

<tr>

<td>Apples</td>

<td>Bananas</td>

</tr>

</table>

This
XML carries information about a piece of furniture:

<table
xmlns="http://www.w3schools.com/furniture">

<name>African Coffee
Table</name>

<width>80</width>

<length>120</length>

</table>

Namespaces in Real Use

XSLT
is an XML language that can be used to transform XML documents into other
formats, like HTML. In the XSLT document below, you can see that most of the
tags are HTML tags. The tags that are not HTML tags have the prefix xsl,
identified by the namespace xmlns:xsl="http://www.w3.org/1999/XSL/Transform":

<?xml
version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet
version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template
match="/">

<html>

<body>

<h2>My CD Collection</h2>

<table border="1">

<tr>

<th
align="left">Title</th>

<th
align="left">Artist</th>

</tr>

<xsl:for-each
select="catalog/cd">

<tr>

<td><xsl:value-of select="title"/></td>

<td><xsl:value-of select="artist"/></td>

</tr>

</xsl:for-each>

</table>

</body>

</html>

</xsl:template>

</xsl:stylesheet>

10 EDI FACT

United Nations/Electronic Data Interchange For
Administration, Commerce and Transport (UN/EDIFACT) is the international EDI standard developed under the United
Nations. The work of maintenance and further development of this
standard is done through the United Nations Centre for Trade Facilitation and
Electronic Business (UN/CEFACT) under the UN Economic Commission for
Europe, in the Finance Domain working group UN CEFACT
TBG5. EDIFACT has been adopted by the International Organization for
Standardization (ISO) as the ISO standard ISO 9735.

The EDIFACT standard provides:

a set
of syntax rules to structure data

an
interactive exchange protocol (I-EDI)

standard
messages which allow multi-country and multi-industry exchange

Example

See below for an example of an EDIFACT message used to
answer to a product availability request:

UNA:+.? '

UNB+IATB:1+6XPPC+LHPPC+940101:0950+1'

UNH+1+PAORES:93:1:IA'

MSG+1:45'

IFT+3+XYZCOMPANY AVAILABILITY'

ERC+A7V:1:AMD'

IFT+3+NO MORE FLIGHTS'

ODI'

TVL+240493:1000::1220+FRA+JFK+DL+400+C'

PDI++C:3+Y::3+F::1'

APD+74C:0:::6++++++6X'

TVL+240493:1740::2030+JFK+MIA+DL+081+C'

PDI++C:4'

APD+EM2:0:1630::6+++++++DA'

UNT+13+1'

UNZ+1+1'

The UNA-segment describes the segment terminator, data
element separator, component data element separator and release character as
follow:

' is a
segment terminator

+ is a
data element separator

:
is a component data element separator

?
is a release character

Note: The line breaks after each segment in this example
have been added for readability. There are typically no line breaks in EDI
data.

UNH+1+PAORES:93:1:IA'- This is the header segment which
is required at the start of every message. This code specifies that the message
name and version is PAORES 93 revision 1 and it was defined by the organisation
IA (IATA).

IFT+3+NO MORE FLIGHTS' - This is an "Interactive
Free Text" segment containing the text "NO MORE FLIGHTS".

UNT+13+1' - This is the tail segment. It indicated that
the message sent contains 13 segments.

Structure

EDIFACT has a hierarchical structure where the top level
is referred to as an interchange, and lower levels contain multiple messages
which consist of segments, which in turn consist of composites.
The final iteration is an element which is derived from the United
Nations Trade Data Element Directory (UNTDED) and are normalised throughout the
EDIFACT standard.

A group or segment can be mandatory (M) or conditional
(C) and can be specified to repeat. For example, C99 indicates between 0 and 99
repetitions of a segment or group, while M99 signifies between 1 and 99
repetitions.

A group, like a message, is a sequence of segments or
groups. The first segment or group beneath a group must be mandatory, and the
group should be made conditional if the logic of the situation demands it.

Service String Advice     UNA  Conditional

+-----
Interchange Header
UNB  Mandatory

| +---
Functional Group Header
UNG  Conditional

| | +- Message
Header
UNH  Mandatory

| | |  User Data Segments
As required

| | +-
Message Trailer
UNT  Mandatory

| +---
Functional Group Trailer  UNE  Conditional

+-----
Interchange Trailer       UNZ  Mandatory

Current state of EDIFACT

There is an apparent battle between XML and EDIFACT. An
equivalent XML message has a larger file size than an EDIFACT message, but it
is easier for users to read (although this is not necessary because the
contents are created to be read by computers). Another possible explanation is
that compatibility is being favored over performance, since more tools exist to
work with XML data than with EDIFACT. EDIFACT-messages can be as much as one tenth
the size of XML-messages. That makes XML less attractive for very high volume
applications.

An advantage of EDIFACT is the availability of agreed
message-contents, which XML must leverage to develop its own similar agreed
contents. RosettaNet
is one of the emerging XML standards and is widely used in semiconductors and
high tech industries.

UBL is another currently being adopted by
Scandinavian governments as a legally required standard for sending invoices to
governments, and was enforced in February 2005 that all invoices to the Danish
government must be sent in an electronic format.

ebXML
is another XML standard built by UN/CEFACT
(along with EDIFACT), and is often seen as a standard best suited for small and
medium enterprises.

However, EDIFACT is likely to remain the most widely used
in high tech, civil aviation, retail and tourism industries, due to the amount
of software that leverages the standard, and the need for integration between
new systems and legacy systems.[citation needed]

Europe has a large EDIFACT installed base because it adopted
the technology early, while the Asian region adopted B2B in later implementations and is therefore
using more XML standards.

EDIFACT will grow further in Europe's
energy market where it is a current requireme

XML/EDIFACT is an Electronic Data Interchange format used in
Business-to-business transactions. It allows EDIFACT
message types to be used by XML systems.

EDIFACT is a formal language for machine readable description
of electronic business documents. It uses a syntax close to delimiter separated
files. This syntax was invented in the 1980s to keep files as small as
possible. Because of the Internet boom around 2000, XML started to become the
most widely supported file syntax. But for example, an invoice is still an
invoice, containing information about buyer, seller, product, due amount.
EDIFACT works perfectly from the content viewpoint, but many software systems
struggle to handle its syntax. So combining EDIFACT vocabulary and grammar with
XML syntax makes XML/EDIFACT.

The rules for XML/EDIFACT are defined by ISO TS 20625.

Use-cases

XML/EDIFACT is used in B2B scenarios as listed below.

1) Newer EAI or B2B systems, e.g. SAP XI, often cannot handle EDI (Electronic Data Interchange) syntax
directly. Simple syntax converters do a 1:1 conversion before. Their input is
an EDIFACT transaction file, their output an XML/EDIFACT instance file.

2) XML/EDIFACT keeps XML B2B transactions relatively
small. XML element names derived from EDIFACT tags are much shorter and more
formal than those derived from natural language. Such formal tags, taken from
the "EDIFACT modelling language", are readable by B2B experts
worldwide.

3) A company does not want to invest into new
vocabularies from scratch. XML/EDIFACT reuses business content defined in
UN/EDIFACT. Since 1987, the UN/EDIFACT library was enriched by global business
needs for all sectors of industry, transport and public services. For XML,
there is no such comprehensive vocabulary available.

4) Large companies can order goods from small companies
via XML/EDIFACT. The small companies use XSL stylesheets to browse the message
content in human readable forms.

Example 1: EDIFACT source code

A name and address (NAD) segment, containing customer ID
and customer address, expressed in EDIFACT syntax:

NAD+BY+CST9955::91++Candy Inc+Sirup street 15+Sugar Town++55555'

Example 2: XML/EDIFACT source code

The same information content in an XML/EDIFACT instance
file:

<S_NAD>

<D_3035>BY</D_3035>

<C_C082><D_3039>CST9955</D_3039><D_3055>91</D_3055></C_C082>

<C_C080><D_3036>Candy Inc</D_3036></C_C080>

<C_C059><D_3042>Sirup
street 15</D_3042></C_C059>

<D_3164>Sugar
Town</D_3164><D_3251>55555</D_3251>

</S_NAD>

Example 3: XML/EDIFACT in Internet Explorer

The same XML/EDIFACT instance presented with help of an XSL stylesheet:

EDIFACT

Advantages all the way

EDIFACT stands for "Electronic Data Interchange For Administration,
Commerce and Transport". UN/EDIFACT (ISO 9735) is a global standard for
the presentation of business and commercial data destined for electronic exchange
data between companies.

Advantages of EDIFACT

Research has shown that around 70% of data requiring manual entry has
already been processed electronically by computer and is therefore already
available. EDIFACT thus has enormous benefits for businesses which opt for
standardised data exchange.

Speed

EDIFACT reduces the time spent repeatedly entering the same data.
Electronic transfer and processing of standardised data is much faster than
sending documents by traditional mail. Data sent electronically is available at
any time, around the clock, no matter where it is processed.

EDIFACT is used for just-in-time (JIT) logistics, thus increasing stock
turnover, reducing stock in hand and reserves and reducing the capital tied up
and the associated capital costs. Cash management is significantly simplified
because payment procedures are quicker and a general summary of orders is
instantly available.

Quality of the data

The data generated directly from computer files or using computers is much
more accurate than data repeatedly entered manually. Manual work is minimised
and the repeated entry of the same data reduced. The use of internationally
standardised message types and codes means that comprehension difficulties are
a thing of the past, irrespective of the language.

General advantages of using
EDIFACT.

Not dependent on software and hardware

Global comprehensibility of the information transmitted electronically

Same message structure for all business partners

Faster message forwarding

Conversion of inputs and outputs eliminates need for new software
investments

Cost and benefits of EDIFACT

The Data exchange by EDIFACT is only possible if partners have an IT
system. The investment consists of a program which allows the data required for
electronic exchange (e.g. consignment data in the case of rail transport) to be
fed from the customer's system to the EDIFACT converter (translator) and back.
An individual cost estimate is required because customers use different
systems.

EDIFACT now makes electronic data that can go no further than the factory
gate a thing of the past. Businesses which invest in EDIFACT are investing in
their future. Their medium-term goal is to automate all transactions between
companies (purchasing, sales, transport, payment transactions, insurance,
etc.), thus substantially reducing administrative costs. By introducing CIS,
SBB has not only optimised rail freight transport, but is also offering its
partners the opportunity to exploit considerable cost-saving potential.

The time taken to amortise the investment depends partly on the volume of
transactions conducted using EDIFACT and the number of partners involved in the
exchange of data. It therefore varies between companies.

EDIFACT in business

For example: You order a particular product from your supplier using an
EDIFACT message (ORDERS). The recipient of the products can now automatically
process your data in its in-house system. Many of the factors required for
delivery of the product (e.g. product, delivery date, delivery address, customer
name, etc.) are already available.

The goods are transferred to the carrier with a transport order (IFTMIN).
The consignee receives notification of delivery (INSDES) at the same time. Both
the consignor and consignee can track the consignment and retrieve useful
information (e.g. estimated date of arrival, current location of the
consignment, etc.).

11 Message Definition

Messages

The WSDL message
element defines an abstract message that can serve as the input or output of an
operation. Messages consist of one or more part elements, where each part is
associated with either an element (when using document style) or a type
(when using RPC style). The basic structure of a message definition is as
follows (* means zero or more and ? means optional):

<definitions
.... >

<message
name="nmtoken"> *

<part name="nmtoken" element="qname"?
type="qname"?/> *

</message>

</definitions>

The
messages and parts must be named making it possible to refer to them from
elsewhere in the WSDL definition. If you're defining an RPC style service, the
message parts represent the method's parameters. In this case, the name of the
part becomes the name of an element in the concrete message and its structure
is determined by the supplied type attribute. If you're defining a document
style service, the parts simply refer to the XML elements that are placed
within the body (referenced by the element attribute). The following
example contains several message definitions that refer to elements by name:

<definitions

xmlns="http://schemas.xmlsoap.org/wsdl/"

xmlns:xs="http://www.w3.org/2001/XMLSchema"

xmlns:y="http://example.org/math/"

xmlns:ns="http://example.org/math/types/"

targetNamespace="http://example.org/math/"

>

...

<message name="AddMessage">

<part
name="parameter" element="ns:Add"/>

</message>

<message
name="AddResponseMessage">

<part
name="parameter" element="ns:AddResponse"/>

</message>

<message
name="SubtractMessage">

<part
name="parameter" element="ns:Subtract"/>

</message>

<message
name="SubtractResponseMessage">

<part
name="parameter" element="ns:SubtractResponse"/>

</message>

...

</definitions>

Although the message
parts typically refer to XML types or elements, they can also refer to non-XML
types. This allows WSDL to represent a wide range of messages that contain a
mixture of data formats, as is the case with multi-part MIME.

Table . Message
Exchange Patterns

MEP

Description

One-way

The endpoint
receives a message.

Request-response

The endpoint
receives a message and sends a correlated message.

Solicit-response

The endpoint sends
a message and receives a correlated message.

Notification

The endpoint sends
a message.

Figure 2: Messages and operations

Figure 3: Interfaces and bindings

Validating
the Custom Message Definition

You can validate the encoding rules,
along with the message definition in XML format, by clicking the validation
button in the XSD Editor. If encoding rules are present, they are validated following
validation of the XML grammar and semantics. An example output showing multiple
errors is shown in the following figure.

Figure 20
Example Validation Result

SOAP, originally defined as Simple Object Access Protocol,
is a protocol specification for exchanging
structured information in the implementation of Web Services
in computer networks. It relies on Extensible Markup Language
(XML) for its message format, and usually relies on other Application
Layer protocols, most notably Remote Procedure Call (RPC) and Hypertext Transfer Protocol (HTTP), for
message negotiation and transmission. SOAP can form the foundation layer of a web services protocol stack, providing a
basic messaging framework upon which web services can be built. This XML based
protocol consists of three parts: an envelope, which defines what is in the
message and how to process it, a set of encoding rules for expressing instances
of application-defined datatypes, and a convention for representing procedure
calls and responses.

As an
example of how SOAP procedures can be used, a SOAP message could be sent to a
web-service-enabled web site such as a real-estate price database, with the
parameters needed for a search. The site would then return an XML-formatted
document with the resulting data, e.g., prices, location, features. With the
data being returned in a standardized machine-parseable format, it can then be
integrated directly into a third-party web site or application.

The SOAP
architecture consists of several layers of specifications: for message format, Message Exchange Patterns (MEP),
underlying transport protocol bindings, message processing models, and protocol
extensibility. SOAP is the successor of XML-RPC,
though it borrows its transport and interaction neutrality and the
envelope/header/body from elsewhere (probably from WDDX).

Message format

XML was chosen as the
standard message format because of its widespread use by major corporations and
open source
development efforts. Additionally, a wide variety of freely available tools significantly eases the transition
to a SOAP-based implementation. The somewhat lengthy syntax of XML can be both a benefit
and a drawback. While it promotes readability for humans, facilitates error
detection, and avoids interoperability problems such as byte-order (Endianness),
it can slow processing speed and can be cumbersome. For example, CORBA, GIOP, ICE, and DCOM use much shorter,
binary message formats. On the other hand, hardware appliances are available to
accelerate processing of XML
messages Binary XML
is also being explored as a means for streamlining the throughput requirements
of XML.

Example
message

POST
/InStock HTTP/1.1

Host:
www.example.org

Content-Type:
application/soap+xml; charset=utf-8

Content-Length:
299

SOAPAction:
"http://www.w3.org/2003/05/soap-envelope"

<?xml version="1.0"?>

<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope">

<soap:Header>

</soap:Header>

<soap:Body>

<m:GetStockPrice
xmlns:m="http://www.example.org/stock">

<m:StockName>IBM</m:StockName>

</m:GetStockPrice>

</soap:Body>

</soap:Envelope>

12 SEGMENTS

Creating
File Segmentation Rules

To
set up a file segmentation rule, click Options > Preferences in dtSearch and
select the "File Segmentation Rules" tab. Each rule has the following
parts:

Name

The
name of a rule is used only to identify it in the File Segmentation Rules
dialog box.

New
document starts at

This
is a marker that indicates when a new document begins. For email message files,
this is often part of a message header such as "Date:" or
"From:". To avoid incorrectly splitting a message, this marker should
be as unique as possible.

How
to check for document boundaries in text

Each
line of the files a rule applies to will be compared against the marker under New document starts at. Three types of
comparison are available:

Require
exact match The entire line must exactly
match the marker.

Match
start of line The start of the line must match
the marker.

Match
regular expression The marker is interpreted as a
regular expression. A document boundary occurs when the marker is found
anywhere in a line. To require a marker to begin at the start of a line,
precede it with the ^ character.

Ignore
case

Match a document boundary even if the capitalization does not match.

First segment in a file is header for other segments
Check
this box to have dtSearch insert the first segment in a file in every following
segment. This option is useful when segmenting XML or HTML files, because it
allows the HTML or XML header to be repeated for each segment.

Filename
filters

For
each rule, a filename filter determines which files the rule applies to. If
more than one rule could apply to a particular file, the first one to match the
filename is the one applied. A rule that does not  have a filter will be
ignored.

Segmenting
XML and HTML

If you use File Segmentation Rule with XML or HTML
files, use the First segment in a file is header for other segments checkbox so
the XML or HTML header will be included for each segment. Otherwise, each
segment will lack the <html> or <?xml> header that is necessary for
correct identification of the file type.

Segment markers for XML and HTML are Based on the
raw text in the file, including tags and comments. For example, suppose you
have an HTML file that looks like this:

<html>

<body>

<h3>Sample File</h3>

<!-- Segment -->

<p>This is the first segment</p>

<!-- Segment -->

<p>This is the second segment</p>

<!-- Segment -->

<p>This is the third segment</p>

You could use "<!-- Segment -->" the
marker separating segments, even though these comments are not visible when you
open an HTML file in dtSearch. Using this marker, and setting the option to
make the first segment a header for the other segments, dtSearch would index
the HTML file as three separate HTML documents:

<html>

<body>

<h3>Sample File</h3>

<!-- Segment -->

<p>This is the first segment</p>

<html>

<body>

<h3>Sample File</h3>

<!-- Segment -->

<p>This is the second segment</p>

<html>

<body>

<h3>Sample File</h3>

<!-- Segment -->

<p>This is the third segment</p>

Developer
Information

File segmentation rules are stored in an XML file
named fileseg.xml.  You can create this file using the dtSearch
Desktop GUI or by writing the XML in a program. To tell the dtSearch Engine to
use file segmentation rules in your application, use the SegmentationRulesFile
property of the Options object (.NET, COM, or Java), or the
segmentationRulesFile member of dtsOptions (C++).

To obtain the text of a segment, you can use the
FileConverter object or DFileConvertJob and pass in the name of a segment, as
retrieved in a search, as the filename.

How
to Unmarshal raw XML segments into arbitrary types

Basic
concept

<root>

<xmlnode
attribute="misc xml data">

<data>Data
1</data>

<data>Data
2</data>

</xmlnode>

<string>Regular
String Data</string>

<xmlnode2>

<misc>Misc
xml to be dealt with later</misc>

</xmlnode2>

</root>

And you
want to save off portions of this XML in your objects, instead of having Castor
map them immediately.

package bizobj;

public class Root {

private
Object anyType;

private
String stringData;

private
String stringXML;

public
Object getAnyType() {

return
anyType;

}

public
void setAnyType(Object anyType) {

this.anyType
= anyType;

}

public
String getStringData() {

return
stringData;

}

public
void setStringData(String stringData) {

this.stringData
= stringData;

}

public
String getStringXML() {

return
stringXML;

}

public
void setStringXML(String stringXML) {

this.stringXML
= stringXML;

}

}

There
are two approaches that can be used for this. The first, approach would be to
use the AnyNode type. The benefits of this approach is that you do not have to
do anything special to get the data in the mapping file, and can both unmarshal
and marshal the xml data. The drawback is that you have to call toString() on
the object to get the XML.

The second approach is to use a custom FieldHandler
implementation to convert the values. The benefit of this approach is that you
are able to convert into any type you want. The drawback is that there is
currently no way to marshal the xml data back into XML. It ends up as XML
encoded data inside the marshalled XML.

Mapping
file

Here is an example mapping file that includes both
examples.

<?xml version="1.0"?>

<!DOCTYPE mapping PUBLIC "-//EXOLAB/Castor
Mapping DTD Version 1.0//EN"

"http://castor.org/mapping.dtd">

<mapping>

<class
name="bizobj.Root">

<field
name="anyType" type="java.lang.Object">

<bind-xml
name="xmlnode" node="element" />

</field>

<field
name="stringData" type="string">

<bind-xml
name="string" node="element" />

</field>

<field
name="stringXML" type="java.lang.Object"
handler="MyHandler">

<bind-xml
name="xmlnode2" node="element" />

</field>

</class>

</mapping>

The
anyType field is set to java.lang.Object. Behind the scenes it is actually an
AnyType object.

Also, notice that the stringXML field is of type
java.lang.Object. This is because Castor looks at that first to determine what
type of parsing needs to be done, then passes it on to the Field Handler, which
converts it into whatever is desired.

Here is an example Field Handler that converts the
input into a string.

import
org.exolab.castor.mapping.GeneralizedFieldHandler;

public class MyHandler extends
GeneralizedFieldHandler {

public
Object convertUponGet(Object value) {

return
(value == null) ? null : value.toString();

}

public
Object convertUponSet(Object value) {

return
(value == null) ? null : value.toString();

}

public
Class getFieldType() {      return
String.class; }

}

13 MAPPING

Castor
XML Mapping

The
Mapping File

The following sections define the syntax for each of
the mapping file artefacts and their semantical meaning.

Sample
domain objects

This section defines a small domain model that will
be referenced by various mapping file (fragments/samples) in the following
sections. The model consists of two two classes Order and OrderItem, where an
order holds a list of order items.

public class Order {

private List orderItems;

private String orderNumber;

public List getOrderItems() {

return
orderItems;

}

public void setOrderItems(List orderItems) {

this.orderItems = orderItems;

}

public String getOrderNumber() {

return orderNumber;

}

public void setOrderNumber(String orderNumber) {

this.orderNumber = orderNumber;

}

}

public class OrderItem {

private String id;

private Integer orderQuantity;

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public Integer getOrderQuantity() {

return orderQuantity;

}

public void setOrderQuantity(Integer orderQuantity) {

this.orderQuantity = orderQuantity;

}

}

As shown
above in bold, the Order instance has a (private) field 'orderItems' to hold a collection
of OrderItem instances. This field is publically exposed by corresponding
getter and setter methods.

The
<mapping> element

<!ELEMENT mapping ( description?, include*, field-handler*, class*,
key-generator* )>

The <mapping> element is the root element of a
mapping file. It contains:

- an
optional description

- zero or more <include> which facilitates
reusing mapping files

- zero of more <field-handler> defining
custom, configurable field handlers

- zero or more <class> descriptions: one for
each class we intend to give mapping information

- zero or more <key-generator>: not used for
XML mapping

A mapping file look like this:

<?xml version="1.0"?>

<!DOCTYPE mapping PUBLIC "-//EXOLAB/Castor
Mapping DTD Version 1.0//EN"

castor.org

"http://castor.org/mapping.dtd">

<mapping>

<description>Description
of the mapping</description>

<include
href="other_mapping_file.xml"/>

<!--
mapping for class 'A' -->

<class
name="A">

.........

</class>

<!--
mapping for class 'B' -->

<class
name="B">

.........

</class>

</mapping>

The <class> element

<!ELEMENT class ( description?, cache-type?,
map-to?, field+ )>

<!ATTLIST class

name
ID
#REQUIRED

extends
IDREF    #IMPLIED

depends
IDREF    #IMPLIED

auto-complete   ( true
|false ) "false"

identity
CDATA    #IMPLIED

access
( read-only | shared | exclusive | db-locked )  "shared"

key-generator
IDREF    #IMPLIED
>

The
<class> element contains all the information used to map a Java class
into an XML document. The content of <class> is mainly used to describe
the fields that will be mapped.

Description
of the attributes

Name
Description

name The fuly-qualified name of the Java class that
we want to map to.

extends The fully qualified name of a parent class.
This attribute should be used only if this class extends another class for
which a class mapping is provided. It should not be used if there's no class
maping for the extended class.

depends Used with Castor JDO only; for more
information on this field, please see the JDO documentation.

auto-complete If true, the class will be
introspected to determine its field and the fields specified in the mapping
file will be used to overide the fields found during the introspection.

identity Used with Castor JDO only; for more
information on this field, please see see the JDO documentation.

access Used with Castor JDO only; for more
information on this field, please see see the JDO documentation.

key-generator Used with Castor JDO only; for more
information on this field, please see see the JDO documentation.

The
auto-complete attributes is interesting as it allow a fine degree of control of
the introspector: it is possible to specifiy only the fields whose Castor
default behavior does not suite our needs. These feature should simplify the
handling of complexe class containing many fields. Please see below for an
example usage of this attribute.

Description
of the content

Name
Description

description An optional description.

cache-type Used with Castor JDO only; for more
information on this field, please see see the JDO documentation.

map-to Used if the name of the element is not the
name of the class. By default, Castor will infer the name of the element to be
mapped from the name of the class: a Java class named 'XxxYyy' will be
transformed in 'xxx-yyy'. If you don't want Castor to generate the name, you
need to use <map-to> to specify the name you want to use. <map-to>
is only used for the root element.

field Zero or more <field> elements, which are
used to describe the properties of the Java class being mapped.

Sample
<class> mappings

The following mapping fragment defines a class mapping
for the OrderItem class:

<class name="mypackage.OrderItem>

<map-to xml="item"/>

<field name="id" type="string">

<bind-xml
name="identity" node="attribute"/>

</field>

</field name="orderQuantity" type="integer">

<bind-xml
name="quantity" node="element"/>

</field>

</class>

When
marshalling an OrderItem instance, this yields the following XML:

<?xml version="1.0" ?>

<item identity="12">

<quantity>100</quantity>

</item>

The
following mapping fragment defines a class mapping for the same class, where
for all properties but id introspection should be used; the use of the
auto-complete attribute instructs Castor XML to use introspection for all
attributes other than 'id', where the given field mapping will be used.

<class name="mypackage.OrderItem
auto-complete="true">

<map-to xml="item"/>

<field name="id" type="string">

<bind-xml
name="identity" node="attribute"/>

</field>

</class>

When
marshalling the very same OrderItem instance, this yields the following XML:

<?xml version="1.0" ?>

<item identity="12">

<order-quantity>100</order-quantity>

</item>

By
removing the <map-to> element from above class mapping, ...

<class name="mypackage.OrderItem
auto-complete="true">

<field name="id" type="string">

<bind-xml
name="identity" node="attribute"/>

</field>

</class>

...
Castor will use introspection to infer the element name from the Java class
name (OrderItem), applying a default naming convention scheme.

When marshalling the very same OrderItem instance,
this yields the following XML:

<?xml version="1.0" ?>

<order-item identity="12">

<order-quantity>100</order-quantity>

</order-item>

The <map-to> element

<!ELEMENT map-to EMPTY>

<!ATTLIST map-to

table
NMTOKEN  #IMPLIED

xml
NMTOKEN  #IMPLIED

ns-uri
NMTOKEN  #IMPLIED

ns-prefix
NMTOKEN  #IMPLIED

ldap-dn
NMTOKEN  #IMPLIED

element-definition  (true|false)
"false"
NEW as of 1.0M3

ldap-oc
NMTOKEN  #IMPLIED>

<map-to> is used to specify the
name of the element that should be associated with the given class.
<map-to> is only used for the root class. If this information is not
present, Castor will:

- for
marshalling, infer the name of the element to be mapped from the name of the
class: a Java class named 'XxxYyy' will be transformed into 'xxx-yyy'.

- for unmarshalling, infer the name of the class
from the name of the element: for an element named 'test-element' Castor will
try to use a class named 'TestElement'

Please note that it is possible to change the naming
scheme used by Castor to translate between the XML name and the Java class name
in the castor.properties file.

Description
of attributes

xml Name
of the element that the class is associated to.

ns-uri Namespace URI

ns-prefix Desired namespace

element-definition True if the descriptor as created
from a schema definition that was of type element (as opposed to a
<complexType> definition). This only is useful in the context of source
code generation.

ldap-dn Not used for Castor XML

ldap-oc Not used for Castor XML

<map-to>
samples

The following mapping fragment defines a <map-to
element for the OrderItem class, manually setting the element name to a value
of 'item'.

<class name="myPackage.OrderItem">

...

<map-to xml="item" />

...

</class>

The following mapping fragment instructs Castor to
assign a namespace URI of http://castor.org/sample/mapping/ to the <item>
element, and use a namespace prefix of 'castor' during un-/marshalling.

<class name="myPackage.OrderItem">

...

<map-to xml="item"
ns-uri="http://castor.org/sample/mapping/"

ns-prefix="castor"/>

...

</class>

When
marshalling an OrderItem instance, this will yield the following XML:

<?xml version="1.0" ?>

<castor:order-item
xmlns:castor="http://castor.org/sample/mapping/"
identity="12">

<castor:order-quantity>100</castor:order-quantity>

</castor:order-item>

The <field> element

<!ELEMENT field ( description?, sql?, bind-xml?, ldap? )>

<!ATTLIST field

name
NMTOKEN  #REQUIRED

type
NMTOKEN  #IMPLIED

handler
NMTOKEN  #IMPLIED

required       ( true |
false )  "false"

direct
( true | false )
"false"

lazy
( true | false )
"false"

transient
( true | false )
"false"

nillable       ( true |
false )  "false"

container
( true | false )
"false"

get-method
NMTOKEN  #IMPLIED

set-method
NMTOKEN  #IMPLIED

create-method  NMTOKEN  #IMPLIED

collection     ( array | vector |
hashtable | collection | set | map )
#IMPLIED>

<field> is used to describe a property of a
Java object we want to marshal/unmarshal. It gives:

- its
identity ('name')

- its type (infered from 'type' and 'collection')

- its access method (infered from 'direct',
'get-method', 'set-method')

From this information, Castor is able to access a
given property in the Java class.

In order to determine the signature that Castor
expects, there are two easy rules to apply.

1. Determine <type>.

- If
there is no 'collection' attribute, the <type> is just the Java type
specified in <type_attribute> (the value of the 'type' attribute in the
XML document). The value of <type_attribute> can be a fully qualified
Java object like 'java.lang.String' or one of the allowed short name:

short
name Primitive type? Java Class

other N java.lang.Object

string N java.lang.String

integer Y java.lang.Integer.TYPE

long Y java.lang.Long.TYPE

boolean Y java.lang.Boolean.TYPE

double Y java.lang.Double.TYPE

float Y java.lang.Float.TYPE

big-decimal N java.math.BigDecimal

byte Y java.lang.Byte.TYPE

date N java.util.Date

short Y java.lang.Short.TYPE

char Y java.lang.Character.TYPE

bytes N byte[]

chars N char[]

strings N String[]

locale N java.util.Locale

Castor
will try to cast the data in the XML file in the proper Java type.

- If
there is a collection attribute, you can use the following table:  name <type> default implementation

array <type_attribute>[]
<type_attribute>[]

arraylist java.util.List java.util.Arraylist

vector java.util.Vector java.util.Vector

hashtable java.util.Hashtable java.util.Hashtable

collection java.util.Collection
java.util.Arraylist

set java.util.Set java.util.Hashset

map java.util.Map java.util.Hashmap

sortedset java.util.SortedSet java.util.TreeSet

The type of the object inside the collection is
<type_attribute>. The 'default implementation' is the type used if the
object holding the collection is found to be null and need to be instantiated.

For hashtable and maps (since 0.9.5.3), Castor will
save both key and values. When marshalling output <key> and <value>
elements. These names can be controlled by using a top-level or nested class
mapping for the org.exolab.castor.mapping.MapItem class.

Note: for backward compatibility with prior versions
of Castor, the saveMapKeys property can be set to false in the
castor.properties file.

For versions prior to 0.9.5.3, hashtable and maps,
Castor will save only the value during marshalling and during unmarshalling
will add a map entry using the object as both the key and value, e.g.
map.put(object, object).

It is necessary to use a collection when the content
model of the element expects more than one element of the specified type.

2. Determine the signature of the function

If 'direct' is set to true, Castor expects to find a
class variable with the given signature:

public <type> <name>;

If 'direct' is set to false or omitted, Castor will access the property
though accessor methods. Castor determines the signature of the accessors as
follow: If the 'get-method' or 'set-method' attributes are supplied, it will
try to find a function with the following signature:

public <type> <get-method>();

or

public void <set-method>(<type> value);

If 'get-method' and 'set-method' attributes are not
provided, Castor will try to find the following function:

public <type> get<capitalized-name>();

or

public void set<capitalized-name>(<type> value);

<capitalized-name> means that Castor takes the
<name> attribute and put its first letter in uppercase without modifying
the other letters.

The content of <field> will contain the
information on how to map this given field to SQL, XML.

Exceptions
concerning collection fields:

The default is to treat the 'get-method' as a simple
getter returning the collection field, and the 'set-method' as a simple getter
used to set a new instance on the collection field.

Parameter
Description

'get-method' If a 'get-method' is provided for a
collection field, Castor - in adition to the default behaviour described above
- will deviate from the standard case for the following special prefixes:

public Iterator iterate...();

A 'get-method' starting with the prefix 'iterate' is
treated as Iterator method for the given collection field.

public Enumeration enum...();

A 'get-method' starting with 'enum' is treated as
Enumeration method for the given collection field.

'set-method' If 'set-method' is provided for a
collection field, Castor - in addition to the default behaviour described above
- will accept an 'add' prefix and expect the following signature:

public void add...(<type> value);

This method is called for each collection element
while unmarshalling.

Description
of the attributes

Name Description

name The field 'name' is required even if no such
field exists in the class. If 'direct' access is used, 'name' should be the
name of a public instance member in the object to be mapped (the field must be
public, not static and not transient). If no direct access and no
'get-/set-method' is specified, this name will be used to infer the name of the
accessors methods.

type The Java type of the field. It is used to
access the field. Castor will use this information to cast the XML information
(like string into integer). It is also used to define the signature of the
accessor methods. If a collection is specified, this is used to specify the
type of the objects held by the collection. See description above for more
details.

required A field can be optional or required.

nillable A field can be of content 'nil'.

transient If true, this field will be ignored during
the marshalling. This is usefull when used together with the
auto-complete="true" option.

direct If true, Castor will expect a public variable
in the containing class and will access it directly (for both reading and
writing).

container Indicates whether the field should be
treated as a container, i.e. only it's fields should be persisted, but not the
containing class itself. In this case, the container attribute should be set to
true (supported in Castor XML only).

collection If a parent expects more than one
occurrence of one of its element, it is necessary to specify which collection
Castor will use to handle them. The type specified is used to define the type
of the content inside the collection.

get-method Optional name of the 'get method' Castor
should use. If this attribute is not set and the set-method attribute is not
set, then Castor will try to infer the name of this method with the algorithm
described above.

set-method Optional name of the 'set method' Castor
should use. If this attribute is not set and the get-method attribute is not
set, then Castor will try to infer the name of this method with the algorithm described
above.

create-method Optionally defines a factory method
for the instantiation of a FieldHandler

handler If present, specifies one of the following:

The fully-qualified class name of a custom field
handler implementation, or

The (short) name of a configurable field handler
definition.

Description
of the content

In the case of XML mapping, the content of a field
element should be one and only one <bind-xml> element describing how this
given field will be mapped into the XML document.

Mapping
constructor arguments (since 0.9.5)

Starting with release 0.9.5, for attribute mapped
fields, support has been added to map a constructor field using the set-method
attribute.

To specify that a field (mapped to an attribute)
should be used as a constructor argument during object initialization, please
specify a set-method attribute on the <field> mapping and use
"%1" - "%9" as the value of the set-method attribute.

For example:

<field name="foo"
set-method="%1" get-method="getFoo"
type="string">

<bind-xml node="attribute"/>

</field>

Note
that because the set-method is specified, the get-method also must be
specified.

Tip: the XML HOW-TO section has a HOW-TO document
for mapping constructor arguments, incl. a fully working mapping.

Sample 1: Defining a custom field handler

The following mapping fragment defines a
<field> element for the member property of the org.some.package.Root
class, specifying a custom FieldHandler implementation.

<class name="org.some.package.Root">

<field name="member" type="string"
handler="org.some.package.CustomFieldHandlerImpl"/>

</class>

Sample 2: Defining a custom configurable field
handler

The same custom field handler as in the previous
sample can be defined with a separate configurable <field-handler>
definition, where additional configuration can be provided.

<field-handler name="myHandler"
class="org.some.package.CustomFieldHandlerImpl">

<param name="date-format"
value="yyyyMMddHHmmss"/>

</field-handler>

and
subsequently be referred to by its name as shown in the following field
mapping:

<class name="org.some.package.Root">

<field name="member" type="string"
handler="myHandler"/>

</class>

Sample
3: Using the container attribute

Assume you have a class mapping for a class Order
which defines - amongst others - a field mapping as follows, where the field
item refers to an instance of a class Item.

<class name="some.example.Order">

...

<field name="item" type="some.example.Item" >

<bind-xml>
name="item" node="element" />

</field>

...

</class>

<class name="some.example.Item">

<field name="id" type="long" />

<field name="description" type="string" />

</class>

Marshalling an instance of Order would
produce XML as follows:

<order>

...

<item>

<id>100</id>

<description>...</description>

</item>

</order>

If you
do not want the Item instance to be marshalled, but only its fields, change the
field mapping for the item member to be as follows:

<field name="item"
type="some.example.Item" container="false" >

<bind-xml> name="item" node="element" />

</field>

The
resulting XML would look as follows:

<order>

...

<id>100</id>

<description>...</description>

</order>

The
<bind-xml> element

Grammar

<!ELEMENT bind-xml (class?, property*)>

<!ATTLIST bind-xml

name
NMTOKEN
#IMPLIED

type
NMTOKEN
#IMPLIED

location CDATA       #IMPLIED

matches  NMTOKENS    #IMPLIED

QName-prefix NMTOKEN #IMPLIED

reference   ( true |
false ) "false"

node        (
attribute | element | text )
#IMPLIED

auto-naming ( deriveByClass | deriveByField ) #IMPLIED

transient   ( true |
false ) "false">

Definiton

The <bind-xml> element is used to describe how
a given Java field should appear in an XML document. It is used both for
marshalling and unmarshalling.

Description
of the attributes:

name The
name of the element or attribute.

Note: The name is a QName, and a namespace prefix
may be used to indicate the element or attribute belongs to a certain
namespace. Note the prefix is not preserved or used during marshalling, it's
simply used for qualification of which namespace the element or attribute
belongs.

auto-naming If no name is specified, this attribute
controls how castor will automatically create a name for the field. Normally,
the name is created using the field name, however many times it is necessary to
create the name by using the class type instead (such as heterogenenous
collections).

type XML Schema type (of the value of this field)
that requires specific handling in the Castor Marshalling Framework (such as
'QName' for instance).

location

(since 0.9.4.4) Allows the user to specify the
"sub-path" for which the value should be marshalled to and from. This
is useful for "wrapping" values in elements or for mapping values
that appear on sub-elements to the current "element" represented by
the class mapping. For more information, see the Location attribute below.

QName-prefix When the field represents a QName
value, a prefix can be provided that is used when marshalling value of type
QName. More information on the use of 'QName-prefix' can be found in the
SourceGenerator Documentation

reference Indicates if this field has to be treated
as a reference by the unmarshaller. In order to work properly, you must specify
the node type to 'attribute' for both the 'id' and the 'reference'. In newer
versions of Castor, 'element' node for reference is allowed. Remember to make
sure that an identity field is specified on the <class> mapping for the
object type being referenced so that Castor knows what the object's identity
is.

matches Allows overriding the matches rules for the
name of the element. It is a standard regular expression and will be used
instead of the 'name' field. A '*' will match any xml name, however it will
only be matched if no other field exists that matches the xml name.

node Indicates if the name corresponds to an
attribute, an element, or text content. By default, primitive types are assumed
to be an attribute, otherwise the node is assumed to be an elemen

transient Allows for making this field transient for
XML. The default value is inherited from the <field> element.

Nested class mapping

Since 0.9.5.3, the bind-xml element supports a
nested class mapping, which is often useful when needing to specify more than
one mapping for a particular class. A good example of this is when mapping
Hashtable/HashMap/Map.

Example

<bind-xml ...>

<class name="org.exolab.castor.mapping.MapItem">

<field
name="key" type="java.lang.String">

<bind-xml name="id"/>

</field>

<field
name="value" type="com.acme.Foo"/>

</class>

</bind-xml>

14
MESSAGE STRUCTURE AND ELECTRONIC ENVELOPING

Structure
of an XML Message

In the context of Microsoft BizTalk Server, an XML
instance message is a valid hierarchy of XML tags that together constitute zero
or more XML envelopes and one or more XML documents. For example, the following
XML instance message consists of a single XML envelope (in regular font) that contains
a single XML document (shown in bold type).

<ns0:envelope
xmlns:ns0="http://myEnvelopeNamespaceURI.org">

<header>

<firstName>John</firstName>

<lastName>Scott</lastName>

</header>

<body>

<ns1:document xmlns:ns1="http://myDocumentNamespaceURI.org">

<message>Hello</message>

</ns1:document>

</body>

</ns0:envelope>

XML envelopes and the XML documents that they
contain can be combined into valid XML instance messages in several different
ways. The remainder of this section describes these different combinations.

XML
Message Envelopes

XML envelopes serve two purposes within XML instance
messages sent and received by Microsoft BizTalk Server:

XML envelopes can contain data that supplements the
data within the XML documents. This data can be promoted into the message
context by the XML disassembler to provide easier access from a variety of
BizTalk Server components. For outbound XML instance messages, the XML
assembler can demote values from the message context into an envelope for
inclusion in the instance message transmission.

XML envelopes can be used to combine multiple XML
documents into a single, valid XML instance message. Without an envelope to
wrap multiple documents within a single root tag, an XML instance message
containing multiple documents would not qualify as well-formed XML.

A typical XML envelope (shown in bold type) contains
both data and a tag used to delimit the one or more XML documents (shown in
regular font) that it contains.

<envelope fieldAttrib1="..."
fieldAttrib2="..." ...>

<fieldElem1>...</fieldElem1>

<fieldElem2>...</fieldElem2>

...

<body>

<document1>

...

</document1>

<document2>

...

</document2>

...

</body>

...

</envelope>

Less common, but still valid, an XML envelope (shown
in bold type) need not contain any data or a tag for delimiting the XML
documents (shown in regular type) that it contains.

Copy

<envelope>

<document1>

...

</document1>

<document2>

...

</document2>

...

</envelope>

In such cases, the XML envelope consists of nothing
other than the starting and ending envelope tags.

Nested
XML Message Envelopes

XML envelopes can be nested to create complex
document structures. Nested XML envelopes can occur in two forms, known as
flexible and canonical. The following example shows the flexible form of
enveloped documents, in which documents and envelopes (shown in bold type) can
appear at the same level within an enclosing envelope.

<envelope1>

<document1/>

<envelope2>

<document2/>

<document3/>

</envelope2>

<document4/>

</envelope1>

The following example shows a similar instance
message that conforms to the canonical form of enveloped documents, in which
all documents appear at the same level within the innermost envelope.

<envelope1>

<envelope2>

<document1/>

<document2/>

<document3/>

<document4/>

</envelope2>

</envelope1>

Given an instance message in either of the forms
described, the XML disassembler will produce document1, document2, document3,
and document4. The message context of each of these documents includes the
properties promoted from the corresponding document as well as the properties
promoted within each of the enclosing envelopes. The following table shows the
promoted properties that will be include in the message context of each
unwrapped documents for both the flexible and canonical examples, given the
property promotions specified in the first column for the various envelopes and
documents.

Specified property
promotions

Resulting message
context properties for flexible example

Resulting message
context properties for canonical example

envelope1: p1

envelope2: p3

document1: p2

document2: p4 and p5

document3: no
promotions

document4: no
promotions

document1: p1, p2

document2: p1, p3, p4,
p5

document3: p1, p3

document4: p1

How
to Create Schemas for Envelopes

After creating an XML message schema as described in
Creating
Schemas for XML Messages, set the Envelope
property of the Schema node to Yes. Depending on certain
characteristics of your envelope schema, such as whether there are multiple
root nodes, you will need to set several other envelope-specific properties.
For more information, see Envelope
Schemas.

The body XPath property of the envelope points to
the element that contains the document elements. The actual element where the
XPath points to does not belong to the document.

The dss:SignRequest element indicates to the
system that it is an electronic signature request. In turn, this element
contains all the desired optional elements, e.g. the css:Name element indicates
the signer certificate – in this case the format is Distinguished Name/X509SubjectName.  In addition, the css:KeyInfoType
element with the X509SubjectName format is used, to indicate that the response
request will return key information in the Distinguished Name/X509SubjectName
format. As we are signing a document, we must add the dss:Document
element, which includes the XML document that is to be signed. And finally, as
you can see in the example, the type of XML digital signature has not been
explicitly included. By this, it is understood that a detached electronic
signature from the original document is being requested in the response.

Later, in other electronic signature requests, we
will show the other two types of requests possible with an XML digital
signature, i.e. the electronic signature request type for adding the resulting
electronic signature inside the original document, known as enveloped electronic
signature, and the electronic signature request type for adding the document
inside the generated electronic signature, known as enveloping electronic
signature.

<?xml version="1.0"
encoding="UTF-8"?>

<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">

<SOAP-ENV:Header><wsse:Security><wsse:UsernameToken
wsu:Id="SecurityToken-4505729303387484391"><wsse:Username>trustedx</wsse:Username><wsse:Password
Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">trustedx</wsse:Password></wsse:UsernameToken></wsse:Security></SOAP-ENV:Header>

<SOAP-ENV:Body
wsu:Id="Id-9027040566202249815">

<dss:SignRequest
xmlns:css="http://www.safelayer.com/TWS"
xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
xmlns:dss="http://www.docs.oasis-open.org/dss/2004/06/oasis-dss-1.0-core-schema-wd-27.xsd"
xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion"
xmlns:xades="http://uri.etsi.org/01903/v1.2.2#"
Profile="urn:safelayer:tws:dss:1.0:profiles:xades:1.0:sign"
RequestID="Id-2828846405853607976">

<dss:OptionalInputs><dss:KeySelector><css:KeySelector><css:Name
Format="urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName">CN=trustedx,
OU=Demo, O=TrustedX,
C=ES</css:Name></css:KeySelector></dss:KeySelector><css:AddSignatureKeyInfo><css:KeyInfoType>X509SubjectName</css:KeyInfoType></css:AddSignatureKeyInfo></dss:OptionalInputs><dss:InputDocuments><dss:Document><dss:XMLData><trustedx
Id="data"><example Id="node1">Simple xml
file</example><description Id="node2"
format="text">XMLDSig/XAdES TrustedX
signatures</description></trustedx></dss:XMLData></dss:Document></dss:InputDocuments></dss:SignRequest>

</SOAP-ENV:Body>

</SOAP-ENV:Envelope>

The
following explanation refers to the response that the TrustedX platform obtains
once the request has been sent. Therefore, you should press the "try"
button (above) to generate this response. Firstly, the electronic signature (dsig:Signature)
has been produced using the XML format. We can see that it is a detached electronic
signature, due to the fact that the dsig:Object
element does not contain the document to be signed. Otherwise, it would be an enveloping
electronic signature. An XML digital signature is made up of various parts, the
first being a reference (dsig:Reference)
from the electronic signature to the signed data. This reference is indicated
in the URI="#data"
attribute. As a means of checking that the data presented from the reference
always match, canonicalization or c14n (dsig:Transform) is used, in this case
exclusive canonicalization. This ensures that all possible XML representations
of the same document match. Once the document has been canonicalized, a hash is
generated and placed in the dsig:DigestValue
element. There is a second reference that performs the same operations;
however, in this case using the signed properties (xades:SignedProperties).
The value of the electronic signature can be found in the dsig:SignatureValue
element.

Given
that the optional element, css:AddSignatureKeyInfo,
was included in the electronic signature request, in the response, we can now
see who the document signer is (dsig:KeyInfo).
In particular, in this case, the style is Distinguished Name/X509SubjectName.

UNIT III

JAVA WEBSERVICES ARCHITECTURE

Web service overview

A Web service is a set of related application functions that can
be programmatically invoked over the Internet. Businesses can dynamically mix
and match Web services to perform complex transactions with minimal
programming. Web services allow buyers and sellers all over the world to
discover each other, connect dynamically, and execute transactions in real time
with minimal human interaction.

Web services are self-contained, self-describing modular
applications that can be published, located, and invoked across the Web.

Web services are self-contained.
On the client side, no additional software is required.  A programming
language with XML and HTTP client support is enough to get you started.
On the server side, a Web server and servlet engine are required.  The
client and server can be implemented in different environments.  It is
possible to Web service enable an existing application without writing a single
line of code.

Web services are self-describing. The client and server need to recognize only the format and
content of request and response messages.  The definition of the message
format travels with the message; no external metadata repositories or code
generation tools are required.

Web services are modular. Simple
Web services can be aggregated to form more complex Web services either by
using workflow techniques or by calling lower layer Web services from a Web
service implementation.

Web Services are platform independent. Web services are based on a concise set of open, XML-based
standards designed to promote interoperability between a Web service and
clients across a variety of computing platforms and programming languages.

Web services might be anything, for example, theatre review
articles, weather reports, credit checks, stock quotations, travel advisories,
or airline travel reservation processes. Each of these self-contained business
services is an application that can easily integrate with other services, from
the same or different companies, to create a complete business process. This
interoperability allows businesses to dynamically publish, discover, and bind a
range of Web services through the Internet.

Service oriented
architecture

Service-oriented architecture (SOA) is
a flexible set of design principles used during the phases of systems development and integration in computing.
A system based on a SOA will package functionality as a suite of interoperable
services that can be
used within multiple, separate systems from several business domains.

SOA also generally provides a way for consumers of
services, such as web-based applications, to be aware of available SOA-based
services. For example, several disparate departments within a company may develop
and deploy SOA services in different implementation languages; their respective
clients will benefit from a well understood,
well defined interface to access them. XML is commonly used for
interfacing with SOA services, though this is not required.

SOA defines how to integrate widely disparate
applications for a Web-based environment and uses multiple implementation
platforms. Rather than defining an API, SOA defines the interface in terms of protocols and
functionality. An endpoint is the entry point for such a SOA
implementation.

Service-orientation requires loose
coupling of services with operating
systems, and other technologies that underlie applications. SOA
separates functions into distinct units, or services,[1]
which developers make accessible over a network in order to allow users to
combine and reuse them in the production of applications. These services and
their corresponding consumers communicate with each other by passing data in a
well-defined, shared format, or by coordinating an activity between two or more
services.

SOA can be seen in a continuum, from older concepts of distributed computing[1][3]
and modular programming, through SOA, and on to
current practices of mashups, SaaS, and Cloud
Computing (which some see as the offspring of SOA).

Overview

The SOA implementations rely
on a mesh of software services. Services comprise unassociated, loosely
coupled units of functionality that have no calls
to each other embedded in them. Each service implements one action, such as
filling out an online application for an account, or viewing an online bank
statement, or placing an online booking or airline ticket order. Rather than
services embedding calls to each other in their source code, they use defined
protocols that describe how services pass
and parse messages using description metadata.

SOA developers associate
individual SOA objects by using orchestration. In the process of
orchestration the developer associates software functionality (the services) in
a non-hierarchical arrangement using a software tool that contains a complete
list of all available services, their characteristics, and the means to build
an application utilizing these sources.

Underlying and enabling all
of this requires metadata in sufficient detail to describe not only the
characteristics of these services, but also the data that drives them. Programmers
have made extensive use of XML in SOA to structure data that they wrap in a nearly
exhaustive description-container. Analogously, the Web Services Description Language
(WSDL) typically describes the services themselves, while the SOAP
protocol describes the communications protocols. Whether these description
languages are the best possible for the job, and whether they will
become/remain the favorites in the future, remain open questions. As of 2008[update]
SOA depends on data and services that are described by metadata that should
meet the following two criteria:

The metadata
should come in a form that software systems can use to configure
dynamically by discovery and incorporation of defined services, and also
to maintain coherence and integrity. For example, metadata could be used
by other applications, like a catalogue, to perform autodiscovery of
services without modifying the functional contract of a service.

The metadata
should come in a form that system designers can understand and manage with
a reasonable expenditure of cost and effort.

SOA aims to allow users to
string together fairly large chunks of functionality to form ad hoc
applications that are built almost entirely from existing software services.
The larger the chunks, the fewer the interface points required to implement any
given set of functionality; however, very large chunks of functionality may not
prove sufficiently granular for easy reuse. Each interface brings with it some
amount of processing overhead, so there is a performance consideration in
choosing the granularity of services. The great promise of SOA suggests that
the marginal cost
of creating the n-th application is low, as all of the software required
already exists to satisfy the requirements of other applications. Ideally, one
requires only orchestration to produce a new application.

For this to operate, no
interactions must exist between the chunks specified or within the chunks
themselves. Instead, humans specify the interaction of services (all of them
unassociated peers) in a relatively ad hoc way with the intent driven by
newly emergent requirements. Thus the need for services as much larger units of
functionality than traditional functions or classes, lest the sheer complexity
of thousands of such granular objects overwhelm the application designer.
Programmers develop the services themselves using traditional languages like Java, C, C++, C#, Visual Basic,
COBOL,
or PHP.

SOA services feature loose
coupling, in contrast to the functions that a linker binds together
to form an executable,
to a dynamically linked library or to an
assembly. SOA services also run in "safe" wrappers (such as Java
or .NET)
and in other programming languages that manage memory allocation and
reclamation, allow ad hoc and late binding, and provide some degree of
indeterminate data typing.

As of 2008[update],
increasing numbers of third-party software companies offer software services
for a fee. In the future, SOA systems may[original research?]
consist of such third-party services combined with others created in-house.
This has the potential to spread costs over many customers and customer uses,
and promotes standardization both in and across industries. In particular, the
travel industry now has a well-defined and documented set of both services and
data, sufficient to allow any reasonably competent software engineer to create
travel-agency software using entirely off-the-shelf software services.[5]
Other industries, such as the finance industry, have also started making
significant progress in this direction.

SOA as an architecture relies
on service-orientation as its fundamental design
principle.[6]
If a service presents a simple interface that abstracts away its underlying
complexity, users can access independent services without knowledge of the
service's platform implementation.[7]

Requirements

In order to efficiently use a
SOA, the architecture must meet the following requirements:

Interoperability
among different systems and programming languages that provides the basis
for integration between applications on different platforms through a
communication protocol. One example of such communication depends on the
concept of messages. Using
messages across defined message channels decreases the complexity of the
end application, thereby allowing the developer of the application to
focus on true application functionality instead of the intricate needs of
a communication protocol.

Desire to
create a federation of resources. Establish and maintain data flow to a Federated database system.
This allows new functionality developed to reference a common business
format for each data element.

Principles

The following guiding
principles define the ground rules for development, maintenance, and usage
of the SOA[8]:

reuse, granularity,
modularity, composability,
componentization and interoperability.

standards-compliance
(both common and industry-specific).

services
identification and categorization, provisioning and delivery, and
monitoring and tracking.

The first publicly published
research of service-orientation from an industry perspective was provided by Thomas Erl of SOA Systems
Inc. who defined eight specific service-orientation
principles common to all primary SOA platforms. These principles
were published in “Service-Oriented Architecture: Concepts, Technology,
and Design”, on the www.soaprinciples.com research site, and in the
September 2005 edition of the Web Services Journal (see Service-orientation).

Standardized
Service Contract – Services adhere to a communications agreement, as defined
collectively by one or more service-description documents.

Service Loose Coupling – Services maintain a relationship that
minimizes dependencies and only requires that they maintain an awareness
of each other.

Service Abstraction – Beyond descriptions in the service
contract, services hide logic from the outside world.

Service Reusability – Logic is divided into services with the
intention of promoting reuse.

Service Autonomy – Services have control over the logic they
encapsulate.

Service Granularity – A design consideration to provide optimal
scope and right granular level of the business functionality in a service
operation.

Service Statelessness - Services minimize resource consumption by
deferring the management of state information when necessary

Service Discoverability – Services are supplemented with
communicative meta data by which they can be effectively discovered and
interpreted.

Service Composability – Services are effective composition
participants,regardless of the size and complexity of the composition.

Some authors also include the
following principles:

Service
Optimization
– All else equal, high-quality services are generally preferable to
low-quality ones.

Service
Relevance
– Functionality is presented at a granularity recognized by the user
as a meaningful service.

Service Encapsulation – Many services are consolidated for use
under the SOA. Often such services were not planned to be under SOA.

Service
Location Transparency – This refers to the ability of a service consumer to invoke a
service regardless of its actual location in the network. This also
recognizes the discoverability property (one of the core principle of SOA)
and the right of a consumer to access the service. Often, the idea of
service virtualization also relates to location transparency. This is
where the consumer simply calls a logical service while a suitable
SOA-enabling runtime infrastructure component, commonly a service bus,
maps this logical service call to a physical service.

The following references
provide additional considerations for defining a SOA implementation:

SOA
Reference Architecture provides a working design of an
enterprise-wide SOA implementation with detailed architecture diagrams,
component descriptions, detailed requirements, design patterns,
opinions about standards, patterns on regulation compliance, standards
templates etc.[9]

Life cycle
management SOA
Practitioners Guide Part 3: Introduction to Services Lifecycle
introduces the services lifecycle and provides a detailed process for
services management through the service lifecycle, from inception to
retirement or repurposing of the services. It also contains an appendix that
includes organization and governance best-practices, templates, comments
on key SOA standards, and recommended links for more information.

SOA
Design Principles provides more information about SOA
realization using Service design principles

In addition, one might take
the following factors into account when defining a SOA implementation:

Efficient
use of system resources

Service
maturity and performance

EAI (Enterprise Application
Integration)

Web services approach

Web services
can implement a service-oriented architecture. Web services make functional
building-blocks accessible over standard Internet protocols independent of
platforms and programming languages. These services can represent either new
applications or just wrappers around existing legacy systems to make them
network-enabled.

Each SOA building block can
play one or both of two roles:

Service
Provider - The
service provider creates a web service
and possibly publishes its interface and access information to the service
registry. Each provider must decide which services to expose, how to make
trade-offs between security and easy availability, how to price the
services, or (if no charges apply) how/whether to exploit them for other
value. The provider also has to decide what category the service should be
listed in for a given broker service and what sort of trading partner
agreements are required to use the service. It registers what services are
available within it, and lists all the potential service recipients. The
implementer of the broker then decides the scope of the broker. Public
brokers are available through the Internet, while private brokers are only
accessible to a limited audience, for example, users of a company
intranet. Furthermore, the amount of the offered information has to be
decided. Some brokers specialize in many listings. Others offer high
levels of trust in the listed services. Some cover a broad landscape of
services and others focus within an industry. Some brokers catalog other
brokers. Depending on the business
model, brokers can attempt to maximize look-up requests, number
of listings or accuracy of the listings. The Universal
Description Discovery and Integration (UDDI) specification
defines a way to publish and discover information about Web services.
Other service broker technologies include (for example) ebXML
(Electronic Business using eXtensible Markup Language) and those based on
the ISO/IEC 11179 Metadata Registry (MDR) standard.

Service
consumer - The
service consumer or web service client locates entries in the
broker registry using various find operations and then binds to the
service provider in order to invoke one of its web services. Whichever
service the service-consumers need, they have to take it into the brokers,
then bind it with respective service and then use it. They can access
multiple services if the service provides multiple services.

Component based service development

Component Based
Development has become the de-facto approach for software development. With
benefits ranging from simplification and parallel working to pluggable
maintenance and reuse the financial gains are significant. These new ideas and
techniques, necessary for successful component and service based development,
are not widely available as this is a fairly new field. Therefore existing
development staff need be provided with a managed migration and automating
tools. You also need a design approach that maps directly to Component Based
Development.

Select Business Solutions has
been recognized as a market-leader in Component Based Development since the
late 90s. We have a proven lifecycle and tools for the analysis, design,
implementation, management and deployment of component and service based
systems. This is fully supported by targeted training and Select Perspective,
the leading process for service and component based development.

Solution
Breakdown

·
Design component and service oriented
systems with Select
Solution Factory.

·
Implement Select
Perspective, the leading Component Based Development life-cycle with
Select
Process Director.

SOAP

SOAP, originally defined as Simple
Object Access Protocol, is a protocol specification for exchanging
structured information in the implementation of Web Services
in computer networks. It relies on Extensible Markup Language
(XML) for its message format, and usually relies on other Application
Layer protocols, most notably Remote Procedure Call (RPC) and Hypertext Transfer Protocol (HTTP), for
message negotiation and transmission. SOAP can form the foundation layer of a web services protocol stack, providing a
basic messaging framework upon which web services can be built. This XML based
protocol consists of three parts: an envelope, which defines what is in the
message and how to process it, a set of encoding rules for expressing instances
of application-defined datatypes, and a convention for representing procedure
calls and responses.

As an example of how SOAP procedures can be used, a SOAP message could be
sent to a web-service-enabled web site such as a real-estate price database,
with the parameters needed for a search. The site would then return an
XML-formatted document with the resulting data, e.g., prices, location,
features. With the data being returned in a standardized machine-parseable format,
it can then be integrated directly into a third-party web site or application.

The SOAP architecture consists of several layers of specifications: for
message format, Message Exchange Patterns (MEP),
underlying transport protocol bindings, message processing models, and protocol
extensibility. SOAP is the successor of XML-RPC,
though it borrows its transport and interaction neutrality and the
envelope/header/body from elsewhere (probably from WDDX).

SOAP
once stood for 'Simple Object Access Protocol' but this acronym was dropped with
Version 1.2 of the standard.[1]
Version 1.2 became a W3C recommendation on June 24, 2003. The
acronym is sometimes confused with SOA, which stands for Service-oriented architecture. SOAP
standards may be part of an SOA application, but the acronyms are unrelated.

SOAP was originally designed
by Dave Winer,
Don Box,
Bob Atkinson, and Mohsen Al-Ghosein in 1998 in a project for Microsoft
(where Atkinson and Al-Ghosein were already working at the time),[2]
as an object-access protocol. The SOAP
specification is currently maintained by the XML Protocol Working Group
of the World Wide Web Consortium.

After SOAP was first
introduced, it became the underlying layer of a more complex set of Web Services,
based on Web Services Description Language
(WSDL) and Universal Description
Discovery and Integration (UDDI). These services, especially UDDI,
have proved to be of far less interest, but an appreciation of them gives a
more complete understanding of the expected role of SOAP compared to how web
services have actually evolved.

Specification

The SOAP specification
defines the messaging framework which consists of:

The SOAP
processing model defining the rules for processing a SOAP message

The SOAP
extensibility model defining the concepts of SOAP features and SOAP
modules

The SOAP
underlying protocol binding framework describing the rules for
defining a binding to an underlying protocol that can be used for
exchanging SOAP messages between SOAP nodes

The SOAP
message construct defining the structure of a SOAP message

Processing model

The SOAP processing model
describes a distributed processing model, its participants, the SOAP nodes
and how a SOAP receiver processes a SOAP message. The following SOAP nodes are
defined:

SOAP sender

A SOAP node that transmits a
SOAP message.

SOAP
receiver

A SOAP node that accepts a
SOAP message.

SOAP message
path

The set of SOAP nodes through
which a single SOAP message passes.

Initial SOAP
sender (Originator)

The SOAP sender that
originates a SOAP message at the starting point of a SOAP message path.

SOAP
intermediary

A SOAP intermediary is both a
SOAP receiver and a SOAP sender and is targetable from within a SOAP message.
It processes the SOAP header blocks targeted at it and acts to forward a SOAP
message towards an ultimate SOAP receiver.

Ultimate
SOAP receiver

The SOAP receiver that is a
final destination of a SOAP message. It is responsible for processing the
contents of the SOAP body and any SOAP header blocks targeted at it. In some
circumstances, a SOAP message might not reach an ultimate SOAP receiver, for
example because of a problem at a SOAP intermediary. An ultimate SOAP receiver
cannot also be a SOAP intermediary for the same SOAP message.

Transport methods

Both SMTP and HTTP are valid application
layer protocols used as Transport for SOAP, but HTTP has gained wider
acceptance as it works well with today's Internet infrastructure; specifically,
HTTP works well with network firewalls. SOAP may also be used over HTTPS (which is the same
protocol as HTTP at the application level, but uses an encrypted transport protocol underneath)
with either simple or mutual authentication; this is the advocated WS-I method to provide web
service security as stated in the WS-I Basic Profile 1.1.

This is a major advantage
over other distributed protocols like GIOP/IIOP or DCOM which are normally
filtered by firewalls. SOAP over AMQP is yet another possibility that some implementations
support.

There is also the SOAP-over-UDP
OASIS standard.

Message format

XML was chosen as the standard
message format because of its widespread use by major corporations and open source
development efforts. Additionally, a wide variety of freely available tools significantly eases the transition
to a SOAP-based implementation. The somewhat lengthy syntax of XML can be both a benefit
and a drawback. While it promotes readability for humans, facilitates error
detection, and avoids interoperability problems such as byte-order (Endianness),
it can slow processing speed and can be cumbersome. For example, CORBA, GIOP, ICE, and DCOM use much shorter,
binary message formats. On the other hand, hardware appliances are available to
accelerate processing of XML
messages.[3][4]
Binary XML
is also being explored as a means for streamlining the throughput requirements
of XML.

Example message

POST /InStock HTTP/1.1

Host: www.example.org

Content-Type: application/soap+xml; charset=utf-8

Content-Length: 299

SOAPAction:
"http://www.w3.org/2003/05/soap-envelope"

<?xml version="1.0"?>

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">

<soap:Header>

</soap:Header>

<soap:Body>

<m:GetStockPrice xmlns:m="http://www.example.org/stock">

<m:StockName>IBM</m:StockName>

</m:GetStockPrice>

</soap:Body>

</soap:Envelope>

Technical critique

Advantages

SOAP is
versatile enough to allow for the use of different transport protocols.
The standard stacks use HTTP as a transport protocol, but other protocols
such as JMS[5]
and SMTP[6]
are also usable.

Since the
SOAP model tunnels fine in the HTTP get/response model, it can tunnel
easily over existing firewalls and proxies, without modifications to the
SOAP protocol, and can use the existing infrastructure.

Disadvantages

Because of
the verbose XML format, SOAP can be considerably slower than competing middleware
technologies such as CORBA. This may not be an issue when only small messages
are sent.[7]
To improve performance for the special case of XML with embedded binary
objects, the Message
Transmission Optimization Mechanism was introduced.

When relying
on HTTP as a transport protocol and not using WS-Addressing
or an ESB, the roles of the interacting
parties are fixed. Only one party (the client) can use the services of the
other. Developers must use polling instead of
notification in these common cases.

WSDL Document Example

The
following example shows the WSDL definition of a simple service providing stock
quotes. The service supports a single operation called GetLastTradePrice, which
is deployed using the SOAP 1.1 protocol over HTTP. The request takes a ticker
symbol of type string, and returns the price as a float. A detailed description
of the elements used in this definition can be found in Section 2 (core
language) and Section 3 (SOAP binding). This example uses a fixed XML format
instead of the SOAP encoding.

Example 1 SOAP 1.1
Request/Response via HTTP

<?xml version="1.0"?>

<definitions name="StockQuote"

targetNamespace="http://example.com/stockquote.wsdl"

xmlns:tns="http://example.com/stockquote.wsdl"

xmlns:xsd1="http://example.com/stockquote.xsd"

xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"

xmlns="http://schemas.xmlsoap.org/wsdl/">

<types>

<schema targetNamespace="http://example.com/stockquote.xsd"

xmlns="http://www.w3.org/2000/10/XMLSchema">

<element name="TradePriceRequest">

<complexType>

<all>

<element name="tickerSymbol" type="string"/>

</all>

</complexType>

</element>

<element name="TradePrice">

<complexType>

<all>

<element name="price" type="float"/>

</all>

</complexType>

</element>

</schema>

</types>

<message name="GetLastTradePriceInput">

<part name="body" element="xsd1:TradePriceRequest"/>

</message>

<message name="GetLastTradePriceOutput">

<part name="body" element="xsd1:TradePrice"/>

</message>

<portType name="StockQuotePortType">

<operation name="GetLastTradePrice">

<input message="tns:GetLastTradePriceInput"/>

<output message="tns:GetLastTradePriceOutput"/>

</operation>

</portType>

<binding name="StockQuoteSoapBinding" type="tns:StockQuotePortType">

<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>

<operation name="GetLastTradePrice">

<soap:operation soapAction="http://example.com/GetLastTradePrice"/>

<input>

<soap:body use="literal"/>

</input>

<output>

<soap:body use="literal"/>

</output>

</operation>

</binding>

<service name="StockQuoteService">

<documentation>My first service</documentation>

<port name="StockQuotePort" binding="tns:StockQuoteBinding">

<soap:address location="http://example.com/stockquote"/>

</port>

</service>

</definitions>

UDDI

Universal Description, Discovery and Integration (UDDI,
pronounced Yu-diː) is a platform-independent, Extensible Markup Language (XML)-based registry
for businesses worldwide to list themselves on the Internet
and a mechanism to register and locate web service
applications. UDDI is an open industry initiative, sponsored by the
Organization for the Advancement of Structured Information Standards (OASIS), enabling businesses to publish
service listings and discover each other and define how the services or
software applications interact
over the Internet.

UDDI was originally proposed as a core Web service
standard.[1]
It is designed to be interrogated by SOAP
messages and to provide access to Web Services Description Language
(WSDL) documents describing the protocol bindings and message formats required
to interact with the web services listed in its directory.

UDDI was written in August
2000, at a time when the authors had a vision of a world in which consumers of
Web Services would be linked up with providers
through a public or private dynamic brokerage system. In this vision, anyone
needing a service such as credit card authentication
would go to their service broker and select one supporting the desired SOAP or
other service interface and meeting other criteria. In such a world, the
publicly operated UDDI node or broker would be critical for everyone. For the
consumer, public or open brokers would only return services listed for public
discovery by others, while for a service producer, getting a good placement in
the brokerage—by relying on metadata of authoritative index
categories—would be critical for effective placement.

UDDI was included in the Web Services Interoperability (WS-I)
standard as a central pillar of web services infrastructure, and the UDDI
specifications supported a publicly accessible Universal Business Registry in
which a naming system was built around the UDDI-driven service broker.

UDDI has not been widely
adopted in the way its designers had hoped.[2]
IBM, Microsoft,
and SAP
announced they were closing their public UDDI nodes in January 2006.[3]
The group defining UDDI, the OASIS Universal Description, Discovery, and
Integration (UDDI) Specification Technical Committee voted to complete its work
in late 2007 and has been closed.[4]
In September 2010, Microsoft announced they were removing UDDI services from
future versions of the Windows Server operating system. Instead, this
capability would be moved to Biztalk.[5]

Some assert[citation needed] that the most
common place that a UDDI system can be found is inside a company where it might
be used to dynamically bind client systems to implementations. They would say
that much of the search metadata permitted in UDDI is not used for this relatively simple
role.

Structure

A UDDI business registration
consists of three components:

White Pages — address, contact,
and known identifiers;

Yellow Pages — industrial
categorizations based on standard taxonomies;

Green Pages — technical
information about services exposed by the business.

White
Pages

White pages give information
about the business supplying the service. This includes the name of the
business and a description of the business - potentially in multiple languages.
Using this information, it is possible to find a service about which some
information is already known (for example, locating a service based on the
provider's name).[6]

Contact information for the
business is also provided - for example the businesses address and phone
number; and other information such as the Dun & Bradstreet Universal Numbering
System number.

Yellow
Pages

Yellow pages provide a
classification of the service or business, based on standard taxonomies. These
include the Standard Industrial Classification
(SIC), the North American Industry
Classification System (NAICS),[7]
or the United
Nations Standard Products and Services Code (UNSPSC) .

Because a single business may
provide a number of services, there may be several Yellow Pages (each
describing a service) associated with one White Page (giving general
information about the business).

Green
Pages

Green pages are used to
describe how to access a Web Service, with information on the service bindings.
Some of the information is related to the Web Service - such as the address of
the service and the parameters, and references to specifications of
interfaces[1]. Other information is not related directly to the Web Service -
this includes e-mail, FTP, CORBA and telephone details for the service. Because
a Web Service may have multiple bindings (as defined in its WSDL description),
a service may have multiple Green Pages, as each binding will need to be
accessed differently.

UDDI Nodes & Registry

UDDI nodes are servers which
support the UDDI specification and belong to a UDDI registry while UDDI
registries are collections of one or more nodes.

SOAP
is an XML-based protocol to exchange messages between a requester and a
provider of a Web Service. The provider publishes the WSDL to UDDI and the
requester can join to it using SOAP.

ebXML

Electronic Business using eXtensible Markup
Language, commonly known
as e-business XML, or ebXML (pronounced ee-bee-ex-em-el) as
it is typically referred to, is a family of XML based standards
sponsored by OASIS and UN/CEFACT
whose mission is to provide an open, XML-based infrastructure that enables the
global use of electronic business information in an
interoperable, secure, and consistent manner by all trading partners.

The ebXML architecture is a unique set of concepts; part theoretical and
part implemented in the existing ebXML standards work.

The ebXML work stemmed from earlier work on ooEDI (object oriented EDI), UML / UMM, XML markup
technologies and the X12 EDI "Future Vision" work
sponsored by ANSI X12 EDI.

The melding of these components began in the original ebXML work and the
theoretical discussion continues today. Other work relates, such as the Object Management Group work and the OASIS
BCM (Business-Centric Methodology) standard (2006).

ebXML was started in 1999 as
a joint initiative between the United Nations Centre for Trade facilitation and
Electronic Business (UN/CEFACT) and Organization for the Advancement of Structured
Information Standards (OASIS). A joint coordinating committee
composed of representatives from each of the two organizations led the effort.
Quarterly meetings of the working groups were held between November 1999 and
May 2001. At the final plenary a Memorandum of Understanding was signed by the
two organizations, splitting up responsibility for the various specifications
but continuing oversight by the joint coordinating committee.

The original project
envisioned five layers of data specification, including XML standards for:

Business
processes,

Collaboration
protocol agreements,

Core data
components,

Messaging,

Registries
and repositories

All work was completed based
on a normative requirements document and the ebXML Technical Architecture
Specification.

After completion of the 6
specifications by the two organizations, 5 parts of the work were submitted to
ISO TC 154 for approval. The International Organization for
Standardization (ISO) has approved the following five ebXML
specifications as the ISO 15000 standard, under the general title, Electronic
business eXtensible markup language:

ISO 15000-1:
ebXML Collaborative Partner Profile Agreement

ISO 15000-2:
ebXML Messaging Service Specification

ISO 15000-3:
ebXML Registry Information Model

ISO 15000-4:
ebXML Registry Services Specification

ISO 15000-5:
ebXML Core Components Technical Specification, Version
2.01.

OASIS technical committees
and UN/CEFACT retain the responsibility for maintaining and advancing the above
specifications. The freebXML.org initiative
was established to promote development and adoption of ebXML-based open-source
software.

Collaborative Partner Profile Agreement

Collaborative Partner Profile
Agreements are XML
based documents specifying a trading agreement between trading partners. Each
trading partner will have their own Collaboration Protocol Profile (CPP)
document that describes their abilities in an XML format. For instance, this
can include the messaging protocols they support, or the security capabilities
they support. A CPA document is the intersection of two CPP documents, and
describes the formal relationship between two parties. The following
information will typically be contained in a CPA document:

Identification
information: the unique identifiers for each party and their roles within
the trading relationship

Security
information: for instance, are digital signatures required, and what
algorithms do they use

Communication
information: the protocols that will be used when exchanging documents

Endpoint
locations: the URL, service and action messages should be sent to

Rules to
follow when acknowledgments are not received for messages, including how
long to wait before resending, and how many times to resend

Whether
duplicate messages should be ignored

Whether
acknowledgments are required for all messages

Messaging Service Specification

The Message Service
Specification (ebMS) describes a communication-neutral mechanism Message
Service Handlers (MSH) must implement in order to exchange business documents.
ebMS2.0 is the current version of the specification. ebMS 2.0 is built as an
extension on top of the SOAP with Attachments specification. The SOAP message contains the
meta-data required to exchange the business document in a secure and reliable
manner, while the business payload is attached to the SOAP message. Multiple
business payloads may be attached to a single message, and the format of the
payloads is beyond the scope of the ebXML specifications. The information
trading partners place in ebMS messages is largely dictated by the CPA
agreement that defines the relationship between them. The following information
is typically contained within ebMS messages:

Unique
message id

Who the
message is for

Who sent the
message

A
conversation id for linking related messages

A digital
signature based on the XML Signature specification

An
indication for whether duplicate messages should be ignored

An
indication for whether acknowledgments are required

ebMS is communication
protocol neutral, although the most common underlying protocols are HTTP and SMTP.

1
J2EE AND WEB SERVICES

Developing Web
Services with Java 2 Platform, Enterprise
Edition (J2EE) 1.4 Platform

The
Java 2 Platform,
Enterprise Edition (J2EE) version 1.4 has evolved to integrate web
services. Web services are now one of the many service delivery channels of the
J2EE platform; existing J2EE components can be easily exposed as web services.
Many benefits of the J2EE platform are available for web services, including
portability, scalability, reliability, and no single-vendor lock-in. For
example, J2EE containers provide transaction support, database connections,
life cycle management, and other services that are scalable and require no code
from application developers.

The
J2EE 1.4 platform provides comprehensive support for web services through the JAX-RPC 1.1 API,
which can be used to develop service endpoints based on SOAP. JAX-RPC 1.1
provides interoperability with web services based on the Web Services
Description Language (WSDL) and Simple Object Access Protocol (SOAP). The J2EE
1.4 platform also supports JSR 109,
that builds upon JAX-RPC and focuses on the programming model for implementing
web services, as well as deploying web services in the J2EE 1.4 platform. In
addition, J2EE 1.4 supports the WS-I
Basic Profile to ensure that web services developed using the J2EE platform are
portable not only across J2EE implementations, but are also interoperable with
any web service developed, using any platform that conforms to the WS-I
standards.

To
develop web services, a developer usually needs extensive knowledge of
XML-based standards and protocols (such as WSDL and SOAP), as well as a fair
amount of programming experience. In the J2EE 1.4 platform, however, developing
web services is seamless, since you don't really need to know about WSDL and
SOAP; the mapping between the Java language and such XML-based standards is
handled by the web service runtime system, thus freeing the developer from such
low-level programming details.

This
article provides a tutorial and step-by-step instructions on how to develop,
deploy, and use web services, using the J2EE 1.4 SDK, with little programming
required. We'll cover:

A brief overview of web services

Overview of JSR 109

Examples of web services and clients

A flavor of the effort involved in developing
web services using the J2EE 1.4 platform

Sample code that you can adapt to your own
web service applications

Overview of Web
Services

Web
services are application components that are designed to support interoperable
machine-to-machine interaction over a network. This interoperability is gained
through a set of XML-based open standards, such as the Web Services Description
Language (WSDL), the Simple Object Access Protocol (SOAP), and Universal
Description, Discovery, and Integration (UDDI). These standards provide a
common and interoperable approach for defining, publishing, and using web
services. If you don't know anything about these technologies yet, no worries:
you can develop web services in the J2EE 1.4 platform without knowing a thing
about these XML-based standards and protocols. Figure 1 shows how the Java APIs
for XML Registries (JAXR) and Java APIs for XML Remote Procedure Calls
(JAX-RPC) play a role in publishing, discovering, and using web services.

Figure 1: J2EE 1.4 Publish-Discover-Invoke model

From
a software architect's point of view, a web service can be considered as a
service-oriented architecture, which consists of a collection of services that
communicate with each other (and end-user clients) through well-defined
interfaces. One advantage of service-oriented architecture is that it allows
the development of loosely coupled applications that can be distributed and
accessed, from any client, across the network.

The
J2EE 1.4 SDK provides the tools you need to quickly build, test, and deploy web
services and clients that interoperate with other web services and clients
running on Java technology-based or non-Java technology-based platforms. In
addition, it enables businesses to expose their existing J2EE applications as
web services. Servlets and Enterprise JavaBeans (EJBs) components can be
exposed as web services that can be accessed by Java technology-based or
non-Java technology-based web service clients. J2EE applications can act as web
service clients themselves, and they can communicate with other web services,
regardless of how they are implemented.

J2EE 1.4 SDK

The
best way to learn about what's new in the J2EE platform is to download the J2EE 1.4 SDK
to get hands-on experience. The J2EE 1.4 SDK includes the following:

J2EE 1.4 Application Server

Java 2 Platform, Standard Edition (J2SE)
1.4.2_01

J2EE Samples (Java Pet Store, Java Adventure
Builder, Smart Ticket, and others)

Sun ONE Message Queue

PointBase Database Server

By
default, the J2EE 1.4 SDK will be installed (on Microsoft Windows) at c:\sun\AppServer,
and the JDK 1.4.2_01 would be installed at c:\sun\AppServer\jdk.

To
configure your installation, just edit your path to include c:\sun\AppServer\bin
and c:\sun\AppServer\jdk\bin. The c:\sun\AppServer\bin
gives you access to several tools, including wscompile, which takes
the service definition interface and generates the client-side stubs or
server-side skeletons, or a WSDL description for the provided interface.

JSR 109

The
process of developing and deploying web services is coupled with the runtime
system. For example, deploying a web service on Apache Axis is different from
deploying the same web service on Apache SOAP or any other platform. The Java
Community Process (JCP) specification JSR 109 (Implementing Enterprise Web
Services) promotes building portable and interoperable web services in the J2EE
1.4 environment. JSR 109 leverages J2EE technologies to provide an industry
standard for developing and deploying web services on the J2EE platform, and it
provides a service architecture that is familiar to J2EE developers. This
specification outlines the lifecycle of web services to include:

Development:
Standardizes the web services programming model as well as the deployment
descriptors

Deployment:
Describes the deployment actions expected of a J2EE 1.4 container

Service publication:
Specifies how the WSDL is made available to clients

Service consumption:
Standardizes the client deployment descriptors and a JNDI lookup model

J2EE Web Services

JAX-RPC
is a Java API for XML-based Remote Procedure Calls (RPC). You can use it to
build web services and clients that use RPC and XML. An RPC is represented
using an XML-based protocol such as SOAP, which defines an envelope structure,
encoding rules, and convention for representing RPC calls and responses, which
are transmitted as SOAP messages over HTTP. The advantage of JAX-RPC is that it
hides the complexity of SOAP messages from the developer. Here is how it works:

The
developer specifies the remote procedures (web services) that can be invoked by
remote clients in a Java programming language interface; the developer
implements the interface. The client view of a web service is a set of methods
that perform business logic on behalf of the client. A client accesses a web
service using a Service Endpoint Interface as defined by JAX-RPC. Client
developers create the client -- a proxy (or a local object that represents the
remote service) that is automatically generated -- and then simply invoke the
methods on the proxy. The developer doesn't need to worry about generating or
parsing SOAP messages; this is all taken care of by the JAX-RPC runtime system.
Note that J2EE web services can be invoked by any web service client, and any
J2EE web service client can invoke any web service.

To
get a feeling for what happens behind the scenes, consider Figure 2, which
shows how a Java client communicates with a Java web service in the J2EE 1.4
platform. Note that J2EE applications can use web services published by other
providers, regardless of how they are implemented. In the case of non-Java
technology-based clients and services, the figure would change slightly. As
mentioned earlier, all the details between the request and the response happen
behind the scenes. You only deal with typical Java programming language
semantics, such as method calls and data types. You need not worry about
mapping Java to XML and vice-versa, or constructing SOAP messages. All this
low-level work is done behind the scenes, allowing you to focus on the
high-level issues.

Figure 2: A Java client calling a J2EE web
service

Note
that a web service client never accesses a service directly; it does so through
the container. This is a good thing, since it allows a web service to benefit
from the added functionality that the container provides -- such as security,
enhanced logging, and quality-of-service guarantees. This means that the
container frees the developer from worrying about such low-level details.

Working with JAX-RPC

When
working with JAX-RPC, remember that it maps Java types to XML/WSDL definitions.
The good news is that you don't need to know the details of these mappings, but
you should be aware that not all J2SE classes can be used as method parameters
or return types in JAX-RPC. JAX-RPC supports the following primitive data
types: boolean, byte, double,
float, int, long,
short, and arrays. In addition, it supports
the following wrapper and utility classes:

java.lang.Boolean

java.lang.Byte

java.lang.Double

java.lang.Float

java.lang.Integer

java.lang.Long

java.lang.Short

java.lang.String

java.math.BigDecimal

java.math.BigInteger

java.net.URI

java.util.Calendar

java.util.Date

JAX-RPC
also supports something called a value
type, which is a class that can be passed between a client and a
service as a parameter or a return value. A value type must follow these rules:

It must have a public default constructor.

It must not implement java.rmi.Remote.

Its fields must be JAX-RPC supported types.
Also, a public
field cannot be final
or transient,
and a non-public field must have the corresponding getter and setter
methods.

Creating Web Services

Building
an XML-RPC style web service using the J2EE 1.4 platform involves five steps:

Design
and code the web service endpoint interface.

Implement
the interface.

Write a
configuration file.

Generate
the necessary files.

Use the deploytool to
package the service in a WAR file and deploy it.

1. Design and Code the Service Endpoint Interface

The
first step in creating a web service is to design and code its endpoint
interface, in which you declare the methods that a web service remote client
may invoke on the service. When developing such an interface, ensure that:

It extends the java.rmi.Remote
interface

It does not have constant declarations such
as public static final

Its methods throw the java.rmi.RemoteException
(or one of its subclasses)

Its method parameters and return data types
are supported JAX-RPC types

To
get started, create a directory of your choice. For the following example, I
created an apps directory under c:\sun\AppServer
and a subdirectory of apps called build. The apps
directory contains the .java files, and the build
directory contains the .class, as well as other files that will be
automatically generated.

The
web service I will be developing for the rest of this article provides a
summation service for adding two numbers. Nothing fancy, but as you will see,
it will demonstrate how to develop, deploy, and use web services. Code Sample 1
shows the service endpoint interface, which is a regular Java language
interface that extends the java.rmi.Remote
interface. The MathFace interface declares one method, add,
which takes two integer values and returns an integer value representing the
sum of the two integer parameters:

Code Sample 1: MathFace.java

package math;

import java.rmi.Remote;

import java.rmi.RemoteException;

public interface MathFace extends Remote {

public int add(int a, int b) throws RemoteException;

}

2. Implement the Service Endpoint Interface

The
next step is to implement the MathFace interface
defined in Code Sample 1, which is quite straightforward, as shown in Code
Sample 2.

Code Sample 2: MathImpl.java

package math;

import java.rmi.RemoteException;

public class MathImpl implements MathFace {

public int add(int a, int b) throws RemoteException {

return a + b;

}

}

Now,
compile the .java files specifying the .class
files to be written to the build directory created
above. The -d option instructs the compiler to write the
output .class files into the build
directory:

prompt>
javac -d build Math*.java

3. Write a Configuration File

The
next step is to define a configuration file to be passed to the wscompile
tool. Here I call the file config.xml (and save it
under the apps directory). In this configuration file, I
describe the name of the service, its namespace, the package name ( math
in this case) and the name of the interface ( MathFace). Code Sample 3
shows the configuration file:

Code Sample 3: config.xml

<?xml
version="1.0" encoding="UTF-8"?>

<configuration

xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">

<service

name="MyFirstService"

targetNamespace="urn:Foo"

typeNamespace="urn:Foo"

packageName="math">

<interface
name="math.MathFace"/>

</service>

</configuration>

This
file tells wscompile to create a WSDL file with the
following information:

The service name is MyFirstService.

The WSDL namespace is urn:Foo.

The classes for the service are in the math package under
the build
directory.

The service endpoint interface is math.MathFace.

4. Generate the Necessary
Mapping Files

Now,
use the wscompile tool to generate the necessary
files. Consider the following command executed from the apps
directory:

prompt>
wscompile -define -mapping build/mapping.xml -d build -nd build -classpath
build config.xml

This
command, which reads the config.xml file created
earlier, creates the MyFirstService.wsdl file and mapping.xml
in the build directory. The command line options or
flags are:

-define:
instructs the tool to read the service endpoint interface and create a
WSDL file.

-mapping:
specifies the mapping file and where it should be written.

-d
and -nd:
specifies where to place generated output files and non-class output
files, respectively.

Believe
it or not, you have now built a web service that is ready to be packaged and
deployed.

The
WSDL file MyFirstService.wsdl, generated by the wscompile
tool, is shown in Code Sample 4. This file provides an XML description (based
on WSDL) of the service that clients can invoke. To understand the details of
the file you need some knowledge of WSDL -- but you don't need to understand all the details, so
don't worry if you have no knowledge of WSDL.

Code Sample 4: MyFirstService.wsdl

<?xml version="1.0" encoding="UTF-8"?>

<definitions name="MyFirstService" targetNamespace="urn:Foo" xmlns:tns="urn:Foo"

xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"

xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">

<types/>

<message name="MathFace_add">

<part name="int_1" type="xsd:int"/>

<part name="int_2" type="xsd:int"/></message>

<message name="MathFace_addResponse">

<part name="result" type="xsd:int"/></message>

<portType name="MathFace">

<operation name="add" parameterOrder="int_1 int_2">

<input message="tns:MathFace_add"/>

<output message="tns:MathFace_addResponse"/></operation></portType>

<binding name="MathFaceBinding" type="tns:MathFace">

<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>

<operation name="add">

<soap:operation soapAction=""/>

<input>

<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"

use="encoded" namespace="urn:Foo"/>

</input>

<output>

<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"

use="encoded" namespace="urn:Foo"/>

</output>

</operation></binding>

<service name="MyFirstService">

<port name="MathFacePort" binding="tns:MathFaceBinding">

<soap:address location="REPLACE_WITH_ACTUAL_URL"/>

</port>

</service>

</definitions>

The
mapping file, mapping.xml, generated by the wscompile
tool is shown in Figure 5. This file follows the JSR 109 standard for Java
<-> WSDL mappings. As you can see, the structure of the JAX-RPC mapping
file matches closely with the structure of a WSDL file -- note the relationship
between Java packages and XML namespaces. Each service offered is represented
as a service-interface-mapping element. This
element contains the mapping for the fully qualified class name of the service
interface, WSDL service names, and WSDL port names. In addition, the JAX-RPC
mapping file provides mappings for WSDL bindings, WSDL port types, WSDL
messages, and so forth. And once again, the good news is that you needn't worry
about the WSDL file (Code Sample 4) of the JAX-RPC mapping file (Code Sample 5)
in order to develop, deploy, and use web services.

Code Sample 5: mapping.xml

<?xml version="1.0" encoding="UTF-8"?>

<java-wsdl-mapping version="1.1" xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee

http://www.ibm.com/webservices/xsd/j2ee_jaxrpc_mapping_1_1.xsd">

<package-mapping>

<package-type>math</package-type>

<namespaceURI>urn:Foo</namespaceURI>

</package-mapping>

<package-mapping>

<package-type>math</package-type>

<namespaceURI>urn:Foo</namespaceURI>

</package-mapping>

<service-interface-mapping>

<service-interface>math.MyFirstService</service-interface>

<wsdl-service-name

xmlns:serviceNS="urn:Foo">serviceNS:MyFirstService</wsdl-service-name>

<port-mapping>

<port-name>MathFacePort</port-name>

<java-port-name>MathFacePort</java-port-name>

</port-mapping>

</service-interface-mapping>

<service-endpoint-interface-mapping>

<service-endpoint-interface>math.MathFace</service-endpoint-interface>

<wsdl-port-type xmlns:portTypeNS="urn:Foo">portTypeNS:MathFace</wsdl-port-type>

<wsdl-binding xmlns:bindingNS="urn:Foo">bindingNS:MathFaceBinding</wsdl-binding>

<service-endpoint-method-mapping>

<java-method-name>add</java-method-name>

<wsdl-operation>add</wsdl-operation>

<method-param-parts-mapping>

<param-position>0</param-position>

<param-type>int</param-type>

<wsdl-message-mapping>

<wsdl-message

xmlns:wsdlMsgNS="urn:Foo">wsdlMsgNS:MathFace_add</wsdl-message>

<wsdl-message-part-name>int_1</wsdl-message-part-name>

<parameter-mode>IN</parameter-mode>

</wsdl-message-mapping>

</method-param-parts-mapping>

<method-param-parts-mapping>

<param-position>1</param-position>

<param-type>int</param-type>

<wsdl-message-mapping>

<wsdl-message

xmlns:wsdlMsgNS="urn:Foo">wsdlMsgNS:MathFace_add</wsdl-message>

<wsdl-message-part-name>int_2</wsdl-message-part-name>

<parameter-mode>IN</parameter-mode>

</wsdl-message-mapping>

</method-param-parts-mapping>

<wsdl-return-value-mapping>

<method-return-value>int</method-return-value>

<wsdl-message

xmlns:wsdlMsgNS="urn:Foo">wsdlMsgNS:MathFace_addResponse</wsdl-message>

<wsdl-message-part-name>result</wsdl-message-part-name>

</wsdl-return-value-mapping>

</service-endpoint-method-mapping>

</service-endpoint-interface-mapping>

</java-wsdl-mapping>

5. Packaging and Deploying the
Service

A
JAX-RPC web service is really a servlet (or a web component, in J2EE
terminology), and hence you can use deploytool to package and
generate all the necessary configuration files, and deploy the service. If you
haven't yet used the deploytool to package and deploy applications,
start the J2EE application server (or default domain) and then follow these
instructions to package and deploy the math service. For the rest of
the article, I will assume that the service can be accessed using the URL http://localhost:8080/math-service/math.

Creating Web Service
Clients

Now,
let's create a client that accesses the math service you have just deployed. A
client invokes a web service in the same way it invokes a method locally. There
are three types of web service clients:

Static Stub:
A Java class that is statically bound to a service endpoint interface. A
stub, or a client proxy object, defines all the methods that the service
endpoint interface defines. Therefore, the client can invoke methods of a
web service directly via the stub. The advantage of this is that it is simple
and easy to code. The disadvantage is that the slightest change of web
service definition lead to the stub being useless... and this means the
stub must be regenerated. Use the static stub technique if you know that
the web service is stable and is not going to change its definition.
Static stub is tied to the implementation. In other words, it is
implementation-specific.

Dynamic Proxy:
Supports a service endpoint interface dynamically at runtime. Here, no
stub code generation is required. A proxy is obtained at runtime and
requires a service endpoint interface to be instantiated. As for
invocation, it is invoked in the same way as a stub. This is useful for
testing web services that may change their definitions. The dynamic proxy
needs to be re-instantiated but not re-generated as is the case with stub.

Dynamic Invocation Interface
(DII): Defines javax.xml.rpc.Call
object instance for dynamic invocation. Unlike stub and proxy, it must be
configured before it can be used. A client needs to provide: operation
name, parameter names, types, modes, and port type. As you can tell, much
more coding is involved here. The major benefit is that since Call is not bound to
anything, there is no impact of changes on the client side (whenever the
web service definition changes). The DII client is outside the scope of
this article.

1. Static Stub Client

Let's
develop a stand-alone client that calls the add method of MyFirstService.
It makes the call through a stub, or a local object that acts as a client proxy
to the remote service. It is called a static stub because the stub is generated
before runtime by the wscompile tool. Before developing the Java
client itself, you need to write a configuration file (in XML) that describes
the location of the WSDL file ( MyFirstService.wsdl). The
configuration file is shown in Code Sample 6. I suggest that you create a new
subdirectory under apps call it static-stub (where you
save the .xml and .java files) and under
that a build subdirectory.

Code Sample 6: config-wsdl.xml

<?xml version="1.0" encoding="UTF-8"?>

<configuration

xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">

<wsdl location="http://localhost:8080/math-service/math?WSDL"

packageName="sstub"/>

</configuration>

As
you can see, the URL http://localhost:8080/math-service/math?WSDL
identifies the location of the WSDL file for MyFirstService. If you
try this URL, you'd see something similar to Figure 3 (assuming you have
deployed the web service developed above).

Once
you have written the configuration file, you're ready to generate client stubs,
using the following command:

prompt>
wscompile -gen:client -d build -classpath build config-wsdl.xml

This
commands reads the MyFirstService.wsdl (the location of which is
specified in the config-wsdl.xml), then generates files based on the
information in the WSDL file and on the command-line flags. The -gen:client
instructs wscompile to generate the stubs, as well as
other needed runtime files such as serializers and value types. The -d
flags tells the tool to write the output to the build subdirectory.

Now,
you're ready to develop the client. A sample implementation is shown in Code
Sample 7. Note that the stub generated earlier is used, and a service endpoint
address is used to locate the service http://localhost:8080/math-service/math.
As you can see, a stub object is created using the MathFirstService_Impl
object generated by the wscompile tool; the
endpoint address that the stub uses to access the service is set; and then the
stub is cast to the MathFace service endpoint interface; finally, the add
method is invoked.

Code Sample 7: MathClient.java

package sstub;

import javax.xml.rpc.Stub;

public class MathClient {

private String endpointAddress;

public static void main(String argv[]) {

try {

// Invoke createProxy() to create a stub object

Stub stub = createProxy();

// Set the endpoint address the stub uses to access the service

stub._setProperty(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY,

"http://localhost:8080/math-service/math");

// Cast the stub to the service endpoint interface (MathFace)

MathFace math = (MathFace) stub;

// Invoke the add method

System.out.println(math.add(12, 24));

} catch (Exception ex) {

ex.printStackTrace();

}

}

private static Stub createProxy() {

// Create a stub object

// Note that MyFirstService_Impl, generated by wscompile, is implementation-specific

return (Stub) (new MyFirstService_Impl().getMathFacePort());

}

}

You
can now compile MathClient.java and write the output to the build
directory:

C:\sun\APPSER~1\apps\static-stub>
javac -classpath build -d build MathClient.java

Note:
If you don't already use Ant,
I'd recommend that you learn how to use it. In this article, however, and for
the benefit of those who do not use it, I am not using Ant.
The easiest way to get things running is to copy all lib/*.jar and lib/endorsed/*.jar to jdk\jre\lib\ext; this
way, you don't have to worry about the classpath for the JAX-RPC classes.

Run
the client:

C:\sun\APPSER~1\apps\static-stub>
java -classpath build sstub.MathClient

36

2. Dynamic Proxy

The client in this case calls a remote
procedure through a dynamic proxy or a class that is created at runtime. Note
that in the case of the static stub, the code relied on an
implementation-specific class, but here (dynamic proxy) the code doesn't have
this limitation. The first step is to create a configuration file. You can use
the one in Code Sample 6 but make sure you change the packageName to
dynamicproxy or whatever you like. Again, create a directory dynamic-proxy
under apps, and build subdirectory under dynamic-proxy.

Now,
use the wscompile to generate the needed interfaces:

C:\Sun\APPSER~1\apps\dynamic-proxy>
wscompile -import -d build -nd build -f:norpc structures -classpath build
config-wsdl.xml

Now,
develop the client. Code Sample 8 provides a sample implementation. Here, an instance
of the service factory is created. The service factory is used to create a
service object that acts as a factory for proxies. As you can see, the createService
method takes two parameters: a URL of the WSDL files and a QName
object, which is a tuple that represents an XML qualified name -- the namespace
URI and the local part of the qualified name (the service name). A proxy object
is then created, and finally the add method is invoked on
that object.

Code Sample 8: MathClient.java

package dynamicproxy;

import java.net.URL;

import javax.xml.rpc.Service;

import javax.xml.rpc.JAXRPCException;

import javax.xml.namespace.QName;

import javax.xml.rpc.ServiceFactory;

import dynamicproxy.FirstIF;

public class MathClient {

public static void main(String[] args) {

try {

String nameSpaceUri = "urn:Foo";

String serviceName = "MyFirstService";

String portName = "MathFacePort";

// Specify the location of the WSDL file

URL url = new URL("http://localhost:8080/math-service/math?WSDL");

// Create an instance of service factory

ServiceFactory serviceFactory = ServiceFactory.newInstance();

// Create a service object to act as a factory for proxies.

Service mathService = serviceFactory.createService(url,

new QName(nameSpaceUri, serviceName));

// Create a proxy

dynamicproxy.MathFace

myProxy = (dynamicproxy.MathFace) mathService.getPort(new

QName(nameSpaceUri,

portName), dynamicproxy.MathFace.class);

// Invoke the add method

System.out.println(myProxy.add(23, 12));

} catch (Exception ex) {

ex.printStackTrace();

}

}

}

Compile
the client:

c:\Sun\APPSER~1\apps\dynamic-proxy>
javac -classpath build -d build MathClient.java

And,
now run the client:

C:\Sun\APPSER~1\apps\dynamic-proxy>
java -classpath build dynamicproxy.MathClient

35

Command-Line J2EE
Application Client

Unlike
a stand-alone client, a J2EE application client can obtain a service interface
using JNDI lookup. In this case, the client developer defines a logical JNDI
name (service reference) for the web service. The container binds the service
interface implementation under the client's environment context java:comp/env
using the logical name of the service reference. The following snippet of code
shows an example:

try {

Context ic = new InitialContext();

MyFirstService myFirstService = (MyFirstService)

ic.lookup("java:comp/env/service/MyFirst");

j2ee.MathFace mathPort = myFirstService.getMathFacePort();

((Stub) mathPort)._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY,

"http://localhost:8080/math-service/math");

System.out.println(mathPort.add(22, 1));

} catch (Exception ex) {

ex.printStackTrace();

System.exit(1);

}

Browser-Based Client

Finally,
let's see how to develop a web client in which the web service is invoked from
a browser-based form (here we use static stub). To start, you need a
configuration file similar to the one in Code Sample 6. Just change the packageName
to whatever you like; here, it's webclient. Once you have
that, generate the client stub using the following command:

c:\Sun\APPSER~1\aps\web\>wscompile
-gen:client -d build -classpath build config-wsdl.xml

The
next step is to write the web client as a servlet or a JavaServer Pages
technology page (JSP). Code Samples 9 and 10 show my JSP implementation of the
web client. Code Sample 9 presents the form to the user and retrieves the
parameters, and Code Sample 10 (based on static stub) is similar to the client
in Code Sample 7.

Code Sample 9: math.jsp

<html>

<head><title>Hello</title></head>

<body bgcolor="#ffcccc">

<h2>Welcome to the Math Web Service</h2>

<form method="get">

<input type="text" name="num1" size="25">

<p></p>

<input type="text" name="num2" size="25">

<p></p>

<input type="submit" value="AddNumbers">

<input type="reset" value="Reset">

</form>

<%

String str1 = request.getParameter("num1");

String str2 = request.getParameter("num2");

if ( str1 != null && str2 != null ) {

%>

<%@include file="add.jsp" %>

<%

}

%>

</body>

</html>

Code Sample 10: add.jsp

<%@ page import="javax.xml.rpc.Stub,javax.naming.*,webclient.*" %>

<%

String resp = null;

int result = 0;

try {

// Create a stub object

Stub stub = (Stub)(new MyFirstService_Impl().getMathFacePort());

// Set the endpoint address the stub uses to access the service

stub._setProperty(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY,

"http://localhost:8080/math-service/math");

// Cast the stub to MathFace

MathFace math = (MathFace)stub;

// Retrieve and parse the parameters from the request message

int x = Integer.parseInt(request.getParameter("num1"));

int y = Integer.parseInt(request.getParameter("num2"));

// Invoke the method

result = math.add(x, y);

} catch (Exception ex) {

}

%>

<h2>The sum is: <%=result%></h2>

The
next step is to deploy the web client as a JSP web component using the deploytool.
Again, if you haven't used deploytool, start the
J2EE application server (if it is not already running) and follow these
instructions (steps 5 to 11) to package and deploy the web client as
a JSP web component. During deployment, I specified this URL http://localhost:8080/math-webservice/add
to be used to access the service. Figure 4 shows the a client calling a web
service into action.

Figure 4: A JSP-based web client calling a web
service

Conclusion

Web
services are the next step in the web's evolution, since they promise the
infrastructure and tools for automation of business-to-business relationships
over the Internet. The integration of web services into the J2EE 1.4 platform
simplifies the task of building and consuming web services, by freeing the Java
technology developer from the low-level details of XML and web services
standards.

The
code samples in this article demonstrate how easy it is to develop web services
using J2EE 1.4. It's important to note that such services can be invoked by
non-J2EE clients; also, J2EE-based clients can consume web services developed
using other technologies.

In
a world of constantly changing technology requirements, J2EE is leading the way
to enable the Enterprise
to integrate the latest and greatest technology standards, while still
leveraging existing IT investment.

2
INTRODUCTION TO JSP AND JAVA SERVLETS

What
are Servlets?

Servlets
are the Java Technologies' answer to CGI programming. They are programs which
run on the server side and generate dynamic content. Why would one prefer to
use Servlets over traditional CGI programming?

Efficiency - Using
CGI programming, each time an HTTP request is received a new process is
started, which can result in poor performance and scalability issues.
Using Servlets, the Java VM is always running, therefore, starting a
Servlet creates a Java thread as opposed to a system process.

Power - Servlets
allow you power unknown by traditional CGI. They allow you to do things
that would either be very difficult or otherwise impossible because they
have access to the entire family of Java APIs. Servlets easily share data
and maintain information, making session tracking and other chores a
breeze.

Security -
Servlets can be run by the Servlet engine in a restrictive sandbox,
similar to web browser's sandbox for applets. The helps protect against
malicious Servlets.

Cost - There are
plenty of "free" or low-cost web servers available for either
personal use or low volume traffic. If you have a web server, chances are
you can add Servlet technology quickly, easily, and best of all, cheaply.

Portability - The
Servlet API takes advantage of the Java platform. It is a fairly simple
API which is supported by nearly all web servers so that Servlets may be
moved from platform to platform, usually without any modification
whatsoever.

A
Servlet is a Java class and thus needs to be executed by the Java VM, called a
Servlet engine. Servlets are loaded by the engine when they are called and
remain running until the servlet is explicitly unloaded or the engine is shut
down. The Java Servlet Development Kit (JSDK) is available for download
from the Sun Site. It includes the Servlet API and a simple Servlet engine.

What
is JSP?

JSP
is a extension of Servlets technology. Anything that is done in JSP can be done
with Servlets, however, JSP allows you to easily mix static HTML with your
code. Typically, it is also easier to read the code and visualize the page that
will ultimately be generated. For instance:

JSP

<HTML>

<HEAD>

<TITLE>Hello World!!</TITLE>

</HEAD>

<BODY>

Hello World! Your name is:<%
out.println(response.getParameter("name"));%>

</BODY>

</HTML>

Servlet

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class HelloWorld extends HttpServlet

{

public void
doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException

{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Hello World!!</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("Hello World! Your name is: "

+ response.getParameter("name"));

out.println("</BODY>");

out.println("</HTML>");

}

}

In
a nutshell, the JSP page is being converted to a normal servlet, with static
data being written to an output stream. There are ways to reduce the actual
amount of code written in the Servlet, but as you can see, even though they
both generate the same output, JSP is easier to read and easier to write.
Clearly, JSP and Servlets have their own distinct roles and uses which allow
the developer freedom and ease of use.

So,
how do I set things up?

There
are a number of different Servlet engines available to supplement whatever
server you are currently using. A list of commonly used engines and other
addons is available here.

Having
tried several different engines, I suggest that you try Allaire's JRun. JRun works
by intercepting all requests for servlets, JSP, etc., executes them, and
returns the response through the Web server to the client. JRun is much more
sophisticated than Sun's Servlet engine and supports more features.

JRun
supports:

Enterprise
Java Beans 1.1

Java Transaction API 1.0

Java Messaging Service 1.0

Java Server Pages 1.1

Java Servlets 2.2

JRun is easy to set up and easy to
configure. Another nice feature is the ability to set JDBC data sources so that
you no longer have to hard code database information into your Servlets or
other applications. Installation

Here
we will briefly outline the installation of JRun. Many of the following steps
are common but may vary from engine to engine.

First
off, make sure that you have JDK 1.2.2 or later installed. Next, disable your
web server and close all other programs. Run the executable.

After
beginning the install and progressing through several self-explanatory prompts,
you will be asked for a port number to use to connect to the server. It is
suggested that you use 8000, however, you may choose any port outside the range
8100 to 8199 (JRun uses a port in this range for its JWS service).

You
need to configure your web server to work with JRun. If you are using IIS 4.0
or 5.0, open the Microsoft Management Console. Select WWW service and then
click edit. Select the local pathfield and set permissions to Execute (include
script). You may set this globally as well by selecting the server, however,
this may have security consequences. If you are prompted to change Inheritance
Overrides, click OK.

You
may now open the JMC (JRun Management Console). To do this, in your browser
type //localhost:8000/ . After logging in as the administrator, you can
configure each server (admin and default). It is suggested that you configure
default first, since this is where applications will be deployed. It is not
really ever necessary to configure the admin server to work with IIS. Select
the default server and select the appropriate third party web server
information. Depending upon your web server, you may have different information
to enter.

Test
all the demos and see if they work!

If
you would like to set up some data sources within JRun, chances are good that
you will need a 3rd party driver. Here
is a fairly complete list.

Installing
your Servlets & JSP pages

Compiling
your Servlets, requires you to properly set the CLASSPATH. For example, if you
are using JRun in a Windows environment with JDK 1.3, you would open a prompt
and do the following:

C:\set CLASSPATH=C:\<JRun directory>\lib\ext\servlet.jar; %CLASSPATH%

To
install your Servlet copy the .java file to C:\<JRun
directory>\servers\default\default-app\WEB-INF\classes

Compile your Servlet:

C:\...\classes\> javac HelloWorld.java

To
test your Servlet, type this URL in your browser: //localhost:8100/default-app/servlet/HelloWorld

In
order to install .jsp pages, simply copy them to your default-app directory.

For
other servers and engines, your necessary steps may vary, however, you will
almost always need to set the classpath to servlet.jar and you always need to
compile Servlets.

A
Simple Example

Let's
see the most simple Servlet example to get you started:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class HelloWeb extends HttpServlet

{

public void
doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException

{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println(<HTML><HEAD><TITLE>Hello Web</TITLE> "
+ "</HEAD><BODY>Hello Web!</BODY></HTML>");

out.close();

}

public void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException

{

doGet(request,
response);

}

}

Let's
break down the code and analyze its parts. First, we import java.io.*, javax.servlet.*,
and javax.servlet.http.* because they contain many classes which are commonly
used by Servlets. You will almost always need to import these packages. Next,
we declare our class, which extends the standard base class for all Servlets.
We also need to override the doGet method of HttpServlet. In the main block of
code, we must set the content type. It is required that all header information
be set before any PrintWriter or ServletOutputStream is requested to write data
to the document. We request a PrintWriter to begin writing data to the response
object. Using the PrintWriter object, we write our text. We then close the
object. We have also overridden the doPost method. In this context, it doesn't
make too much sense, however, in most circumstances this is something you will
want to do. For instance, if you are receiving data using POST data as oppose
GET data, this will allow your Servlet to handle both circumstances easily.

3
SERVLETS

What
Is a Servlet?

A servlet
is a Java programming language class used to extend the capabilities of servers
that host applications accessed via a request-response programming model.
Although servlets can respond to any type of request, they are commonly used to
extend the applications hosted by Web servers. For such applications, Java
Servlet technology defines HTTP-specific servlet classes.

The javax.servlet and javax.servlet.http packages provide interfaces and classes for
writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods.

When
implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost,
for handling HTTP-specific services.

The Example Servlets

This chapter
uses the Duke's Bookstore application to illustrate the tasks involved in
programming servlets. Table 10-1
lists the servlets that handle each bookstore function. Each programming task
is illustrated by one or more servlets. For example, BookDetailsServlet
illustrates how to handle HTTP GET requests, BookDetailsServlet and
CatalogServlet show how to construct responses, and CatalogServlet illustrates
how to track session information.

Table 10-1 Duke's Bookstore
Example Servlets

Function

Servlet

Enter the
bookstore

BookStoreServlet

Create the
bookstore banner

BannerServlet

Browse the
bookstore catalog

CatalogServlet

Put a book
in a shopping cart

CatalogServlet,

BookDetailsServlet

Get
detailed information on a specific book

BookDetailsServlet

Display
the shopping cart

ShowCartServlet

Remove one
or more books from the shopping cart

ShowCartServlet

Buy the
books in the shopping cart

CashierServlet

Receive an
acknowledgement for the purchase

ReceiptServlet

The data for
the bookstore application is maintained in a database and accessed through the
helper class database.BookDB. The database package also contains the class
BookDetails, which represents a book. The shopping cart and shopping cart items
are represented by the classes cart.ShoppingCart and cart.ShoppingCartItem,
respectively.

The source
code for the bookstore application is located in the
j2eetutorial/examples/src/web/bookstore1 directory created when you unzip the
tutorial bundle To build, deploy, and run the example, follow these steps.

Go to j2eetutorial/examples and build the example by running ant
bookstore1

Start
the j2ee server.

Start deploytool.

Start the Cloudscape database server by running cloudscape -start.

Load the bookstore data into the database by running ant
create-web-db.

Create a J2EE application called Bookstore1App.

Select FileNewApplication.

In the file chooser, navigate to
j2eetutorial/examples/src/web/bookstore1.

In the File Name field, enter Bookstore1App.

Click New Application.

Click OK.

Create the WAR and add the BannerServlet Web component and all of
the Duke's Bookstore content to the Bookstore1App application.

Select FileNewWeb
Component.

Click the Create New WAR File In Application radio button and
select Bookstore1App from the combo box. Enter Bookstore1WAR in the field
labeled WAR Display Name.

Click Edit to add the content files.

In the Edit Archive Contents dialog box, navigate to
j2eetutorial/examples/build/web/bookstore1. Select BannerServlet.class,
BookStoreServlet.class, BookDetailsServlet.class, CatalogServlet.class,
ShowCartServlet.class, CashierServlet.class, and ReceiptServlet.class.
Click Add. Add errorpage.html and duke.books.gif. Add the cart, database,
exception, filters, listeners, messages, and util packages. Click OK.

Click Next.

Select the Servlet radio button.

Click Next.

Select BannerServlet from the Servlet Class combo box.

Click Next twice.

In the Component Aliases pane, click Add and then type /banner in
the Alias field.

Click Finish.

Add each of the Web components listed in Table 10-2.
For each servlet, click the Add to Existing WAR File radio button and
select Bookstore1WAR from the combo box. Since the WAR contains all of the
servlet classes, you do not have to add any more content.

Table 10-2 Duke's Bookstore Web
Components

Web Component Name

Servlet Class

Component Alias

BookStoreServlet

BookStoreServlet

/enter

CatalogServlet

CatalogServlet

/catalog

BookDetailsServlet

BookDetailsServlet

/bookdetails

ShowCartServlet

ShowCartServlet

/showcart

CashierServlet

CashierServlet

/cashier

ReceiptServlet

ReceiptServlet

/receipt

Add a resource reference for the Cloudscape database.

Select Bookstore1WAR.

Select the Resource Refs tab.

Click Add.

Select javax.sql.DataSource from the Type column

Enter jdbc/BookDB in the Coded Name field.

Enter jdbc/Cloudscape in the JNDI Name field.

Add the listener class listeners.ContextListener (described in Handling
Servlet Life-Cycle Events).

Select the Event Listeners tab.

Click Add.

Select the listeners.ContextListener class from the drop-down field
in the Event Listener Classes pane.

Add an error page (described in Handling
Errors).

Select the File Refs tab.

In the Error Mapping panel, click Add.

Enter exception.BookNotFoundException in the Error/Exception field.

Enter /errorpage.html in the Resource To Be Called field.

Repeat for exception.BooksNotFoundException and
javax.servlet.UnavailableException.

Add the filters filters.HitCounterFilter and filters.OrderFilter
(described in Filtering
Requests and Responses).

Select the Filter Mapping tab.

Click Edit Filter List.

Click Add.

Select filters.HitCounterFilter from the Filter Class column. The
deploytool utility will automatically enter HitCounterFilter in the
Display Name column.

Click Add.

Select filters.OrderFilter from the Filter Class column. The
deploytool utility will automatically enter OrderFilter in the Display
Name column.

Click OK.

Click Add.

Select HitCounterFilter from the Filter Name column.

Select Servlet from the Target Type column.

Select BookStoreServlet from the Target column.

Repeat for OrderFilter. The target type is Servlet and the target
is ReceiptServlet.

Enter the context root.

Select Bookstore1App.

Select the Web Context tab.

Enter bookstore1.

Deploy the application.

Select ToolsDeploy.

Click Finish.

Open the bookstore URL http://<host>:8000/bookstore1/enter.

Troubleshooting

The section Common
Problems and Their Solutions (in particular, Web
Client Runtime Errors) lists some reasons why a Web client can fail. In
addition, Duke's Bookstore returns the following exceptions:

BookNotFoundException: Returned if a book can't be located in the
bookstore database. This will occur if you haven't loaded the bookstore
database with data by running ant create-web-db or if the Cloudscape
server hasn't been started or it has crashed.

BooksNotFoundException: Returned if the bookstore data can't be
retrieved. This will occur if you haven't loaded the bookstore database
with data by running ant create-web-db or if the Cloudscape server hasn't
been started or has crashed.

UnavailableException: Returned if a servlet can't retrieve the Web context
attribute representing the bookstore. This will occur if you haven't added
the listener class to the application.

Since we
have specified an error page, you will see the message The application is
unavailable. Please try later. If you don't specify an error page, the Web
container generates a default page containing the message A Servlet Exception
Has Occurred and a stack trace that can help diagnose the cause of the
exception. If you use errorpage.html, you will have to look in the Web
container's log to determine the cause of the exception. Web log files reside
in the directory

$J2EE_HOME/logs/<host>/web

and are named catalina.<date>.log.

The
<logs> element is the directory specified by the log.directory entry in
the default.properties file. The default value is logs. The <host>
element is the name of the computer. See the Configuration Guide
provided with the J2EE SDK for more information about J2EE SDK log files.

Servlet Life Cycle

The
life cycle of a servlet is controlled by the container in which the servlet has
been deployed. When a request is mapped to a servlet, the container performs
the following steps.

If an instance of the servlet does not exist,
the Web container

Loads the servlet class.

Creates an instance of the servlet class.

Initializes the servlet instance by calling
the init
method. Initialization is covered in Initializing
a Servlet.

Invokes the service
method, passing a request and response object. Service methods are
discussed in the section Writing
Service Methods.

If
the container needs to remove the servlet, it finalizes the servlet by calling the
servlet's destroy method. Finalization is discussed in Finalizing a
Servlet.

Handling Servlet Life-Cycle Events

You
can monitor and react to events in a servlet's life cycle by defining listener
objects whose methods get invoked when life cycle events occur. To use these
listener objects, you must define the listener class and specify the listener
class.

Defining
The Listener Class

You
define a listener class as an implementation of a listener interface. Table 10-3
lists the events that can be monitored and the corresponding interface that
must be implemented. When a listener method is invoked, it is passed an event
that contains information appropriate to the event. For example, the methods in
the HttpSessionListener interface are passed an HttpSessionEvent,
which contains an HttpSession.

Table 10-3
Servlet Life-Cycle Events

Object

Event

Listener Interface and Event Class

Web
context (See Accessing
the Web Context)

Initialization
and destruction

javax.servlet.ServletContextListener
and

ServletContextEvent

Attribute
added, removed, or replaced

javax.servlet.ServletContextAttributeListener
and

ServletContextAttributeEvent

Session
(See Maintaining
Client State)

Creation,
invalidation, and timeout

javax.servlet.http.HttpSessionListener
and

HttpSessionEvent

Attribute
added, removed, or replaced

javax.servlet.http.HttpSessionAttributeListener
and

HttpSessionBindingEvent

The
listeners.ContextListener class creates and
removes the database helper and counter objects used in the Duke's Bookstore
application. The methods retrieve the Web context object from ServletContextEvent
and then store (and remove) the objects as servlet context attributes.

import database.BookDB;

import javax.servlet.*;

import util.Counter;

public final class ContextListener

implements ServletContextListener {

private ServletContext context = null;

public void contextInitialized(ServletContextEvent event) {

context = event.getServletContext();

try {

BookDB bookDB = new BookDB();

context.setAttribute("bookDB", bookDB);

} catch (Exception ex) {

System.out.println(

"Couldn't create database: " + ex.getMessage());

}

Counter counter = new Counter();

context.setAttribute("hitCounter", counter);

context.log("Created hitCounter" +

counter.getCounter());

counter = new Counter();

context.setAttribute("orderCounter", counter);

context.log("Created orderCounter" +

counter.getCounter());

}

public void contextDestroyed(ServletContextEvent event) {

context = event.getServletContext();

BookDB bookDB = context.getAttribute(

"bookDB");

bookDB.remove();

context.removeAttribute("bookDB");

context.removeAttribute("hitCounter");

context.removeAttribute("orderCounter");

}

}

Specifying
Event Listener Classes

You
specify a listener class for a WAR in the deploytool Event Listeners
inspector (see Event
Listeners).

Handling Errors

Any
number of exceptions can occur when a servlet is executed. The Web container
will generate a default page containing the message A
Servlet Exception Has Occurred when an exception occurs, but you
can also specify that the container should return a specific error page for a
given exception. You specify error pages for a WAR in the deploytool
File Refs inspector

Sharing
Information

Web components, like most
objects, usually work with other objects to accomplish their tasks. There are
several ways they can do this. They can use private helper objects (for
example, JavaBeans components), they can share objects that are attributes of a
public scope, they can use a database, and they can invoke other Web resources.
The Java Servlet technology mechanisms that allow a Web component to invoke
other Web resources are described in the section Invoking
Other Web Resources.

Using
Scope Objects

Collaborating Web components
share information via objects maintained as attributes of four scope objects.
These attributes are accessed with the [get|set]Attribute
methods of the class representing the scope. Table 10-4
lists the scope objects. Figure 10-1
shows the scoped attributes maintained by the Duke's Bookstore application

Table 10-4 Scope Objects

Scope Object

Class

Accessible From

Web context

javax.servlet.ServletContext

Web components within a Web context (see Accessing
the Web Context)

session

javax.servlet.http.HttpSession

Web components handling a request that belongs
to the session (see Maintaining
Client State)

request

Subtype of javax.servlet.ServletRequest

Web components handling the request

page

javax.servlet.jsp.PageContext

The JSP page that creates the object (see
Chapter 11)

.

Figure 10-1 Duke's Bookstore
Scoped Attributes

Controlling
Concurrent Access to Shared Resources

In a multithreaded server, it
is possible for shared resources to be accessed concurrently. Besides scope
object attributes, shared resources include in-memory data such as instance or
class variables, and external objects such as files, database connections, and
network connections. Concurrent access can arise in several situations:

Multiple Web components
accessing objects stored in the Web context

Multiple Web components
accessing objects stored in a session

Multiple threads within a
Web component accessing instance variables. A Web container will typically
create a thread to handle each request. If you want to ensure that a
servlet instance handles only one request at a time, a servlet can
implement the SingleThreadModel interface.
If a servlet implements this interface, you are guaranteed that no two
threads will execute concurrently in the servlet's service method. A Web
container can implement this guarantee by synchronizing access to a single
instance of the servlet, or by maintaining a pool of Web component
instances and dispatching each new request to a free instance. This
interface does not prevent synchronization problems that result from Web
components accessing shared resources such as static class variables or
external objects.

When resources can be accessed
concurrently, they can be used in an inconsistent fashion. To prevent this, you
must control the access using the synchronization techniques described in the Threads lesson in The Java
Tutorial. In the previous section we showed
five scoped attributes shared by more than one servlet: bookDB,
cart, currency, hitCounter,
and orderCounter. The bookDB
attribute is discussed in the next section. The cart, currency, and counters
can be set and read by multiple multithreaded servlets. To prevent these
objects from being used inconsistently, access is controlled by synchronized
methods. For example, here is the util.Counter class:

public class Counter {

private int counter;

public Counter() {

counter = 0;

}

public synchronized int getCounter() {

return counter;

}

public synchronized int setCounter(int c) {

counter = c;

return counter;

}

public synchronized int incCounter() {

return(++counter);

}

}

Accessing
Databases

Data that is shared between Web
components and is persistent between invocations of a J2EE application is
usually maintained by a database. Web components use the JDBC 2.0 API to access
relational databases. The data for the bookstore application is maintained in a
database and accessed through the helper class database.BookDB. For example, ReceiptServlet invokes the BookDB.buyBooks
method to update the book inventory when a user makes a purchase. The buyBooks
method invokes buyBook for each book contained in the
shopping cart. To ensure the order is processed in its entirety, the calls to buyBook
are wrapped in a single JDBC transaction. The use of the shared database
connection is synchronized via the [get|release]Connection
methods.

public void buyBooks(ShoppingCart cart) throws OrderException {

Collection items = cart.getItems();

Iterator i = items.iterator();

try {

getConnection();

con.setAutoCommit(false);

while (i.hasNext()) {

ShoppingCartItem sci = (ShoppingCartItem)i.next();

BookDetails bd = (BookDetails)sci.getItem();

String id = bd.getBookId();

int quantity = sci.getQuantity();

buyBook(id, quantity);

}

con.commit();

con.setAutoCommit(true);

releaseConnection();

} catch (Exception ex) {

try {

con.rollback();

releaseConnection();

throw new OrderException("Transaction failed: " +

ex.getMessage());

} catch (SQLException sqx) {

releaseConnection();

throw new OrderException("Rollback failed: " +

sqx.getMessage());

}

}

}

Initializing
a Servlet

After the Web container loads and instantiates the
servlet class and before it delivers requests from clients, the Web container
initializes the servlet. You can customize this process to allow the servlet to
read persistent configuration data, initialize resources, and perform any other
one-time activities by overriding the init method of the Servlet interface. A servlet that cannot complete its
initialization process should throw UnavailableException. All
the servlets that access the bookstore database (BookStoreServlet, CatalogServlet, BookDetailsServlet, and ShowCartServlet) initialize a variable in their init method
that points to the database helper object created by the Web context listener:

public class CatalogServlet extends HttpServlet {

private BookDB bookDB;

public void init() throws ServletException {

bookDB =
(BookDB)getServletContext().

getAttribute("bookDB");

if (bookDB ==
null) throw new

UnavailableException("Couldn't get database.");

}

}

4
OVERVIEW OF JAVA SERVER PAGES

1. Overview

JavaServer Pages (JSP) lets you
separate the dynamic part of your pages from the static HTML. You simply write
the regular HTML in the normal manner, using whatever Web-page-building tools
you normally use. You then enclose the code for the dynamic parts in special
tags, most of which start with "<%"
and end with "%>". For
example, here is a section of a JSP page that results in something like
"Thanks for ordering Core Web Programming" for a URL of http://host/OrderConfirmation.jsp?title=Core+Web+Programming:

Thanks for ordering

<I><%= request.getParameter("title") %></I>

You normally give your file a .jsp
extension, and typically install it in any place you could place a normal Web
page. Although what you write often looks more like a regular HTML file than a
servlet, behind the scenes, the JSP page just gets converted to a normal servlet,
with the static HTML simply being printed to the output stream associated with
the servlet's service method.
This is normally done the first time the page is requested, and developers can
simply request the page themselves when first installing it if they want to be
sure that the first real user doesn't get a momentary delay when the JSP page
is translated to a servlet and the servlet is compiled and loaded. Note also
that many Web servers let you define aliases that so that a URL that appears to
reference an HTML file really points to a servlet or JSP page.

Aside from the regular HTML,
there are three main types of JSP constructs that you embed in a page:
scripting elements, directives, and actions. Scripting elements let you
specify Java code that will become part of the resultant servlet, directives
let you control the overall structure of the servlet, and actions let
you specify existing components that should be used, and otherwise control the
behavior of the JSP engine. To simplify the scripting elements, you have access
to a number of predefined variables such as request in the snippet
above.

Note that this tutorial covers
version 1.0 of the JSP specification. JSP has changed dramatically since
version 0.92, and although these changes were almost entirely for the better,
you should note that version 1.0 JSP pages are almost totally incompatible with
the earlier JSP engines. Note that this JSP tutorial is part of a larger
tutorial on servlets and JSP at http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/.

2.
Syntax Summary

JSP
Element

Syntax

Interpretation

Notes

JSP Expression

<%= expression %>

Expression
is evaluated and placed in output.

XML
equivalent is

<jsp:expression>

expression

</jsp:expression>.
Predefined variables are request,
response, out, session, application, config, and pageContext (available
in scriptlets also).

JSP Scriptlet

<% code %>

Code
is inserted in service method.

XML equivalent is

<jsp:scriptlet>

code

</jsp:scriptlet>.

JSP Declaration

<%! code %>

Code is inserted in body of servlet
class, outside of service method.

XML equivalent is

<jsp:declaration>

code

</jsp:declaration>.

JSP page
Directive

<%@ page att="val" %>

Directions to the servlet engine
about general setup.

XML equivalent is

<jsp:directive.page att="val"\>.
Legal attributes, with default values in bold, are:

import="package.class"

contentType="MIME-Type"

isThreadSafe="true|false"

session="true|false"

buffer="sizekb|none"

autoflush="true|false"

extends="package.class"

info="message"

errorPage="url"

isErrorPage="true|false"

language="java"

JSP include
Directive

<%@ include file="url" %>

A file on the local system to be
included when the JSP page is translated into a servlet.

XML
equivalent is

<jsp:directive.include

file="url"\>.

The URL must be a relative one. Use the jsp:include
action to include a file at request time instead of translation time.

JSP Comment

<%-- comment --%>

Comment; ignored when JSP page is translated
into servlet.

If you want a comment in the
resultant HTML, use regular HTML comment syntax of <-- comment -->.

The jsp:include
Action

<jsp:include

page="relative URL"

flush="true"/>

Includes a file at the time the page
is requested.

If you want to include the file at
the time the page is translated, use the page
directive with the include
attribute instead. Warning: on
some servers, the included file must be an HTML file or JSP file, as
determined by the server (usually based on the file extension).

The jsp:useBean
Action

<jsp:useBean att=val*/> or

<jsp:useBean att=val*>

...

</jsp:useBean>

Find or build a Java Bean.

Possible attributes are:

id="name"

scope="page|request|session|application"

class="package.class"

type="package.class"

beanName="package.class"

The jsp:setProperty
Action

<jsp:setProperty att=val*/>

Set bean properties, either
explicitly or by designating that value comes from a request parameter.

Legal attributes are

name="beanName"

property="propertyName|*"

param="parameterName"

value="val"

The jsp:getProperty
Action

<jsp:getProperty

name="propertyName"

value="val"/>

Retrieve and output bean properties.

The jsp:forward
Action

<jsp:forward

page="relative URL"/>

Forwards request to another page.

The jsp:plugin
Action

<jsp:plugin

attribute="value"*>

...

</jsp:plugin>

Generates OBJECT or EMBED tags, as
appropriate to the browser type, asking that an applet be run using the Java
Plugin.

3. Template Text: Static HTML

In many cases, a large percent of your
JSP page just consists of static HTML, known as template text. In all
respects except one, this HTML looks just like normal HTML, follows all the
same syntax rules, and is simply "passed through" to the client by
the servlet created to handle the page. Not only does the HTML look
normal, it can be created by whatever tools you already are using for
building Web pages. For example, I used Allaire's HomeSite for most of the JSP
pages in this tutorial.

The one minor exception to the "template
text is passed straight through" rule is that, if you want to have "<%"
in the output, you need to put "<\%" in the
template text.

4.
JSP Scripting Elements

JSP scripting elements let you insert
Java code into the servlet that will be generated from the current JSP page.
There are three forms:

Expressions of
the form <%= expression %>
that are evaluated and inserted into the output,

Scriptlets of
the form <% code %>
that are inserted into the servlet's service
method, and

Declarations of
the form <%! code %>
that are inserted into the body of the servlet class, outside of any
existing methods.

Each of these
is described in more detail below.

4.1
JSP Expressions

A JSP expression is used to
insert Java values directly into the output. It has the following form:

<%= Java Expression %>

The Java expression is evaluated,
converted to a string, and inserted in the page. This evaluation is performed
at run-time (when the page is requested), and thus has full access to
information about the request. For example, the following shows the date/time
that the page was requested:

Current time: <%= new java.util.Date() %>

To simplify these expressions, there
are a number of predefined variables that you can use. These implicit objects
are discussed in more detail later, but for the purpose of expressions, the
most important ones are:

request, the HttpServletRequest;

response, the HttpServletResponse;

session, the HttpSession
associated with the request (if any); and

out, the PrintWriter (a
buffered version of type JspWriter)
used to send output to the client.

Here's an
example:

Your hostname: <%= request.getRemoteHost() %>

Finally, note that XML authors can use
an alternative syntax for JSP expressions:

<jsp:expression>

Java Expression

</jsp:expression>

Remember that XML elements, unlike
HTML ones, are case sensitive. So be sure to use lowercase.

4.2
JSP Scriptlets

If you want to do something more
complex than insert a simple expression, JSP scriptlets let you insert
arbitrary code into the servlet method that will be built to generate the page.
Scriptlets have the following form:

<% Java Code %>

Scriptlets have access to the same
automatically defined variables as expressions. So, for example, if you want
output to appear in the resultant page, you would use the out variable.

<%

String queryData = request.getQueryString();

out.println("Attached GET data: " + queryData);

%>

Note that code inside a scriptlet gets
inserted exactly as written, and any static HTML (template text) before
or after a scriptlet gets converted to print
statements. This means that scriptlets need not contain complete Java
statements, and blocks left open can affect the static HTML outside of the
scriptlets. For example, the following JSP fragment, containing mixed template
text and scriptlets

<% if (Math.random() < 0.5) { %>

Have a <B>nice</B> day!

<% } else { %>

Have a <B>lousy</B> day!

<% } %>

will get converted to something like:

if (Math.random() < 0.5) {

out.println("Have a <B>nice</B> day!");

} else {

out.println("Have a <B>lousy</B> day!");

}

If you want to use the characters
"%>"
inside a scriptlet, enter "%\>"
instead. Finally, note that the XML equivalent of <% Code %>
is

<jsp:scriptlet>

Code

</jsp:scriptlet>

4.3
JSP Declarations

A JSP declaration lets you
define methods or fields that get inserted into the main body of the servlet
class (outside of the service method
processing the request). It has the following form:

<%! Java Code %>

Since declarations do not generate any
output, they are normally used in conjunction with JSP expressions or
scriptlets. For example, here is a JSP fragment that prints out the number of
times the current page has been requested since the server booted (or the
servlet class was changed and reloaded):

<%! private int accessCount = 0; %>

Accesses to page since server reboot:

<%= ++accessCount %>

As with scriptlets, if you want to use
the characters "%>",
enter "%\>"
instead. Finally, note that the XML equivalent of <%! Code %>
is

<jsp:declaration>

Code

</jsp:declaration>

5.
JSP Directives

A JSP directive affects the
overall structure of the servlet class. It usually has the following form:

<%@ directive attribute="value" %>

However, you can also combine multiple
attribute settings for a single directive, as follows:

<%@ directive attribute1="value1"

attribute2="value2"

...

attributeN="valueN" %>

There are two main types of directive:
page, which lets
you do things like import classes, customize the servlet superclass, and the
like; and include, which
lets you insert a file into the servlet class at the time the JSP file is
translated into a servlet. The specification also mentions the taglib directive, which
is not supported in JSP version 1.0, but is intended to let JSP authors define
their own tags. It is expected that this will be the main new contribution of
JSP 1.1.

5.1
The JSP page Directive

The page
directive lets you define one or more of the following case-sensitive
attributes:

import="package.class" or import="package.class1,...,package.classN".
This lets you specify what packages should be imported. For example:

<%@ page
import="java.util.*" %>

The import
attribute is the only one that is allowed to appear multiple times.

contentType="MIME-Type" or

contentType="MIME-Type;
charset=Character-Set"

This specifies the MIME type of the output. The default is text/html. For
example, the directive

<%@ page
contentType="text/plain" %>

has the same effect as the scriptlet

<%
response.setContentType("text/plain"); %>

isThreadSafe="true|false". A value of true (the default)
indicates normal servlet processing, where multiple requests can be
processed simultaneously with a single servlet instance, under the
assumption that the author synchronized access to instance variables. A
value of false
indicates that the servlet should implement SingleThreadModel,
with requests either delivered serially or with simultaneous requests
being given separate servlet instances.

session="true|false". A value of true (the default)
indicates that the predefined variable session
(of type HttpSession)
should be bound to the existing session if one exists, otherwise a new
session should be created and bound to it. A value of false indicates that
no sessions will be used, and attempts to access the variable session will result
in errors at the time the JSP page is translated into a servlet.

buffer="sizekb|none". This specifies the buffer size
for the JspWriter
out. The
default is server-specific, but must be at least 8kb.

autoflush="true|false". A value of true, the default,
indicates that the buffer should be flushed when it is full. A value of false, rarely used,
indicates that an exception should be thrown when the buffer overflows. A
value of false
is illegal when also using buffer="none".

extends="package.class". This indicates the superclass
of servlet that will be generated. Use this with extreme caution, since
the server may be using a custom superclass already.

info="message". This defines a string that can
be retrieved via the getServletInfo
method.

errorPage="url". This specifies a JSP page that
should process any Throwables
thrown but not caught in the current page.

isErrorPage="true|false". This indicates whether or not
the current page can act as the error page for another JSP page. The
default is false.

language="java". At some point, this is intended
to specify the underlying language being used. For now, don't bother with
this since java
is both the default and the only legal choice.

The XML syntax
for defining directives is

<jsp:directive.directiveType attribute=value />

For example, the XML equivalent of

<%@ page import="java.util.*" %>

is

<jsp:directive.page import="java.util.*" />

5.2 The JSP include Directive

This directive lets you include files
at the time the JSP page is translated into a servlet. The directive looks like
this:

<%@ include file="relative url" %>

The URL specified is normally
interpreted relative to the JSP page that refers to it, but, as with relative
URLs in general, you can tell the system to interpret the URL relative to the
home directory of the Web server by starting the URL with a forward slash. The
contents of the included file are parsed as regular JSP text, and thus can
include static HTML, scripting elements, directives, and actions.

For example, many sites include
a small navigation bar on each page. Due to problems with HTML frames, this is
usually implemented by way of a small table across the top of the page or down
the left-hand side, with the HTML repeated for each page in the site. The include
directive is a natural way of doing this, saving the developers from the
maintenance nightmare of actually copying the HTML into each separate file.
Here's some representative code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE>Servlet Tutorial: JavaServer Pages (JSP) 1.0</TITLE>

<META NAME="author" CONTENT="[email-masked]">

<META NAME="keywords" CONTENT="...">

<META NAME="description" CONTENT="...">

<LINK REL=STYLESHEET

HREF="Site-Styles.css"

TYPE="text/css">

</HEAD>

<BODY>

<%@ include file="/navbar.html" %>

<!-- Part specific to this page ... -->

</BODY>

</HTML>

Note that since the include directive inserts
the files at the time the page is translated, if the navigation bar changes,
you need to re-translate all the JSP pages that refer to it. This is a good
compromise in a situation like this, since the navigation bar probably changes
infrequently, and you want the inclusion process to be as efficient as
possible. If, however, the included files changed more often, you could use the
jsp:include
action instead. This includes the file at the time the JSP page is requested,
and is discussed in the tutorial section on JSP actions.

6.
Example Using Scripting Elements and Directives

Here is a simple example showing the
use of JSP expressions, scriptlets, declarations, and directives. You can also download the source
or try it on-line.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE>Using JavaServer Pages</TITLE>

<META NAME="author" CONTENT="Marty Hall -- [email-masked]">

<META NAME="keywords"

CONTENT="JSP,JavaServer Pages,servlets">

<META NAME="description"

CONTENT="A quick example of the four main JSP tags.">

<LINK REL=STYLESHEET

HREF="My-Style-Sheet.css"

TYPE="text/css">

</HEAD>

<BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE"

VLINK="#551A8B" ALINK="#FF0000">

<CENTER>

<TABLE BORDER=5 BGCOLOR="#EF8429">

<TR><TH CLASS="TITLE">

Using JavaServer Pages</TABLE>

</CENTER>

<P>

Some dynamic content created using various JSP mechanisms:

<UL>

<LI><B>Expression.</B><BR>

Your hostname: <%= request.getRemoteHost() %>.

<LI><B>Scriptlet.</B><BR>

<% out.println("Attached GET data: " +

request.getQueryString()); %>

<LI><B>Declaration (plus expression).</B><BR>

<%! private int accessCount = 0; %>

Accesses to page since server reboot: <%= ++accessCount %>

<LI><B>Directive (plus expression).</B><BR>

<%@ page import = "java.util.*" %>

Current date: <%= new Date() %>

</UL>

</BODY>

</HTML>

Here's a typical result:

7.
Predefined Variables

To simplify code in JSP expressions
and scriptlets, you are supplied with eight automatically defined variables,
sometimes called implicit objects. The available variables are request, response, out, session, application, config, pageContext, and page. Details for each
are given below.

7.1
request

This is the HttpServletRequest
associated with the request, and lets you look at the request parameters (via getParameter), the
request type (GET, POST, HEAD, etc.), and the
incoming HTTP headers (cookies, Referer,
etc.). Strictly speaking, request is allowed to be a subclass of ServletRequest other than
HttpServletRequest,
if the protocol in the request is something other than HTTP. This is almost
never done in practice.

7.2
response

This is the HttpServletResponse associated
with the response to the client. Note that, since the output stream (see out below) is buffered,
it is legal to set HTTP status codes and response headers, even though
this is not permitted in regular servlets once any output has been sent to the
client.

7.3
out

This is the PrintWriter used to send
output to the client. However, in order to make the response object (see the
previous section) useful, this is a buffered version of PrintWriter called JspWriter. Note that you
can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive. This was
discussed in Section 5.
Also note that out is used
almost exclusively in scriptlets, since JSP expressions automatically get
placed in the output stream, and thus rarely need to refer to out explicitly.

7.4
session

This is the HttpSession object
associated with the request. Recall that sessions are created automatically, so
this variable is bound even if there was no incoming session reference. The one
exception is if you use the session
attribute of the page directive
(see Section 5)
to turn sessions off, in which case attempts to reference the session variable
cause errors at the time the JSP page is translated into a servlet.

7.5
application

This is the ServletContext as
obtained via getServletConfig().getContext().

7.6
config

This is the ServletConfig object for
this page.

7.7
pageContext

JSP introduced a new class called PageContext to
encapsulate use of server-specific features like higher performance JspWriters. The idea is that,
if you access them through this class rather than directly, your code will
still run on "regular" servlet/JSP engines.

7.8
page

This is simply a synonym for this, and is not very
useful in Java. It was created as a placeholder for the time when the scripting
language could be something other than Java.

8. Actions

JSP actions use constructs in
XML syntax to control the behavior of the servlet engine. You can dynamically
insert a file, reuse JavaBeans components, forward the user to another page, or
generate HTML for the Java plugin. Available actions include:

jsp:include - Include a file at the time the
page is requested. See Section 8.1.

jsp:useBean - Find or instantiate a
JavaBean. See Section 8.2
for an overview, and Section 8.3
for details.

jsp:setProperty - Set the property of a
JavaBean. See Section 8.4.

jsp:getProperty - Insert the property of a
JavaBean into the output. See Section 8.5.

jsp:forward - Forward the requester to a new
page. See Section 8.6.

jsp:plugin - Generate browser-specific code
that makes an OBJECT
or EMBED tag
for the Java plugin. See Section 8.7.

These actions
are described in more detail below. Remember that, as with XML in general, the
element and attribute names are case sensitive.

8.1 The jsp:include Action

This action lets you insert files into
the page being generated. The syntax looks like this:

<jsp:include page="relative URL" flush="true" />

Unlike the include directive,
which inserts the file at the time the JSP page is translated into a servlet,
this action inserts the file at the time the page is requested. This pays a
small penalty in efficiency, and precludes the included page from containing
general JSP code (it cannot set HTTP headers, for example), but it gains
significantly in flexibility. For example, here is a JSP page that inserts four
different snippets into a "What's New?" Web page. Each time the
headlines change, authors only need to update the four files, but can leave the
main JSP page unchanged.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE>What's New</TITLE>

<LINK REL=STYLESHEET

HREF="My-Style-Sheet.css"

TYPE="text/css">

</HEAD>

<BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE"

VLINK="#551A8B" ALINK="#FF0000">

<CENTER>

<TABLE BORDER=5 BGCOLOR="#EF8429">

<TR><TH CLASS="TITLE">

What's New at JspNews.com</TABLE>

</CENTER>

<P>

Here is a summary of our four most recent news stories:

<OL>

<LI><jsp:include page="news/Item1.html" flush="true"/>

<LI><jsp:include page="news/Item2.html" flush="true"/>

<LI><jsp:include page="news/Item3.html" flush="true"/>

<LI><jsp:include page="news/Item4.html" flush="true"/>

</OL>

</BODY>

</HTML>

Here's a typical result:

8.2
The jsp:useBean Action

This action lets you load in a
JavaBean to be used in the JSP page. This is a a very useful capability because
it lets you exploit the reusability of Java classes without sacrificing the
convenience that JSP adds over servlets alone. The simplest syntax for
specifying that a bean should be used is:

<jsp:useBean id="name" class="package.class" />

This usually means "instantiate
an object of the class specified by class,
and bind it to a variable with the name specified by id." However, as
we'll see shortly, you can specify a scope
attribute that makes the bean associated with more than just the current page.
In that case, it is useful to obtain references to existing beans, and the jsp:useBean action
specifies that a new object is instantiated only if there is no existing one
with the same id and scope. Now, once you have
a bean, you can modify its properties via jsp:setProperty,
or by using a scriptlet and calling a method explicitly on the object with the
variable name specified earlier via the id
attribute. Recall that with beans, when you say "this bean has a property
of typeX called foo", you
really mean "this class has a method called getFoo
that returns something of type X, and another method called setFoo that takes an X
as an argument." The jsp:setProperty
action is discussed in more detail in the next section, but for now note that
you can either supply an explicit value,
give a param attribute
to say that the value is derived from the named request parameter, or just list
the property to indicate that the value should be derived from the request
parameter with the same name as the property. You read existing properties in a
JSP expression or scriptlet by calling the appropriate getXxx method, or
more commonly, by using the jsp:getProperty
action.

Note that the class specified
for the bean must be in the server's regular class path, not the part
reserved for classes that get automatically reloaded when they change. For
example, in the Java Web Server, it and all the classes it uses should go in the
classes directory or be in a jar file in the lib
directory, not be in the servlets directory.

Here is a very simple example
that loads a bean and sets/gets a simple String parameter.

BeanTest.jsp

You can also download the source
or try it on-line.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE>Reusing JavaBeans in JSP</TITLE>

<LINK REL=STYLESHEET

HREF="My-Style-Sheet.css"

TYPE="text/css">

</HEAD>

<BODY>

<CENTER>

<TABLE BORDER=5>

<TR><TH CLASS="TITLE">

Reusing JavaBeans in JSP</TABLE>

</CENTER>

<P>

<jsp:useBean id="test" class="hall.SimpleBean" />

<jsp:setProperty name="test"

property="message"

value="Hello WWW" />

<H1>Message: <I>

<jsp:getProperty name="test" property="message" />

</I></H1>

</BODY>

</HTML>

SimpleBean.java

Here's the source code for the bean
used in the BeanTest JSP page. You can also download the source.

package hall;

public class SimpleBean {

private String message = "No message specified";

public String getMessage() {

return(message);

}

public void setMessage(String message) {

this.message = message;

}

}

Here's a typical result:

8.3
More jsp:useBean Details

The
simplest way to use a bean is to use

<jsp:useBean id="name" class="package.class" />

to load the bean, then use jsp:setProperty
and jsp:getProperty
to modify and retrieve bean properties. However, there are two other options.
First, you can use the container format, namely

<jsp:useBean
...>

Body

</jsp:useBean>

to indicate that the Body portion should be executed only when the bean
is first instantiated, not when an existing bean is found and used. As
discussed below, beans can be shared, so not all jsp:useBean
statements result in a new bean being instantiated. Second, in addition to id and class, there are three
other attributes that you can use: scope,
type, and beanName. These
attributes are summarized in the following table.

Atribute

Usage

id

Gives a name to the variable that
will reference the bean. A previous bean object is used instead of
instantiating a new one if one can be found with the same id and scope.

class

Designates the full package name of
the bean.

scope

Indicates the context in which the
bean should be made available. There are four possible values: page, request, session, and application. The
default, page, indicates
that the bean is only available on the current page (stored in the PageContext of the
current page). A value of request
indicates that the bean is only available for the current client request
(stored in the ServletRequest
object). A value of session
indicates that the object is available to all pages during the life of the
current HttpSession.
Finally, a value of application
indicates that it is available to all pages that share the same ServletContext. The
reason that the scope matters is that a jsp:useBean
entry will only result in a new object being instantiated if there is no
previous object with the same id
and scope.
Otherwise the previously existing object is used, and any jsp:setParameter
elements or other entries between the jsp:useBean
start and end tags will be ignored.

type

Specifies the type of the variable
that will refer to the object. This must match the classname or be a
superclass or an interface that the class implements. Remember that the name
of the variable is designated via the id
attribute.

beanName

Gives the name of the bean, as you
would supply it to the instantiate
method of Beans. It is
permissible to supply a type
and a beanName, and
omit the class
attribute.

8.4
The jsp:setProperty Action

You use jsp:setProperty
to give values to properties of beans that have been referenced earlier. You
can do this in two contexts. First, you can use jsp:setProperty
after, but outside of, a jsp:useBean
element, as below:

<jsp:useBean id="myName" ... />

...

<jsp:setProperty name="myName"

property="someProperty" ... />

In this case, the jsp:setProperty is
executed regardless of whether a new bean was instantiated or an existing bean
was found. A second context in which jsp:setProperty
can appear is inside the body of a jsp:useBean
element, as below:

<jsp:useBean id="myName" ... >

...

<jsp:setProperty name="myName"

property="someProperty" ... />

</jsp:useBean>

Here, the jsp:setProperty is
executed only if a new object was instantiated, not if an existing one was
found.

There are four possible
attributes of jsp:setProperty:

Attribute

Usage

name

This required attribute designates
the bean whose property will be set. The jsp:useBean
element must appear before the jsp:setProperty
element.

property

This required attribute indicates
the property you want to set. However, there is one special case: a value of "*" means
that all request parameters whose names match bean property names will be
passed to the appropriate setter methods.

value

This optional attribute specifies the
value for the property. String values are automatically converted to numbers,
boolean, Boolean, byte, Byte, char, and Character via the
standard valueOf method
in the target or wrapper class. For example, a value of "true" for a boolean or Boolean property will
be converted via Boolean.valueOf,
and a value of "42"
for an int or Integer property will
be converted via Integer.valueOf.
You can't use both value and param, but it is
permissible to use neither. See the discussion of param below.

param

This optional attribute designates
the request parameter from which the property should be derived. If the
current request has no such parameter, nothing is done: the system does not
pass null to the
setter method of the property. Thus, you can let the bean itself supply
default values, overriding them only when the request parameters say to do
so. For example, the following snippet says "set the numberOfItems property
to whatever the value of the numItems
request parameter is, if there is such a request parameter. Otherwise don't
do anything."

<jsp:setProperty name="orderBean"

property="numberOfItems"

param="numItems" />

If you omit both value and param, it is the same
as if you supplied a param name that
matches the property name.
You can take this idea of automatically using the request property whose name
matches the property one step further by supplying a property name of "*" and
omitting both value and param. In this case,
the server iterates through available properties and request parameters,
matching up ones with identical names.

Here's an example that uses a
bean to create a table of prime numbers. If there is a parameter named numDigits
in the request data, it is passed into the bean's numDigits property.
Likewise for numPrimes.

JspPrimes.jsp

To download the JSP source, right
click on the source code link.
You can also download the source code for the NumberedPrimes
bean referenced by the jsp:useBean element.
Browse the source code directory
for other Java classes used by NumberedPrimes.
The best way to try it out on-line is to start with the HTML page that acts as a front end
to it.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE>Reusing JavaBeans in JSP</TITLE>

<LINK REL=STYLESHEET

HREF="My-Style-Sheet.css"

TYPE="text/css">

</HEAD>

<BODY>

<CENTER>

<TABLE BORDER=5>

<TR><TH CLASS="TITLE">

Reusing JavaBeans in JSP</TABLE>

</CENTER>

<P>

<jsp:useBean id="primeTable" class="hall.NumberedPrimes" />

<jsp:setProperty name="primeTable" property="numDigits" />

<jsp:setProperty name="primeTable" property="numPrimes" />

Some <jsp:getProperty name="primeTable" property="numDigits" />

digit primes:

<jsp:getProperty name="primeTable" property="numberedList" />

</BODY>

</HTML>

Here's a typical result:

8.5 The jsp:getProperty Action

This element retrieves the value of a
bean property, converts it to a string, and inserts it into the output. The two
required attributes are name, the name of a bean previously referenced via
jsp:useBean, and property, the property whose value should be inserted. Here's
an example; for more examples, see Sections 8.2
and 8.4.

<jsp:useBean id="itemBean" ... />

...

<UL>

<LI>Number of items:

<jsp:getProperty name="itemBean" property="numItems" />

<LI>Cost of each:

<jsp:getProperty name="itemBean" property="unitCost" />

</UL>

8.6
The jsp:forward Action

This action lets you forward the
request to another page. It has a single attribute, page, which should
consist of a relative URL. This could be a static value, or could be computed
at request time, as in the two examples below.

<jsp:forward page="/utils/errorReporter.jsp" />

<jsp:forward page="<%= someJavaExpression %>" />

8.7
The jsp:plugin Action

This action lets you insert the
browser-specific OBJECT or EMBED element needed to
specify that the browser run an applet using the Java plugin.

9. Comments and Character Quoting
Conventions

There are a small number of special
constructs you can use in various cases to insert comments or characters that
would otherwise be treated specially. Here's a summary:

Syntax

Purpose

<%-- comment --%>

A JSP comment. Ignored by
JSP-to-scriptlet translator. Any embedded JSP scripting elements, directives,
or actions are ignored.

<!-- comment -->

An HTML comment. Passed through to
resultant HTML. Any embedded JSP scripting elements, directives, or actions
are executed normally.

<\%

Used in template text (static HTML)
where you really want "<%".

%\>

Used in scripting elements where you
really want "%>".

\'

A single quote in an attribute that
uses single quotes. Remember, however, that you can use either single or
double quotes, and the other type of quote will then be a regular character.

\"

A double quote in an attribute that
uses double quotes. Remember, however, that you can use either single or
double quotes, and the other type of quote will then be a regular character.

%\>

%> in an attribute.

<\%

<% in an attribute.

Benefits for Developers

If
you are a Web page developer or designer who is familiar with HTML, you can:

Use JSP technology
without having to learn the Java language:
You can use JSP technology without learning how to write Java scriplets.
Although scriptlets are no longer required to generate dynamic content, they
are still supported to provide backward compatibility.

Extend the JSP
language: Java tag library developers and
designers can extend the JSP language with "simple tag handlers,"
which utilize a new, much simpler and cleaner, tag extension API. This spurs
the growing number of pluggable, reusable tag libraries available, which in turn
reduces the amount of code needed to write powerful Web applications.

Easily write and
maintain pages: The JavaServer Pages Standard Tag Library
(JSTL) expression language is now integrated into JSP technology and has been
upgraded to support functions. The expression language can now be used instead
of scriptlet expressions.

JSP
Technology and Java Servlets

JSP
technology uses XML-like tags that encapsulate the logic that generates the content
for the page. The application logic can reside in server-based resources (such
as JavaBeans
component architecture) that the page accesses with these tags. Any
and all formatting (HTML or XML) tags are passed directly back to the response
page. By separating the page logic from its design and display and supporting a
reusable component-based design, JSP technology makes it faster and easier than
ever to build Web-based applications.

JavaServer
Pages technology is an extension of the Java Servlet technology.
Servlets are platform-independent, server-side modules that fit seamlessly into
a Web server framework and can be used to extend the capabilities of a Web
server with minimal overhead, maintenance, and support. Unlike other scripting
languages, servlets involve no platform-specific consideration or
modifications; they are application components that are downloaded, on demand,
to the part of the system that needs them. Together, JSP technology and
servlets provide an attractive alternative to other types of dynamic Web
scripting/programming by offering: platform independence; enhanced performance;
separation of logic from display; ease of administration; extensibility into
the enterprise; and, most importantly, ease of use.

Today
servlets are a popular choice for building interactive Web applications.
Third-party servlet containers are available for Apache Web Server, Microsoft
IIS, and others.
Servlet containers are usually a component of Web and application servers, such
as BEA WebLogic Application Server, IBM WebSphere, Sun Java
System Web Server, Sun Java
System Application Server, and others.

Community
Background

The
JSP specification is the product of industry-wide collaboration with industry
leaders in the enterprise software and tools markets, led by Sun Microsystems.
Sun has made the JSP specification freely available to the developer community,
with the goal that every Web server and application server will support the JSP
interface. JSP pages share the "Write Once, Run Anywhere" advantages
of Java technology. JSP technology is a key component in the Java 2 Platform, Enterprise Edition,
Sun's highly scalable architecture for enterprise applications.

JavaServer
Pages (JSP) is a Java technology that helps software developers serve dynamically
generated web pages based on HTML, XML, or other document
types. Released in 1999 as Sun's answer to ASP and PHP,[citation needed] JSP was designed
to address the perception that the Java programming environment didn't provide
developers with enough support for the Web.

To deploy and run, the Apache Tomcat
Server is used. It is an open source servlet container developed by the Apache
Software Foundation (ASF). Tomcat implements the Java Servlet and the
JavaServer Pages (JSP) specifications from Sun Microsystems, and provides a
"pure Java" HTTP web server environment for Java code to run.

Architecturally, JSP may be
viewed as a high-level abstraction of Java servlets.
JSP pages are loaded in the server and are operated from a structured special installed
Java server packet called a Java EE Web Application, often packaged as a .war or .ear file archive.

JSP allows Java code and
certain pre-defined actions to be interleaved with static web markup content,
with the resulting page being compiled and executed on the server to deliver an
HTML or XML document. The compiled pages and any dependent Java libraries use
Java bytecode rather than a native software format, and must therefore be
executed within a Java virtual machine (JVM) that integrates
with the host operating system to provide an abstract
platform-neutral environment.

JSP syntax is a fluid mix of
two basic content forms: scriptlet elements and markup. Markup is
typically standard HTML or XML, while scriptlet
elements are delimited blocks of Java code which may be intermixed with the
markup. When the page is requested the Java code is executed and its output is
added, in situ, with the surrounding markup to create the final page. JSP pages
must be compiled to Java bytecode classes before they can be executed, but such
compilation is needed only when a change to the source JSP file has occurred.

Java code is not required to
be complete (self contained) within its scriptlet element block, but can
straddle markup content providing the page as a whole is syntactically correct
(for example, any Java if/for/while blocks opened in one scriptlet element must
be correctly closed in a later element for the page to successfully compile).
This system of split inline coding sections is called step over scripting
because it can wrap around the static markup by stepping over it. Markup which
falls inside a split block of code is subject to that code, so markup inside an
if block will only appear in the output when the if condition
evaluates to true; likewise markup inside a loop construct may appear multiple
times in the output depending upon how many times the loop body runs. The JSP
syntax adds additional XML-like
tags, called JSP actions, to invoke built-in functionality. Additionally, the
technology allows for the creation of JSP tag libraries that act as extensions
to the standard HTML or XML tags. JVM operated tag libraries provide a platform independent way of extending the
capabilities of a web server. Note that not all commercial Java
servers are Java EE specification compliant. Starting with version
1.2 of the JSP specification, JavaServer Pages have been developed under the Java Community Process. JSR 53 defines
both the JSP 1.2 and Servlet 2.3 specifications and JSR 152 defines the JSP 2.0
specification. As of May 2006 the JSP 2.1 specification has been released under
JSR 245 as part of Java EE 5. As of Dec 10, 2009 the JSP 2.2 specification has
been released as a maintenance release of JSR 245.

Example

JSPs are compiled into servlets
by a JSP compiler.
The compiler either generates a servlet in Java code that is then compiled by
the Java compiler, or it may compile the servlet to byte code
which is directly executable. JSPs can also be interpreted
on-the-fly, reducing the time taken to reload changes.

Regardless of whether the JSP
compiler generates Java source code for a servlet or emits the byte code directly,
it is helpful to understand how the JSP compiler transforms the page into a
Java servlet. For example, consider the following input JSP and its resulting
generated Java Servlet.

Input JSP

<%@ page
errorPage="myerror.jsp" %>

<%@ page import="com.foo.bar" %>

<html>

<head>

<%! int serverInstanceVariable = 1;%>

<% int localStackBasedVariable = 1; %>

<table>

<tr><td><%= toStringOrBlank( "expanded inline data " +
1 ) %></td></tr>

Resulting
servlet

package jsp_servlet;

import java.util.*;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.jsp.*;

import javax.servlet.jsp.tagext.*;

import com.foo.bar; //
Imported as a result of <%@ page import="com.foo.bar" %>

import …

class
_myservlet implements javax.servlet.Servlet, javax.servlet.jsp.HttpJspPage {

// Inserted
as a

// result
of <%! int serverInstanceVariable = 1;%>

int
serverInstanceVariable = 1;

…

public
void _jspService( javax.servlet.http.HttpServletRequest
request,

javax.servlet.http.HttpServletResponse response )

throws
javax.servlet.ServletException,

java.io.IOException

{

javax.servlet.ServletConfig
config = …; // Get the servlet config

Object page = this;

PageContext pageContext = …;
// Get the page context for this request

javax.servlet.jsp.JspWriter out = pageContext.getOut();

HttpSession session = request.getSession( true );

try {

out.print( "<html>\r\n" );

out.print( "<head>\r\n" );

…

// From <% int localStackBasedVariable = 1; %>

int localStackBasedVariable =
1;

…

out.print( "<table>\r\n" );

out.print( " <tr><td>" );

// From <%= toStringOrBlank( "expanded inline
data " + 1 ) %>

out.print(
toStringOrBlank( "expanded inline
data " + 1 ) );

out.print( " </td></tr>\r\n" );

…

} catch ( Exception _exception ) {

// Clean up and redirect to error page in <%@ page
errorPage="myerror.jsp" %>

}

}

}

JSP 2.0

The new version of the JSP
specification includes new features meant to improve programmer productivity.
Namely:

An Expression Language (EL) which allows
developers to create Velocity-style templates (among other things).

A
faster/easier way to display parameter values.

A clear way
to navigate nested beans.

The Java EE
5 Platform has focused on easing development by making use of Java language annotations that were introduced by
J2SE 5.0. JSP 2.1 supports this goal by defining annotations for dependency
injection on JSP tag handlers and context listeners. Another key concern of the
Java EE 5 specification has been the alignment of its web tier technologies,
namely JavaServer Pages (JSP), JavaServer
Faces (JSF), and the JavaServer Pages Standard Tag Library
(JSTL). The outcome of this effort has been the Unified Expression Language
(EL), which integrates the expression languages defined by JSP 2.0 and JSF 1.1.

The main key additions to the
Unified EL that came out of the alignment work have been: A pluggable API for
resolving variable references into Java objects and for resolving the
properties applied to these Java objects, support for deferred expressions,
which may be evaluated by a tag handler when needed, unlike their regular
expression counterparts, which get evaluated immediately when a page is
executed and rendered, and support for l-value expression, which appear on the
left hand side of an assignment operation. When used as an l-value, an EL
expression represents a reference to a data structure, for example: a JavaBeans
property, that is assigned some user input. The new Unified EL is defined in
its own specification document, which is delivered along with the JSP 2.1
specification. Thanks to the Unified EL, JSTL tags, such as the JSTL iteration
tags, can now be used with JSF components in an intuitive way. JSP 2.0
introduced a problem in the tag library section on how the JSP version
information was represented. The specification itself is inconsistent,
sometimes referring to a jsp-version element, and at other times a version
attribute on the root element. JSF specifications have gone with the later
interpretation; however some JSP implementations still expect the jsp-version
element.

UNIT
IV

ACTIVE
SERVER PAGES

Active
Server Pages (ASP), also known as Classic ASP or ASP
Classic, was Microsoft's first server-side script-engine
for dynamically-generated web pages. Initially
released as an add-on to Internet Information Services (IIS) via
the Windows NT 4.0 Option Pack (ca 1998), it was
subsequently included as a free component of Windows Server (since the initial
release of Windows 2000 Server). ASP.NET
has superseded ASP.

ASP 2.0 provided six built-in
objects: Application, ASPError, Request,
Response, Server, and Session. Session, for example, represents a cookie-based
session that maintains the state of variables from page to page. The Active
Scripting engine's support of the Component Object Model (COM) enables ASP websites
to access functionality in compiled libraries such as DLLs.

This
two-module tutorial provides a step-by-step introduction to several ASP
features. The tutorial shows how to build sample applications and demonstrates
key concepts you'll need to understand when developing your own ASP pages. (11
printed pages)

Welcome
to the Active Server Pages (ASP) tutorial. If you are new to Microsoft®
Internet Information Services (IIS), this introduction provides necessary
information about tutorial directory structure and permission issues. The two
tutorial modules show you how to build sample applications, while demonstrating
key concepts you'll need to understand when developing your own ASP pages. We
suggest you work through each lesson in Module One before starting Module Two.

This
article contains the following sections:

Introduction.
This section defines what ASP is, how it works, and other technologies
that can be used in conjunction with ASP to create active content on your
Web site. It also describes the directory structure you should use for the
tutorial and security considerations that may affect your ability to run
the tutorial.

Module
One. This module introduces the creation of an ASP page, and
focuses on the collection and transfer of data. It contains the following
lessons:

Write
and Run an ASP Page. Describes how to use Visual Basic®
Scripting Edition (VBScript) and HTML tags.

Send
Information by Using Forms. Shows how to use forms to send
information.

Create
a Guest Book. Shows how to create a sign-in book on your ASP
page for visitors to your Web site.

Display
an Excel Spreadsheet in ASP. Explains how to display an Excel
spreadsheet on an ASP page.

Module
Two. This module contains the following lessons:

Rotate
Information Randomly. Shows how to rotate ads on your Web page
randomly.

Record
Traffic with a Page Counter. Demonstrates the use of a page
counter to track the number of hits a page receives.

Introduction

Microsoft®
Active Server Pages (ASP) is a server-side scripting technology that can be
used to create dynamic and interactive Web applications. An ASP page is an HTML
page that contains server-side scripts that are processed by the Web server
before being sent to the user's browser. You can combine ASP with Extensible
Markup Language (XML), Component Object Model (COM), and Hypertext Markup
Language (HTML) to create powerful interactive Web sites.

Server-side
scripts run when a browser requests an .asp file from the Web server. ASP is
called by the Web server, which processes the requested file from top to bottom
and executes any script commands. It then formats a standard Web page and sends
it to the browser.

It
is possible to extend your ASP scripts using COM components and XML. COM
extends your scripting capabilities by providing a compact, reusable, and
secure means of gaining access to information. You can call components from any
script or programming language that supports Automation. XML is a meta-markup
language that provides a format to describe structured data by using a set of
tags. As you work through the lessons in each module, save your work in the
C:\Inetpub\Wwwroot\Tutorial directory to view the content on your Web site. If
you did not customize your installation of IIS, C:\Inetpub\Wwwroot was created
as the default home directory. To load and run the tutorial samples, you must
have administrator privileges on the computer running IIS. The default IIS
security settings should allow you to run the tutorial, but you may need to
change your security settings on the directory if you encounter access
violations. See the product documentation for more information about IIS
security settings.

Module
One

This
module explains how to create ASP pages (.asp files) that use the fundamental
features of HTML, ASP, and VBScript. This module includes the following
lessons:

Write
and Run an ASP Page. Describes how to use Visual Basic®
Scripting Edition (VBScript) and HTML tags.

Send
Information by Using Forms. Shows how to display forms on an
HTML page.

Create a
Guest Book. Uses forms to gather information from visitors,
store the information in a database, and display the database contents in
a Web page.

Display
an Excel Spreadsheet in ASP. Explains how to display an Excel
spreadsheet in a Web page.

Write
and Run an ASP Page

The
best way to learn about ASP pages is to write your own. This lesson covers
VBScript syntax and coding samples. To create an ASP page, use a text editor to
insert script commands into an HTML page. Saving the page with an .asp file
name extension tells the Web server how to process the script commands. To view
the results of a script, request the page using a Web browser. VBScript is the
default scripting language for ASP, and most of the examples in the tutorial
are scripted in VBScript. In HTML, you use brackets as delimiters around the
tags:

<example>

In
VBScript, you use the percent sign with brackets as delimiters around the tags:

<%example%>

You
can put many tags inside one pair of VBScript delimiters:

<%example, samples%>

Example
1

This
example displays the words "Hello World". To run this example, cut
and paste it into an empty file and save it in the C:\Inetpub\Wwwroot\Tutorial
directory as Example1.asp. Make sure to save your file with an .asp extension.
Some text editors automatically change the file name extension to .txt when the
Text Document option is selected in the Save dialog box. To
prevent this, select the All Files(*.*) option. Exit your text editor as
the server may not be able to display an HTML page that is open in a text
editor. View your page with your browser by typing http://<Your Server
Name>/Tutorial/Example1.asp in the address bar. When running Example 1,
the page is processed by the Web server in the following sequence:

Assigns the text "Hello World" to
the variable FirstVar.

Uses HTML to make an HTML page.

Uses <%FirstVar%>
to print out the value of the variable FirstVar.

Ends the HTML page.

<%@
Language=VBScript %>

<html>

<head>

<title>Example
1</title>

</head>

<body>

<%

FirstVar
= "Hello world!"

%>

<%=FirstVar%>

</body>

</html>

Example
2

This
example incorporates a FOR loop in the ASP page. The FOR loop is a statement
that prints "Hello World" 10 times. To create Example 2, use the file
from Example 1 and add the FOR loop code as shown in the following code sample.
Save the file as Example2.asp. View it in your browser.

<%@
Language=VBScript %>

<html>

<head>

<title>Example
2</title>

</head>

<body>

<%

FirstVar
= "Hello world!"

%>

<%FOR
i=1 TO 10%>

<%=FirstVar%>

<%NEXT%>

</body>

</html>

Example
3

In
this example, a time stamp is added to the ASP page. The word time is a
function; it is a predefined VBScript function variable containing the current
time. There are more than 90 functions in VBScript. Add the code for time
shown in the following code sample to Example2.asp and save it as Example3.asp.
View it in your browser.

<%@ Language=VBScript %>

<html>

<head>

<title>Example
3</title>

</head>

<body>

<%

FirstVar
= "Hello world!"

%>

The
time is: <%=time%> <BR>

<%FOR
i=1 TO 10%>

<%=FirstVar%>

<%NEXT%>

</body>

</html>

Example
4

This
example displays the message "Good Morning Everyone" if the hour is
between 4:00 A.M. and 6:00 P.M. It displays the message "Good Night
Everyone" if the hour is between 6:00 P.M. and 4:00 A.M. Add the IF THEN
statement in the code shown below to Example3.asp and save it as Example4.asp.

<%@ Language=VBScript %>

<html>

<head>

<title>Example
4</title>

</head>

<body>

<%IF
Hour(time)>18 OR Hour(time)<4 THEN%>

Good
Night Everyone.

<%ELSE%>

Good
Morning Everyone.

<%END
IF%>

</body>

</html>

Send
Information by Using Forms

A
common use of intranet and Internet server applications is to process a form
submitted by a browser. With ASP, you can embed scripts written in VBScript
directly into an HTML file to process the form. ASP processes the script
commands and returns the results to the browser. In this lesson, you create an
HTML page that displays various elements of an HTML form. Later in this module,
you use this knowledge of forms to build a guest book application on your Web
site.

This
lesson contains the following examples:

Button example. Displays selection buttons in
the form.

Text example. Displays text boxes in the
form.

Button
example

In
this example, there are three input lines that use "buttons," and two
default buttons-RESET and SUBMIT. The Post method is used to send data
from the client browser to the Web server. Open your text editor, create a new
file, and paste in the following code. Save the file as Button.htm and view the
page in your browser.

<html>

<head>

<title>Button
Form</title>

</head>

<body>

<FORM
NAME="Button Example" METHOD="POST"
ACTION="tutorial/button.htm">

Computer
Programming Experience:

<P>

<INPUT
TYPE="button" NAME="choice" VALUE="Less than
1">Less

than 1 year.<BR>

<INPUT
TYPE="button" NAME="choice" VALUE="1 to 5">1-5
years.<BR>

<INPUT
TYPE="button" NAME="choice" VALUE="More than
5">More

than 5 years.

</P>

<P><INPUT
TYPE="reset" VALUE="Clear Form">

<INPUT
TYPE="submit" VALUE="Submit">

</P>

</form>

</body>

</html>

Text
example

In
this example, you create text fields in a form. Open a new file in your text
editor, paste in the following code, and save the file as Text.htm:

<html>

<head>

<title>Text
Form</title>

</head>

<body>

<FORM
NAME="Text Example" FORM METHOD="POST"
ACTION="tutorial/text.htm">

<TABLE>

<TR>

<TD
ALIGN="RIGHT" VALIGN="MIDDLE">Name?

<TD
ALIGN="LEFT">

<INPUT
TYPE="text" NAME="name" VALUE=""

SIZE="20" MAXLENGTH="150">

<TR>

<TD
ALIGN="RIGHT" VALIGN="MIDDLE">Company?

<TD
ALIGN="LEFT">

<INPUT
TYPE="text" NAME="company" VALUE=""

SIZE="25" MAXLENGTH="150">

<TR>

<TD
ALIGN="RIGHT" VALIGN="MIDDLE">

Email
Address?

<TD
ALIGN="LEFT">

<INPUT
TYPE="text" NAME="email" VALUE=""

SIZE="25" MAXLENGHT="150">

</TABLE>

<INPUT
TYPE="reset">

<INPUT
TYPE="Submit" NAME="Submit" VALUE="Submit">

</form>

</body>

</html>

Create
a Guest Book

This
lesson describes how to develop a guest book application. Guest books allow
visitors to your site a chance to give you feedback. Information such as the
visitor's name, e-mail address, and comments can be available to you.

Create
the guest book database

You
must first create an Access database called Guestbook.mdb and save it in the
C:\Inetpub\Wwwroot\Tutorial directory. The database must have the fields with
the properties described in the following table.

Field
Name

Data
Type and General Properties

ID

AutoNumber,
Field Size=Long Integer, New Values=Increment, Indexed=Yes(No Duplicates)

TB1

Text,
Field Size=255, Required=No, Allow Zero Length=Yes, Indexed=No

TB2

Text,
Field Size=255, Required=No, Allow Zero Length=Yes, Indexed=No

TB3

Text,
Field Size=255, Required=No, Allow Zero Length=Yes, Indexed=No

TB4

Text,
Field Size=255, Required=No, Allow Zero Length=Yes, Indexed=No

MB1

Memo,
Required=No, Allow Zero Length=Yes

After
you create the database, you need to create a data source name (DSN) connection
to the database so your ASP application can interact with it. The DSN must be
created on the Web server that is running the ASP application. If you move the
ASP application to a different Web server, you have to re-create the DSN on the
new Web server. The following procedure describes how to create a DSN on
Windows NT and Windows 2000.

In the ODBC Data Source Administrator, select
the ODBC icon.

Select File DSN.

Select Add, select Microsoft Access
Driver, and click Next.

Type in a descriptive name for your file DSN
(Guestbook) and click Next.

Click Finish, click Select,
specify the location of the database file, and select OK.

Click OK twice. After you specify the
location of the database file, the ODBC Data Source Administrator creates
a file DSN for it.

<% @Language=VBScript %>

<html
dir=ltr>

<head>

<TITLE>Guest
Book</TITLE>

</head>

<body
bgcolor="#FFFFFF" text="#000000">

<%

IF
request.form ("Message")="True" THEN

strTB1=request.form("To")

strTB2=request.form("EMailAdd")

strTB3=request.form("CC")

strTB4=request.form("Subject")

strMB1=request.form("Memo")

IF
strMB1 = "" THEN

iLenMB1=255

ELSE

iLenMB1
= Len(strMB1)

END
IF

'Connects
to the Access driver and Access database in the Inetpub

'directory
where the database is saved

strProvider
= "Driver={Microsoft Access Driver (*.mdb)};

DBQ=C:\Inetpub\Wwwroot\Tutorial\guestbook.mdb;"

'Creates
an instance of an Active Server component

set
objConn = server.createobject("ADODB.Connection")

'Opens
the connection to the data store

objConn.Open
strProvider

'Instantiate
Command object and use ActiveConnection property to

'attach
connection to Command object

set
cm = Server.CreateObject("ADODB.Command")

cm.ActiveConnection
= objConn

'Define
SQL query

cm.CommandText
="INSERT INTO Guestbook (TB1,TB2,TB3,TB4,MB1)

VALUES (?,?,?,?,?)"

'Define
query parameter configuration information for guestbook fields

set
objparam=cm.createparameter(, 200, , 255, strTB1)

cm.parameters.append
objparam

set
objparam=cm.createparameter(, 200, , 255, strTB2)

cm.parameters.append
objparam

set
objparam=cm.createparameter(, 200, , 255, strTB3)

cm.parameters.append
objparam

set
objparam=cm.createparameter(, 200, , 255, strTB4)

cm.parameters.append
objparam

set
objparam=cm.createparameter(, 201, , iLenMB1, strMB1)

cm.parameters.append
objparam

cm.execute

response.write("Thank
you!")

ELSE%>

<h1>Guestbook</h1>

<!--Post
information to Guestbook form -->

<form
name=guestbook.asp
action="guestbook.asp"
method="POST">

<p>To</p>

<p><input
type="Text" name="To"></p>

<p>Email
Address</p>

<p><input
type="Text" name="EmailAdd"></p>

<p>
CC</p>

<p><input
type="Text" name="CC"></p>

<p>Subject</p>

<p><input
type="Text" name="Subject"></p>

<p>Message</p>

<p><textarea
name="Memo" rows=6 cols=70></textarea></p>

<input  type="HIDDEN"
name="Message" value="True">

<input
type="submit" value="Submit information">

</form>

<%End
if%>

</body>

</html>

View
the database in a browser

Using
a database to collect information left by visitors is a safe and simple way to
make your Web site more useful. Once information is entered in a database, you
can either open the database in the application in which it was originally
created, or you can use a Web page containing another script to view and edit
the data. The following is a script that allows visitors to view and edit your
database. To learn more about how to limit access to resources on your site,
see "NTFS Security, Part 1: Implementing NTFS Standard Permissions on Your
Web Site," available at http://www.microsoft.com/technet/iis/ntfssec.asp.

<% @Language=VBScript %>

<html
dir=ltr>

<head>

<title>View
Guest Book</title>

</head>

<body
bgcolor="#FFFFFF" text="#000000">

<%

'This
section makes it possible for visitors to sort the data in the

columns in ascending order.

if
request.form("sort")<> "" THEN

StrSort=request.form("sort")

ELSE

StrSort="TB1
ASC"

END
IF

strQuery="SELECT
* FROM Guestbook ORDER BY " &StrSort

'Database
path statement describing the driver to use and the

path to the desired database.

strProvider
= "Driver=Microsoft Access Driver (*.mdb);
DBQ=C:\Inetpub\Wwwroot\Tutorial\guestbook.mdb;"

IF
Request("ID") <> "" THEN

strIDNum=Request("ID")

'Creates
an instance of an Active server component

set
objConn = server.createobject("ADODB.Connection")

'Opens
the connection to the data store

objConn.Open
strProvider

'Instantiate
Command object and use ActiveConnection property to

'attach
connection to Command object

set
cm = Server.CreateObject("ADODB.Command")

cm.ActiveConnection
= objConn

'Define
SQL query

cm.CommandText
= "DELETE FROM Guestbook WHERE ID = " &strIDNum

cm.Execute

END
IF

'Instantiate
a Recordset object and open a recordset using

'the
Open method

Set
rst = Server.CreateObject("ADODB.recordset")

rst.Open
strQuery, strProvider

%>

<h1>Guest
Book</h1>

<form
name=viewdb.asp action=viewdb.asp method=post>

<table
border=1 cellspacing=3 cellpadding=3 rules=box>

<%

ON
ERROR RESUME NEXT

IF
rst.EOF THEN

Response.Write
"There are no entries in the database."

ELSE%>

<tr>

<%

'Deletes
rows from the database, this cannot be undone

Response.Write
"<td width=200><center>Delete
Record</center></td>"

FOR
i = 1 to rst.Fields.Count -1

Response.Write
"<td width=200><input name=sort value=" & rst(i).Name

& "
type=submit></td>"

NEXT

WHILE
NOT rst.EOF %>

<tr>

<%

Response.Write
"<td align=left valign=top bgcolor='#ffffff'>

<a href=viewdb.asp?id="
& rst(0) & ">Delete</a></td>"

FOR
i = 1 to rst.fields.count - 1

Response.Write
"<td align=left valign=top bgcolor='#ffffff'>" & rst(i)

&"</td>"

NEXT

rst.MoveNext

WEND

END
IF

%>

</table>

</form>

</body>

</html>

Display an Excel
Spreadsheet in ASP

This
lesson demonstrates a technique that can be used to display a Microsoft Excel
spreadsheet in a Web page. There are several standard server components
supplied with IIS. One of these is the ActiveX® Data Objects (ADO)
component, which is used as a connection mechanism to provide access to data.
In the database lesson earlier, we used ADO.
We use it again here to show you how to view and edit a spreadsheet with a Web
browser.

To
prepare your Excel spreadsheet for display in an Active Server Page:

Create a spreadsheet using either
Excel 98 or Excel 2000 and save it as ASPTOC.xls in the
C:\Inetpub\Wwwroot\ directory.

Note: Do not include any special formatting or column labels when
creating the spreadsheet.

Highlight the rows and columns on
the spreadsheet that you want displayed in the Web page.

On the Insert menu, choose
Name, and select Define.

If there are any names listed,
select them and select Delete.

Type a name for the workbook,
select Add, and select OK.

To
display the spreadsheet in a Web page, you must create a DSN for the
spreadsheet. The process is the same as it was for the database lesson earlier
in this module. The only difference is that you must select the {Microsoft
Excel Driver (*.xls)} option for the DSN.

Once
you have created the spreadsheet and named the table in the spreadsheet, and
also created a DSN for the spreadsheet, you are ready to create the page that
displays the contents. Paste the following code into a new file and name it
ASPTOC.asp. Save it in the C:\Inetpub\Wwwroot\Tutorial directory and view the
page in your browser.

<%@Language=VBScript %>

<html>

<head>

<title>
Displaying An Excel Spreadsheet in an Web Page </title>

</head>

<body
bgcolor="#FFFFFF" text="#000000" >

<h1>ASP
Table of Contents</h1>

<%

'Creates
an instance of an Active Server Component

Set oConn =
Server.CreateObject("ADODB.Connection")

'Connects
to the Excel driver and the Excel spreadsheet

'in
the directory where the spreadsheet was saved

strConn
= "Driver={Microsoft Excel Driver (*.xls)};
DBQ=C:\Inetpub\Wwwroot\Tutorial\ASPTOC.xls;"

'Opens
the connection to the data store

oConn.Open strConn

'Selects
the records from the Excel spreadsheet

strCmd
= "SELECT * from `ASPTOC`"

Set
oRS = Server.CreateObject("ADODB.Recordset")

'Opens
the recordset

oRS.Open
strCmd, oConn

'Prints
the cells and rows in the table

Response.Write
"<table border=1><tr><td>"

'Gets
records in spreadsheet as a string and prints them in the table

Response.Write
oRS.GetString (, , "</tr><td>",
"</td></tr><tr><td>",

NBSPACE)

%>

</body>

</html>

Module
Two

This
module explains how to develop an ASP page that delivers services useful in
e-commerce. This module includes the following lessons:

Rotate Ad
Information. Randomly rotate ads on your Web page.

Redirect
Users from Ad Links. Redirect browsers to advertisers' sites when
users click on an ad image.

Count Page
Hits. Track the number of times users request a page.

Rotate Ad Information

Advertising
is big business on the Web. This lesson explains how to take advantage of the
Ad Rotator component installed with ASP by describing how to use this component
to rotate advertisements on your Web pages. The Ad Rotator component selects an
advertisement for your Web page each time the user refreshes or loads the Web
page. Two files are required to set up the Ad Rotator component: an Ad Rotator
Include file and an ad images data file. By setting up these two files, this
component can be called by any ASP page on your site. Changes to the ad
parameters are not done on all the sites containing the ad, but to the ad
images data file. This saves lots of time if the ad appears on numerous pages
within your Web site.

This
lesson explains how to:

Write an Ad
Rotator Include File. Creates the ad-image links on any page that
calls this file.

Create an Ad
Image Data File. Specifies global ad-display data and information
specific to each ad.

Test the Ad
Rotator. Uses an ASP page that calls the Ad Rotator logic Include
file and the image data file to display and rotate ads.

Write an Ad Rotator Include
file

Include
files are used to store information that will be used by more than one ASP or
HTML file. By creating an Ad Rotator Include file, when changes need to be made
to specific information, you only need to change the information in one
location. This lesson will guide you in creating an Ad Rotator Include file
containing a function named getAd(). This function randomly selects ads to
display on your ASP pages. You can call this file from within any ASP page
intended to display the rotated ads. When you test calling the Include file
from an ASP page (see Test the Ad
Rotator), you will use some images from Microsoft.com for ad images.

Open
a new file in your text editor, paste in the following script, and save the
file as Adrotatorlogic.inc:

<%

Function
getAd()

Dim
load

'Create
an instance of the AdRotator component

Set
load=Server.CreateObject("MSWC.AdRotator")

'Set
the target frame, if any. This is the frame

'where
the URL will open up. If the HTML page does

'not
find the target name, the URL will be opened

'in
a new window.

load.TargetFrame
= "Target = new"

'Get
a random advertisement from the text file.

getAd
= load.GetAdvertisement("adimagedata.txt")

End
Function

%>

Create an ad images data file

An
ad images data file is created to provide information about the ads to be
displayed. By placing the data in one text file, when changes need to be made,
you only need to change the data in one location. The ASP page (with the logic
in the Include file) sends data in the ad images data file to the Ad Rotator
component. The component then selects an ad for display.

The
data file is divided into two sections that are separated by an asterisk (*).
The first section provides information common to all the ads to be displayed.
The second section lists data relevant to each ad.

The following outlines the structure of an ad
images data file:

REDIRECTION.
URL, the path and name of the ASP file that redirects browsers that
select ad images.

WIDTH.
The width of ad images in pixels. Default is 440.

HEIGHT.
The height of ad images in pixels. Default is 60.

BORDER.
The border thickness around ad images. Default is 1.

*.
Separates the first section from the second section.

AdURL.
Virtual path and filename of the image file containing the advertisement.

AdHomeURL.
URL to jump to when this link is selected. To indicate there is no link,
use a hyphen.

Text.
Text to display if browser does not support graphics.

Impressions.
An integer indicating the relative weight, or probability, that this ad
will be selected for display. For example, if two ads were displayed, one
with an impression of 3 and the other with 7, then the one with 3 would
have a 30 percent probability of being selected, while the other would
have a 70 percent probability.

Open
a new file in your text editor, paste in the following script, and save the
file as Adimagedata.txt:

REDIRECT adrotatorredirect.asp

WIDTH
250

HEIGHT
60

BORDER
0

*    ' separates the general data
from the image information

images/windows_logo.gif

http://www.microsoft.com/windows

Microsoft
Windows

2

images/office_logo.gif

http://www.microsoft.com/office

Office
2000

3

Test the Ad Rotator

To
test the system, you will need an ASP page that calls the Ad Rotator Include
file and the ad images data file, and then displays the ads. First, you will
need test ad images stored on your site.

Acquire
and store the ad images as follows:

Create
a directory named Images in the tutorial folder:
C:\Inetpub\Wwwroot\Tutorial\Images.

Download
the Office logo file, available at http://www.microsoft.com/office/images/office_logo.gif,
from the Microsoft Office Web site, and save it as Office_logo.gif in
C:\Inetpub\Wwwroot\Tutorial\Images.

Download
the Windows logo file, available at
http://www.microsoft.com/windows/images/bnrwinfam.gif(, from the Microsoft
Windows Web site, and save it as Windows_logo.gif in C:\Inetpub\Wwwroot\Tutorial\Images.

Open
a new file in your text editor, paste in the following script, and save the
file as Displayad.asp:

<%@ Language="VBScript"
%>

<!--Call
the Include file, which in turn -->

<!--calls
the ad images data text file-->

<!--#include
file="adrotatorlogic.inc"-->

<html>

<head>

<title>Test
Ad Display Page</title>

</head>

<body>

<h1>Test
Ad Display Page</h1>

<!--Display
the ad banner-->

<p><%=getAd()%></p>

<p>The
space above should contain an image displaying either the

Microsoft Windows family logo or
the Microsoft Office

family logo.</p>

<ul>

<li
type="disc">This indicates that Displayad.asp, Adrotatorlogic.inc,

and Adimagedata.txt are working
together to correctly display the

images.</li>

<li
type="disc">Repeatedly refreshing the page should result in the

Windows and Office logos
displaying in random order.</li>

<li
type="disc">After you save Adrotatorredirect.asp, clicking on the

displayed image should cause a new
window to open, displaying the

home page corresponding to the
displayed logo.</li>

<li
type="disc">After you add the hit counter script to this page,

under "Statistics" you
should see the number of page hits since

the script was added.</li>

</ul>

<br><br><br><br><br>

<h3>Statistics</h3>

<%
Set pageCount = Server.CreateObject("MSWC.PageCounter") %>

<!--Increment
the counter-->

<%
pageCount.PageHit %>

<p>You
are visitor number <% =pageCount.Hits %> to this Web page.</p>

</body>

</html>

Redirect Users from Ad Links

When
a user clicks the ad, the browser appends a query string to the request to the
server. Then, the server directs the user's browser to the ad's URL.

Open
a new file in your text editor, paste in the following script, and save the
file as Adrotatorredirect.asp:

<%@Language=VBScript %>

<html>

<head>

<title>Redirection
Page</title>

</head>

<body>

<%

'Set
the response buffer on

Response.Buffer
= True

Dim
lsURL

'Obtain
the URL from the query string

lsURL
= Request.QueryString("URL")

'Clear
the response and redirect to URL

Response.Clear()

Response.Redirect(lsURL)

%>

</body>

</html>

To
check your work, use Displayad.asp. When you click on an ad, you should see a
new window displaying an appropriate ad-related Web page.

Count Page Hits

It
is important to know how many hits your Web pages get. This data helps
determine how changes to your Web site may affect your customers' viewing
habits. More importantly, it provides useful insight as to how customers are
navigating through your site and where ads should be placed. Sites with high
trafficking have higher advertisement prices associated with them. The data
gathered from a page hit counter provides you with trafficking information to
begin negotiating advertisement prices for your Web pages.

The
Page Counter component uses an internal object to record page hit-count totals
for all pages on the server. At regular intervals, this object saves all
information to a text file so that no counts are lost due to power loss or
system failure. The Page Counter component uses the following three methods:

Hits().
This displays the number of hits for a Web page. The default is the
current page.

PageHit().
This increments the hit count for the current page.

Reset().
This resets the hit count for a page to zero. The default is the current
page.

An
in-use sample of this script can be seen at the bottom of the Displayad.asp
script. To place a page hit counter on a Web page, place the following script
where you want the counter displayed on the page:

<% Set pageCount =
Server.CreateObject("MSWC.PageCounter") %>

<%
pageCount.PageHit %>

You
are visitor number <% =pageCount.Hits %> to this Web site.

ASP
is a powerful tool for making dynamic and interactive Web pages.

In
our ASP tutorial you will learn about ASP, and how to execute scripts on your
server.

ASP
is a powerful tool for making dynamic and interactive Web pages.

In
our ASP tutorial you will learn about ASP, and how to execute scripts on your
server.

Our
"Show ASP" tool makes it easy to learn ASP, it shows both the ASP
source code and the HTML output of the code.

<html>

<body>

<%

response.write("My first ASP script!")

%>

</body>

</html>

1 HTML AND VBSCRIPT FUNDAMENTALS

HTML,
which stands for HyperText Markup Language, is the predominant markup
language for web pages. HTML is the basic building-blocks of webpages.

HTML is written in the form
of HTML elements
consisting of tags, enclosed in angle brackets (like <html>), within the web page
content. HTML tags normally come in pairs like <h1> and </h1>. The
first tag in a pair is the start tag, the second tag is the end tag
(they are also called opening tags and closing tags). In between
these tags web designers can add text, tables, images, etc.

The purpose of a web browser
is to read HTML documents and compose them into visual or audible web pages.
The browser does not display the HTML tags, but uses the tags to interpret the
content of the page.

HTML elements form the
building blocks of all websites. HTML allows images and objects to be embedded and can be
used to create interactive forms. It provides a means to
create structured documents by denoting structural semantics
for text such as headings, paragraphs, lists, links, quotes and other items. It
can embed scripts in languages such as JavaScript
which affect the behavior of HTML webpages.

Web browsers can also refer
to Cascading Style Sheets (CSS) to define the
appearance and layout of text and other material. The W3C, maintainer of both
the HTML and the CSS standards, encourages the use of CSS over explicitly
presentational HTML markup

Markup

HTML markup consists of
several key components, including elements (and their attributes),
character-based data types, character references and entity
references. Another important component is the document type declaration, which
triggers standards mode rendering.

The Hello world program, a common computer
program employed for comparing programming languages, scripting languages and markup
languages is made of 9 lines of code
although in HTML newlines
are optional:

<!DOCTYPE html>

<html>

<head>

<title>Hello HTML</title>

</head>

<body>

<p>Hello World!</p>

</body>

</html>

(The text
between <html> and </html> describes the web page, and The text
between <body> and </body> is the visible page content except for
the markup text '<title>Hello HTML</title>' —which evinces as
the browser tab title.)

This Document Type
Declaration is for HTML5. If the <!doctype html> declaration is not included, various browsers will
revert to "quirks mode" for rendering.[41]

Elements

Main article:
HTML element

HTML documents are composed
entirely of HTML elements that, in their most general form have three
components: a pair of tags, a "start tag" and "end
tag"; some attributes within the start tag; and finally, any
textual and graphical content between the start and end tags, perhaps
including other nested elements. The HTML element is everything between
and including the start and end tags. Each tag is enclosed in angle
brackets.

The general form of an HTML
element is therefore: <tag attribute1="value1" attribute2="value2">content</tag>.
Some HTML elements are defined as empty elements and take the form <tag attribute1="value1"
attribute2="value2" >. Empty elements may enclose
no content. The name of an HTML element is the name used in the tags. Note that
the end tag's name is preceded by a slash character, "/", and that in
empty elements the slash does not appear. If attributes are not mentioned,
default values are used in each case.

Element
examples

Header of the HTML
document:<head>...</head>. Usually the title should be included in
the head, for example:

<head>

<title>The title</title>

</head>

Headings: HTML headings are
defined with the <h1> to <h6> tags:

<h1>Heading1</h1>

<h2>Heading2</h2>

<h3>Heading3</h3>

<h4>Heading4</h4>

<h5>Heading5</h5>

<h6>Heading6</h6>

Paragraphs:

<p>Paragraph 1</p>  <p>Paragraph 2</p>

Line breaks:<br>. The
difference between <br> and <p> is that 'br' breaks a line without
altering the semantic structure of the page, whereas 'p' sections the page into
paragraphs. Note also that 'br' is an empty element in that, while it
may have attributes, it can take no content and it does not have to have an end
tag.

<p>This <br> is a paragraph <br> with <br>
line breaks</p>

Comments:

<!-- This is a comment -->

Comments can help
understanding of the markup and do not display in the webpage.

There are several types of
markup elements used in HTML.

Structural
markup describes the purpose of text

For
example, <h2>Golf</h2>
establishes "Golf" as a second-level heading.
Structural markup does not denote any specific rendering, but most web browsers
have default styles for element formatting. Content may be further styled using
Cascading Style Sheets (CSS).

Presentational
markup describes the appearance of the text, regardless of its purpose

For
example <b>boldface</b> indicates
that visual output devices should render "boldface" in bold text, but
gives little indication what devices that are unable to do this (such as aural
devices that read the text aloud) should do. In the case of both <b>bold</b>
and <i>italic</i>, there
are other elements that may have equivalent visual renderings but which are
more semantic in nature, such as <strong>strong text</strong>
and <em>emphasised text</em>
respectively. It is easier to see how an aural user agent should interpret the
latter two elements. However, they are not equivalent to their presentational
counterparts: it would be undesirable for a screen-reader to emphasize the name
of a book, for instance, but on a screen such a name would be italicized. Most presentational
markup elements have become deprecated under the HTML 4.0 specification, in
favor of using CSS for styling.

Hypertext
markup makes parts of a document into links to other documents

An
anchor element creates a hyperlink in the document and its href
attribute sets the link's target URL. For example the HTML markup, <a href="http://en.wikipedia.org/">Wikipedia</a>,
will render the word "Wikipedia" as a hyperlink. To
render an image as a hyperlink, an 'img' element is inserted as content into
the 'a' element. Like 'br', 'img' is an empty element with attributes but no
content or closing tag. <a
href="http://example.org"><img src="image.gif"
alt="descriptive text" width="50" height="50"
border="0"></a>.

Attributes

Most of the attributes of an
element are name-value pairs, separated by "="
and written within the start tag of an element after the element's name. The
value may be enclosed in single or double quotes, although values consisting of
certain characters can be left unquoted in HTML (but not XHTML).[42][43]
Leaving attribute values unquoted is considered unsafe.[44]
In contrast with name-value pair attributes, there are some attributes that
affect the element simply by their presence in the start tag of the element,[5]
like the ismap
attribute for the img element.[45]

There are several common
attributes that may appear in many elements:

The id attribute provides a document-wide unique identifier for an element.
This is used to identify the element so that stylesheets can alter its
presentational properties, and scripts may alter, animate or delete its
contents or presentation. Appended to the URL of the page, it provides a
globally unique identifier for the element, typically a sub-section of the
page. For example, the ID "Attributes" in http://en.wikipedia.org/wiki/HTML#Attributes

The class attribute provides a way of classifying similar elements. This can be
used for semantic
or presentation purposes. For example, an HTML document might semantically
use the designation class="notation" to indicate that all elements with this class value are subordinate
to the main text of the document. In presentation, such elements might be
gathered together and presented as footnotes on a page instead of
appearing in the place where they occur in the HTML source. Class
attributes are used semantically in microformats.
Multiple class values may be specified; for example class="notation
important" puts the element into both the 'notation' and the
'important' classes.

An author may use the style attribute to assign presentational properties to a particular
element. It is considered better practice to use an element's id or class attributes to select
the element from within a stylesheet, though sometimes this can be too
cumbersome for a simple, specific, or ad hoc styling.

The title attribute is used to attach subtextual explanation to an element. In
most browsers this attribute is displayed as a tooltip.

The lang attribute identifies the natural language of the element's contents,
which may be different from that of the rest of the document. For example,
in an English-language document:

·
<p>Oh
well, <span lang="fr">c'est la vie</span>, as they say in France.</p>

The abbreviation element, abbr, can be used to demonstrate some of these attributes:

<abbr id="anId" class="jargon" style="color:purple;" title="Hypertext Markup
Language">HTML</abbr>

This example displays as
HTML; in most browsers, pointing the cursor at the abbreviation should display
the title text "Hypertext Markup Language."

Most elements also take the
language-related attribute dir to specify text direction, such as with "rtl"
for right-to-left text in, for example, Arabic,
Persian
or Hebrew.[46]

Character
and entity references

See also: List of XML
and HTML character entity references and Unicode and
HTML

As of version 4.0, HTML
defines a set of 252 character entity references and a set of
1,114,050 numeric character references, both of
which allow individual characters to be written via simple markup, rather than
literally. A literal character and its markup counterpart are considered
equivalent and are rendered identically.

The ability to
"escape" characters in this way allows for the characters < and & (when written as &lt; and &amp;, respectively) to be
interpreted as character data, rather than markup. For example, a literal < normally indicates the start of a tag, and & normally indicates the start of a character entity
reference or numeric character reference; writing it as &amp; or &#x26; or &#38; allows & to be included in the content of an element or in the
value of an attribute. The double-quote character ("), when used to quote an
attribute value, must also be escaped as &quot; or &#x22; or &#34; when it appears within the
attribute value itself. Equivalently, the single-quote character ('), when used to quote an attribute value, must also be
escaped as &#x27;
or &#39;
(not as &apos;
except in XHTML documents[47])
when it appears within the attribute value itself. If document authors overlook
the need to escape such characters, some browsers can be very forgiving and try
to use context to guess their intent. The result is still invalid markup, which
makes the document less accessible to other browsers and to other user agents
that may try to parse the document for search and
indexing purposes for example.

Escaping also allows for
characters that are not easily typed, or that are not available in the
document's character encoding, to be represented within
element and attribute content. For example, the acute-accented e (é), a character typically found only on Western European
keyboards, can be written in any HTML document as the entity reference &eacute; or as the numeric references
&#233;
or &#xE9;,
using characters that are available on all keyboards and are supported in all
character encodings. Unicode character encodings such as UTF-8 are compatible with
all modern browsers and allow direct access to almost all the characters of the
world's writing systems.[48]

Data types

HTML defines several data types
for element content, such as script data and stylesheet data, and a plethora of
types for attribute values, including IDs, names, URIs, numbers, units of
length, languages, media descriptors, colors, character encodings, dates and
times, and so on. All of these data types are specializations of character
data.

Document type declaration

HTML documents are required
to start with a Document Type Declaration (informally, a
"doctype"). In browsers, the doctype helps to define the rendering
mode—particularly whether to use quirks mode.

The original purpose of the
doctype was to enable parsing and validation of HTML documents by SGML tools
based on the Document Type Definition (DTD). The DTD to
which the DOCTYPE refers contains a machine-readable grammar specifying the
permitted and prohibited content for a document conforming to such a DTD.
Browsers, on the other hand, do not implement HTML as an application of SGML
and by consequence do not read the DTD. HTML5 does not define a
DTD, because of the technology's inherent limitations, so in HTML5 the doctype
declaration, <!doctype
html>, does not refer to a DTD.

An example of an HTML 4
doctype is

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

This declaration references
the DTD for the 'strict' version of HTML 4.01. SGML-based validators read the
DTD in order to properly parse the document and to perform validation. In
modern browsers, a valid doctype activates standards mode as opposed to quirks mode.

In addition, HTML 4.01
provides Transitional and Frameset DTDs, as explained
below.

Semantic HTML

Main
article: Semantic HTML

Semantic HTML is a way of
writing HTML that emphasizes the meaning of the encoded information over its
presentation (look). HTML has included semantic markup from its inception,[49]
but has also included presentational markup such as <font>, <i> and <center> tags.
There are also the semantically neutral span and div
tags. Since the late 1990s when Cascading Style Sheets were beginning to
work in most browsers, web authors have been encouraged to avoid the use of
presentational HTML markup with a view to the separation of presentation and
content.[50]

In a 2001 discussion of the Semantic Web,
Tim Berners-Lee and others gave examples of ways in which intelligent software
'agents' may one day automatically trawl the Web and find, filter and correlate
previously unrelated, published facts for the benefit of human users.[51]
Such agents are not commonplace even now, but some of the ideas of Web 2.0,
mashups and price comparison websites may be coming
close. The main difference between these web application hybrids and
Berners-Lee's semantic agents lies in the fact that the current aggregation
and hybridisation of information is usually designed in by web developers, who
already know the web locations and the API semantics of the
specific data they wish to mash, compare and combine.

An important type of web
agent that does trawl and read web pages automatically, without prior knowledge
of what it might find, is the Web crawler or search-engine spider. These
software agents are dependent on the semantic clarity of web pages they find as
they use various techniques and algorithms to read and index millions of web pages a day and
provide web users with search facilities without which the World Wide
Web would be only a fraction of its current usefulness.

In order for search-engine
spiders to be able to rate the significance of pieces of text they find in HTML
documents, and also for those creating mashups and other hybrids as well as for
more automated agents as they are developed, the semantic structures that exist
in HTML need to be widely and uniformly applied to bring out the meaning of
published text.[52]

Presentational markup tags
are deprecated
in current HTML and XHTML recommendations and are illegal in HTML5.

Good semantic HTML also
improves the accessibility of web documents (see also Web Content Accessibility Guidelines).
For example, when a screen reader or audio browser can correctly ascertain the
structure of a document, it will not waste the visually impaired user's time by
reading out repeated or irrelevant information when it has been marked up
correctly.

Delivery

HTML documents can be
delivered by the same means as any other computer file. However, they are most
often delivered either by HTTP from a web server
or by email.

HTTP

Main
article: Hypertext Transfer Protocol

The World Wide
Web is composed primarily of HTML documents transmitted from web
servers to web browsers using the Hypertext Transfer Protocol (HTTP).
However, HTTP is used to serve images, sound, and other content, in addition to
HTML. To allow the Web browser to know how to handle each document it receives,
other information is transmitted along with the document. This meta data
usually includes the MIME type (e.g. text/html or application/xhtml+xml) and the
character encoding (see Character encoding in HTML).

In modern browsers, the MIME
type that is sent with the HTML document may affect how the document is
initially interpreted. A document sent with the XHTML MIME type is expected to
be well-formed
XML; syntax errors may cause the browser to fail to render it. The same
document sent with the HTML MIME type might be displayed successfully, since
some browsers are more lenient with HTML.

The W3C recommendations state
that XHTML 1.0 documents that follow guidelines set forth in the
recommendation's Appendix C may be labeled with either MIME Type.[53]
The current XHTML 1.1 Working Draft also states that XHTML 1.1 documents should[54]
be labeled with either MIME type.[55]

HTML
e-mail

Main
article: HTML email

Most graphical email clients
allow the use of a subset of HTML (often ill-defined) to provide formatting and
semantic
markup not available with plain text. This may include typographic
information like coloured headings, emphasized and quoted text, inline images
and diagrams. Many such clients include both a GUI editor for composing HTML e-mail
messages and a rendering engine for displaying them. Use of HTML in e-mail is
controversial because of compatibility issues, because it can help disguise phishing
attacks, because it can confuse spam
filters and because the message size is larger than plain text.

Naming conventions

The most common filename extension for files
containing HTML is .html. A common abbreviation of this is .htm,
which originated because some early operating systems and file systems, such as
DOS and FAT, limited file extensions to three letters.

HTML Application

Main article: HTML
Application

An HTML Application (HTA;
file extension ".hta") is a Microsoft
Windows application that uses HTML and Dynamic HTML in a browser to
provide the application's graphical interface. A regular HTML file is confined
to the security model of the web browser, communicating only to web servers and
manipulating only webpage objects and site cookies.
An HTA runs as a fully trusted application and therefore has more privileges,
like creation/editing/removal of files and Windows
Registry entries. Because they operate outside the browser's
security model, HTAs cannot be executed via HTTP, but must be downloaded (just
like an EXE file)
and executed from local file system.

Current variations

HTML
is precisely what we were trying to PREVENT— ever-breaking links, links
going outward only, quotes you can't follow to their origins, no version
management, no rights management. Since its inception, HTML and its associated
protocols gained acceptance relatively quickly. However, no clear standards
existed in the early years of the language. Though its creators originally
conceived of HTML as a semantic language devoid of presentation details,[57]
practical uses pushed many presentational elements and attributes into the
language, driven largely by the various browser vendors. The latest standards
surrounding HTML reflect efforts to overcome the sometimes chaotic development
of the language[58]
and to create a rational foundation for building both meaningful and
well-presented documents. To return HTML to its role as a semantic language,
the W3C has developed style languages such as CSS and XSL to shoulder the burden
of presentation. In conjunction, the HTML specification has slowly reined in
the presentational elements.

There are two axes
differentiating various variations of HTML as currently specified: SGML-based
HTML versus XML-based HTML (referred to as XHTML) on one axis, and strict
versus transitional (loose) versus frameset on the other axis.

SGML-based versus XML-based HTML

One difference in the latest
HTML specifications lies in the distinction between the SGML-based
specification and the XML-based specification. The XML-based specification is
usually called XHTML
to distinguish it clearly from the more traditional definition. However, the
root element name continues to be 'html' even in the XHTML-specified HTML. The
W3C intended XHTML 1.0 to be identical to HTML 4.01 except where limitations of
XML over the more complex SGML require workarounds. Because XHTML and HTML are
closely related, they are sometimes documented in parallel. In such
circumstances, some authors conflate the
two names as (X)HTML or X(HTML).

Like HTML 4.01, XHTML 1.0 has
three sub-specifications: strict, transitional and frameset.

Aside from the different
opening declarations for a document, the differences between an HTML 4.01 and
XHTML 1.0 document—in each of the corresponding DTDs—are largely
syntactic. The underlying syntax of HTML allows many shortcuts that XHTML does
not, such as elements with optional opening or closing tags, and even EMPTY
elements which must not have an end tag. By contrast, XHTML requires all
elements to have an opening tag and a closing tag. XHTML, however, also
introduces a new shortcut: an XHTML tag may be opened and closed within the
same tag, by including a slash before the end of the tag like this: <br/>.
The introduction of this shorthand, which is not used in the SGML declaration
for HTML 4.01, may confuse earlier software unfamiliar with this new
convention. A fix for this is to include a space before closing the tag, as
such: <br />.[59]

To understand the subtle
differences between HTML and XHTML, consider the transformation of a valid and
well-formed XHTML 1.0 document that adheres to Appendix C (see below) into a
valid HTML 4.01 document. To make this translation requires the following
steps:

The language
for an element should be specified with a lang
attribute rather than the XHTML xml:lang
attribute. XHTML
uses XML's built in language-defining functionality attribute.

Remove the
XML namespace (xmlns=URI). HTML has no facilities for namespaces.

Change the
document type declaration from XHTML 1.0 to HTML 4.01. (see DTD
section for further explanation).

If present, remove
the XML declaration. (Typically this is: <?xml
version="1.0" encoding="utf-8"?>).

Ensure that
the document's MIME type is set to text/html. For both HTML and XHTML, this comes from the HTTP Content-Type header
sent by the server.

Change the
XML empty-element syntax to an HTML style empty element (<br/>
to <br>).

Those are the main changes
necessary to translate a document from XHTML 1.0 to HTML 4.01. To translate
from HTML to XHTML would also require the addition of any omitted opening or
closing tags. Whether coding in HTML or XHTML it may just be best to always
include the optional tags within an HTML document rather than remembering which
tags can be omitted.

A well-formed XHTML document
adheres to all the syntax requirements of XML. A valid document adheres to the
content specification for XHTML, which describes the document structure.

The W3C recommends several
conventions to ensure an easy migration between HTML and XHTML (see HTML Compatibility Guidelines).
The following steps can be applied to XHTML 1.0 documents only:

Include both
xml:lang and
lang
attributes on any elements assigning language.

Use the
empty-element syntax only for elements specified as empty in HTML.

Include an
extra space in empty-element tags: for example <br />
instead of <br/>.

Include
explicit close tags for elements that permit content but are left empty (for
example, <div></div>,
not <div />).

Omit the XML
declaration.

By carefully following the
W3C's compatibility guidelines, a user agent should be able to interpret the
document equally as HTML or XHTML. For documents that are XHTML 1.0 and have
been made compatible in this way, the W3C permits them to be served either as
HTML (with a text/html MIME type),
or as XHTML (with an application/xhtml+xml or application/xml
MIME type). When delivered as XHTML, browsers should use an XML parser, which
adheres strictly to the XML specifications for parsing the document's contents.

Transitional versus strict

HTML 4 defined three
different versions of the language: Strict, Transitional (once called Loose)
and Frameset. The Strict version is intended for new documents and is
considered best practice, while the Transitional and Frameset versions were
developed to make it easier to transition documents that conformed to older
HTML specification or didn't conform to any specification to a version of HTML
4. The Transitional and Frameset versions allow for presentational markup,
which is omitted in the Strict version. Instead, cascading style sheets are encouraged to
improve the presentation of HTML documents. Because XHTML 1 only defines an XML
syntax for the language defined by HTML 4, the same differences apply to XHTML
1 as well. The Transitional version allows the following parts of the
vocabulary, which are not included in the Strict version:

A
looser content model

Inline
elements and plain text are allowed directly in: body, blockquote,
form, noscript
and noframes

Presentation
related elements

underline
(u)(Deprecated.
can confuse a visitor with a hyperlink.)

strike-through
(s)

center(Deprecated. use CSS instead.)

font(Deprecated. use CSS instead.)

basefont(Deprecated. use CSS instead.)

Presentation
related attributes

background(Deprecated. use CSS instead.) and bgcolor(Deprecated.
use CSS instead.) attributes for body(required
element according to the W3C.) element.

align(Deprecated. use CSS instead.) attribute on div, form,
paragraph (p)
and heading (h1...h6)
elements

align(Deprecated. use CSS instead.), noshade(Deprecated.
use CSS instead.), size(Deprecated.
use CSS instead.) and width(Deprecated.
use CSS instead.) attributes on hr
element

align(Deprecated. use CSS instead.), border, vspace and hspace
attributes on img
and object(caution:
the object
element is only supported in Internet Explorer(from the major browsers))
elements

align(Deprecated. use CSS instead.) attribute on legend and caption
elements

align(Deprecated. use CSS instead.) and bgcolor(Deprecated.
use CSS instead.) on table
element

nowrap(Obsolete), bgcolor(Deprecated.
use CSS instead.), width,
height on td and th elements

bgcolor(Deprecated. use CSS instead.) attribute on tr element

clear(Obsolete) attribute on br element

compact attribute on dl,
dir and menu
elements

type(Deprecated. use CSS instead.), compact(Deprecated.
use CSS instead.) and start(Deprecated.
use CSS instead.) attributes on ol
and ul elements

type and value
attributes on li
element

width attribute on pre
element

Additional
elements in Transitional specification

menu(Deprecated. use CSS instead.) list (no substitute,
though unordered list is recommended)

dir(Deprecated. use CSS instead.) list (no substitute,
though unordered list is recommended)

isindex(Deprecated.) (element requires server-side support
and is typically added to documents server-side, form and input
elements can be used as a substitute)

applet (Deprecated. use the object
element instead.)

The language(Obsolete)
attribute on script element (redundant with the type
attribute).

Frame
related entities

iframe

noframes

target(Deprecated in the map,
link and form
elements.) attribute on a,
client-side image-map (map),
link, form and base
elements

The Frameset version includes
everything in the Transitional version, as well as the frameset element (used instead of body) and the frame element.

Frameset
versus transitional

In addition to the above
transitional differences, the frameset specifications (whether XHTML 1.0 or
HTML 4.01) specifies a different content model, with frameset replacing body, that contains either frame elements, or optionally noframes with a body.

Summary
of specification versions

As this list demonstrates,
the loose versions of the specification are maintained for legacy support.
However, contrary to popular misconceptions, the move to XHTML does not imply a
removal of this legacy support. Rather the X in XML stands for extensible and
the W3C is modularizing the entire specification and opening it up to
independent extensions. The primary achievement in the move from XHTML 1.0 to
XHTML 1.1 is the modularization of the entire specification. The strict version
of HTML is deployed in XHTML 1.1 through a set of modular extensions to the
base XHTML 1.1 specification. Likewise, someone looking for the loose
(transitional) or frameset specifications will find similar extended XHTML 1.1
support (much of it is contained in the legacy or frame modules). The
modularization also allows for separate features to develop on their own
timetable. So for example, XHTML 1.1 will allow quicker migration to emerging
XML standards such as MathML (a presentational and semantic math language based on
XML) and XForms—a
new highly advanced web-form technology to replace the existing HTML forms.

In summary, the HTML 4.01 specification
primarily reined in all the various HTML implementations into a single clearly
written specification based on SGML. XHTML 1.0, ported this specification, as
is, to the new XML defined specification. Next, XHTML 1.1 takes advantage of
the extensible nature of XML and modularizes the whole specification. XHTML 2.0
will be the first step in adding new features to the specification in a
standards-body-based approach.

Hypertext features not in HTML

HTML lacks some of the
features found in earlier hypertext systems, such as typed links,
source
tracking, fat links and others.[60]
Even some hypertext features that were in early versions of HTML have been
ignored by most popular web browsers until recently, such as the link element
and in-browser Web page editing.

Sometimes Web services or
browser manufacturers remedy these shortcomings. For instance, wikis and content management systems allow surfers
to edit the Web pages they visit.

WYSIWYG editors

There are some WYSIWYG
editors (What You See Is What You Get), in which the user lays out everything
as it is to appear in the HTML document using a graphical user interface (GUI), where the editor
renders this as an HTML document, no longer requiring the author to have
extensive knowledge of HTML.

The WYSIWYG editing model has
been criticized,[61][62]
primarily because of the low quality of the generated code; there are voices
advocating a change to the WYSIWYM model (What You See Is What You Mean).

WYSIWYG editors remains a
controversial topic because of their perceived flaws such as:

Relying
mainly on layout as opposed to meaning, often using markup that does not
convey the intended meaning but simply copies the layout.

Often
producing extremely verbose and redundant code that fails to make use of
the cascading nature of HTML and CSS.

Often
producing ungrammatical markup often called tag soup.

As a
great deal of information of HTML documents is not in the layout, the
model has been criticized for its 'what you see is all you get'-nature.

Nevertheless, since WYSIWYG
editors offer convenience over hand-coded pages as well as not requiring the
author to know the finer details of HTML, they still dominate web authoring.

VBScript Fundamentals

VBScript Features

The
following table is a list of Microsoft Visual Basic Scripting Edition
(VBScript) features.

Category                      Keywords

Array
handling   Array, Dim, Erase,
IsArray, LBound, Private, Public, ReDim, UBound

Array Function

Returns
a Variant containing an array.

Array(

arglist

)

Remarks

The
required arglist argument is a comma-delimited list of values that are assigned
to the elements of an array contained with the Variant. If no arguments are
specified, an array of zero length is created.

The
notation used to refer to an element of an array consists of the variable name
followed by parentheses containing an index number indicating the desired
element.

All
arrays in Visual Basic Scripting Edition (VBScript) are zero-based.

The
Array function is used to create single-dimension arrays. For information about
multi-dimensional arrays, see VBScript Variables.

Note:

A
variable that is not declared as an array can still contain an array. Although
a Variant variable containing an array is conceptually different from an array
variable containing Variant elements, the array elements are accessed in the
same way.

Example

The
following example illustrates the use of the Array function.

'
Create a single-dimension array and assign three elements.

Dim
A

A
= Array(10,20,30)

'
Set B to the third element in the array (which is 30).

'
The array is zero-based.

B
= A(2)

Dim Statement

Declares
variables and allocates storage space.

Dim varname[([subscripts])][, varname[([subscripts])]] . . .

Arguments

varname

Name
of the variable; follows standard variable naming conventions.

subscripts

Dimensions
of an array variable; up to 60 multiple dimensions may be declared. The
subscripts argument uses the following syntax:

upperbound
[,upperbound] . . .

The
lower bound of an array is always zero.

Remarks

Variables
declared with Dim at the script level are available to all procedures within
the script. At the procedure level, variables are available only within the
procedure.

You
can also use the Dim statement with empty parentheses to declare a dynamic
array. After declaring a dynamic array, use the ReDim statement within a
procedure to define the number of dimensions and elements in the array. If you
try to redeclare a dimension for an array variable whose size was explicitly
specified in a Dim statement, an error occurs.

For
more information about using the Dim statement to create variables and arrays,
see Visual Basic Scripting Edition (VBScript) Variables.

The
following examples illustrate the use of the Dim statement:

Dim Names(9)       ' Declare
an array with 10 elements.

Dim
Names()        '
Declare a dynamic array.

Dim
MyVar, MyNum   ' Declare two
variables.

Erase Statement

Reinitializes
the elements of fixed-size arrays and deallocates dynamic-array storage space.

Erase array

Arguments

The array argument
is the name of the array variable to be erased.

Remarks It
is important to know whether an array is fixed-size (ordinary) or dynamic
because Erase behaves differently depending on the type of
array. Erase recovers no memory for fixed-size
arrays. Erase sets the elements of a fixed array as follows:

Type
of array

Effect
of Erase on fixed-array elements

Fixed
numeric array

Sets
each element to zero.

Fixed
string array

Sets
each element to zero-length ("").

Array
of objects

Sets
each element to the special value Nothing.

Erase frees
the memory used by dynamic arrays. Before your program can refer to the dynamic
array again, it must redeclare the array variable's dimensions using
a ReDim statement.

The
following example illustrates the use of the Erase statement.

Dim
NumArray(9)

Dim
DynamicArray()

ReDim
DynamicArray(9)   ' Allocate
storage space.

Erase
NumArray   ' Each element is
reinitialized.

Erase
DynamicArray   ' Free memory
used by array.

Assignments    Set

Comments       Comments using ' or Rem

Constants/Literals        Empty, False, Nothing,
Null, True

Control flow     Do...Loop, For...Next, For Each...Next,
If...Then...Else, Select Case, While...Wend, With

Conversions    Abs, Asc, AscB, AscW, CBool, CByte, CCur, CDate,
CDbl, Chr, ChrB, ChrW, CInt, CLng, CSng, CStr,DateSerial, DateValue, Fix, Hex,
Int, Oct, Sgn, TimeSerial, TimeValue

Dates/Times     Date, DateAdd, DateDiff, DatePart,
DateSerial, DateValue, Day, Hour, Minute, Month, MonthName,Now, Second, Time,
TimeSerial, TimeValue, Weekday, WeekdayName, Year

Declarations     Class, Const, Dim, Function, Private,
Property Get, Property Let, Property Set, Public, ReDim, Sub

Error Handling Err, On Error

Expressions     Eval, Execute, RegExp, Replace, Test

Formatting
Strings       FormatCurrency,
FormatDateTime, FormatNumber, FormatPercent

Input/Output     InputBox, LoadPicture, MsgBox

Literals Empty, False, Nothing, Null, True

Math     Atn, Cos, Exp, Log, Randomize, Rnd, Sin,
Sqr, Tan

Miscellaneous  Eval Function, Execute Statement, RGB Function

Objects            CreateObject,
Err Object, GetObject, RegExp

Operators         Addition (+), And,
Division (/), Equality (=), Eqv, Exponentiation (^), Greater Than (>),
Greater Than or Equal To (>=), Imp, Inequality (<>), Integer Division
(\), Is, Less Than (<), Less Than or Equal To (<=), Modulus arithmetic
(Mod), Multiplication (*), Negation (-), Or, String concatenation (&),
Subtraction (-), Xor

Options            Option
Explicit

Procedures      Call, Function, Property Get, Property
Let, Property Set, Sub

Rounding         Abs, Fix, Int,
Round, Sgn

Script Engine ID          ScriptEngine,
ScriptEngineBuildVersion, ScriptEngineMajorVersion, ScriptEngineMinorVersion

Strings Asc, AscB, AscW, Chr, ChrB, ChrW, Filter, InStr, InStrB, InStrRev,
Join, LCase, Len, LenB, Left, LeftB,LTrim, Mid, MidB, Replace, Right, RightB,
RTrim, Space, Split, StrComp, String, StrReverse,  Trim,UCase

Variants           IsArray,
IsDate, IsEmpty, IsNull, IsNumeric, IsObject, TypeName, VarType

2
ASP CONCEPTS

ASP Pages syntax
and concepts: Technology overview.

The
ASP pages is the primary programming technique in ALP. It is simple and easy to
learn. Even developers with no experience in similar technologies would be able
to learn the basics for hours and begin developing their own applications with
ALP. The ASP is extensible and needs from the developer to know the basic
techniques and syntax only, any further details can be learned when needed and
ignored when the application being written doesn't need them.  The term ASP comes from 'Active Server
Pages" introduced in Microsoft Internet Information Server. ALP implements
on its own Active Local Pages technology which is very similar in the means of
usage, but is also different because it is especially designed for development
of desktop/stand-alone applications running on the user's macine.

Although
ALP targets scenarios different from the scenarios targeted by a WEB server it
preserves and employs the same techniques. These techniques are in the first
place convenient and easy to program in form oriented applications. These are
applications in which the user interacts with the application by
filling/altering the contents of forms, tables, lists. On the other hand this
gives the developers one more important benefit - the ALP pages are by default
almost fully compatible with the Active Server Pages technology and almost
always an application written for ALP can be deployed on Microsoft IIS WEB
server without need of changes in the code! Because of this compatibility we
will refer to the ALP pages as ASP pages.

The
request-response abstraction

The
Request-Response is a kind of Client-Server technique. It can be characterized
as a pure Client-Server in contrast to the majority of the technologies which
are client-server, but still allow part of the work to be done on the
"client" side without interaction with the "server" side.

ASP
is a Request-Response technology where on the client side the user uses a
viewer (usually WEB browser) and on the content shown in the viewer is
generated on the server side. The user interacts with the application by
"submitting" requests and receiving "responses". Thus the user
actions, for example clicking a button or a link, lead to requests sent to the
server which returns a response content which changes what the user sees in
his/her viewer/browser. So, the user sees an user interface in the viewer, what
he/she sees is defined by the content displayed by the viewer. Usually this is
based on HTML and the WEB browser draws the HTML on the user's screen allowing
him/her to view it and perform certain actions which will lead to
request-response pair of background actions that will change the HTML content
displayed in the viewer/browser. While it is not yet popular, it is not
impossible to use ASP with ALP and IIS and non-HTML/XML based viewers and
content.

Considering
the above a brief comparison between ASP and a typical form based development
tools such as Visual Basic, Delphi and many others, points out one significant
difference: In the traditional form based development environments the form
shown to the user has more or less static base structure and the client-server
applications change the contents/values of some elements of the form when the
user invokes certain actions. In ASP (and especially ALP where the conditions
under which the application works are the same) the entire form is replaced
each time the information shown in it needs to change. Thus in ASP the
interactions with the server have more clear effect - the user sees a
"document" displayed by the viewer and when the user does something
the document changes/re-generates.

Still,
we should not forget about DHMTL here. If DHTML techniques are used in the
displayed document the application may implement certain functionality on the
client side and avoid full regeneration of the entire document presented to the
user when the user action can be serviced without need to contact the server.

Client and server
- where are they?

In
a traditional form based software development environment the client is usually
the application code that controls the form presented to the user, and the
server is usually a database engine - sometimes remote, sometimes embedded and
actually part of the same application that is otherwise a client. So, the
separation of the client and the server is mostly logical and ALP is not an
exception. In ALP the client side is the document code (HTML or XML) code
displayed by the viewer/browser and the server side is the ASP code that
generates this document code. If we include a database in the picture we can
even think of the application as of a 3-tier application where the database is
the 3-d layer. As in the case of the other environments all the layers may be
in single application separated only logically, but of course they can be
separated in different processes and even on different machines. Thus an ALP
ASP application which runs on a stand-alone machine and uses the for example
the supplied ALP embedded database engine (See SQLite COM) will combine all the
layers in a single monolith application. Still the logical separation of the
layers is very clear and the same application can be distributed on 3 separate
machines - the client side (the viewer) on the user's machine, the ASP
processor on a WEB server machine and the database server on another machine.

ASP concepts,
structure and syntax

If
you are new to ALP and ASP you can learn how to write applications in just a few
moments. Follow the topics below to learn how to write pages, how to integrate
them in one application and how to perform actual tasks by using the components
supplied with ALP and 3-d party components.

The ASP page
structure

When
we speak about an ASP page, we assume by default the basic building block of
the ASP applications. The single ASP page combines the document code (usually
HTML or XML), script code that generates/replaces parts of the document code
and is designed to service single request by generating the response document
code which is then displayed in the viewer/browser.

Interaction with
the user

The
ASP pages receive the request as s set of values grouped in several
collections. They represent the details about the request, the user actions/selections
involved in it. The ASP pages interact with the user by inspecting the request
data and responding accordingly.

Application wide
state the Application and Session objects

The
ASP pages themselves have very short life-time. They terminate after responding
to the request. However the applications need to keep and transfer some data
and objects across the requests and refer to them from different pages when
they service different requests. ASP strictly distinguishes 3 variable scopes -
page (request) scope, Session (user) scope and application (global) scope.

Initializing the
application - global.asa file

As
the separate ASP pages service single requests it is logical to have a special
place for the application initialization. In the global.asa file the ASP
applications can instantiate and initialize variables and objects for the
session and application scope.

Using the
components to perform the actual tasks

The
above topics explain how the ASP applications work, but the applications can do
a little useful work up to this point. To perform something of real use the ASP
applications need components. The components are libraries that provide certain
functionality to the application. The applications create objects from these
libraries and use their members (properties and methods) to perform their
actual work. Many components are designed to work together - e.g the page
creates an object, then calls a method on it which returns another object, or
the application creates two or more objects, initializes them and passes one
object to another in order to cause certain action.

The ALP Run-time
library.

ALP
supplies standard run-time library to the ASP applications. It contains
components that give the applications ability to work with files, databases, network
connections, organize their run-time data and persist it, run background
threads and so on. However the ASP applications are not limited to it - they
can use thousands of  3-d party
components to gain access to more system features, access and control other
applications working on the same machine, work with corporate database servers
and so on.

How to build
components that will integrate with ALP

The
ALP run-time library contains multipurpose components. They are used in ASP
practically the same way they are used in other environments. Because they are
universal, it is convenient to have them this way, but if the developer wants
to build own specialized  components
for certain ASP application(s) it is more practical to integrate them with ALP
tightly and thus save some ASP coding and simplify their usage. This is most
often useful for components implementing business logic over data processed
partially in the ASP code, components that process part of the request and
present it to the ASP code in more convenient form and so on. In such case it
is useful to provide these components with means to access the ASP object model
directly without need to write countless lines of code simply to transfer data
from the request to the object. The ALP developers can build such components in
C, VB, VBScript/JScript and other COM enabled languages. Sometimes the very
reason for building such a component is to benefit of a specific feature of a
language not directly usable in ASP - this article explains how this can be
done.

Active Server Pages: An Introduction
to Web-based Application Development

Welcome. This article is the first of
many in an ongoing series about developing  web content using
Microsoft’s Active Server Pages. It is intended for developers and
webmasters who are new to Microsoft’s active content strategy including Internet Information Server
(IIS), Active Server Pages (ASP), Active
Data Objects (ADO) and the Component
Object Model (COM) but are not necessarily new to the Windows NT Platform,
Microsoft products or web development  in general.

This series will be produced bi-weekly
to provide how-to information on building web applications from the ground up
in the Active Server Pages environment. We will cover topics such as scripting,
database access, component object development and application integration using
the suite of tools provided in Microsoft Visual Studio 97 and Internet
Information Server.

If you’ve been building dynamic
web sites using tools such as Perl, C, ISAPI or other technologies such as
Microsoft’s Internet Database Connector or Allaire’s Cold Fusion, I
urge you to read ahead to see what’s possible using the latest
server-side technology from Microsoft - Active Server Pages.

An Introduction to the Active Platform

Microsoft has a very 'active'
perspective on how application architectures should be created.  For that
matter, the word 'active' or more specifically, the term ActiveX, has become a
standard part of packaging  just about every product concept released from
Microsoft within the last year.

Active Platform is the name given to
Microsoft's component-based application development model for the
Web. Active Platform is divided into three major sections:

Active
Desktop - an ActiveX-enabled client
architecture designed to house components and language-independent
scripting environments

Active
Server - primarily intended to provide
an execution environment for running business logic distributed across
enterprise application servers

ActiveX
Technologies - the object-based underpinnings
of all of the above - commonly referred to as The Component Object Model,
or COM

Given that definition, let's turn our
attention to where server-based applications are created.

The Active Server Side of Things

Active Server components actually
constitute what we traditionally think of as the 'middle' tier, or business
rule layer of an enterprise application.  These components are responsible
for encapsulating the majority of an application's transaction and database
logic.  For example, you might decide to place the logic for a complex
calculation that requires access to several database tables inside an Active
Server component.  This component would then be invoked by other Active
Server components during execution of one or more of your enterprise
applications.

The server-side execution
environment  that makes much of this possible is named Active Server Pages
(formerly code-named "Denali"), an
environment   in Microsoft Internet Information Server that executes
ActiveX Scripts and ActiveX Components on a server.

Welcome to Active Server Pages

Active Server Pages are a key
component of Microsoft’s dynamic web content strategy. With Active Server
Pages, a software developer can create interactive and personalized web pages
for their World Wide Web site or corporate intranet without having to
understand the internals of a web server or complex application programming
interfaces. In addition, Active Server Pages is extensible via software
components written using Microsoft’s Component Object Model so
you’ll be able to take advantage of code you’ve already written
using languages such as Visual Basic, C++ or Java.

A Little History

The World Wide Web came to life in
1990 when researchers at Switzerland’s
CERN laboratory needed to distribute documents
and graphics via the Internet but needed something more than simple file
transfers. It’s a familiar story, but it was this series of events that
led up to the creation of the most significant evolutionary period in
application development.

From Web Sites to Web Applications

After the initial introduction of the
web, a specification emerged: CGI, or the Common Gateway Interface. This
specification allowed resources, in the form of executable programs, to be
requested by a web browser and  executed by a web server via a standard
Uniform Resource Locator or URL.

These CGI-based programs could take
user input in the form of command line parameters and use the standard input
and output file handles of a program to receive and generate HTML output in
response to a browser’s request. In addition, various pieces of state
information located on the server could be interrogated by the program during
execution and used to make logic decisions as to how this processing should
occur. The ultimate goal: use this logic and processing capability to provide a
custom experience for the user on the other side of the browser.

In one way or another, what emerged
was a means of using logic far beyond the capabilities of HTML to accomplish
standard data processing functionality such as input validation and database
access and the power to distribute that processing across the world.

Where Active Server Pages Fit In

Active Server Pages were introduced
with release 3 of Microsoft’s web server, Internet Information Server or
IIS. Active Server Pages are actually a series of dynamic link libraries or
DLLs that are installed on your web server by either a standalone installation
program or as part of the Visual Studio 97 setup for Visual InterDev. These
DLLs give IIS the ability to interpret and process information via the use of a
script file (called an ASP script) that is resident in your web application
directory.

Scripts and Why They Are Different

Once you complete the installation of
Active Server Pages, a web browser can request scripts just as if it were
requesting an HTML file. The difference is these files contain Active Server
Page script, usually in the form of VBSCRIPT or JSCRIPT, and have a file
extension of .ASP.  When requested, these scripts execute in the Active
Server Page environment instead of being simply returned to the browser and
produce output for sending back to the requesting browser.

You may be wondering just how quickly,
if at all, you or your web developers could take advantage of this technology.

For starters, let’s take a look
at how you get your Active Server Pages environment up and running. Then
we’ll build our first script that dynamically generates an HTML page.

Installing the Active Server Pages
Environment In Windows NT

Whether your platform is Windows NT
Server 4.0, Windows NT Workstation 4.0 or Windows 95, you will need to first
install and start a web server that is compatible with the Active Server Pages
environment.

To date, each of these platforms
provide a web server that supports Active Server pages. For Windows NT Server
there is Microsoft’s Internet Information Server, for Windows NT
Workstation there’s Microsoft’s Peer Web Services, and for Windows
95, there’s Personal Web Server. If you’ve ever installed Windows
NT Server 4.0, you have probably been asked if you want to install Internet
Information Server. Answering ‘Yes’ to this question will install
the default configuration for Internet Information Server version 2.0. Then,
you’ll need to install NT Service Pack 3. This will upgrade your current
IIS 2.0 installation  to 3.0, the necessary release for Active Server
Pages.

After installing IIS 3.0, you’ll
need to install Active Server Pages. You’ll find this installation either
on the Microsoft Web download
page, NT Service Pack 3, or as part of your Visual Studio 97 installation.

Now you’re ready to write your
first script:

Active Server Pages 101

The following script can be written
using a text editor such as the Windows NotePad.  Its' intent is to
display four lines of text in the browser window that say "Hello ASP
World!" each in a larger font:

HELLO.ASP

Notice there is a mixture of what
appears to be HTML and BASIC. The BASIC is actually VBSCRIPT and the HTML is,
you guessed it, plain vanilla HTML.  Let’s take a quick tour of this
example and see what it’s made up of and what it produces as its final
output in the browser. HELLO.ASP includes three standard HTML elements: HEAD,
TITLE and BODY. For all intents and purposes, this is the proposed HTML page to
be sent to the requesting browser when the HELLO.ASP page executes.  If you look closely, you’ll see
several occurrences of "<%" and "%>".
These angle-bracket percent signs are the opening and closing tags for a block
of ASP script. You should note that ASP is not really a script, its actually a
host environment for any number scripting languages such as VBSCRIPT, JSCRIPT
and others including even a third-party Active Server Page version of   PerlScript.

A Dissection of HELLO.ASP

The first line of HELLO.ASP is actually
a special scripting tag that tells the ASP interpreter to set the default
scripting language to VBSCRIPT.  As discussed earlier, the target language
could have very well been JSCRIPT. The only condition is that the language in
question must be registered as a valid scripting language in the server’s
registry.

<%@ LANGUAGE="VBSCRIPT"
%>

The next five or so lines are
HTML. We set a title then we open the BODY section of the document.

<HTML>

<HEAD>

<TITLE>My First ASP Script!</TITLE>

</HEAD>

<BODY>

The next three lines make up the
substance of our ASP script.

If you are familiar with the BASIC
language, you’ll immediately recognize the ‘for-next’ looping
construct in the code sample below. For those of you who are not,
‘for-next’ is a BASIC language construct that allows a block of
code to execute for a number of times. In this example, ‘x’ is a
variable that initially has a value of three and is incremented until, or to,
the number 6 – in other words we execute the code between the for
and the next four times.

<%
for x = 3 to 6 %>

<FONT SIZE=<% =x %>>Hello ASP World!</FONT><BR>

<% next %>

The code within the body of the loop
is as follows:

<FONT SIZE=<% =x %>>Hello
ASP World!</FONT><BR>

The only thing left to explain is the <%
=x %> occurring on the right of the SIZE= attribute of the FONT
tag. This notation indicates that the contents of a variable named x
will be substituted (which in this case will be 3, 4, 5 or 6) into the line
prior to sending the HTML back to the browser. What’s actually generated
and sent back to the requesting browser, is pure HTML that looks like this:

<HTML>

<HEAD>

<TITLE>My First ASP Script!</TITLE>

</HEAD>

<BODY>

<FONT SIZE=3>Hello ASP World!</FONT><BR>

<FONT SIZE=4>Hello ASP World!</FONT><BR>

<FONT SIZE=5>Hello ASP World!</FONT><BR>

<FONT SIZE=6>Hello ASP World!</FONT><BR>

</BODY>

</HTML>

And
what’s rendered in the browsers document window looks like this: Hello
ASP World!

Hello ASP
World!

Hello ASP
World!

Hello ASP
World!

Hello ASP
World!

3 USING REQUEST

Request Object

It is called a request when a
browser asks for a page from a server, . To get information from the user,the
ASP Request object is used. Its collections, properties, and methods are
described below:

Collections:

Collection Description

ClientCertificate Contains all the
field values stored in the client certificate

Cookies Contains all the cookie
values sent in a HTTP request

Form Contains all the form (input)
values from a form that uses the post method

QueryString Contains all the
variable values in a HTTP query string

ServerVariables Contains all the
server variable values

Properties

Property Description

TotalBytes Returns the total number
of bytes the client sent in the body of the request

Methods

Method Description

BinaryRead Retrieves the data sent
to the server from the client as part of a post request and stores it in a safe
array

Send query information when a user
clicks on a link using QueryString

<html>

<body>

<a
href="demo_simplequerystring.asp?color=green">Example</a>

<%

Response.Write(Request.QueryString)

%>

</body>

</html>

O/P:

Example color=green

How to use information from forms

<html>

<body>

<form
action="demo_simpleform.asp" method="post">

Your name: <input
type="text" name="fname" size="20" />

<input type="submit"
value="Submit" />

</form>

<%

dim fname

fname=Request.Form("fname")

If fname<>"" Then

Response.Write("Hello " & fname & "!<br
/>")

Response.Write("How are you today?")

End If

%>

</body>

</html>

O/P:

Your Name:

Results:

Hello Ravi!

How are you today?

4 RESPONSE

Response Object

To
send output to the user from the server,the ASP Response object is used. Its
collections, properties, and methods are described below:

Collections:

Collection
Description

Cookies
Sets a cookie value. If the cookie does not exist, it will be created, and take
the value that is specified

Properties

Property
Description

Buffer
Specifies whether to buffer the page output or not

CacheControl
Sets whether a proxy server can cache the output generated by ASP or not

Charset
Appends the name of a character-set to the content-type header in the Response
object

ContentType
Sets the HTTP content type for the Response object

Expires
Sets how long (in minutes) a page will be cached on a browser before it expires

ExpiresAbsolute Sets a date and time when
a page cached on a browser will expire

IsClientConnected
Indicates if the client has disconnected from the server

Pics
Appends a value to the PICS label response header

Status
Specifies the value of the status line returned by the server

Methods

Method
Description

AddHeader
Adds a new HTTP header and a value to the HTTP response

AppendToLog
Adds a string to the end of the server log entry

BinaryWrite
Writes data directly to the output without any character conversion

Clear
Clears any buffered HTML output

End
Stops processing a script, and returns the current result

Flush
Sends buffered HTML output immediately

Redirect
Redirects the user to a different URL

Write
Writes a specified string to the output

Write text with ASP

<html>

<body>

<%

response.write("Hello
World!")

%>

</body>

</html>

O/P:

Hello
World!

Format text with HTML tags in ASP

<html>

<body>

<%

response.write("<h2>You
can use HTML tags to format the text!</h2>")

%>

<%

response.write("<p
style='color:#0000ff'>This text is styled with the style
attribute!</p>")

%>

</body>

</html>

O/P:

You
can use HTML tags to format the text!

This
text is styled with the style attribute!

Redirect
the user to a different URL

<%

if
Request.Form("select")<>"" then

Response.Redirect(Request.Form("select"))

end
if

%>

<html>

<body>

<form
action="demo_redirect.asp" method="post">

<input
type="radio" name="select"

value="demo_server.asp">

Server
Example<br>

<input
type="radio" name="select"

value="demo_text.asp">

Text
Example<br><br>

<input
type="submit" value="Go!">

</form>

</body>

</html>

O/P:

Server Example

Text Example

Demonstrates
the use of the write method. To write to the browser.

<%@
Language=VBScript%>

<%
strFileTitle = "Writing"%>

<%ifnotLCase(Request.QueryString("PageView"))
= "source" then%>

<%ShowHeader
strFileTitle%>

<%<
Response.Write "<HTML>"

Response.Write
"<HEAD>"

Response.Write
"<META
NAME=""GENERATOR"" Content=""Microsoft Visual
Studio 6.0"">"

Response.Write
"</HEAD>"

Response.Write
"<BODY>"

Response.Write
"This example is done completely using Response.Write
statement.<BR><BR>"

Response.Write
"If you need to produce quotation marks you use &quot;&quot;"

Response.Write
"</BODY>"

Response.Write
"</HTML>"

ShowFooter

%>

O/P:

This
example is done completely using Response.Write statement.

If
you need to produce quotation marks you use "

5 APPLICATION

An application is a group of ASP files that
work together to perform some purpose

In ASP,the Application object is used to tie
these files together.

Application Object

A
group of ASP files may be called an application on the Web . Some purpose can
be achieved when the ASP file work together.In ASP ,the Application object is
used to tie these files together. For storing and accessing variables from any
page, just like the Session object,the Application object is used . The
difference is that in Sessions there is one Session object for EACH user while
ALL users share one Application object. In the Particular application (like
database connection information),the Application object should hold information
that will be used by many pages . This means it is possible access the
information from any page. In an Application object , you can change the
information in one place and the changes will automatically be reflected on all
pages.

Store and Retrieve Application
Variables

In
the application,application variables can be accessed and changed by any page .
You can create Application variables using "Global.asa" like this:

<script
language="vbscript" runat="server">

Sub
Application_OnStart

application("vartime")=""

application("users")=1

End
Sub

</script>   In the example above we have
created two Application variables: "vartime" and "users".

Application variables can be accessed
like this:

There are

<%

Response.Write(Application("users"))

%>

active
connections

Loop Through the Contents
Collection

All
application variables wil be stored in Contents collection .To see what's
stored in it ,you can loop through the Contents collection, :

<%

dim
i

For
Each i in Application.Contents

Response.Write(i
& "<br />")

Next

%>

You can use the Count property if you do
not know the number of items in the Contents collection :

<%

dim
i

dim
j

j=Application.Contents.Count

For
i=1 to j

Response.Write(Application.Contents(i)
& "<br />")

Next

%>

Loop Through the StaticObjects
Collection

To
see the values of all objects stored in the Application object,you can loop
through the StaticObjects collection :

<%

dim
i

For
Each i in Application.StaticObjects

Response.Write(i
& "<br />")

Next

%>

Lock and Unlock

Using
"Lock" method,you can lock an application : The users cannot change
the Application variables(other than the one currently accessing it),when an
application is locked . Using "Unlock" method,you can unlock an
application: This method is used to remove the lock from the Application
variable:>

<% Application.Lock

'do
some application object operations

Application.Unlock

%>

6 SESSION

To
store information about, or change settings for a user session, the
Session object is used .

Session
object is a Variables that holds information about one single user, and
are available to all pages in one application

In
ASP,the Session Object is a great tool for the modern web site. It allows you
to keep information specific to each of your site's visitors. You don't
have to worry about passing information page to page because information
like username, shopping cart, and location can be stored for the life of
the session

The Session object

When
you are working with an application, you open it, do some changes and then you
close it. This is much like a Session. The computer knows who you are. It knows
when you start the application and when you end. But on the internet there is
one problem: the HTTP address doesn't maintain state so that the web server
does not know who you are and what you do.

By
creating a unique cookie for each user,ASP solves this problem . The cookie is
sent to the client and it contains information that identifies the user. This
interface is called the Session object.

For
a user session,the Session object is used to store information about, or change
settings . Session object is a variable that holds information about one single
user, and are available to all pages in one application. Common information
stored in session variables are name, id, and preferences. The server creates a
new Session object for each new user, and destroys the Session object when the
session expires.

When does a Session Start?

A
session starts when:

After
a new user requests an ASP file, and the Global.asa file includes a
Session_OnStart procedure

In
a Session variable,a value is stored.

To
instantiate an object with session scope a user requests an ASP file, and the
Global.asa file uses the <object> tag.

When
does a Session End?

If
a user has not requested or refreshed a page in the application for a specified
period,a session ends . By default, this is 20 minutes.

you
can set the Timeout property if you want to set a timeout interval that is
shorter or longer than the default,

The
example below sets a timeout interval of 10 minutes:

<%

Session.Timeout=10

%>

You may use the Abandon method to end a
session immediately:

<%

Session.Abandon

%>

Note: WHEN they should end is the main
problem with sessions. If the user's last request was the final one or not we
do not know. So how long we should keep the session "alive", we do
not know. Waiting too long for an idle session uses up resources on the server,
but the user has to start all over again because the server has deleted all the
information if the session is deleted too soon. Finding the right timeout
interval can be difficult!

Tip:
If you are using session variables, store SMALL amounts of data in them.

Store and Retrieve Session
Variables

You
can store variables in it is the most important thing about the Session object
. .

The
example below will set the Session variable username to "Martin
Luther" and the Session variable age to "40":

<%

Session("username")="Martin
Luther"

Session("age")=40

%>

It
can be reached from ANY page in the ASP application if the value is stored in a
session variable

Welcome
<%Response.Write(Session("username"))%>

The
above example returns: "Welcome Martin Luther".

In
the Session object,you can also store user preferences and then access that
preference to choose what page to return to the user.

If
the user has a low screen resolution,the example below specifies a text-only
version of the page

<%If
Session("screenres")="low" Then%>

This
is the text version of the page

<%Else%>

This
is the multimedia version of the page

<%End
If%>

Remove Session Variables

All
session variables are stored in Contents collection

To
remove a session variable with the Remove method is possible.

If
the value of the session variable "age" is lower than 18,the example
below removes the session variable "sale"

<%

If
Session.Contents("age")<18 then

Session.Contents.Remove("sale")

End
If

%>

Use
the RemoveAll method to remove all variables in a session,:

<%

Session.Contents.RemoveAll()

%>

Loop Through the Contents
Collection

All
session variables are stored in Contents collection .To see what's stored in it
,you can loop through the Contents collection, :

<%

Session("username")="Donald
Duck"

Session("age")=50

dim
i

For
Each i in Session.Contents

Response.Write(i
& "<br />")

Next

%>

O/P:

username

age

You
can use the Count property if you do not know the number of items in the
Contents collection,:

<%

dim
i

dim
j

j=Session.Contents.Count

Response.Write("Session
variables: " & j)

For
i=1 to j

Response.Write(Session.Contents(i)
& "<br />")

Next

%>

O/P:

Session
variables: 2

Donald
Duck

50

Loop Through the StaticObjects
Collection

To
see the values of all objects stored in the Session object you can loop through
the StaticObjects collection,:

<%

dim
i

For
Each i in Session.StaticObjects

Response.Write(i
& "<br />")

Next

%>

7 SERVER OBJECTS

To access properties and methods on the server, the
ASP Server object is used. The ASP Server object is used to
access properties and methods on the server. Its properties and methods are
described below:

Properties

Property

Description

ScriptTimeout

Sets or returns the
maximum number of seconds a script can run before it is terminated

Methods

Method

Description

CreateObject

Creates an instance
of an object

Execute

Executes an ASP
file from inside another ASP file

GetLastError()

Returns an ASPError
object that describes the error condition that occurred

HTMLEncode

Applies HTML
encoding to a specified string

MapPath

Maps a specified
path to a physical path

Transfer

Sends (transfers)
all the information created in one ASP file to a second ASP file

URLEncode

Applies URL
encoding rules to a specified string

Check when this
file was last modified

html>

<body>

<%

Set
fs = Server.CreateObject("Scripting.FileSystemObject")

Set
rs = fs.GetFile(Server.MapPath("demo_lastmodified.asp"))

modified
= rs.DateLastModified

%>

This
file was last modified on: <%response.write(modified)

Set
rs = Nothing

Set
fs = Nothing

%>

</body>

</html>

O/P:

This
file was last modified on: 9/12/2006 6:40:45 AM

8 USING COOKIES

What is a Cookie?

A
cookie is often used to identify a user. A cookie is a small file that the
server embeds on the user's computer. Each time the same computer requests a
page with a browser, it will send the cookie too. With ASP, you can both create
and retrieve cookie values.

How to Create a Cookie?

The
"Response.Cookies" command is used to create cookies.

Note:
The Response.Cookies command must appear BEFORE the <html> tag.

In
the example below, we will create a cookie named "firstname" and
assign the value "Alex" to it:

<%

Response.Cookies("firstname")="Alex"

%>

It
is also possible to assign properties to a cookie, like setting a date when the
cookie should expire:

<%

Response.Cookies("firstname")="Alex"

Response.Cookies("firstname").Expires=#May
10,2012#

%>

How to Retrieve a Cookie Value?

The
"Request.Cookies" command is used to retrieve a cookie value.

In
the example below, we retrieve the value of the cookie named
"firstname" and display it on a page:

<%

fname=Request.Cookies("firstname")

response.write("Firstname="
& fname)

%>

Output:
Firstname=Alex

A Cookie with Keys

If
a cookie contains a collection of multiple values, we say that the cookie has Keys.

In
the example below, we will create a cookie collection named "user".
The "user" cookie has Keys that contains information about a user:

<%

Response.Cookies("user")("firstname")="John"

Response.Cookies("user")("lastname")="Smith"

Response.Cookies("user")("country")="Norway"

Response.Cookies("user")("age")="25"

%>

Read all Cookies

Look
at the following code:

<%

Response.Cookies("firstname")="Alex"

Response.Cookies("user")("firstname")="John"

Response.Cookies("user")("lastname")="Smith"

Response.Cookies("user")("country")="Norway"

Response.Cookies("user")("age")="25"

%>

Assume
that your server has sent all the cookies above to a user.

Now
we want to read all the cookies sent to a user. The example below shows how to
do it (note that the code below checks if a cookie has Keys with the HasKeys
property):

<html>

<body>

<%

dim
x,y

for
each x in Request.Cookies

response.write("<p>")

if Request.Cookies(x).HasKeys then

for each y in
Request.Cookies(x)

response.write(x
& ":" & y & "=" & Request.Cookies(x)(y))

response.write("<br />")

next

else

Response.Write(x &
"=" & Request.Cookies(x) & "<br />")

end if

response.write "</p>"

next

%>

</body>

</html>

Output:

firstname=Alex

user:firstname=John

user:lastname=Smith

user:country=Norway

user:age=25

What if a Browser Does NOT
Support Cookies?

If
your application deals with browsers that do not support cookies, you will have
to use other methods to pass information from one page to another in your
application. There are two ways of doing this:

1. Add parameters to a URL

You
can add parameters to a URL:

<a
href="welcome.asp?fname=John&lname=Smith">Go to Welcome
Page</a>

And
retrieve the values in the "welcome.asp" file like this:

<%

fname=Request.querystring("fname")

lname=Request.querystring("lname")

response.write("<p>Hello
" & fname & " " & lname &
"!</p>")

response.write("<p>Welcome
to my Web site!</p>")

%>

2. Use a form

You
can use a form. The form passes the user input to "welcome.asp" when
the user clicks on the Submit button:

<form
method="post" action="welcome.asp">

First
Name: <input type="text" name="fname" value=""
/>

Last
Name: <input type="text" name="lname" value=""
/>

<input
type="submit" value="Submit" />

</form>

Retrieve
the values in the "welcome.asp" file like this:

<%

fname=Request.form("fname")

lname=Request.form("lname")

response.write("<p>Hello
" & fname & " " & lname &
"!</p>")

response.write("<p>Welcome
to my Web site!</p>")

UNIT V

.NET FRAMEWORK

THE .NET FOUNDATION

Microsoft .NET Framework

The Microsoft .NET Framework is
a computing model that make things easier for application development for the
distributed environment of the Internet. The .NET Framework is an environment
for building, deploying, and running Web Services and other applications. The
key components of the .NET Framework are the CLR and the .NET Framework class
library. The .NET Framework is a managed, type safe, multi-language environment
for application development and execution.

.NET Framework is a set of core
technologies that facilitates:

·
Easier
application development, deployment and maintenance by providing rich tools,
enhanced IDE, Better run time services etc.

·
Make
information available anytime, anywhere and helps in developing better
distributed applications via Web Services, ADO.NET DataSets and complete XML
support.

With .NET, you can develop
various types of applications as follows:

Windows
Form based applications (Rich client applications).

Console
based applications.

ASP.NET
Web applications (Browser based applications).

Web
services (Programmable application component that provides some useful
functionality, such as application logic, and is available to any number
of potentially incongruent systems through the use of Internet standards
such as XML and HTTP).

Component
Libraries (Components which encapsulate some business logic).

Windows
Custom Controls (Your own windows controls).

Web
Custom Controls (Your own web controls).

Windows
Services (Applications that run as services in the background).

Overall
architecture of the .NET

What Is .NET?

This
is a loaded question, but what it really comes down to is that .NET means
different things to different people. Much of what Microsoft is now offering
has the .NET name somewhere in its title, but what .NET means really depends on
whom you ask. The official one-line answer is that .NET is Microsoft’s
platform for XML Web services. Microsoft’s .NET Framework is a new computing
platform built with the Internet in mind, but without sacrificing the
traditional desktop application platform. The Internet has been around for a
number of years now, and Microsoft has been busy developing technologies and
tools that are totally focused on it. These earlier technologies, however, were
built on Windows DNA (Distributed interNet Applications Architecture), which
was based on COM (Component Object Model). Microsoft’s COM was in
development many years before the Internet became the force that we know today.
Consequently, the COM model has been built upon and added to in order to adapt
it to the changes brought about by the Internet. With the .NET Framework,
Microsoft built everything from the ground up with Internet integration as the
goal. Building a platform from the ground up also allowed the .NET Framework
developers to look at the problems and limitations that inhibited application development
in the past and to provide the solutions that were needed to quickly speed past
these barriers.

The
.NET vision

There
is a vision of the future at Microsoft, and this vision is strongly influencing
the direction of its products. The vision is that in the future all devices
will be connected in one way or another. The view is that all business and
household devices (telephones, microwaves, computers, televisions, and so
forth) will be connected to the Internet one day and will, therefore, be able to
communicate across this medium to perform the functionality needed to turn them
into superior products. The thought is that these products and devices will use
standardized languages such as XML and SOAP to communicate over standard
protocols such as HTTP. That is where XML Web services come in! XML Web
services are going to be the means for all these products and devices to
communicate the information and requests that they will need to perform some
type of functionality or registration.

The .NET solution

Figure
: A unified model.

In
anticipation of this future, Microsoft has developed the .NET Framework and the
tools necessary to build in this new environment. Microsoft realized that it
had many languages and tools that basically did the same thing. Admittedly,
some languages and tools did certain things better than others, but all of them
worked towards the same goal, and there was plenty of overlap

The .NET Framework

To get around
the problem of having multiple development environments, Microsoft developed an
environment that is a unified development environment. This framework is the platform
for the entire .NET idea. The framework is language-neutral and built to
provide you with the tools and solutions that you need to build rich
applications in the stateless environment of the Internet. The .NET Framework
includes two main components . the Common Language Runtime and the Base Class
Libraries.

The .NET IDE

Instead of a
multitude of tools for development, the .NET team created a single tool for developing
Windows Forms, ASP.NET Web Applications, and XML Web services. This tool is
Visual Studio .NET. As a developer, you will find Visual Studio .NET an
indispensable tool. It is finely interwoven within the .NET Framework and will
give you full and complete access to everything that .NET has to offer. Visual
Studio .NET is discussed further in the next chapter.

The .NET
languages

In the past,
you chose the development language for an application based upon the functionality
that you were trying to perform. Some languages were more powerful than others,
but at the same time they might have required a higher level of understanding
and were, in most cases, more difficult to program in.

The .NET
Enterprise Servers

The marketing
folks at Microsoft made things a little more confusing when they started naming
everything with a .NET suffix. Shortly after the introduction of .NET, all the forthcoming
.NET Enterprise Servers rebranded themselves as part of the .NET platform.

.NETs Foundation

The foundation
of the .NET platform is the .NET Framework, which we have already introduced.
The .NET Framework sits on top of the operating system and is made up of two parts,
the Common Language Runtime and the Base Class Libraries. Each one of these
parts plays an important role in the development of .NET applications and
services.

The Common
Language Runtime

Many different
languages and platforms provide a runtime, and the .NET Framework is no exception.
You will find, however, that this runtime is quite different from most. The
Common Language Runtime (CLR) in the .NET Framework manages the execution of
the code and provides access to a variety of services that will make the
development process easier.

The CLR has
been developed to be far superior to previous runtimes, such as the VB runtime,
by attaining the following:

_
Cross-language integration

_ Code access
security

_ Object
lifetime management

_ Debugging
and profiling support

Code that is
compiled and targeted to the CLR is known as managed code. Managed code provides
metadata that is needed for the CLR to provide the services of
multilanguage support, code security, object lifetime management, and memory
management.

Compilation to
managed code

The .NET
Framework requires that you use a language compiler that is targeted at the
CLR, such as the Visual Basic .NET, C#, C++ .NET, or JScript .NET compilers
provided by Microsoft.

Note that
there are a lot of third-party compilers on the market (such as COBOL and
Perl), and the number will continue to grow.

Garbage
collection

The .NET
Framework is a garbage-collected environment. Garbage collection is the process
of detecting when objects are no longer in use and automatically destroying
those objects, thus freeing memory. Garbage collection is not a new concept. It
has been used in other languages for quite some time. In fact, Java has a
garbage collection system in place. Other languages, such as C++, do not have a
garbage collection. C++ developers themselves are required to take care of the destruction
of objects and the freeing of memory.

Namespaces

The .NET
Framework is made up of hundreds of classes. Many of the applications that you build
in .NET are going to take advantage of these classes in one way or another.
Because the number of classes is so large and you will need to get at them in a
logical fashion, the .NET Framework organizes these classes into a class structure
called a namespace. There are a number of namespaces, and they are
organized in an understandable and straightforward way.

1
INTRODUCING .NET FRAMEWORK

Describing the .NET Framework 3.0

The goal in application development is
always the same: create the best possible software in the least amount of time.
Yet the bar is continually raised, as the platforms on which developers build
get better and better. In Windows, for example, the original Win32 interface
has been subsumed by the much more functional .NET Framework. Both version 1.0
of the Framework, released in 2002, and version 2.0, released in 2005, provide
a significantly better and more productive environment for people who design
and write Windows software.

The .NET Framework 3.0 (formerly known
as WinFX) is the next step in this progression. Applications built on this new
version of the Framework can be created with Visual Studio 2005, making it feel
familiar to most Windows developers. But the .NET Framework 3.0 is also an
evolution, adding more to what version 2.0 of the Framework already provides.
Scheduled to be released in late 2006, the .NET Framework 3.0 will be available
for Windows Vista, Windows Server 2003, and Windows XP.

This paper provides a big-picture view
of the .NET Framework 3.0 and its components. The goal is to make clear what
this new release is, examine how its technologies can be used, and provide
brief explanations of those technologies.

Building Modern Applications: The
Challenges

Creating a typical application today is
not a simple task—the requirements are substantial. Traditional concerns
such as working with stored data and allowing access through a Web browser are
still important, but they're no longer enough. Modern applications also present
a range of new challenges, including the following:

Organizations
are increasingly taking a process-oriented view of what they do. Since
most applications automate some part of a business process, it can be
useful to make the steps in this process explicit in the code. An effective
way to do this is by using workflow technology, an approach that requires support
for workflow-based applications.

Applications
commonly communicate with other applications, both inside and outside the
organization. Modern applications also must often fit into a
service-oriented architecture (SOA), exposing some of their functionality
as interoperable services accessible by other software. Achieving these
goals requires support for service-oriented applications.

The
people who use an application commonly need a way to convey information
about who they are. Many different technologies for defining and using a
digital identity are in use, and problems such as phishing are common.
Given this, a modern application and the people who use it can benefit from
consistent user control of digital identities.

The
requirements for a modern user interface have grown significantly.
Providing real business value can commonly require working with various
kinds of documents, using two- and three-dimensional graphics, displaying
video, and more. All of this also needs to be available for both native
Windows clients and Web browsers. Meeting these needs requires a unified
approach to diverse user interfaces.

Given that today's applications
commonly need to tackle some or all of these challenges, the platform those
applications are built on should also address all of them in a coherent and
usable way. The goal of the .NET Framework 3.0 is to do exactly this for
Windows applications.

Addressing the Challenges: What the .NET
Framework 3.0 Provides

As figure 1 shows, version 3.0 of the
.NET Framework builds on the previous release. In fact, nothing in version 2.0
of the .NET Framework is changed, so existing applications created for this
foundation will continue to work as always. The .NET Framework 3.0 does add
four new components, however: Windows Workflow Foundation, Windows
Communication Foundation, Windows CardSpace, and Windows Presentation
Foundation. This section takes a brief look at what the .NET Framework 2.0 and
each of these new components provides.

Figure 1

The .NET Framework 2.0: A
General-Purpose Foundation for Windows Applications

While it's still possible to write
software that directly uses the Win32 interface, the .NET Framework has become
the mainstream environment for new Windows applications. Among its most
important parts are the following:

ASP.NET,
which supports the creation of Web-accessible applications.

ADO.NET,
allowing applications to access relational and other types of data.

Windows
Forms, supporting the creation of graphical user interfaces (GUIs) for
Windows applications.

System.XML,
which lets applications work with XML-defined data, including using XSLT
and XPath.

Version 2.0 of the Framework added
several useful things to its predecessor, including substantially improved
technology for creating ASP.NET Web applications, support for 64-bit
applications running on 64-bit versions of Windows, and a new approach to
handling transactions. While some parts of the .NET Framework 2.0 are largely
superseded by the new components added in version 3.0, as described later, the
technologies in version 2.0 remain a fundamental part of this new release.

Windows Workflow Foundation: Support
for Workflow-Based Applications

A workflow is a simple idea: it's just
a series of steps performed in some order. One might even argue that every
application implements a workflow, since every application executes some
process. Yet the traditional approach to creating an application using C# or
Visual Basic or some other programming language is to make the steps in this
process implicit in the code. This certainly works, but it also embeds the
process itself deeply into a program's logic, making that process more
difficult to implement and to change.

Using workflow technology to implement
process logic can be an effective way to address this problem. Rather than
intertwining the logic in ordinary code, each step in the process is explicitly
defined, then executed by a workflow engine. The result is a clean
implementation of the process itself.

Workflow engines are not a new idea;
several are available today for Windows and for other systems. Microsoft even
provides workflow engines embedded in some of its products. Yet because
workflow is becoming a mainstream approach to creating applications, providing
a single workflow technology for Windows makes sense. This is exactly what's
done by Windows Workflow Foundation (the official acronym for which is WF).
By providing a common workflow technology for Windows, WF gives any
workflow-based application the same foundation to build on. Software provided
by Microsoft will use WF, including the Microsoft Office 2007 system and
Windows SharePoint Services, as will applications created by others.

Providing a common workflow technology
presents some challenges, however. For instance, how can a single approach meet
the diverse set of requirements presented by different workflow applications?
The answer adopted by WF is to take a very general view of workflow. As figure
2 shows, a WF workflow is just a group of activities that are executed
by the WF engine. Each activity is actually a class, and it can contain any
work that the workflow's creator deems necessary. Activities can potentially be
reused across different workflows, making it easier to create automated
solutions to new problems.

Figure 2

Another challenge in providing a
common workflow technology stems from the traditional division between
human-oriented and system-oriented workflows. Workflow applications that are
used primarily by people need to be flexible, allowing things such as
on-the-fly changes to the process. Those used primarily by systems, that is, by
software, tend to be more static, but must be as efficient as possible. WF is
intended for both kinds of uses, and so it includes human-oriented features,
such as the ability to make changes to a running workflow, along with support
for more system-oriented behaviors.

By providing a common workflow
technology for Windows in WF, the .NET Framework 3.0 makes this useful paradigm
for building software generally available to developers. As a process-oriented
view of software continues to gain in popularity, the use of workflow will
likely grow as well.

Windows Communication Foundation:
Support for Service-Oriented Applications

Whether they're built using workflow
or with some other approach, most applications need to communicate with other
applications. How this communication is done has taken a big step forward in
the last few years. After decades of disagreement, all of the major vendors
have agreed to support the same protocols for application communication. Based
on SOAP, this global agreement on Web services makes interoperability between
applications built on different technology platforms, such as J2EE and the .NET
Framework, significantly simpler than it has been in the past. It also makes the
idea of service-oriented architecture much more plausible for most
organizations.

Plenty of approaches to communication
already exist, of course. In the .NET Framework 2.0, for example, the choices
include the following:

ASP.NET
Web Services, providing interoperable SOAP-based communication.

.NET
Remoting, focusing on communication between .NET applications.

Enterprise
Services, offering support for scalable, transactional applications.

System.Messaging,
supporting queued messaging through Microsoft Message Queuing (MSMQ).

Web
Services Enhancements (WSE), an extension to ASP.NET Web Services that
provides support for more recent specifications such as WS-Security.

All of these technologies have value,
and all have had a role to play. Yet why are there several different solutions
to address what is essentially the same problem? Why not instead create a
single foundation for application communication based on interoperable
services?

This is exactly what's done by Windows
Communication Foundation (WCF). Rather than requiring developers to use a
different technology with a different application programming interface for
each kind of communication, WCF (originally code-named "Indigo")
provides a common approach using a common API. In the .NET Framework 3.0 environment,
most applications that might have used one of the technologies just listed will
instead use WCF for communication.

WCF provides strong support for
interoperable communication through SOAP, an essential part of modern
computing. This includes support for several of the WS-* specifications,
including WS-Security, WS-ReliableMessaging, and WS-AtomicTransaction. WCF
doesn't require SOAP, however, and so other approaches can also be used,
including an optimized binary protocol, queued messaging using MSMQ, and simple
REST-based communication. WCF also takes an explicitly service-oriented
approach to communication. Rather than attempt to provide transparent
communication between objects, WCF interposes the slightly different
abstraction of a service between the communicating parties. One result of this
is to loosen some of the tight couplings that can exist in distributed object
systems, making interaction less error-prone and easier to change.

Communication between applications,
whether within an organization or across organizations, is a fundamental part
of modern software. The .NET Framework 3.0 addresses this challenge by using
the service-oriented approach of WCF.

Windows CardSpace: Consistent User
Control of Digital Identities

Think about how people represent
themselves today on the Internet. In the majority of cases, a person's digital
identity is expressed as a simple username. Combined with a password, this
identity is used to access email accounts, Internet merchants, and even on-line
banks and other financial institutions. Yet despite their simplicity (and
ubiquity), usernames and passwords have several drawbacks. Here are the two
most important:

People
have a hard time remembering all of the usernames and passwords they've
chosen for different sites. Many people use the same values for different
sites, easing the memory problem but increasing the security risk.

Usernames,
passwords, and other personal information can be stolen by phishers. By
sending deceptive emails, phishers entice their victim to log in to a Web
site that looks just like, say, the site of the victim's bank. The site is
actually controlled by the phisher, however, and so once the victim enters
his username and password, the phisher can use this information to
masquerade as the user at the real site.

Reducing the severity of these
problems requires a new approach to managing digital identities. Windows
CardSpace, originally code-named "InfoCard," is an important part of
that approach. To help people keep track of their digital identities, CardSpace
represents each identity as a distinct information card. If a Web site
accepts CardSpace logins, users attempting to log in to that site will see a
CardSpace selection screen like the one shown in figure 3. By choosing a card,
users also choose a digital identity that will be used to access this site.
Rather than remembering a plethora of usernames and passwords, users need only
recognize the card they wish to use. Different cards can also contain different
information, allowing users to control exactly what each site learns about
them.

Figure 3

The identities represented by these
cards are created by one or more identity providers. Any organization
can offer an identity provider, and rather than relying on simple usernames and
passwords, the identities each one provides will typically use stronger
cryptographic mechanisms to allow users to prove their identity. CardSpace
itself also includes a self-issued identity provider that runs on client
machines. With this provider, users can create their own identities that don't
rely on passwords for authentication. Web sites can accept these self-issued
CardSpace identities rather than relying on the usual password-based approach,
reducing the problems that passwords bring.

If passwords aren't used to log in to
a site, phishers can't steal those passwords. Still, if phishers can trick a
user into logging into a bogus site, they might be able to acquire other
information from the user, such as sensitive medical information. Preventing
this requires that users be able to distinguish real sites from the look-alike
fakes created by phishers. To allow this, the organization that owns a Web site
can get a high-assurance certificate. Unlike today's simple SSL
certificates, acquiring this new kind of certificate involves a much more
rigorous process, including stronger proof that the organization applying for
it actually is who it claims to be. A high-assurance certificate can also carry
a company's logo and other information to help the user correctly determine
whether a site using this certificate is legitimate. When a user accesses a new
site, CardSpace always displays the information in that site's certificate using
a standard screen. Based on the strength of the certificate received, this
screen will indicate different levels of assurance of the site's identity. The
goal is to force users to make an explicit decision to trust a site, then help
them make the right choices about which sites to trust.

Windows CardSpace is actually part of
a larger identity metasystem. Based entirely on open, public protocols,
this metasystem defines a way to use different digital identity technologies
consistently across diverse platforms (including operating systems other than
Windows) and diverse applications (including Web browsers other than Internet
Explorer). By providing a common way to select identities and more for Windows,
CardSpace fills a key role in the metasystem. And by addressing the fundamental
problem of identity, CardSpace also plays an important part in the .NET
Framework 3.0.

Windows Presentation Foundation: A
Unified Approach to Diverse User Interfaces

The user interface is an important
part of nearly every application. Yet what users expect from those interfaces
has advanced significantly. Traditional menu-driven GUIs are still required, of
course, but applications may also need to display video, run animations, use
two- and three-dimensional graphics, and work with various kinds of documents.
And all of this must be possible whether the application is accessed from a
stand-alone desktop client or through a Web browser.

Traditionally, all of these aspects of
the user interface have been provided in different ways on Windows. For
example, a developer can use Windows Forms, part of the .NET Framework, to
build a Windows GUI. Creating a Web browser interface requires using HTML and
perhaps Java applets or JavaScript code. Displaying video might rely on Windows
Media Player or software such as Adobe's Flash Player, while document formats
might be defined by Microsoft Word or Adobe's PDF or something else. The
challenge for developers is clear: building a coherent user interface for
different kinds of clients using diverse technologies isn't simple.

A primary goal of Windows Presentation
Foundation (WPF), originally code-named "Avalon," is to address this
challenge. By offering a consistent technical underpinning for all of these
user interface aspects, WPF makes life simpler for developers. By taking a more
modern approach, including support for video, animation, two- and
three-dimensional graphics, and various kinds of documents, WPF can let users
work with information in new ways. And by providing a common foundation for
desktop clients and browser clients, WPF makes it easier to build applications
that address both.

The example interface shown in figure
4, containing images, live graphics, three-dimensional views, and more,
illustrates some of what WPF provides. Rather than requiring developers with
skills in diverse technologies, user interfaces like this one can now be
created in a more consistent way.

Figure 4

One challenge that has long faced the
creators of user interfaces stems from the different roles required for
building effective interfaces. Software developers are needed to create the
logic behind the interface, but they're rarely the best people to define the
interface's look and feel. Designers, specialists in human/machine interaction,
are typically a much better choice for this role. Yet older technologies such
as Windows Forms are focused entirely on the developer. There's no truly
effective way for developers and designers to collaborate. To address this
problem, WPF relies on the eXtensible Application Markup Language (XAML). An
XML-based language, XAML allows specifying a user interface declaratively
rather than in code. This makes it much easier for tools to generate and work
with an interface specification based on the visual representation created by a
designer. In fact, Microsoft is providing a new product, Expression Interactive
Designer, to do exactly this. Designers will be able to use this tool (and
others provided by third parties) to create the look of an interface, then have
a XAML definition of that interface generated for them. The developer imports
this definition into Visual Studio, then creates the logic the interface
requires.

When developers create a stand-alone
WPF application, one that runs directly on Windows, they have access to
everything WPF provides. To create a client that runs inside a Web browser,
however, developers can build an XAML browser application, commonly
referred to as an XBAP. Built on the same foundation as a stand-alone
WPF application, an XBAP allows presenting the same style of user interface
within a downloadable browser application. The same code can potentially be
used for both kinds of applications, which means that developers no longer need
different skill sets for desktop and browser clients. As is typical for this
kind of rich Internet application, an XBAP downloaded from the Internet runs in
a secure sandbox, which limits what the application can do. Still, a large subset
of the user interface functionality available to a stand-alone WPF application
can also be used in an XBAP.

Both WPF stand-alone applications and
XBAPs can take advantage of WPF's modern graphics support, including the
ability to use hardware acceleration, support for vector graphics, and more. By
providing support for more powerful graphics, WPF makes possible a range of
data visualization options that aren't possible with Windows Forms or other
earlier technologies. WPF also provides the foundation for the XML Paper
Specification (XPS), which defines a standard format for viewing, distributing,
and printing fixed-format documents.

User interfaces are a complex and
important part of modern applications. Through WPF, the .NET Framework 3.0
presents a more complete and consistent solution to the challenges these
interfaces present. The goal is to let people who create user
interfaces—both developers and designers—do their jobs more
effectively.

Applying
the .NET Framework 3.0: A Scenario

One way to understand how a group of
technologies works together is to look at an example of how they can be used.
Imagine, for example, an application that lets customers and agents submit
insurance applications. If it were implemented using the .NET Framework 3.0,
this application might look something like figure 5.

Figure 5

The application's business logic,
shown in the upper left of the diagram, is implemented using a WF workflow. Handling
an application for insurance is a multi-step process, including evaluating the
application against this organization's underwriting rules, perhaps checking
the applicant's credit, and maybe even getting a manager's approval. The
workflow implements each of these steps as an activity, relying on other
software as needed. To access stored data, for instance, the activities in this
workflow use ADO.NET.

This insurance company provides a call
center, allowing its customers to apply for insurance over the phone. The
client software used by the people staffing that call center, shown in the
upper right of the diagram, is implemented as a stand-alone WPF application.
This client communicates with the application's business logic using WCF, using
a binary protocol optimized for WCF-WCF communication. As the figure shows, the
call center workers rely on Windows CardSpace to select the identity they will
use when logging into this application.

Customers can also apply for insurance
over the Web, and insurance agents can submit applications, as well. To allow
this, the application uses ASP.NET to communicate with Web browsers. As shown
in the lower left corner of the diagram, customers using Internet Explorer to
access this application through an ordinary HTML interface can still use
CardSpace to select the identity they wish to present. Third parties can also
implement an identity selection mechanism for other client operating systems
and browsers, allowing the identity metasystem to extend to non-Windows clients
and Web browsers.

Insurance agents who access this
application over the Internet may well need a more functional interface.
Accordingly, they can rely on an XBAP rather than a simple HTML interface. As
shown in the lower center of the diagram, this gives those customers a large
share of the user interface functionality provided by the WPF desktop
application used in the call center. Both are built on the same foundation, and
so the application's developers can reuse the same code in the two types of
clients. And as with the other kinds of clients, agents can use CardSpace to
select the identity they wish to present to the application.

Finally, it's likely that this
application will need to access and be accessed by other applications. If
approving a customer requires a credit check, for example, this will most
likely be done through a call to an external service. Or perhaps the
application accepts requests directly from other software, exposing services
that these external applications can invoke. For cases like these, shown in the
lower right of the figure, the application relies on WCF to communicate using
standard Web services. Whatever technology these applications are built on,
WCF's support for SOAP makes interacting with them straightforward.

This scenario illustrates how some of
the .NET Framework 3.0's most important components might be used in a typical
application. Quite a few options have been omitted, and so don't view this
simple example as a complete illustration of what this technology family provides.
Instead, the goal is to give a clear idea of how the various parts of the .NET
Framework 3.0 can be used in concert to address real business problems.

Understanding
the .NET Framework 3.0: The Technologies

To really get a feel for what the .NET
Framework 3.0 provides, it's useful to dig a little deeper into each of its
constituent technologies. This section provides a short tutorial on each of the
five parts of the .NET Framework 3.0. For a more detailed introduction to each
one, see For Further Reading at the end of this paper.

The .NET Framework 2.0

Figure 6

The .NET Framework 2.0 is a
fundamental part of Windows development today, and it's also the foundation of
the .NET Framework 3.0. Figure 6 illustrates the Framework's two parts: the
Common Language Runtime (CLR) and the .NET Framework class library. Some
components of the .NET Framework 3.0, including WF, WCF, and WPF, are
implemented largely as extensions to the .NET Framework class library. As
described earlier, however, while many parts of the class library remain an
important part of a developer's world, others are subsumed by new technologies
provided by the .NET Framework 3.0. ASP.NET, for example, is still the
foundation for creating browser-accessible applications, and ADO.NET is still
used to work with stored data. .NET Framework 3.0 developers might use WPF
rather than Windows Forms to create a native Windows GUI, however, and they'll
typically prefer WCF over ASP.NET Web Services, .NET Remoting, or Enterprise
Services. Despite these changes, it's important to understand that even in a
NET Framework 3.0 world, the previous version of the Framework remains a
central part of a developer's life.

Windows Workflow Foundation

A process-oriented design, driven by a
workflow, can be the right approach for a significant fraction of Windows
software. The purpose of WF is to let developers create and execute these
workflow-based applications. Figure 7 shows the components WF provides to do
this.

Figure 7

As described earlier, every workflow
is built from some number of activities. Both workflows and activities are just
classes, so both can be created directly in code. WF also provides the Workflow
Designer, a Visual Studio-hosted graphical tool for constructing workflows.
However a workflow is created, its activities can be drawn from the Base
Activity Library (BAL) provided with WF or from any other source.

Once a workflow has been defined, it's
eventually executed by the WF runtime engine. This engine relies on a group of
runtime services for persisting the workflow's state, tracking the workflow's
execution, and more. All of these things—the runtime services, the
runtime engine, and the workflow itself—are contained within some host
process. This process can be any Windows process, ranging from a simple console
or WPF application running on a desktop to a scalable server process.

Understanding WF requires knowing at
least a little about all of its components. The following sections take a brief
look at each one.

Workflows

Stripped to its essentials, a workflow
is nothing more than a group of activities. WF provides built-in support for
two styles of workflow:

Sequential
workflows, which execute activities in a defined order. Like a traditional
flow chart, a sequential workflow can contain branches, loops, and other
control structures. By default, however, activities execute in sequence,
one after another.

State
machine workflows, which implement a traditional finite state machine.
Like any state machine, which activity executes at a particular time is
determined by the combination of the current state and whatever event has
been received.

The sequential option is useful for
well-defined workflows, such as those used in purely software-based processes.
They're relatively simple to create and understand, and they initially feel
more natural to most developers. State machine workflows are a better choice
when the path of execution is less predictable. A good example of this is a
workflow that involves interactions with people, any of whom can cancel the
workflow at any point. Addressing this situation with a sequential workflow is
possible, but every step could be a branch: Do this if the workflow isn't
cancelled, do something else if it is cancelled. Modeling this kind of behavior
using a state machine is significantly simpler, since a request to cancel the
workflow is just another event that can be received and handled at any point.

Support for state machine workflows is
one example of how WF attempts to provide support for human as well as system
workflow. Another example of this is WF's support for changing a running
workflow. People can be capricious, and it's not uncommon for someone involved
in a workflow to wish to add a step, delete a step, or make some other change
in the process while it's underway. To accommodate this in a controlled way, WF
allows the developer who creates a workflow to specify whether and how that
workflow can be modified while it's executing.

The Base Activity Library

Developers are free to create custom
activities. In fact, Microsoft's goal is to foster the growth of a WF ecosystem
full of reusable activities. Still, starting with a common set of fundamental
activities makes life simpler for everyone. Providing this common set is the
role of the Base Activity Library (BAL).

A workflow isn't required to use
anything from the BAL. Still, many developers will find that the BAL makes
their lives simpler, especially at first. Among the activities contained in the
BAL are the following:

IfElse:
executes the activities contained in two or more possible paths based on
whether a condition is met.

While:
repeatedly executes one or more activities as long as a condition is true.

Sequence:
executes a group of activities one at a time in a defined order.

Parallel:
executes two or more groups of activities in parallel.

Code:
executes a defined chunk of code.

Listen:
waits for a specific event, then executes one or more activities when that
event is received.

InvokeWebService:
calls a Web service.

State:
represents a state in a workflow's state machine.

EventDriven:
defines a transition containing one or more activities that should be
executed when a specific event is received while in a particular state.

Policy:
allows defining and executing business rules using a WF-supplied rules
engine.

Rather than define a particular
language for specifying workflows, WF instead takes the more general approach
of using activities. The BAL provides one "language," but everybody
using WF is free to define their own, as well.

Tools for Windows Workflow Foundation:
The Workflow Designer

One of the advantages of creating
applications using workflows is the ability to define the workflow graphically.
WF's Workflow Designer allows this, as shown in figure 8. By default, the
activities in the BAL appear in the Toolbox, letting a developer drag and drop
them onto the tool's design surface to create a workflow.

Figure 8

Some developers prefer to write
code—they don't like graphical designers. WF allows this approach, too
(and sometimes requires it: activities are generally built directly in code).
It's also possible to combine the two approaches, creating a workflow using
both the Workflow Designer and direct coding. The goal is to let developers use
the approach that's most productive for them. And to allow broader tool
support, workflows can also be expressed in XAML, the same language used by
WPF. In fact, workflows created using the Workflow Designer default to a XAML
definition.

The Runtime Engine and Runtime
Services

As described earlier, the WF runtime
engine has the job of executing the activities in a workflow. As part of doing
this, it relies on a group of runtime services. WF includes standard
implementations of these services, but ambitious developers can replace them if
desired. These services support a few different things, but two stand out as
most interesting:

Persistence:
A workflow that's blocked waiting for some event can use this service to
have its in-memory state automatically persisted to disk. When the event
occurs, the service will automatically reload the workflow's state and
restart execution. This is especially useful for workflows that involve
people, since hours, days, or more might elapse while waiting for a
response.

Tracking:
The activities in a workflow cleanly demarcate the execution of the
process they implement. WF's tracking service allows a developer to cause
information about the workflow's execution to be automatically written to
a database. For example, a developer might wish to track when a workflow
starts and ends, when each of its activities starts and ends, and other
information.

Windows Workflow Foundation and Other
Microsoft Technologies

Introducing new approaches inevitably
influences what already exists. The new technologies in the .NET Framework 3.0
are no exception, and each one has an impact on other Microsoft technologies.
With WF, the initial impact is felt most strongly by Windows SharePoint
Services, the Microsoft Office 2007 system, and BizTalk Server.

To let developers more easily create
workflow applications for document collaboration and other kinds of information
sharing, Windows SharePoint Services, version 3 hosts the WF runtime. Office
SharePoint Server 2007, part of the Office 2007 system, builds on the WF
support in Windows SharePoint Services. Among other things, adding this server
allows displaying InfoPath forms directly in Office 2007 client applications
and using a set of pre-defined workflows for common scenarios such as approving
a document.

Anyone familiar with BizTalk Server
has certainly noticed by now the similarity between this product's
orchestration capabilities and what WF provides. In fact, the release following
BizTalk Server 2006 will replace the product's existing orchestration function
with WF, providing tools to help migrate existing orchestrations to WF
workflows. It's important to understand, however, that WF and BizTalk Server
2006 address quite distinct problems:

WF
provides a general framework for creating workflow-based Windows
applications. It can be hosted in any process, use any kind of activities,
and address any kind of business problem, including both human and system
workflows.

BizTalk
Server is a licensed product focused on enterprise application
integration, business-to-business integration, and managing business
processes. It offers a large set of adapters for connecting to diverse
systems and software, accelerators for implementing standards such as
RosettaNet and SWIFT, and support for business activity monitoring.
BizTalk Server also provides a management infrastructure and tools, along
with support for increased scalability.

Because it's the standard workflow
technology for Windows, WF may well show up in other Microsoft products and
technologies in the future. Whatever Microsoft chooses to do, WF will certainly
find a home in a number of applications created by its customers.

Windows Communication Foundation

The change to service-oriented
communication marks a shift in how applications interact. Explicitly designed
to support service-oriented applications, WCF reflects this shift. This section
describes the most important aspects of WCF, including services and clients,
communication options, and support for security, reliable communication, and
transactions.

Services and Clients

Figure 9

As figure 9 shows, the fundamental
idea of WCF is simple: a service exposes an interface that can be accessed by a
client. That interface can be defined using the Web Services Description
Language (WSDL), then turned into code, or it can be defined directly in a
language such as C# or Visual Basic. For a simple interface exposing an
insurance application service, the latter approach might look something like
this:

[ServiceContract]

interface
IInsuranceApplication

{

[OperationContract]

int Submit(int policyType, string
ApplicantName);

[OperationContract]

bool CheckStatus(int applicationNumber);

[OperationContract]

bool Cancel(int applicationNumber);

}

The definition of this C# interface is
marked with the ServiceContract attribute. This attribute indicates that
WCF can expose methods in this interface as remotely-callable operations. Which
of the interface's methods are exposed depends on which are marked with the OperationContract
attribute. In this simple example, every method is marked with this attribute,
and so all of them will be exposed to remote callers. This isn't required,
however—it's legal to apply OperationContract to only some of an
interface's methods. Whichever choice is made, some class in the application
must implement this interface, providing actual code for the methods the
interface defines. Once this is done, WCF automatically makes the methods
marked with OperationContract accessible to clients of this service.

Figure 10 gives a slightly more
detailed view of how a service is actually exposed to its clients. Rather than
access an interface directly, a client instead connects to a specific endpoint.
A service can expose multiple endpoints, potentially allowing different clients
to access it in different ways.

Figure 10

As the figure shows, each endpoint
specifies three things:

A
contract describing the operations that can be invoked using this
endpoint. The contract can be identified using just the name of the
interface that defines these operations, which here is
IInsuranceApplication.

A
binding defining how the endpoint's operations can be invoked. Each
binding defines several things, including what protocol should be used to
invoke the operations, what kind of security should be used, and more. WCF
includes a set of pre-defined bindings, such as the BasicHttpBinding shown
here, for the most common cases, and it's also possible to define custom
bindings. Because a single service can expose multiple endpoints, it can
simultaneously allow access to different kinds of clients over different
protocols and with different security options.

An
address indicating where this endpoint can be found. As shown in
the figure, the address is represented as a URL.

The basics of WCF are simple. As with
most communication technologies, the details can get complex—there are
many options—but creating ordinary WCF applications isn't hard.

Communication Options

Different kinds of applications built
by different kinds of developers need different ways to communicate. The
simplest approach for most developers is remote procedure call (RPC), which
lets a client invoke remote operations much like local ones. Given the
interface shown earlier, for example, a client could invoke any operation in
the usual synchronous way, waiting patiently until a response comes back. This
option is easy for developers, and it's the right choice in some circumstances.

WCF also provides several other
options, however. They include the following:

Calls
that have no response. Marked with the attribute OneWay, this kind
of communication can be useful for sending events or other one-way
interactions.

Asynchronous
message-based communication, using direct sends and receives with XML
messages.

Explicit
manipulation of SOAP messages, including the ability to insert elements
directly in the SOAP header.

WCF also allows developers to control
various local aspects of how a service behaves. Using the ServiceBehavior
attribute, for example, they can set whether the service is single or
multi-threaded, whether a new instance of the service is created for each call,
and other options.

Security, Reliability, and
Transactions

Basic communication—the ability
to move data between systems—is useful, but it's rarely enough. Most
applications need more. For example, the great majority of distributed
applications need some kind of security. Providing security can be complex,
given the range of different approaches and diversity of technologies in use
today. To let developers create secure distributed applications without forcing
them to understand all of the details, WCF relies primarily on bindings for
security. For example, the BasicHttpBinding shown earlier can be configured to
use HTTPS rather than plain HTTP, and other bindings provide more security
options. WsHttpBinding, for instance, supports WS-Security, allowing
interoperable SOAP-based authentication, data integrity, and data confidentiality.
Developers can also create a custom binding that provides the exact security
services their application needs.

Making sure that communication is
reliable is also essential for many applications. The traditional Web services
approach, sending SOAP over HTTP, is sufficient in some cases, and it's what's
done when the BasicHttpBinding is used. There are plenty of situations,
however, in which this widely-used choice isn't enough. Messages that go
through one or more SOAP intermediaries, for instance, can't rely on this
simple approach for end-to-end reliability. For these cases, WCF implements
WS-ReliableMessaging. By choosing a binding that supports this option, such as
WsHttpBinding, a developer can automatically get interoperable reliable message
transfer.

Distributed transactions can also be
important in some applications. WCF builds on System.Transactions, part
of the .NET Framework 2.0, to allow the creation of transactional software. A
method can use the OperationBehavior attribute to indicate that it
requires a transaction and to define how that transaction behaves. To allow
distributed transactions that are interoperable across vendor boundaries, WCF
relies on the WS-AtomicTransaction specification. Using the technology defined
in this multi-vendor agreement, WCF applications can participate in
transactions that span diverse technologies, including J2EE and others.

Windows Communication Foundation and
Other Microsoft Technologies

As mentioned earlier, WCF supersedes
several earlier Microsoft technologies for creating distributed applications.
Most applications that would have been built using ASP.NET Web Services, .NET
Remoting, Enterprise Services, System.Messaging, or WSE will instead be built
on WCF. WCF applications can interoperate with ASP.NET Web Services
applications—both support standard SOAP—as well as applications
built on Enterprise Services, MSMQ, and version 3.0 of WSE. WCF can also be
used by BizTalk Server 2006, and a future version of BizTalk Server will build
even more directly on what WCF provides.

It's important to understand that even
though new .NET Framework 3.0 applications won't commonly use them, all of the
technologies that WCF supersedes are still part of this version of the
Framework, and they'll all be supported as usual. Applications built using
earlier versions of these technologies will also continue to run normally;
installing and using the .NET Framework 3.0 won't break existing code.

Windows CardSpace

Whether it's through a Web browser or
some other kind of client, users routinely access applications across a
network. Since these applications commonly require users to identify themselves
in some way, the inescapable corollary is that people are regularly forced to
acquire and present identity information to remote software. Accessing Internet
applications through a browser provides a very common example of this, and
users on intranets commonly face the problem as well.

As described earlier, people most
often rely on usernames and passwords for digital identities today, with all of
the problems this entails. Windows CardSpace, part of the larger identity
metasystem, offers an alternative approach to addressing these problems. To get
a deeper understanding of how CardSpace does this, the place to start is with
the basic concepts of the identity metasystem.

Windows CardSpace and the Identity
Metasystem

When users access an application,
whether from a Web browser or an application-specific client or something else,
they commonly present some kind of digital identity. Digital identities come in
many varieties, but virtually all of them are represented on the network by a security
token. While a simple security token can be just a username, a more complex
token might include an X.509 certificate or an XML document. However they're
represented, security tokens are today's typical mechanism for representing
digital identities on the network.

While it's tempting to believe that
we'll all one day adopt a common security token format, the reality is that
diverse approaches will continue to be used. Just as we today carry multiple
identity cards in our wallet—drivers license, credit card, airline
frequent flyer card, and more—we'll always have diverse digital
identities represented by diverse kinds of security tokens. No single identity
system can provide a universal answer, and so multiple security tokens will
always be necessary.

Yet users still need some way to work
consistently with their diverse digital identities. Even though no single
identity system will suffice, it's possible to create a system of identity
systems—an identity metasystem—that allows using a myriad of
digital identities in a consistent way. Working with others, Microsoft has led
the process of defining this metasystem. Based on open Web services technologies,
such as WS-Security and WS-Trust, this metasystem defines how digital
identities can be acquired and used, regardless of the type of security token
they depend on.

The process of issuing, acquiring, and
using digital identities can be thought of as requiring three distinct roles.
Those roles are the following:

User:
Sometimes called the subject, the user is the entity that has a
digital identity.

Identity
provider: An identity provider supplies a
digital identity for a user. For the digital identity assigned to you by
your employer, for example, the identity provider is typically a system
such as Active Directory. For the digital identity you use with Amazon,
the identity provider is effectively you, since you define your own
username and password. Digital identities created by different identity
providers can carry different information and provide different levels of
assurance that users really are who they claim to be.

Relying
party: A relying party is an
application that in some way relies on a digital identity. A relying party
will frequently use an identity (that is, the information contained in
this identity's security token) to authenticate a user, then make an
authorization decision, such as allowing this user to access some
information. A relying party might also use the identity to get a credit
card number, to verify that the same user is accessing it at different
times, or for other purposes. Typical examples of relying parties include
Internet Web sites, such as banks, online merchants, and auction sites,
and any application that accepts requests through Web services.

These three kinds of entities interact
in the identity metasystem. Figure 11 illustrates these interactions, along
with where CardSpace fits in.

Figure 11

The process begins when a user
accesses a relying party through a CardSpace-aware application. To learn what
type of security tokens this relying party will request, the application must
get the relying party's policy (step 1). For a browser accessing a Web site,
which is likely to be the most common case, the site's policy is expressed in
HTML and sent back as part of a Web page. For applications accessed through Web
services, however, the application instead uses the industry-standard protocol
defined by WS-MetadataExchange to ask the relying party for its policy. In this
case, the policy is expressed using WS-SecurityPolicy, another industry
standard. However the policy information is acquired, it always indicates what
kind of security tokens this relying party will accept and what information
those tokens must contain.

Once CardSpace knows what kind of
security tokens the relying party needs, it displays the identity screen shown
earlier. Each digital identity available to this user is represented as an
information card on this screen. Cards issued by an external relying party are
referred to as managed cards, while those issued by CardSpace's
self-issued provider are known as self-issued cards. Both kinds of cards
can be shown on this screen, and the user can potentially select one of either
type. To make this decision easier, the screen indicates which identities meet
the requirements of the relying party by graying out cards that don't qualify.
The user then selects one of these as the digital identity he wants to use
(step 2).

A card doesn't contain an actual
security token, however. Instead, it holds the information necessary to locate
a particular identity provider and request a security token for this user. (In
fact, each card is originally created by some identity provider.) CardSpace
uses the contents of the card selected by the user to request a security token
from the identity provider that issued that card (step 3). This request is made
using WS-Trust, another industry-standard protocol, and users authenticate
themselves to the identity provider using Kerberos, an X.509 certificate and
digital signature, or another mechanism. The token is returned in an encrypted
form, which also contains a timestamp to prevent this token from being stolen
off the wire and reused in the future.

Once the requested security token is
returned, it's sent to the relying party (step 4). How the relying party uses
the information in the token can vary. If the token contains an X.509
certificate, for example, and is accompanied by a digital signature, the
relying party will likely use the token to authenticate the user. There's no
requirement that tokens be used for authentication or for any other security-related
purpose, however. (In fact, the term "security token" is a misnomer.)
A token might carry information such as proof of a user's age, eligibility for
a discount at an Internet shopping site, or anything else. Authentication is
one important use for security tokens, but it's not the only option.

It's important to note that neither
CardSpace nor the identity metasystem as a whole is aware of the format or
technology used for the security token. Rather than trying to create a new
single source for digital identities or a standard format for security tokens,
the goal of the metasystem is to provide a coherent way to use any digital
identity based on any kind of security token. By providing a Windows
implementation of key parts of the metasystem, CardSpace plays an important
role in making this general approach to digital identity a reality.

Fighting Phishing

Identity providers are often distinct
from the user, such as when an identity is assigned by an employer. Yet there
are plenty of situations in which the identity provider is actually users
themselves. If CardSpace isn't used, for instance, accessing many Web sites
requires giving a username and password, both of which are defined by users.
Once the users have created this identity, they can later supply the username
and password, then check their bank balance, buy a book, or do whatever else
this site allows.

Because they depend on passwords,
however, these kind of self-issued identities are targets for attackers, as
described earlier. To help reduce these attacks, CardSpace provides an
alternative way to create a self-issued identity. This self-issued identity
provider runs locally on the user's Windows system. Rather than relying on a
username and password, the security tokens created by the self-issued identity
provider are defined using the Security Assertion Markup Language (SAML), an
OASIS-defined standard. These tokens rely on public key technology rather than
passwords to prove the user's identity, and if a relying party accepts them,
they can play the same role as the traditional username and password. The
advantage is that there is no longer a password for phishers to steal. Reducing
the use of passwords, together with the stronger proof of a site's identity
provided by the high-assurance certificates described earlier, can make
phishing a much less serious problem.

Windows CardSpace and Other Microsoft
Technologies

CardSpace is related to several other
Microsoft technologies, including the following:

WCF:
Because it relies on Web services standards such as WS-Security and
WS-Trust, CardSpace uses WCF for communication. In fact, the creator of a
WCF application can cause that application to use CardSpace just by
specifying a particular binding.

Active
Directory: Although it's not possible
today, Active Directory will eventually be able to act as an identity
provider in the metasystem.

Windows
Live ID (formerly known as Passport): As with
Active Directory, Microsoft has announced that its Live ID authentication
system will also be modified to act as an identity provider. Note that
CardSpace isn't a replacement for Live ID, since the two address quite
different problems. Instead, Live ID will become part of the identity
metasystem just like any other identity provider.

Microsoft also provides other
identity-related technologies that address somewhat different problems than
CardSpace. Active Directory Federation Services (ADFS), for instance, focuses
on federating identities across organizations. This is an important challenge,
and it's faced by many firms that need to work with other organizations. This
problem is quite distinct, however, from the broader issues addressed by
CardSpace and the identity metasystem.

Windows Presentation Foundation

Workflow-based logic, service-oriented
communication, and identity are all important in modern applications. Yet users
often care most about what they see: the user interface. The goal of WPF is to
address the challenges of creating user interfaces for modern applications. As
described next, WPF provides a range of capabilities to do this.

The Capabilities of Windows
Presentation Foundation

A developer is free to create a WPF
application's interface entirely in C#, Visual Basic, or some other CLR-based
language. As described earlier, however, WPF also allows specifying an
interface using the XML-based XAML. Elements and attributes in XAML map
directly to the classes and properties that WPF provides. For example, here's a
simple button defined in XAML:

<Button
Background="Red">

No

</Button>

This example creates a red button that
contains the text "No." The exact same result could also be produced
with the following code:

Button
btn = new Button();

btn.Background
= Brushes.Red;

btn.Content
= "No";

However it's defined, virtually every
WPF application follows the same basic model. The application inherits from
WPF's standard Application object, which provides basic methods, events, and
properties. A WPF application can have either a traditional dialog-driven
interface or a navigational interface, letting it function much like a browser
application. An application built in the latter style is typically implemented
as a group of pages, each consisting of a user interface defined in XAML
together with some logic defined in code. To link these pages together, XAML
provides a Hyperlink element, much like HTML. The application displays one page
at a time, lets a user move back and forth among its pages, maintains a history
list, and more. Although a navigation application can run inside a Web browser
as an XBAP, this isn't required; a developer is free to use this interface
style in stand-alone WPF applications, as well. The goal is to create software
that combines the best aspects of a browser interface and a native Windows
interface.

Whatever style its interface uses, a
WPF application can rely on panels for basic layout. Each panel
typically contains controls, and those provided by WPF include Button,
TextBox, ComboBox, Menu, and many more. How those controls
are positioned depends on what type of panel is chosen. A Grid, for instance,
allows positioning controls on a specified grid, while a Canvas lets the
developer place controls anywhere within its boundaries. And as usual in a GUI,
events generated by the user are caught and handled by the various controls and
other classes in the application. It's also possible to apply styles and
templates to groups of controls, which makes it easier for applications to have
a uniform look.

WPF supports much more than these
basic user interface functions, including the following:

Documents:
A WPF application can display XPS documents using XAML's FixedDocument
tag. An application can also display flow documents using the FlowDocument
tag. A flow document can behave like a traditional on-screen document,
allowing the user to scroll through its contents. By setting various
attributes on this tag, however, a developer can make the document more
adaptive to its surroundings. A document can display a page at a time, for
example, freeing its reader from the need to scroll back and forth. WPF
can also automatically determine how many columns a document should be
broken into based on the size of the window in which it's displayed. The
goal is to allow on-screen documents to be as readable as possible.

Graphics:
WPF includes support for creating two-dimensional and three-dimensional
vector graphics. For 2D work, WPF provides standard abstractions such as
shapes, brushes, and pens, while allowing 3D graphics to define a model
that can be assigned lighting and camera position information. Unlike
earlier technologies such as Windows Forms, which relies on GDI+ for
graphics, WPF graphics aren't partitioned off using a separate set of
concepts that developers must understand. Instead, the XAML elements used
for graphics can be combined naturally with those used for anything else
in a user interface. Buttons can have graphical content, text and graphics
can be combined, and more.

Images:
Using XAML's Image tag, a WPF application can display images in
various formats, including JPEG, GIF, and others. WPF relies on the
Windows Imaging Component (WIC) to provide a standard framework for
codecs, software that displays and stores images. As usual in WPF, an Image
element can be combined with others, allowing things such as a button that
displays an image rather than a simple text label.

Media:
A WPF application can use the MediaElement tag to display video and
audio in various formats, including WMV, AVI, and MPEG. Once again, this
element can be combined with other XAML elements, allowing things such as
a 3D cube that displays video on its sides.

Animation:
WPF provides built-in support for animating most parts of a user
interface. A circle can grow and shrink, for example, or a button can
smoothly change size. Applications can also define storyboards containing
timelines, allowing coordinated sequences of animations to occur.

Data
Binding: Because many WPF applications
display data, it's useful to have automatic support for mapping data to
user interface elements. WPF provides this kind of data binding for
information contained in objects and other sources. WPF data binding also
allows sorting and filtering data before it's displayed.

Applying Windows Presentation
Foundation

WPF provides a large set of user
interface functionality, allowing developers and designers to create very
appealing user interfaces. Yet no matter how lovely a client application looks,
some organizations might resist using it because of deployment issues. If
rolling out a new version of the client requires physically touching every
desktop machine that this application is installed on, the cost of upgrades can
be significant. One common way to avoid this problem today is to create
browser-based clients rather than native Windows clients. Yet native Windows
clients can generally have better, more responsive user interfaces than
browsers. To address the challenge of deploying these clients, stand-alone WPF
applications can be put into place using ClickOnce. A technology that first
appeared in the .NET Framework 2.0, ClickOnce lets Internet Explorer users
select an application over the Web, then have it automatically installed on
their local machine. Once installed, the application can also be automatically
updated when a new version is made available. The goal is to combine the simplicity
and inexpensive deployment of a Web client with the power and functionality of
a stand-alone WPF application.

Especially when they're deployed using
ClickOnce, stand-alone WPF applications are a good client choice in many
situations. Yet there are cases where this kind of application isn't
appropriate, even when its users could benefit from the kind of interface that
WPF allows. Think about the remote insurance agents in the scenario described
earlier, for instance, or an Internet merchant that wishes to provide 3D
graphics, video, and the other modern features that WPF supports. It often
won't be reasonable to expect this application's users to install a native WPF
application to access the site. A better solution would be to give users a
WPF-style interface inside their Web browser.

XAML browser
applications—XBAPs—are designed to do this. Rather than deploying a
stand-alone WPF application, an Internet Explorer user can download an XBAP
directly into the browser. Running inside Internet Explorer, this application
can then present the user with a WPF-based user interface. Yet downloading and
running code from Internet Web sites can be dangerous. To protect the user from
malicious developers, all XBAPs downloaded from the Internet run in a partially
trusted sandbox. Based on the code access security provided by the .NET
Framework, this sandbox limits what XBAPs can do. For instance, an XBAP
downloaded from the Internet can't create stand-alone windows or launch new
windows, display a Save dialog launched by the XBAP itself, or access the file
system except in an isolated storage area. Yet despite the restrictions imposed
by the sandbox, an XBAP can still use a large fraction of WPF functionality,
including 2D and 3D graphics, animations, on-screen documents, images, video,
and more.

As described earlier, WPF lets
applications display adaptive documents using XAML's FlowDocument
element. Documents whose appearance changes based on how they're displayed
aren't always the best solution, though. Fixed-format documents, which always
look the same on a screen and a printer, are sometimes a better choice. WPF's
XPS documents address this problem. Defined using a subset of XAML, XPS
documents can be read on any system that provides an XPS reader. They also provide
a new print format for Windows, allowing complex graphics to be printed with
more fidelity. And to make working with different kinds of documents more
consistent, both XPS documents and Office 2007 documents use Microsoft's Open
Packaging Conventions, which define common ways to store document content,
digitally sign documents, and more.

Tools for Windows Presentation
Foundation

It's possible to create any WPF user
interface directly in code and/or XAML using a basic text editor. Most people
would prefer to work with better tools, however, and so Microsoft provides
extensions to Visual Studio 2005 that let developers create WPF applications.
The next release of Visual Studio, code-named "Orcas," will provide
still more capability with the Visual Designer for Windows Presentation
Foundation. Using this tool, developers will be able to graphically create the
user interface they wish to see, then let the tool generate the code for this
interface.

Yet developers often aren't the best
people to define user interfaces. Designers are usually much better at this
kind of work, since they specialize in communicating with people. Most
designers don't write code, though, and so the Visual Designer for Windows
Presentation Foundation, hosted inside Visual Studio, isn't an effective tool
for this group. To let designers work effectively in the WPF world, Microsoft
has created Expression Interactive Designer. A designer can use this tool to
define the look and feel of an interface, specify animations, and more, then
let the tool generate an XAML version of what is created. A developer can
import this XAML into Visual Studio and add code for things such as handling
events. Because both Visual Studio and Expression Interactive Designer use the
same build system, it's possible for developers and designers to work on a
project iteratively, each using the tool they're comfortable with. The goal is
to help people from the divergent disciplines of design and software
engineering work together effectively.

Windows Presentation Foundation and
Other Microsoft Technologies

Like other .NET Framework 3.0
components, WPF has an impact on existing Microsoft technologies. The most
important of these are the following:

Windows
Forms: The .NET Framework's original
approach for creating application GUIs, Windows Forms is used in many
applications today. Recognizing this, WPF allows Windows Forms controls to
be hosted in WPF applications and WPF controls to be hosted in Windows
Forms applications. For example, a Windows Forms application might host a
WPF control that provides three-dimensional data visualization. While
there are some limitations, creating applications that use both
technologies is certainly possible. Note too that existing Windows Forms
applications will continue to work unchanged in a .NET Framework 3.0
world.

Win32
and Microsoft Foundation Classes (MFC): As with
Windows Forms, it's possible to host WPF controls in existing applications
built using these existing technologies, and vice versa. Interoperability
is somewhat more complex than with Windows Forms, however, because unlike
Windows Forms, Win32-based and MFC-based applications aren't build on the
CLR. Accordingly, interoperability with WPF also requires mapping between
CLR-based code and native Win32 code.

Direct3D:
Part of the DirectX family of APIs, Direct3D lets applications create and
display 3D graphics. With the advent of the .NET Framework 3.0, mainstream
Windows applications can use the 3D capabilities in WPF rather than the
more specialized approach that Direct3D provides. Still, some applications
that need higher performance, such as 3D games, will continue to use
Direct3D. In fact, under the covers, WPF relies on Direct3D for all
rendering.

Windows
Communication Foundation: As was shown in
the scenario earlier, WPF applications can use WCF. XBAPs typically cannot
use WCF, however, because WCF requires full trust. Every XBAP downloaded
from the Internet runs in a partial trust sandbox, which prohibits it from
accessing WCF. XBAPs can use ASP.NET Web Services, however, allowing them
to make SOAP calls that interoperate with WCF and other Web services
implementations.

"WPF/E":
One more aspect of WPF is also worth mentioning here, even though it's not
part of the .NET Framework 3.0. Code-named "WPF/E," its goal is
to support WPF-style interfaces on systems that don't support WPF itself.
As the "E" in its name suggests, this technology is meant to be
available everywhere, including Macintoshes, small devices, and other
systems. Scheduled to ship sometime after WPF itself, WPF/E will provide a
subset of full WPF functionality, including 2D graphics, animation, and
video.

Getting
the .NET Framework 3.0: Distribution Options

For an application to use the .NET
Framework 3.0, this version of the Framework must be installed on the machines
this application runs on. For Windows Vista, this is straightforward: The .NET
Framework 3.0 is installed by default. This means that new machines with
Windows Vista installed or existing machines upgraded to Vista
will automatically be able to run .NET Framework 3.0 applications.

2
BRIEF HISTORY

The .NET
Framework is a powerful system in which to develop software applications, but
it can feel huge and confusing especially to those who don't understand the
context in which it was created. Take a short trip down computer memory lane to
discover why .NET was necessary in this sample chapter from Start-to-Finish
Visual Basic 2005: Learn Visual Basic 2005 as You Design and Develop a Complete
Application. Also investigate the .NET Object, crucial for understanding
software development in .NET, the parts of the .NET Framework (the Common
Language Runtime, the Common Language Specification, the Common Type System,
.NET Class Libraries, Assemblies and Manifests, Metadata and Attributes, and
Versioning). Then, study the Visual Basic development process step by step and
look at an overview of current Visual Studio features and enhancements.
Finally, load a sample program into Visual Studio, run it, and examine the code
that was written to develop a multifaceted application.

.NET Framework version
history

Microsoft started development on the .NET
Framework in the late 1990s originally under the name of Next
Generation Windows Services (NGWS). By late 2000 the first beta versions of
.NET 1.0 were released.[1]

Version 3.0 of the .NET Framework is included with Windows Server 2008 and Windows Vista.
Version 3.5 is included with Windows 7, and can also be installed on Windows XP
and the Windows Server 2003 family of operating
systems.[2]
On April 12, 2010, .NET Framework 4 was released alongside Visual Studio 2010.

The .NET Framework family also includes two versions for mobile
or embedded device use. A reduced version of the
framework, the .NET Compact Framework, is available on Windows CE platforms, including Windows
Mobile devices such as smartphones.
Additionally, the .NET Micro Framework is targeted at
severely resource-constrained devices.

Version

Version
Number

Release
Date

Visual
Studio

Default
in Windows

1.0

1.0.3705.0

2002-02-13

Visual
Studio .NET

1.1

1.1.4322.573

2003-04-24

Visual
Studio .NET 2003

Windows
Server 2003

2.0

2.0.50727.42

2005-11-07

Visual
Studio 2005

Windows
Server 2003 R2

3.0

3.0.4506.30

2006-11-06

Windows
Vista, Windows Server 2008

3.5

3.5.21022.8

2007-11-19

Visual
Studio 2008

Windows
7, Windows Server 2008 R2

4.0

4.0.30319.1

2010-04-12

Visual
Studio 2010

A more complete listing of the releases of the .NET Framework
may be found on the List of .NET Framework versions

NET
Framework 1.0

This is the
first release of the .NET Framework, released on 13 February 2002 and available
for Windows 98, Me, NT 4.0, 2000, and XP. Mainstream support by Microsoft
for this version ended 10 July 2007, and extended support ended 14 July 2009.

.NET Framework
1.1

This is the
first major .NET Framework upgrade. It is available on its own as a redistributable package or
in a software development kit, and was published on 3 April 2003. It is also
part of the second release of Microsoft Visual Studio .NET (released as Visual Studio
.NET 2003). This is the first version of the .NET Framework to be included as
part of the Windows operating system, shipping with Windows Server 2003. Mainstream support for
.NET Framework 1.1 ended on 14 October 2008, and extended support ends on 8
October 2013. Since .NET 1.1 is a component of Windows Server 2003, extended
support for .NET 1.1 on Server 2003 will run out with that of the OS –
currently 14 July 2015. .NET 1.1 is the last available version for Windows NT
4.0.

If .NET
Framework 1.0 is removed, installing only .NET Framework 1.1 also provides the
system support for version 1.0, except in rare instances where an application
will not run because it checks the version number of a library.

Changes in
1.1 in comparison with 1.0

Built-in support for mobile ASP.NET
controls. Previously available as an add-on for .NET Framework, now part
of the framework.

Security changes – enable Windows Forms
assemblies to execute in a semi-trusted manner from the Internet, and
enable Code Access Security in ASP.NET
applications.

Built-in support for ODBC and Oracle databases.
Previously available as an add-on for .NET Framework 1.0, now part of the
framework.

.NET Compact Framework – a
version of the .NET Framework for small devices.

Internet Protocol version 6 (IPv6)
support.

Numerous API changes.

.NET
Framework 2.0

Released
with Visual Studio 2005, Microsoft SQL Server 2005, and BizTalk
2006.

The 2.0 Redistributable Package can be downloaded
for free from Microsoft,
and was published on 22 January 2006.

The 2.0 Software Development Kit (SDK) can be
downloaded for free from Microsoft.

It is included as part of Visual Studio 2005 and Microsoft SQL Server 2005.

Version 2.0 without any Service Pack is the last
version with support for Windows 98 and Windows
Me. Version 2.0 with Service Pack 2 is the last version with
official support for Windows 2000 although there have been some
unofficial workarounds published online to use a subset of the
functionality from Version 3.5 in Windows 2000.[5]
Version 2.0 with Service Pack 2 requires Windows
2000 with SP4 plus KB835732 or KB891861 update, Windows
XP with SP2 or later and Windows Installer 3.1 (KB893803-v2)

It shipped with Windows Server 2003 R2 (not installed
by default).

Changes in
2.0 in comparison with 1.1

Generics

Language support for generics built directly into the .NET
CLR.

Full 64-bit support for both the x64 and the IA-64
hardware platforms.

Numerous API changes.

SQL Server integration – .NET
2.0, VS 2005, and SQL Server 2005 are all tied together. This means that
instead of using T-SQL, one can build stored procedures and triggers in any
of the .NET-compatible languages.

A new hosting API for native applications wishing to
host an instance of the .NET runtime. The new API gives a fine grain
control on the behavior of the runtime with regards to multithreading,
memory allocation, assembly loading and more (detailed
reference). It was initially developed to efficiently host the
runtime in Microsoft SQL Server, which
implements its own scheduler and memory manager.

Many additional and improved ASP.NET web controls.

New data controls with declarative data binding.

New personalization features for ASP.NET, such as
support for themes, skins, master pages and webparts.

.NET Micro Framework – a version
of the .NET Framework related to the Smart Personal Objects
Technology initiative.

Membership provider

Partial classes

Nullable types

Anonymous methods

Iterators

Data tables

.NET
Framework 3.0

.NET
Framework 3.0, formerly called WinFX,[6]
was released on 21 November 2006. It includes a new set of managed code
APIs that are an integral part of Windows Vista
and Windows Server 2008 operating systems. It is
also available for Windows XP SP2 and Windows Server 2003 as a download. There are no
major architectural changes included with this release; .NET Framework 3.0 uses
the Common Language Runtime of .NET Framework
2.0.[7]
Unlike the previous major .NET releases there was no .NET Compact Framework
release made as a counterpart of this version. Version 3.0 of the .NET
Framework shipped with Windows Vista. It also shipped with Windows Server 2008
as an optional component (disabled by default).

.NET
Framework 3.0 consists of four major new components:

Windows Presentation Foundation
(WPF), formerly code-named Avalon; a new user
interface subsystem and API based on XML and vector
graphics, which uses 3D computer graphics hardware and Direct3D
technologies. See WPF SDK
for developer articles and documentation on WPF.

Windows Communication Foundation
(WCF), formerly code-named Indigo; a service-oriented messaging system
which allows programs to interoperate locally or remotely similar to web
services.

Windows Workflow Foundation
(WF) allows for building of task automation and integrated transactions
using workflows.

Windows CardSpace, formerly
code-named InfoCard; a software component which securely stores a person's
digital identities and provides a unified interface for choosing the
identity for a particular transaction, such as logging in to a website.

.NET
Framework 3.5

Version 3.5
of the .NET Framework was released on 19 November 2007, but it is not included
with Windows Server 2008. As with .NET Framework
3.0, version 3.5 uses the CLR of version 2.0. In addition, it installs .NET
Framework 2.0 SP1, (installs .NET Framework 2.0 SP2 with 3.5 SP1) and .NET
Framework 3.0 SP1 (installs .NET Framework 3.0 SP2 with 3.5 SP1), which adds
some methods and properties to the BCL classes in version 2.0 which are
required for version 3.5 features such as Language Integrated Query (LINQ). These
changes do not affect applications written for version 2.0, however.[8]

As with
previous versions, a new .NET Compact Framework 3.5 was released in tandem with
this update in order to provide support for additional features on Windows
Mobile and Windows Embedded CE devices.

The source
code of the Base Class Library in this version has been partially
released (for debugging reference only) under the Microsoft Reference Source License.

Changes
since version 3.0

New language features in C# 3.0 and VB.NET 9.0 compiler

Adds support for expression trees and lambda
methods

Extension methods

Expression
trees to represent high-level source code at runtime.[10]

Anonymous types with static type inference

Language Integrated Query (LINQ)
along with its various providers

LINQ
to Objects

LINQ
to XML

LINQ
to SQL

Paging support for ADO.NET

ADO.NET synchronization API to synchronize local
caches and server side datastores

Asynchronous network I/O API.[10]

Peer-to-peer networking stack, including a managed PNRP
resolver[11]

Managed wrappers for Windows Management
Instrumentation and Active Directory APIs[12]

Enhanced WCF and WF runtimes, which
let WCF work with POX and JSON
data, and also expose WF workflows as WCF services.[13]
WCF services can be made stateful using the WF persistence model.[10]

Support for HTTP
pipelining and syndication feeds.[13]

ASP.NET AJAX is included.

Service Pack
1

The .NET
Framework 3.5 Service Pack 1 was released on 11 August 2008. This release adds
new functionality and provides performance improvements under certain
conditions,[14]
especially with WPF where 20-45% improvements are expected. Two new data
service components have been added, the ADO.NET Entity Framework and ADO.NET Data Services. Two new assemblies
for web development, System.Web.Abstraction and System.Web.Routing, have been
added; these are used in the ASP.NET MVC Framework and, reportedly,
will be utilized in the future release of ASP.NET Forms applications. Service
Pack 1 is included with SQL Server 2008 and Visual Studio 2008 Service Pack 1. It also
featured a new set of controls called "Visual Basic Power Packs"
which brought back Visual Basic controls such as "Line" and
"Shape". Version 3.5 SP1 of the .NET Framework shipped with Windows
7. It also shipped with Windows Server 2008 R2 as an optional component
(disabled by default).

.NET
Framework 3.5 SP1 Client Profile

For the .NET
Framework 3.5 SP1 there is also a new variant of the .NET Framework, called the
".NET Framework Client Profile", which at 28 MB is significantly
smaller than the full framework and only installs components that are the most
relevant to desktop applications.[15]
However, the Client Profile amounts to this size only if using the online
installer on Windows XP SP2 when no other .NET Frameworks are installed. When
using the off-line installer or any other OS, the download size is still
250 MB.

.NET
Framework 4

Key focuses
for this release are:

Parallel Extensions to improve
support for parallel computing, which target multi-core
or distributed systems.[17]
To this end, technologies like PLINQ (Parallel LINQ),[18]
a parallel implementation of the LINQ engine, and Task Parallel Library, which exposes
parallel constructs via method calls. are included.

New Visual Basic .NET and C# language features,
such as statement lambdas, implicit line continuations,
dynamic dispatch, named
parameters, and optional parameters.

Support for Code
Contracts.

Inclusion of new types to work with arbitrary-precision arithmetic
(System.Numerics.BigInteger)
and complex numbers (System.Numerics.Complex).

History

Microsoft
announced the intention to ship .NET Framework 4 on 29 September 2008. The Public Beta
was released on 20 May 2009.

On 28 July
2009, a second release
of the .NET Framework 4 beta was made available with experimental software transactional memory support.[21]
This functionality is not available in the final version of the framework.

On 19
October 2009, Microsoft released Beta 2 of the .NET Framework 4. At the same
time, Microsoft announced the expected launch date for .NET Framework 4 as the
22 March 2010.[22]
This launch date was subsequently delayed to 12 April 2010.

On 10
February 2010, a release candidate was published: Version:RC.

On 12 April
2010, the final version
of .NET Framework 4.0 was launched alongside the final release of Visual Studio
2010.

Windows Server AppFabric

After the
release of the .NET Framework 4, Microsoft released a set of enhancements,
named Windows
Server AppFabric, for application server capabilities in the form of
AppFabric Hosting and in-memory distributed caching support.

Future
versions

Microsoft
has revealed some details about what will come in the next version of the .NET
Framework. A central theme is the introduction of a compiler as a service that
enables programmers to embed compilers in their applications. One purpose of
this would be to provide scripting engines for applications.

Anders
Hejlsberg, main architect of the C# programming language, has shown
a REPL
(read-eval-print loop) built on an early internal version of the API.

3
BUILDING BLOCKS OF .NET PLATFORM

Overview

A
.NET Building Block is a .zip or .war file
that has a certain structure defined by Blackboard. This structure primarily
consists of a file-directory hierarchy containing ASP.NET code tied together by
a Blackboard Learning System manifest. There are many different types of
Building Blocks that can be built, including new content types, collaboration
tools and portal modules. This section discusses the definition of a .NET Building
Block in depth and offers a number of examples.

There are three
building blocks of .NET Framework, which are as follows:

Common Language Runtime
(CLR): It is used to execute the managed code. It was designed to support
multiple languages.

Common Type System (CTS):
It provides every language running on the .NET platform with a base set of
data types.

Common Language
Specification (CLS): It describes a common level of language
functionality. It is a set of rules that a language compiler must have in order
to create .NET applications that run in the CLR.

Building Blocks of .Net Platforms (CLR, CTS, CLS)

CLR (Common Language Runtime):
Programmatically speaking, the term runtime can be understood as a collection
of external services that are required to execute a given compiled unit of
code. The CLR is the layer of the .NET Framework that makes the source code
into an intermediate language which is language independent. This language is
called the Microsoft Intermediate Language.

The key difference between the .NET runtime and the
various other runtimes I just mentioned is the fact that the .NET runtime
provides a single well-defined runtime layer that is shared by all languages
and platforms that are .NET-know.

The primary role of the CLR is to locate, load, and
manage .NET types on your behalf. The CLR also takes care of a number of
low-level details such as memory management and performing security
checks.

CTS (Common Type System): In the world
of .NET, “type” is simply a generic term used to refer to a
member from the set {class, structure, interface, enumeration, delegate}. When
you build solutions using a .NET-aware language, you will most likely interact
with each of these types. The Common Type System (CTS) is a formal
specification that documents how types must be defined in order to be hosted by
the CLR.

Every language running on the .NET platform has a base
set of data types provided by CTS.  CTS is responsible for defining type
of .NET languages. Most of the languages running on .NET platform use aliases
for using those CTS types. For example, a four-byte integer value is
represented by the CTS type System.Int32. C# defines an alias for this called
type called int and in VB.NET called Integer.

CLS (Common Language System): The Common
Language Specification (CLS), which is a set of basic language features needed
by many .Net applications to fully interact with other objects regardless of
the language in which they were implemented. The CLS represents the guidelines
defined by for the .NET Framework. These specifications are normally used by
the compiler developers and are available for all languages, which target the
.NET Framework.

Building Blocks APIs and Runtime

The Blackboard Learning System exposes several .NET APIs to access
run-time information. This provides useful functionality in the Building Block.
These Building Block APIs are broadly categorized into several distinct
sub-sets: Data Objects and Persistence, Session, Gradebook, and Authorization.

Assemblies—The
building blocks of Microsoft .NET framework

We have had a look at the concepts of Assemblies, Metadata, Manifests, Global
Assembly Cache, etc, in the first part of this series of articles two part
articles on Microsoft .NET Assemblies. This concluding part of this series
would discuss the related tools and utilities that are used for various
purposes. Let us first delve into the assembly tools available with the
Microsoft .NET framework.

The Assembly tools

The assembly tools that are available as executable files along with the Microsoft
.NET framework are ilasm, ildasm, sn, al and gacutil. The ilasm tool is the
assembler that converts the source to a .NET assembly file. The ildasm.exe is
the disassembler and is used to inspect the internals of an assembly. The sn
tool is used to create an unique strong name for an assembly. The strong name
is stored in a file that consists of the unique strong name and the public o
private keys associated. Note that the private assemblies do not require any
strong name as they reside in the same application folder. Strong name is
required for unique identification of the shared assemblies only. To create a
strong name, follow the command given below that creates a strong name and
stores the same in a file. The al.exe is the assembly linker that installs the
assembly in the global assembly cache. Refer to the following command that
shows how we can use the al utility to store the assembly in the global
assembly cache such that it can be shared by applications:

al /install:hello.dll

The
Global Assembly Cache is the store where the assemblies are stored globally for
them to be shared across multiple applications. Refer to the command below that
illustrates how we can make an assembly called hello.dll globally accessible
such that the same can be assessed by multiple applications.

gacutil /i hello.dll

Note that an assembly having a strong name associated can also be stored
elsewhere other than the GAC, like the application’s directory and still
made globally accessible. However, in such a case, the assembly has to be
deployed using the XCOPY command.

Deploying an Assembly in the Global Assembly Cache

This following section discusses how we can install an assembly in the
Global Assembly Cache to make it globally assessable. Please follow the same
sequence of events as is illustrated below for installing the assembly in the
GAC.

a.) First, create a key pair using the sn utility that creates a strong name
and stores the same in a physical file. At the command prompt, type the
following:

sn -k hello.snk

This would create a file called hello.snk containing the key pair.

b.) Now, compile the application to create a dynamic linked library (dll) file.

c.) Now invoke the gacutil utility on the dll file created above to install the
assembly in the GAC as shown below.

gacutil /i hello.dll

d.) Lastly, ensure that you sign the assembly by using the following command.

We can also view the contents of the global assembly
cache, using the following command at the command prompt.

gacutil /l

In order to remove an assembly from the GAC, use the following command at the
command prompt.

gacutil /u hello.dll

The above command would remove the assembly hello.dll from the global assembly
cache.

4
ROLE OF .NET CLASS LIBRARIES

Introduction to
the .NET Framework Class Library

The .NET Framework includes classes,
interfaces, and value types that expedite and optimize the development process
and provide access to system functionality. To facilitate interoperability
between languages, the .NET Framework types are CLS-compliant and can therefore
be used from any programming language whose compiler conforms to the common
language specification (CLS).

The .NET Framework types are the
foundation on which .NET applications, components, and controls are built. The
.NET Framework includes types that perform the following functions:

Represent
base data types and exceptions.

Encapsulate
data structures.

Perform
I/O.

Access
information about loaded types.

Invoke
.NET Framework security checks.

Provide
data access, rich client-side GUI, and server-controlled, client-side GUI.

The .NET Framework provides a rich set
of interfaces, as well as abstract and concrete (non-abstract) classes. You can
use the concrete classes as is or, in many cases, derive your own classes from
them. To use the functionality of an interface, you can either create a class
that implements the interface or derive a class from one of the .NET Framework
classes that implements the interface.

Naming Conventions

.NET Framework types use a dot syntax
naming scheme that connotes a hierarchy. This technique groups related types
into namespaces so they can be searched and referenced more easily. The first
part of the full name — up to the rightmost dot — is the namespace
name. The last part of the name is the type name. For example, System.Collections.ArrayList
represents the ArrayList type, which belongs to the System.Collections
namespace. The types in System.Collections can be used to manipulate
collections of objects.

This naming scheme makes it easy for
library developers extending the .NET Framework to create hierarchical groups
of types and name them in a consistent, informative manner. It is expected that
library developers will use the following guideline when creating names for
their namespaces:

CompanyName.TechnologyName

For example, the namespace
Microsoft.Word conforms to this guideline.

The use of naming patterns to group
related types into namespaces is a very useful way to build and document class
libraries. However, this naming scheme has no effect on visibility, member
access, inheritance, security, or binding. A namespace can be partitioned
across multiple assemblies and a single assembly can contain types from
multiple namespaces. The assembly provides the formal structure for versioning,
deployment, security, loading, and visibility in the common language runtime.

For more information on namespaces and
type names, see Common Type
System.

System Namespace

The System
namespace is the root namespace for fundamental types in the .NET Framework.
This namespace includes classes that represent the base data types used by all
applications: Object (the root of the inheritance hierarchy), Byte,
Char, Array, Int32, String, and so on. Many
of these types correspond to the primitive data types that your programming
language uses. When you write code using .NET Framework types, you can use your
language's corresponding keyword when a .NET Framework base data type is
expected.

The following table lists some of the
value types the .NET Framework supplies, briefly describes each type, and
indicates the corresponding type in Visual Basic, C#, and the Managed
Extensions for C++. The table also includes entries for the Object and String
classes, for which many languages have corresponding keywords.

Category

Class name

Description

Visual Basic data type

C# data type

Managed Extensions for C++ data type

JScript data type

Integer

Byte

An 8-bit unsigned integer.

Byte

byte

char

Byte

SByte

An 8-bit signed integer.

Not
CLS-compliant.

SByte

No
built-in type.

sbyte

signed char

SByte

Int16

A 16-bit signed integer.

Short

short

short

short

Int32

A 32-bit signed integer.

Integer

int

int

-or-

long

int

Int64

A 64-bit signed integer.

Long

long

__int64

long

UInt16

A 16-bit unsigned integer.

Not
CLS-compliant.

UInt16

No
built-in type.

ushort

unsigned short

UInt16

UInt32

A 32-bit unsigned integer.

Not
CLS-compliant.

UInt32

No
built-in type.

uint

unsigned int

-or-

unsigned long

UInt32

UInt64

A 64-bit unsigned integer.

Not
CLS-compliant.

UInt64

No
built-in type.

ulong

unsigned __int64

UInt64

Floating point

Single

A single-precision (32-bit) floating-point
number.

Single

float

float

float

Double

A double-precision (64-bit) floating-point
number.

Double

double

double

double

Logical

Boolean

A Boolean value (true or false).

Boolean

bool

bool

bool

Other

Char

A Unicode (16-bit) character.

Char

char

wchar_t

char

Decimal

A 96-bit decimal value.

Decimal

decimal

Decimal

Decimal

IntPtr

A signed integer whose size depends on the
underlying platform (a 32-bit value on a 32-bit platform and a 64-bit value
on a 64-bit platform).

IntPtr

No
built-in type.

IntPtr

No
built-in type.

IntPtr

No
built-in type.

IntPtr

UIntPtr

An unsigned integer whose size depends on the
underlying platform (a 32- bit value on a 32-bit platform and a 64-bit value
on a 64-bit platform).

Not
CLS-compliant.

UIntPtr

No
built-in type.

UIntPtr

No
built-in type.

UIntPtr

No
built-in type.

UIntPtr

Class objects

Object

The root of the object hierarchy.

Object

object

Object*

Object

String

An immutable, fixed-length string of Unicode
characters.

String

string

String*

String

The
.NET Framework Class Libraries

The
.NET Framework class libraries are monumentally important to providing language
interoperability because they allow developers to use a single programming
interface to all the functionality exposed by the CLR. If you've ever used more
than one dissimilar language in development for Windows, you'll love this
feature. In fact, the .NET Framework class libraries are forging a
revolutionary trend in compiler development. Before .NET, most compiler writers
developed a language with the ability to do most of its own work. Even a
language such as C++, which was designed as a scaled-down grouping of
functionality to be used in conjunction with a class library, has at least some
functionality on its own. However, in the world of .NET, languages are becoming
little more than syntactical interfaces to the .NET Framework class libraries.

As
an example, let's first take a look at the standard "Hello, World"
application in C++ and then compare it to an application that does the same
thing in C#: -

#include
<iostream.h>

int
main(int argc, char* argv[])

{

cout << "Hello,
World!" << endl;

return 0;

}

Notice
that the application first includes a header file with the declaration of the cout
function. The application's main function-every C/C++ application's
entry point-uses the cout function to write the string "Hello,
World" to the standard output device. However, what's important to note
here is that you can't write this application in any .NET language without the
.NET Framework class libraries. That's right: .NET languages don't even have
the most basic compiler features, such as the ability to output a string to the
console. Now I know that technically the cout function is implemented in
the C/C++ runtime, which is itself a library. However, basic C++ tasks such as
string formatting, file I/O, and screen I/O are at least logically considered
part of the base language. With C#-or any .NET language for that matter-the
language itself has almost no ability to do even the most menial task without
the .NET Framework class library.

Let's
look at the "Hello, World" example in C# to see what I mean: -

using
System;

class
Hello

{

public static void Main()

{

Console.WriteLine("Hello, World");

}

}

So,
what does this common set of class libraries mean to you, and is it a good
thing? Well, it depends on your vantage point. A common set of class libraries
means that all languages, theoretically, have the same capabilities because
they all have to use these class libraries to accomplish anything except
declaring variables.

One
gripe I've seen on discussion boards is, "Why have multiple languages if
they all have the same capabilities?" For the life of me, I don't
understand this complaint. As someone that has worked in many multilanguage
environments, I can attest that there's a great benefit to not having to
remember what language can do what with the system and how it does it. After
all, our job as developers is to produce code, not to worry about whether a
favorite language has this advantage or that advantage.

Another
question I've seen frequently is, "If all these .NET languages can do the
same thing, why do we need more than one?" The answer relates to the fact
that programmers are creatures of habit. Microsoft certainly didn't want to
pick one language out of the many available and force millions of programmers
to toss out their years of experience in other languages. Not only might a
programmer have to become familiar with a new API, he or she might have to
master a completely different syntax. Instead, a developer can continue using
the language that's best suited for the job. After all, the name of the game is
productivity. Changing what doesn't need to be changed is not part of that
equation.

NOTE

While
in theory the .NET Framework class libraries enable compilers to make all the
CLR's functionality available to a language's users, this is not always the
case. One point of contention at Microsoft between the .NET Framework class
libraries team and the different compiler teams is that although the .NET
Framework class libraries team has attempted to expose all its functionality to
the different languages, there's nothing-besides meeting minimal CLS
standards-that requires the different compiler teams to implement every single
feature. When I asked several Microsoft developers about this discrepancy, I
was told that instead of each language having access to every exposed bit of
.NET Framework functionality, each compiler team has decided to implement only
the features that they feel are most applicable to their users. Luckily for us,
however, C# happens to be the language that seems to have provided an interface
to almost all of the .NET Framework functionality.

5 UNDERSTANDING CTS, CLR, CLS

CLR
- CTS - CLS

The
.NET Framework provides a runtime environment called the Common Language
Runtime or CLR (similar to the Java Virtual Machine or JVM in Java), which
handles the execution of code and provides useful services for the
implementation of the program.

The
Common Language Runtime is the underpinning of the .NET Framework. CLR
takes care of code management at program execution and provides various
beneficial services such as memory management, thread management, security
management, code verification, compilation, and other system services. The
managed code that targets CLR benefits from useful features such as
cross-language integration, cross-language exception handling, versioning,
enhanced security, deployment support, and debugging.

Common
Type System
(CTS) describes how types are declared, used and managed in the runtime and
facilitates cross-language integration, type safety, and high performance code
execution.

The
Common Language Specification (CLS) is an agreement among language
designers and class library designers to use a common subset of basic language
features that all languages have to follow.

CLR Execution Model:

6
DEPLOYING .NET

HOW
TO: Deploy Applications That Are Built on the .NET Framework

This
step-by-step article describes important considerations for deploying
applications that are built on the .NET Framework. This is one of a series of
articles that provide detailed information for applications that are built on
the .NET Framework.

The
articles in this series include the following:

818016
(http://support.microsoft.com/kb/818016/EN-US/ ) HOW TO: Deploy
Applications That Are Built on the .NET Framework

818013
(http://support.microsoft.com/kb/818013/EN-US/ ) HOW TO: Support
Applications That Are Built on the .NET Framework

818015
(http://support.microsoft.com/kb/818015/EN-US/ ) HOW TO: Tune and Scale
Performance of Applications That Are Built on the .NET Framework

818014
(http://support.microsoft.com/kb/818014/EN-US/ ) HOW TO: Secure
Applications That Are Built on the .NET Framework

Create the Web.Config File for an
ASP.NET Application

The
Web.config file is an XML file that contains application-specific settings that
override system defaults. While most ASP applications that are built on the
.NET Framework are deployed with a Web.config file, the Web.config file is
optional. You may have to create a Web.config file to override default settings
on an application-by-application basis.

For
additional information about how to create a Web.config file for an application
that does not already have one, click the following article number to view the
article in the Microsoft Knowledge Base:

815178
(http://support.microsoft.com/kb/815178/EN-US/ ) HOW TO: Create the
Web.Config File for an ASP.NET Application

Edit the Configuration of an ASP.NET
Application

All
systems where the .NET Framework has been deployed have system-wide ASP.NET
configuration settings that are defined in the <system.web> element of
the Machine.config file. You can modify these settings (frequently, you must
modify these settings) on an application-by-application basis.

For
additional information about how to override .NET framework default
configuration settings for a specific application, click the following article
numbers to view the articles in the Microsoft Knowledge Base:

307626
(http://support.microsoft.com/kb/307626/EN-US/ ) INFO: ASP.NET
Configuration Overview

815178
(http://support.microsoft.com/kb/815178/EN-US/ ) HOW TO: Edit the
Configuration of an ASP.NET Application

Determine
if a Client System Meets the Minimum Requirements for Installing the .NET
Framework

Before
you can deploy applications that are built on the .NET Framework to a client
system, that system must have specific software components and patches
installed. Most client systems meet the requirements. However, you may have to
manually verify that a specific system is ready to receive the .NET Framework
redistributables.

For
additional information about how to deploy the .NET framework to client
systems, click the following article number to view the article in the
Microsoft Knowledge Base:

815177
(http://support.microsoft.com/kb/815177/EN-US/ ) HOW TO: Determine
Whether a Client Meets the Minimum
Requirements for Installing the .NET Framework

Determine
if a Server System Meets the Minimum Requirements for Installing the .Net
Framework

Before
you can deploy applications that are built on the .NET Framework to a server,
the server must have specific software components and patches installed. Most
server systems meet the requirements. However, you may have to manually verify
that a specific system is ready to receive the .NET Framework redistributables.

For
additional information about how to deploy the .NET framework to server
systems, click the following article number to view the article in the
Microsoft Knowledge Base:

815176
(http://support.microsoft.com/kb/815176/EN-US/ ) HOW TO: Determine
Whether a Server Meets the Minimum Requirements for Installing the .NET
Framework

Selectively Enable and Disable
ASP.NET Functionality in IIS

When
the .NET Framework is installed on a server computer running Internet
Information Services (IIS), ASP.NET is automatically enabled for virtual
servers. However, you might not want this configuration. As new ASP Web
applications that are built on the .NET Framework are deployed to a server
computer running IIS 5.0, you can control which virtual servers and directories
support ASP.NET and which virtual servers do not.

For
additional information about how to enable and disable ASP.NET functionality
for virtual servers and directories in IIS 5.0, click the following article
number to view the article in the Microsoft Knowledge Base:

815175
(http://support.microsoft.com/kb/815175/EN-US/ ) HOW TO: Selectively
Enable or Disable ASP.NET Functionality in IIS

Configure Custom Error Messages for
an ASP.NET Application

Many
sites change IIS default error message to display a user-friendly page or to
notify an administrator. When a server computer running IIS 5.0 has custom
error messages, and an ASP Web application that is built on the .NET Framework
is deployed to that server computer, errors in the ASP.NET application do not
use IIS 5.0 custom error messages unless the application is specifically
configured to do so.

For
additional information about how to configure custom error messages for ASP
applications built on the .NET Framework, click the following article numbers
to view the articles in the Microsoft Knowledge Base:

306355
(http://support.microsoft.com/kb/306355/EN-US/ ) HOW TO: Create Custom
Error Reporting Pages in ASP.NET by Using Visual C# .NET

308132
(http://support.microsoft.com/kb/308132/EN-US/ ) HOW TO: Create Custom
Error Reporting Pages in ASP.NET Using Visual Basic .NET

Make
Application-Specific and Directory-Specific Configuration Settings in an
ASP.NET Application

The
most common way to override system defaults for a whole ASP.NET application is
to create or edit a Web.config file for that application. However,
configuration changes frequently must apply only to specific files or folders
in an application. There are two ways to limit the scope of configuration
changes:

Add
the <location> configuration element to the Machine.config file to the
Web.config file.

-or-

Add additional Web.config files to
subfolders.

For
additional information about how to apply changes that affect specific
applications and directories, click the following article number to view the
article in the Microsoft Knowledge Base:

815174
(http://support.microsoft.com/kb/815174/EN-US/ ) HOW TO: Make Application
and Directory-Specific Configuration Settings in an ASP.NET Application

Configure Session State
Management for ASP.NET Applications

ASP.NET
has new features for Session State Management. Session state settings in
ASP.NET are configured through the Web.config file of an ASP.NET application.
Several Sessions State Management options are available in ASP.NET. These
options include mode (inproc, State Server, SQL Server), cookieless state
management, out-of process mode stateserver, and the port settings. For more
information about ASP.NET
Session State
Management, visit the following Microsoft Web site:

http://msdn2.microsoft.com/en-us/library/ms972429.aspx
(http://msdn2.microsoft.com/en-us/library/ms972429.aspx)

For
additional information, click the following article number to view the article
in the Microsoft Knowledge Base:

307626
(http://support.microsoft.com/kb/307626/EN-US/ ) INFO: ASP.NET
Configuration Overview

Build and Deploy a .NET Security
Policy Deployment Package

The
.NET Framework introduces security policy. The security policy is a new way to
control the resources that an application can gain access to on a system. It
defines an application’s authorization based on the application's
location or source. As an administrator, you can control security policy on a
computer-by-computer basis. However, you can use deployment packages as a more
scaleable method for deploying and managing security policies in Active
Directory environments.

For
additional information about how to build and deploy .NET security policies by
using deployment packages, click the following article number to view the
article in the Microsoft Knowledge Base:

815173
(http://support.microsoft.com/kb/815173/EN-US/ ) HOW TO: Build and
Deploy a .NET Security Policy Deployment Package

Migrate an ASP Web Application to
ASP.NET While Retaining Existing File Names

ASP.NET
offers many benefits over the earlier ASP 3.0 scripting environment.
Specifically, ASP applications that are built on the .NET Framework offer
improved performance, scalability, and reliability. As a result, many new ASP
applications that are built on the .NET Framework are actually upgrades to
existing ASP 3.0 applications.

One
of the challenges of upgrading an application from ASP 3.0 to ASP.NET is that
the two environments use different file name extensions. By default, ASP 3.0
uses .asp file name extensions. However, ASP.NET uses .aspx file name
extensions. Although the different file name extensions permit the two
applications to be located in a single folder, they require bookmarks and
hyperlinks to be changed before the ASP 3.0 application is taken offline.

For
additional information about how to migrate from ASP 3.0 to ASP.NET while using
the same file names, click the following article number to view the article in
the Microsoft Knowledge Base:

815172
(http://support.microsoft.com/kb/815172/EN-US/ ) HOW TO: Migrate an ASP
Web Application to ASP.NET While Retaining Existing File Name Extensions

Configure
an ASP.NET Application to Use the Same Authentication and Authorization as an Existing ASP Web Application

ASP.NET
includes more flexible and sophisticated authentication and authorization
systems than ASP 3.0. By default, you can use only Windows authentication to
authenticate ASP 3.0 applications. Also, you can control authorization only by
using NTFS file permissions.

ASP.NET
supports Windows authentication, and can impersonate the end-user in much the
same way that ASP 3.0 does. However, by default, this setting is not enabled.

For
additional information about how to configure an ASP.NET application to
authenticate and authorize users in a way that is similar to the way that an
existing ASP 3.0 application does this, click the following article number to
view the article in the Microsoft Knowledge Base:

815171
(http://support.microsoft.com/kb/815171/EN-US/ ) HOW TO: Configure an
ASP.NET Application to Use the Same
Credentials as an ASP 3.0 Application

Deploy an ASP.NET Web Application by
Using XCopy Deployment

You
can deploy your ASP.NET Web application by using the MS-DOS xcopy command-line
utility. However, it is a good idea to deploy your project instead of using
xcopy. As with the Copy Project command, xcopy does not register or verify the
location of assemblies. Also, for Web projects, xcopy does not automatically
configure IIS directory settings. For additional information, click the
following article number to view the article in the Microsoft Knowledge Base:

326355
(http://support.microsoft.com/kb/326355/EN-US/ ) HOW TO: Deploy an
ASP.NET Web Application Using Xcopy Deployment

Set Up Multiple Server ASP.NET Web
Applications and Web Services

For
most uses of ASP.NET, a single server can handle all requests in a timely
manner. However, many environments must deploy multiple servers to handle consistently
high volumes of traffic, to support processor-intensive applications, to
respond to sudden bursts in traffic, or to meet redundancy requirements.

For
additional information, click the following article number to view the article
in the Microsoft Knowledge Base:

815162
(http://support.microsoft.com/kb/815162/EN-US/ ) HOW TO: Set Up
Multi-Server ASP.NET Web Applications and Web Services

7
BUILDING C# APPLICATIONS

Building C# .NET applications

DB2(R) provides a batch
file, bldapp.bat, for compiling and linking DB2 C# .NET applications, located
in the sqllib\samples\.NET\cs directory, along with sample programs that can be
built with this file. The batch file takes one parameter, %1, for the name of
the source file to be compiled (without the .cs extension).

Procedure

To build the program, DbAuth, from the source file, DbAuth.cs, enter:

bldapp DbAuth

To ensure you have the parameters you
need when you run the executable, you can specify different combinations of
parameters depending on the number entered:

No parameters.
Enter just the program name:

DbAuth

One parameter.
Enter the program name plus the database alias:

DbAuth <db_alias>

Two parameters.
Enter the program name plus user ID and password:

DbAuth <userid> <passwd>

Three parameters.
Enter the program name plus the database alias, user ID, and password:

DbAuth <db_alias> <userid> <passwd>

Four parameters.
Enter the program name plus server name, port number, user ID, and
password:

DbAuth <server> <portnum> <userid> <passwd>

Five parameters.
Enter the program name plus database alias, server name, port number, user
ID, and password:

DbAuth <db_alias> <server> <portnum> <userid> <passwd>

Building a C#
Application

Let’s start by creating a simple console application—that
is, one without any windows that just runs from the command line. Start the
Visual Studio.NET program, and select File | New Project. From the selection
box, choose C# Console application, as shown in Figure 3-1.

Figure 3-1 The New Project selection window: selecting a console application.

This will bring up a module with Main
already filled in. You can type in the rest of the code as follows.

Console.WriteLine ("Hello C# World");

You can compile this and run it by pressing F5. When you
compile and run the program by pressing F5, a DOS window will appear and print
out the message "Hello C# World" and then exit.

C# applications fall within two distinct categories:
command-line or console applications and Windows applications. By using the
AppWizards, you'll find that both are easy to create in terms of the template
code necessary to outline a project.

For our first project we build the familiar Hello World
console application. We'll name this project HelloWorld. The second
application, which appears closer to the end of this chapter, is called
CircleArea. This is a full-fledged, object-oriented Windows application.

Both
projects are intended to introduce you to the Visual Studio AppWizards and show
you how to build the basic template code that will be part of every project
developed in this book. These are good places to set bookmarks and take notes
in the margins.

Installing Visual Studio with C# Support

Access to a system running
Visual Studio with C# support is a pre-requisite for this tutorial. If you do
not have a copy of Visual Studio you have the option of either downloading and
installing the free Visual Studio Express product or a free 90-day trial of
Visual Studio Professional. During the installation process it is important to
ensure that C# support is selected.

Once Visual Studio is
installed, launch it from the Windows Start menu.

[edit] Creating a new Visual Studio C#
Project

Once Visual Studio is running
the first step is to create a new project. Do this by selecting New Project
from the File menu. This will cause the New Project window to
appear containing a range of different types of project. For the purposes of
this tutorial we will be developing a Windows Forms Application so
make sure that this option is selected. At the bottom of the window is a field
for providing a project name

. This will most likely display a default file name along
the lines of WindowsFormsApplication1. Change this to HelloCSharp
and press the OK button to initiate the creation of the new project.

Once the new project has been
created the main Visual Studio window will appear. At the center of this window
will be a new form in which we will create the user interface for our sample C#
application.

[edit] Adding Components to the Windows
Form

At this point we have a new
Visual Studio project and are ready to begin the process of adding user interface components to our
application. At the moment our Windows Form (entitled Form1) is empty. The next
step is to start dragging components from the Toolbox to the Form.

To access the Toolbox click
on the Toolbox tab located along the left hand edge of the main Visual
Studio window. This will display the Toolbox which contains a number of
different categories of components available for addition to the Form.

If the All Common
Components category is currently folded click on the small + sign to unfold
the list of components. With the components visible drag and drop two Button
components and two TextBox components onto the Form
canvas position and resize them such that the Form appears as shown in the
following figure.

ADGRPID:|SERVTYPE:

[edit] Changing Component Names

As components are added to
the Form, Visual Studio assigns default names to each one. It is via these
names that any C# code will interact with the user interface of the
application. For this reason it is important to specify meaningful names which
identify the component when referenced in the C# source code. It is
recommended, therefore, that the default names provided by Visual Studio be
replaced by more meaningful ones.

This and other properties
relating to components are specified through the Properties panel which
is located in the bottom right hand corner of the main Visual Studio window.
Begin by selecting the top TextEdit component in the Form area so that the
panel displays the properties for this component. Scroll to the top of the list
of properties until the (Name) value is visible and change this name
from textBox1 to welcomeText:

Repeat the above task by
selecting each component in the Form in turn and changing the (Name)
property. The second textBox should be named nameText, the left hand and
right hand buttons helloButton and closeButton respectively.

[edit] Changing Component Properties

In addition to changing the
names of components it is also possible to change a myriad array of different
properties via the properties panel. To demonstrate this concept we will change
the text on the two buttons such that they read "Hello" and
"Close". Select helloButton in the Form, scroll down the list
of properties to locate the Text value and change it from button1
to Hello. Repeat this for closeButton so that it displays Close.

To try out the application so
far press the F5 button on your keyboard to build and run the
application. After a few seconds the executing application will appear. Enter
some text into the TextBoxes to prove it is a live application.

[edit] Adding Behavior to a Visual
Studio C# Application

The next task in creating our
application is to add some functionality so that things happen when we press
the two buttons in our form. This behavior is controlled via events. For
example, when a button is pressed a Click event is triggered. All we
need to do, therefore, is write some code for the Click events of our
buttons. To display the code associated with the closeButton double
click on it. The display will change to show the code for the application.
Amongst the code is the closeButton_Click event method:

When the closeButton is
pressed by the user we want the application to exit. We can achieve this by
calling the Close() method in the closeButton_Click event:

private void closeButton_Click(object sender, EventArgs e)

{

Close();

}

The next task is to read the
text entered into nameText and use it to display a message in welcomeText.
This will take place when helloButton is pressed. Click on the Form1.cs
[Design] tab above the code area to return to the visual view of the Form
and double click on helloButton to access the code. This time we will be
adding code to the helloButton_Click event method to read the value from
nameText, combine it with some extra text and then display the result in
welcomeText:

private void helloButton_Click(object sender, EventArgs e)

{

welcomeText.Text = "Hello " + nameText.Text;

}

We will learn more about what
is happening in the above method in later chapters but in summary we are
setting the Text property of the welcomeText component to a
string comprised of a string containing "Hello " and the Text
property value of the nameText component.

Build and run the application
by pressing F5 and when the application runs

enter your name into the second text field and press the Hello
button. The hello message will subsequently appear in the top text field. Press
the Close button to exit the application.