Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Unit I
What is the computer network?
The computer network is the communication of data from one computer to one or
more computers by any means such as people, wires, cables, or a telecommunications
system.
A local area network (LAN) is the communication of a number of computers by
cable connecting to each one in a single location, usually a single floor of a building or all
the computers in a small company. LANs may be contrasted with wide area networks
(WANs). Stated simply, WANs are the communication between LANs by telephone lines
leased form the various telephone companies, satellite links, packet radio, or microwave
transceivers.
WANs are private and owned by the business that operates with them. The
Internet has emerged as both the largest and the least expensive WAN in the world
recently. Many companies take advantage of it now by forming private WANs, known as
VPNs, or Virtual Private Networks, through encrypted communications over the Internet.
Network Type
There are three roles for computers in a local area network.
The first role is a being clients which use but do not provide network resources.
The second one is a being peers which both use and provide network resources. The last
one is a being servers which provide network resources. The role of a computer is
determined simply by use in the network many times.
Server (domain) / Client Networks
Server-based (also called client-server) networks are defined by the presence of
servers on a network that provide security and administration of the networks. It consists
with many clients and one or more servers. Clients (often called the "front end") request
services, such as file storage and printing, and servers (often called the "back end")
deliver them.
In Windows NT or Windows 2000, server-based networks are organized into
domains. Domains are collections of networks and clients that share security trust
information. Domain security and logon permission are controlled by special servers
called domain controllers. There is one master domain controller, called the Primary
Domain Controller (PDC) and the secondary domain controllers called Backup Domain
Controller (BDC) may assist PDC during busy times or when the PDC is not available for
some reason.
The
server-based
networks
have
many
advantages,
including:
Central file storage, which allows all users to work form the same set of data and
provides easy backup of critical data and keeps data from getting lost among computers
Ability of servers to pool available hardware and software, lowering overall costs
Optimized dedicated servers, which are faster than peers at sharing network
Freeing
of
users
from
the
task
of
managing
network
Easy
manageability
of
a
large
number
of
users
Ability
to
share
expensive
equipment,
such
as
laser
printers
Less intrusive strong central security, since a single password need to access all shared
resources on the network
Server-based
networks
also
have
some
disadvantages,
including:
Expensive
dedicated
hardware
Expensive network operating system software and client licenses
A dedicated network administrator (usually required)
Peer Networks :
Every computer on peer network is equal and can communicate with any other
computer on the network to which it has been granted access rights. So basically, every
computer on peer network functions as both a server and a client. The peer network
is more common in small business.
The advantages are:
No extra investment for server software and hardware are needed
No network administrator is needed
Easy setup
Lower cost
The disadvantages are:
Additional load on computers for resource sharing
Lack of central organization, which can make data hard to find
Users must administer their own computers
Weak and intrusive security
Hybrid Networks :
Hybrid networks have all three types of computers and have active domains and
workgroups. This means that network users have access to any resources being shared by
peers in their workgroup while most shared resources are located on servers
The advantages of hybrid networks are same as the advantages of server-based and peerbased networks. Hybrid network shares the disadvantages of server-based network.
Network Topology
Network topology are the physical layout of the network that the locations of the
computers and how the cable is run between them. It is important to use the right
topology. Each topology has its own strengths and weakness.
Bus topology
A bus topology connects computers along a single or more cable to connect
linearly as figure 1. A network that uses a bus topology is referred to as a "bus network"
which was the original form of Ethernet networks. Ethernet 10Base2 (also known as
thinnet) is used for bus topology.
The TCP/IP model consists of four layers (RFC 1122).[1][2] From lowest to highest, these
are the Link Layer, the Internet Layer, the Transport Layer, and the Application Layer.
History
The Internet Protocol Suite resulted from work done by Defense Advanced Research
Projects Agency (DARPA) in the early 1970s. After building the pioneering ARPANET
in 1969, DARPA started work on a number of other data transmission technologies. In
1972, Robert E. Kahn was hired at the DARPA Information Processing Technology
Office, where he worked on both satellite packet networks and ground-based radio packet
networks, and recognized the value of being able to communicate across them. In the
spring of 1973, Vinton Cerf, the developer of the existing ARPANET Network Control
Program (NCP) protocol, joined Kahn to work on open-architecture interconnection
models with the goal of designing the next protocol generation for the ARPANET.
By the summer of 1973, Kahn and Cerf had worked out a fundamental reformulation,
where the differences between network protocols were hidden by using a common
internetwork protocol, and, instead of the network being responsible for reliability, as in
the ARPANET, the hosts became responsible.
With the role of the network reduced to the bare minimum, it became possible to join
almost any networks together, no matter what their characteristics were, thereby solving
Kahn's initial problem. One popular saying has it that TCP/IP, the eventual product of
Cerf and Kahn's work, will run over "two tin cans and a string."
A computer called a router (a name changed from gateway to avoid confusion with other
types of gateways) is provided with an interface to each network, and forwards packets
back and forth between them. The idea was worked out in more detailed form by Cerf's
networking research group at Stanford in the 197374 period, resulting in the first TCP
specification
DARPA then contracted with BBN Technologies, Stanford University, and the University
College London to develop operational versions of the protocol on different hardware
platforms. Four versions were developed: TCP v1, TCP v2, a split into TCP v3 and IP v3
in the spring of 1978, and then stability with TCP/IP v4 the standard protocol still in
use on the Internet today.
In March 1982, the US Department of Defense declared TCP/IP as the standard for all
military computer networking In 1985, the Internet Architecture Board held a three day
workshop on TCP/IP for the computer industry, attended by 250 vendor representatives,
promoting the protocol and leading to its increasing commercial use.
The functional groups of protocols and methods are the Application Layer, the Transport
Layer, the Internet Layer, and the Link Layer (RFC 1122). It should be noted that this
10
model was not intended to be a rigid reference model into which new protocols have to fit
in order to be accepted as a standard.
The following table provides some examples of the protocols grouped in their respective
layers.
DNS, TFTP, TLS/SSL, FTP, Gopher, HTTP, IMAP, IRC,
NNTP, POP3, SIP, SMTP,SMPP, SNMP, SSH, Telnet, Echo,
RTP, PNRP, rlogin, ENRP
Application
Routing protocols like BGP and RIP which run over TCP/UDP,
may also be considered part of the Internet Layer.
Transport
Link
Different authors have interpreted the RFCs differently regarding the question whether
the Link Layer (and the TCP/IP model) covers Physical Layer issues, or if a hardware
layer is assumed below the Link Layer. Some authors have tried to use other names for
the Link Layer, such as network interface layer, in view to avoid confusion with the Data
Link Layer of the seven layer OSI model. Others have attempted to map the Internet
Protocol model onto the OSI Model. The mapping often results in a model with five
layers where the Link Layer is split into a Data Link Layer on top of a Physical Layer. In
literature with a bottom-up approach to Internet communication [8][9][11], in which hardware
issues are emphasized, those are often discussed in terms of Physical Layer and Data
Link Layer.
The Internet Layer is usually directly mapped into the OSI Model's Network Layer, a
more general concept of network functionality. The Transport Layer of the TCP/IP model,
sometimes also described as the host-to-host layer, is mapped to OSI Layer 4 (Transport
Layer), sometimes also including aspects of OSI Layer 5 (Session Layer)
11
in a centralized system would spell disaster. This was during the height
of the Cold War, and the inevitable nuclear war looked very close to
happening.
Services like Email found their first usage through the ARPANET
system, and its obvious benefits were lauded by all who participated.
The popular bulletin-board system, Usenet, was developed between
the 70s and 80s. Around this stage all of the main universities in the
US were connected to the network and used it for transmitting
experimental data and educational resources. It was found to be an
excellent method of sharing information. In 1973 the first international
(and indeed intercontinental) connection was made to the University
College of London in England.
The rise of USENET
USENET contributed more than anything else to the way the Internet
began to take off. The spirit of information sharing and discussion
that is the hallmark of the net was encapsulated in this system.
The introduction of personal computers in the late 70s brought a
large new audience to the developing Internet. They used email and
participated in discussions on networks like Usenet, Bitnet. The
Internet was growing exponentially. IRC (Internet Relay Chat) became
available in 1988 and communities formed in chat rooms.
World-Wide Web unleashed
It was only in 1991 that what we now call the World-Wide Web was
introduced, developed by Mr. Tim Berners-Lee, with assistance
from Robert Caillau (while both were working at CERN. Tim's now a
member of the W3C). Tim saw the need for a standard linked
information system accessible across the range of different
computers in use. It had to be simple so that it could work on both
dumb terminals and high-end graphical X-Window platforms. He got
some pages up and was able to access them with his 'browser'.
Quickly researchers got interested and started designing web sites and
browsers. In 1993 the first proper web-browser, Mosaic, took the
Internet by storm; having been developed at the National Center for
Supercomputer Applications (NCSA). As soon as it was ported to PCs
and Macs it immediately effected a boom in web usage.
13
Quickly services were set up for domain registration and sites began
turning up on the web, running on very basic HTML. Even at this stage,
malicious viruses and worms were infiltrating computers connected to
the Internet. Important sites like the White House and Pizza Hut
appeared. Online shopping sites showed up.The www was quickly the
most popular service on the Internet.
It was around 1995 when the first large ISPs like AOL and CompuServe
began offering Internet access to the masses. Technology like Sun's
Java and search engines are released. The somewhat legendary
browser war was in full swing between Netscape and Microsoft, with
new browser releases coming every month and the web becoming
14
15
ISPs
Client
A
HYUNDAI
Client
B
AT & T
Client
B
Branch A
Branch B
ISPs
DIRECT
ACCESS BY
MNCS
Client
A
BRITISH
TELECOME
16
i)
ii)
Servers run special software (Web sever software ) that allows them to
i)
ii)
17
18
which the web server send back to the client when the client connects
to the physical domain and points to a specific virtual domain hosted
on physical domain.
When an internet client requests for a connection to a virtual
domain on the internet, the request is routed to the proper internet
server using TCP/IP. The web server running on this internet Server
then handles the request, resolves(maps) the virtual domain Name
sent along with the request to an appropriate sub directory on the
internet server where the web site is hosted.
19
Applications of Internet
E-Mail
Electronic Mail works in much the same way as traditional mail (now
charmingly labelled 'snail-mail') does. Anyone is allowed to sign up for
an email address and then people can send you messages, or attach
files from their computer and send them too. The main benefit of email
is the close to instantaneous delivery of messages that occurs. You
can send an email to the other side of the world and it will arrive in less
than a minute. You can also sign up to weekly newsletters and have
information you want delivered right to your computer.
File Transfer Protocol
While web pages are transferred between computers using the http
protocol, other types of files are sent using FTP. People can share files,
like music and videos, among each other and the rest of the world by
uploading them to a server and allowing others to download them to
their own computers.
Internet Relay Chat
IRC is a service that allows you to connect to your chosen channel and
talk in real-time to people with the same interests as you. You can
download mIRC and start chatting right away.
USENET
USENET (Unix User Network) is a system of bulletin boards where you
and anyone else can post messages and people will read and reply to
them. As with IRC, you will find boards set up for all sorts of groups of
people.
IP address
20
An Internet Protocol (IP) address is a numerical identification and logical address that is
assigned to devices participating in a computer network utilizing the Internet Protocol for
communication between its nodes.Although IP addresses are stored as binary numbers,
they are usually displayed in human-readable notations, such as 208.77.188.166 (for
IPv4), and 2001:db8:0:1234:0:567:1:1 (for IPv6). The role of the IP address has been
characterized as follows: "A name indicates what we seek. An address indicates where it
is. A route indicates how to get there."
The original designers of TCP/IP defined an IP address as a 32-bit number and this
system, now named Internet Protocol Version 4 (IPv4), is still in use today. However, due
to the enormous growth of the Internet and the resulting depletion of the address space, a
new addressing system (IPv6), using 128 bits for the address.
The Internet Protocol also has the task of routing data packets between networks, and IP
addresses specify the locations of the source and destination nodes in the topology of the
routing system. For this purpose, some of the bits in an IP address are used to designate a
subnetwork. The number of these bits is indicated in CIDR notation, appended to the IP
address, e.g., 208.77.188.166/24.
With the development of private networks and the threat of IPv4 address exhaustion, a
group of private address spaces was set aside by RFC 1918. These private addresses may
be used by anyone on private networks. They are often used with network address
translators to connect to the global public Internet.
The Internet Assigned Numbers Authority (IANA) manages the IP address space
allocations globally. IANA works in cooperation with five Regional Internet Registries
(RIRs) to allocate IP address blocks to Local Internet Registries (Internet service
providers) and other entities
IP versions
The Internet Protocol (IP) has two versions currently in use Each version has its own
definition of an IP address. Because of its prevalence, the generic term IP address
21
typically
still
refers
to
the
addresses
defined
by
IPv4.
IP version 4 addresses
IPv4 uses 32-bit (4-byte) addresses, which limits the address space to 4,294,967,296 (232)
possible unique addresses. However, IPv4 reserves some addresses for special purposes
such as private networks (~18 million addresses) or multicast addresses (~270 million
addresses). This reduces the number of addresses that can be allocated as public Internet
addresses, and as the number of addresses available is consumed, an IPv4 address
shortage appears to be inevitable in the long run. This limitation has helped stimulate the
push towards IPv6, which is currently in the early stages of deployment and is currently
the only offering to replace IPv4.
IPv4 addresses are usually represented in dot-decimal notation (four numbers, each
ranging from 0 to 255, separated by dots, e.g. 208.77.188.166). Each part represents 8
bits of the address, and is therefore called an octet. In less common cases of technical
writing, IPv4 addresses may be presented in hexadecimal, octal, or binary
representations. When converting, each octet is usually treated as a separate number.
IPv4 networks
In the early stages of development of the Internet protocol, network administrators
interpreted an IP address as a structure of network number and host number. The highest
order octet (most significant eight bits) was designated the network number and the rest
of the bits were called the rest field or host identifier and were used for host numbering
within a network. This method soon proved inadequate as additional networks developed
that were independent from the existing networks already designated by a network
number. In 1981, the Internet addressing specification was revised with the introduction
of classful network architecture.
Classful network design allowed for a larger number of individual network assignments.
The first three bits of the most significant octet of an IP address was defined as the class
of the address. Three classes (A, B, and C) were defined for universal unicast addressing.
22
Depending on the class derived, the network identification was based on octet boundary
segments of the entire address. Each class used successively additional octets in the
network identifier, thus reducing the possible number of hosts in the higher order classes
(B and C). The following table gives an overview of this system.
Class
First octet in
binary
0XXXXXXX
0 - 127
b.c.d 27 = 128
10XXXXXX
128 - 191
a.b
c.d
214 = 16,384
216 - 2 = 65,534
110XXXXX
192 - 223
a.b.c
221 = 2,097,152
28 - 2 = 254
The articles 'subnetwork' and 'classful network' explain the details of this design.
Although classful network design was a successful developmental stage, it proved
unscalable in the rapid expansion of the Internet and was abandoned when Classless
Inter-Domain Routing (CIDR) was created for the allocation of IP address blocks and
new rules of routing protocol packets using IPv4 addresses. CIDR is based on variablelength subnet masking (VLSM) to allow allocation and routing on arbitrary-length
prefixes.
Today, remnants of classful network concepts function only in a limited scope as the
default configuration parameters of some network software and hardware components
(e.g. netmask), and in the technical jargon used in network administrators' discussions.
IP version 6 addresses
23
24
IP address translation
Multiple client devices can appear to share IP addresses: either because they are part of a
shared hosting web server environment or because an IPv4 network address translator
(NAT) or proxy server acts as an intermediary agent on behalf of its customers, in which
case the real originating IP addresses might be hidden from the server receiving a request.
A common practice is to have a NAT hide a large number of IP addresses in a private
network. Only the "outside" interface(s) of the NAT need to have Internet-routable
addresses.
Most commonly, the NAT device maps TCP or UDP port numbers on the outside to
individual private addresses on the inside. Just as a telephone number may have sitespecific extensions, the port numbers are site-specific extensions to an IP address.
In small home networks, NAT functions usually take place in a residential gateway
device, typically one marketed as a "router". In this scenario, the computers connected to
the router would have 'private' IP addresses and the router would have a 'public' address
to communicate with the Internet. This type of router allows several computers to share
one public IP address.
25
A socket is not a port, though there is a close relationship between them. A socket is
associated with a port, though this is a many-to-one relationship. Each port can have a
single passive socket, awaiting incoming connections, and multiple active sockets, each
corresponding to an open connection on the port.
26
The Domain Name System (DNS) is a hierarchical naming system for computers,
services, or any resource participating in the Internet. It associates various information
with the domain names assigned to each of the participants. Most importantly, it
translates domain names meaningful to humans into the numerical (binary) identifiers
associated with networking equipment for the purpose of locating and addressing these
devices world-wide. An often used analogy to explain the Domain Name System is that it
serves as the "phone book" for the Internet by translating human-friendly computer
hostnames into IP addresses. For example, www.example.com translates to
208.77.188.166.
The Domain Name System makes it possible to assign domain names to groups of
Internet users in a meaningful way, independent of each user's physical location. Because
of this, World-Wide Web (WWW) hyperlinks and Internet contact information can
remain consistent and constant even if the current Internet routing arrangements change
or the participant uses a mobile device. Internet domain names are easier to remember
than
IP
addresses
such
as
208.77.188.166
(IPv4)
or
2001:db8:1f70::999:de8:7648:6e8 (IPv6). People take advantage of this when they
recite meaningful URLs and e-mail addresses without having to know how the machine
will actually locate them.
27
The Domain Name System distributes the responsibility of assigning domain names and
mapping those names to IP addresses by designating authoritative name servers for each
domain. Authoritative name servers are assigned to be responsible for their particular
domains, and in turn can assign other authoritative name servers for their sub-domains.
This mechanism has made the DNS distributed, fault tolerant, and helped avoid the need
for a single central register to be continually consulted and updated.
In general, the Domain Name System also stores other types of information, such as the
list of mail servers that accept email for a given Internet domain. By providing a worldwide, distributed keyword-based redirection service, the Domain Name System is an
essential component of the functionality of the Internet.
Other identifiers such as RFID tags, UPC codes, International characters in email
addresses and host names, and a variety of other identifiers could all potentially utilize
DNS.
The Domain Name System also defines the technical underpinnings of the functionality
of this database service. For this purpose it defines the DNS protocol, a detailed
specification of the data structures and communication exchanges used in DNS, as part of
the Internet Protocol Suite (TCP/IP). The DNS protocol was developed and defined in the
early 1980s and published by the Internet Engineering Task Force (cf. History).
28
Domain names, arranged in a tree, cut into zones, each served by a nameserver.
The domain name space consists of a tree of domain names. Each node or leaf in the tree
has zero or more resource records, which hold information associated with the domain
name. The tree sub-divides into zones beginning at the root zone. A DNS zone consists of
a collection of connected nodes authoritatively served by an authoritative nameserver.
(Note that a single nameserver can host several zones.)
Administrative responsibility over any zone may be divided, thereby creating additional
zones. Authority is said to be delegated for a portion of the old space, usually in form of
sub-domains, to another nameserver and administrative entity. The old zone ceases to be
authoritative for the new zone.
The rightmost label conveys the top-level domain (for example, the address
www.example.com has the top-level domain com).
Each label to the left specifies a subdivision, or subdomain of the domain above
it. Note: subdomain expresses relative dependence, not absolute dependence.
For example: example.com is a subdomain of the com domain, and
www.example.com is a subdomain of the domain example.com. In theory, this
subdivision can go down 127 levels. Each label can contain up to 63 octets. The
whole domain name may not exceed a total length of 253 octets. [6] In practice, some
domain registries may have shorter limits.
29
A hostname refers to a domain name that has one or more associated IP addresses;
ie: the 'www.example.com' and 'example.com' domains are both hostnames,
however, the 'com' domain is not.
DNS servers
The Domain Name System is maintained by a distributed database system, which uses
the client-server model. The nodes of this database are the name servers. Each domain or
subdomain has one or more authoritative DNS servers that publish information about that
domain and the name servers of any domains subordinate to it. The top of the hierarchy is
served by the root nameservers: the servers to query when looking up (resolving) a toplevel domain name (TLD).
DNS resolvers
The client-side of the DNS is called a DNS resolver. It is responsible for initiating and
sequencing the queries that ultimately lead to a full resolution (translation) of the
resource sought, e.g., translation of a domain name into an IP address.
A DNS query may be either a recursive query or a non-recursive query:
A non-recursive query is one in which the DNS server may provide a partial
answer to the query (or give an error).
A recursive query is one where the DNS server will fully answer the query (or
give an error). DNS servers are not required to support recursive queries.
The resolver (or another DNS server acting recursively on behalf of the resolver)
negotiates use of recursive service using bits in the query headers.
Resolving usually entails iterating through several name servers to find the needed
information. However, some resolvers function simplistically and can communicate only
with a single name server. These simple resolvers rely on a recursive query to a recursive
name server to perform the work of finding information for them.
Tunneling protocol
Computer networks use a tunneling protocol when one network protocol (the delivery
protocol) encapsulates a different payload protocol. By using tunneling one can (for
example) carry a payload over an incompatible delivery-network, or provide a secure
path through an untrusted network.
Tunneling typically contrasts with a layered protocol model such as those of OSI or
TCP/IP. The tunnel protocol usually (but not always) operates at a higher level in the
model than does the payload protocol, or at the same level. Protocol encapsulation carried
31
out by conventional layered protocols, in accordance with the OSI model or TCP/IP
model (for example: HTTP over TCP over IP over PPP over a V.92 modem) does not
count as tunneling.
To understand a particular protocol stack, network engineers must understand both the
payload and delivery protocol sets.
As an example of network layer over network layer, Generic Routing Encapsulation
(GRE), a protocol running over IP (IP Protocol Number 47), often serves to carry IP
packets, with RFC 1918 private addresses, over the Internet using delivery packets with
public IP addresses. In this case, the delivery and payload protocols are compatible, but
the payload addresses are incompatible with those of the delivery network.
In contrast, an IP payload might believe it sees a data link layer delivery when it is
carried inside the Layer 2 Tunneling Protocol (L2TP), which appears to the payload
mechanism as a protocol of the data link layer. L2TP, however, actually runs over the
transport layer using User Datagram Protocol (UDP) over IP. The IP in the delivery
protocol could run over any data-link protocol from IEEE 802.2 over IEEE 802.3 (i.e.,
standards-based Ethernet) to the Point-to-Point Protocol (PPP) over a dialup modem link.
Tunneling protocols may use data encryption to transport insecure payload protocols over
a public network (such as the Internet), thereby providing VPN functionality. IPSec has
an end-to-end Transport Mode, but can also operate in a tunneling mode through a trusted
security gateway.
Overview
GRE tunnels are designed to be completely stateless. This means that each tunnel endpoint does not keep any information about the state or availability of the remote tunnel
end-point. A consequence of this is that the local tunnel end-point router does not have
the ability to bring the line protocol of the GRE tunnel interface down if the remote endpoint is unreachable. The ability to mark an interface as down when the remote end of the
link is not available is used in order to remove any routes (specifically static routes) in the
routing table that use that interface as the outbound interface. Specifically, if the line
protocol for an interface is changed to down, then any static routes that point out that
32
interface are removed from the routing table. This allows for the installation of an
alternate (floating) static route or for policy-based routing (PBR) to select an alternate
next-hop or interface.
Normally, a GRE tunnel interface comes up as soon as it is configured and it stays up as
long as there is a valid tunnel source address or interface which is up. The tunnel
destination IP address must also be routable. This is true even if the other side of the
tunnel has not been configured. This means that a static route or PBR forwarding of
packets via the GRE tunnel interface remains in effect even though the GRE tunnel
packets do not reach the other end of the tunnel.
Tunnel keepalives
The GRE tunnel keepalive mechanism is slightly different than for Ethernet or serial
interfaces. It gives the ability for one side to originate and receive keepalive packets to
and from a remote router even if the remote router does not support GRE keepalives.
Since GRE is a packet tunneling mechanism for tunneling IP inside IP, a GRE IP tunnel
packet can be built inside another GRE IP tunnel packet. For GRE keepalives, the sender
pre-builds the keepalive response packet inside the original keepalive request packet so
that the remote end only needs to do standard GRE decapsulation of the outer GRE IP
header and then forward the inner IP GRE packet. This mechanism causes the keepalive
response to forward out the physical interface rather than the tunnel interface. This means
that the GRE keepalive response packet is not affected by any output features on the
tunnel interface.
Another attribute of GRE tunnel keepalives is that the keepalive timers on each side are
independent and do not have to match. The problem with the configuration of keepalives
only on one side of the tunnel is that only the router that has keepalives configured marks
its tunnel interface as down if the keepalive timer expires. The GRE tunnel interface on
the other side, where keepalives are not configured, remains up even if the other side of
the tunnel is down. The tunnel can become a black-hole for packets directed into the
tunnel from the side that did not have keepalives configured. In a large hub-and-spoke
GRE tunnel network, it might be appropriate to only configure GRE keepalives on the
spoke side and not on the hub side. This is because it is often more important for the
spoke to discover that the hub is unreachable and therefore switch to a backup path (Dial
Backup for example).
Before GRE keepalives were implemented, there were only three reasons for a GRE
tunnel to shut down:
These three rules (missing route, interface down and mis-routed tunnel destination) are
problems local to the router at the tunnel endpoints and do not cover problems in the
33
intervening network. For example, these rules do not cover the case in which the GRE
tunneled packets are successfully forwarded, but are lost before they reach the other end
of the tunnel. This causes data packets that go through the GRE tunnel to be "black
holed", even though an alternate route that uses PBR or a floating static route via another
interface is potentially available. Keepalives on the GRE tunnel interface are used in
order to solve this issue in the same way as keepalives are used on physical interfaces.
With Cisco IOS Software Release 12.2(8)T, it is possible to configure keepalives on a
point-to-point GRE tunnel interface. With this change, the tunnel interface dynamically
shuts down if the keepalives fail for a certain period of time. In order to better understand
how GRE tunnel keepalives work, these sections discuss some other common keepalive
mechanisms.
Example uses
Protocol
5. Application
RADIUS
4. Transport
UDP
Encapsulation
GRE
3. Network
IPv4
2. Data Link
Ethernet
34
1. Physical
From what can be seen in the diagram above, protocol encapsulation (not specifically
GRE) breaks the layering order in the OSI model terms. It may be viewed as a separator
between two different protocol stacks, one acting as a carrier for another.
IP as a delivery protocol
GRE packets which are encapsulated within IP will use IP protocol type 47.
Packet header
A GRE packet header structure is represented in the diagram below.
Bits 04
57
C R K S s Recur
812
1315
1631
Flags
Version
Protocol Type
Checksum (optional)
Offset (optional)
Key (optional)
Routing (optional)
The packet fields are as follows:
Checksum Present (C), 1-bit
The Checksum field is present and contains valid information if set. If either the
Checksum Present bit or the Routing Present bit are set, the Checksum and Offset
fields are both present.
Routing Present (R), 1-bit
If set then the Offset field is present and contains valid information. If either the
Checksum Present bit or the Routing Present bit are set, the Checksum and Offset
fields are both present.
35
SSH tunneling
An SSH tunnel consists of an encrypted tunnel created through an SSH protocol
connection. Users may set up SSH tunnels to tunnel unencrypted traffic over a network
through an encrypted channel. For example, Windows machines can share files using the
SMB protocol, a non-encrypted protocol. If one were to mount a Microsoft Windows filesystem remotely through the Internet, someone snooping on the connection could see
transferred files. To mount the Windows file-system securely, one can establish an SSH
36
tunnel that routes all SMB traffic to the remote fileserver through an encrypted channel.
Even though the SMB protocol itself contains no encryption, the encrypted SSH channel
through which it travels offers security.
To set up an SSH tunnel, one configures an SSH client to forward a specified local port to
a port on the remote machine. Once the SSH tunnel has been established, the user can
connect to the specified local port to access the network service. The local port need not
have the same port number as the remote port.
SSH tunnels provide a means to bypass firewalls that prohibit certain Internet services
so long as a site allows outgoing connections. For example, an organization may prohibit
a user from accessing Internet web pages (port 80) directly without passing through the
organization's proxy filter (which provides the organization with a means of monitoring
and controlling what the user sees through the web). But users may not wish to have their
web traffic monitored or blocked by the organization's proxy filter. If users can connect to
an external SSH server, they can create an SSH tunnel to forward a given port on their
local machine to port 80 on a remote web server. To access the remote web server users
would point their browser to http://localhost/.
Some SSH clients support dynamic port forwarding that allows the user to create a
SOCKS 4/5 proxy. In this case users can configure their applications to use their local
SOCKS proxy server. This gives more flexibility than creating an SSH tunnel to a single
port as previously described. SOCKS can free the user from the limitations of connecting
only to a predefined remote port and server.
37
Proxy server
Schematic representation of a proxy server, where the computer in the middle acts as the
proxy server between the other two.
In computer networks, a proxy server is a server (a computer system or an
application program) that acts as a go-between for requests from clients seeking resources
from other servers. A client connects to the proxy server, requesting some service, such as
a file, connection, web page, or other resource, available from a different server. The
proxy server evaluates the request according to its filtering rules. For example, it may
filter traffic by IP address or protocol. If the request is validated by the filter, the proxy
provides the resource by connecting to the relevant server and requesting the service on
behalf of the client. A proxy server may optionally alter the client's request or the server's
response, and sometimes it may serve the request without contacting the specified server.
In this case, it 'caches' responses from the remote server, and returns subsequent requests
for the same content directly.
A proxy server has two purposes:
A proxy server that passes requests and replies unmodified is usually called a
gateway or sometimes tunneling proxy.
A proxy server can be placed in the user's local computer or at various points
between the user and the destination servers or the Internet. A reverse proxy is a proxy
used as a front-end to accelerate and cache in-demand resources (such as a web page).
38
Web proxy
A proxy that focuses on WWW traffic is called a "web proxy". The most common
use of a web proxy is to serve as a web cache. Most proxy programs (e.g. Squid) provide
a means to deny access to certain URLs in a blacklist, thus providing content filtering.
This is often used in a corporate, educational or library environment, and anywhere else
where content filtering is desired. Some web proxies reformat web pages for a specific
purpose or audience (e.g., cell phones and PDAs).
AOL dialup customers used to have their requests routed through an extensible
proxy that 'thinned' or reduced the detail in JPEG pictures. This sped up performance but
caused problems, either when more resolution was needed or when the thinning program
produced incorrect results. This is why in the early days of the web many web pages
would contain a link saying "AOL Users Click Here" to bypass the web proxy and to
avoid the bugs in the thinning software.
39
Some common methods used for content filtering include: URL or DNS
blacklists, URL regex filtering, MIME filtering, or content keyword filtering. Some
products have been known to employ content analysis techniques to look for traits
commonly used by certain types of content providers.
A content filtering proxy will often support user authentication, to control web
access. It also usually produces logs, either to give detailed information about the URLs
accessed by specific users, or to monitor bandwidth usage statistics. It may also
communicate to daemon based and/or ICAP based antivirus software to provide security
against virus and other malware by scanning incoming content in real time before it
enters the network.
Hostile proxy
Proxies can also be installed in order to eavesdrop upon the dataflow between
client machines and the web. All accessed pages, as well as all forms submitted, can be
captured and analyzed by the proxy operator. For this reason, passwords to online
services (such as webmail and banking) should always be exchanged over a
cryptographically secured connection, such as SSL.
40
Forced proxy
The term "forced proxy" is ambiguous. It means both "intercepting proxy"
(because it filters all traffic on the only available gateway to the Internet) and its exact
opposite, "non-intercepting proxy" (because the user is forced to configure a proxy in
order to access the Internet).
Forced proxy operation is sometimes necessary due to issues with the interception of TCP
connections and HTTP. For instance, interception of HTTP requests can affect the
usability of a proxy cache, and can greatly affect certain authentication mechanisms. This
is primarily because the client thinks it is talking to a server, and so request headers
required by a proxy are unable to be distinguished from headers that may be required by
an upstream server (esp authorization headers). Also the HTTP specification prohibits
caching of responses where the request contained an authorization header.
Suffix proxy
A suffix proxy server allows a user to access web content by appending the name of the
proxy server to the URL of the requested content (e.g. "en.wikipedia.org.6a.nl").
41
Suffix proxy servers are easier to use than regular proxy servers. The concept appeared in
2003 in form of the IPv6Gate and in 2004 in form of the Coral Content Distribution
Network.
Encryption / SSL acceleration: when secure web sites are created, the SSL
encryption is often not done by the web server itself, but by a reverse proxy that is
equipped with SSL acceleration hardware. See Secure Sockets Layer.
Furthermore, a host can provide a single "SSL proxy" to provide SSL encryption
for an arbitrary number of hosts; removing the need for a separate SSL Server
Certificate for each host, with the downside that all hosts behind the SSL proxy
have to share a common DNS name or IP address for SSL connections.
Load balancing: the reverse proxy can distribute the load to several web servers,
each web server serving its own application area. In such a case, the reverse proxy
may need to rewrite the URLs in each web page (translation from externally
known URLs to the internal locations).
Serve/cache static content: A reverse proxy can offload the web servers by
caching static content like pictures and other static graphical content.
Compression: the proxy server can optimize and compress the content to speed up
the load time.
Spoon feeding: reduces resource usage caused by slow clients on the web servers
by caching the content the web server sent and slowly "spoon feeding" it to the
client. This especially benefits dynamically generated pages.
Security: the proxy server is an additional layer of defense and can protect against
some OS and WebServer specific attacks. However, it does not provide any
protection to attacks against the web application or service itself, which is
generally considered the larger threat.
42
Extranet Publishing: a reverse proxy server facing the Internet can be used to
communicate to a firewalled server internal to an organization, providing extranet
access to some functions while keeping the servers behind the firewalls. If used in
this way, security measures should be considered to protect the rest of your
infrastructure in case this server is compromised, as its web application is exposed
to attack from the Internet.
Circumventor
A circumventor is a method of defeating blocking policies implemented using
proxy servers. Ironically, most circumventors are also proxy servers, of varying degrees
of sophistication, which effectively implement "bypass policies".
A circumventor is a web-based page that takes a site that is blocked and
"circumvents" it through to an unblocked web site, allowing the user to view blocked
pages. A famous example is elgooG, which allowed users in China to use Google after it
had been blocked there. elgooG differs from most circumventors in that it circumvents
only one block.
A September 2007 report from Citizen Lab recommended Web based proxies
Proxify, StupidCensorship, and CGIProxy. Alternatively, users could partner with
individuals outside the censored network running Psiphon or Peacefire/Circumventor. A
more elaborate approach suggested was to run free tunneling software such as UltraSurf,
and FreeGate, or pay services Anonymizer and Ghost Surf. Also listed were free
application tunneling software Gpass and HTTP Tunnel, and pay application software
Relakks and Guardster. Lastly, anonymous communication networks JAP ANON, Tor,
and I2Poffer a range of possibilities for secure publication and browsing.
Students are able to access blocked sites (games, chatrooms, messenger, offensive
material, internet pornography, social networking, etc.) through a circumventor. As fast as
the filtering software blocks circumventors, others spring up. However, in some cases the
filter may still intercept traffic to the circumventor, thus the person who manages the
filter can still see the sites that are being visited.
Circumventors are also used by people who have been blocked from a web site.
Another use of a circumventor is to allow access to country-specific services, so
that Internet users from other countries may also make use of them. An example is
country-restricted reproduction of media and webcasting.
The use of circumventors is usually safe with the exception that circumventor
sites run by an untrusted third party can be run with hidden intentions, such as collecting
personal information, and as a result users are typically advised against running personal
data such as credit card numbers or passwords through a circumventor.
An example of one way to circumvent a content-filtering proxy server is by
tunnelling through to another proxy server, usually controlled by the user, which has
unrestricted access to the internet. This is often achieved by using a VPN type tunnel,
43
such as VPN itself or SSH, through a port left open by the proxy server to be
circumvented. Port 80 is almost always open to allow the use of HTTP, as is Port 443 to
allow the use of HTTPS. Through the use of encryption, tunnelling to a remote proxy
server, provided the remote proxy server is itself secure, is not only difficult to detect, but
also difficult to intercept.
In some network configurations, clients attempting to access the proxy server are
given different levels of access privilege on the grounds of their computer location or
even the MAC address of the network card. However, if one has access to a system with
higher access rights, they could use that system as a proxy server for which the other
clients use to access the original proxy server, consequently altering their access
privileges.
Content filter
Many work places, schools, and colleges restrict the web sites and online services
that are made available in their buildings. This is done either with a specialized proxy,
called a content filter (both commercial and free products are available), or by using a
cache-extension protocol such as ICAP, that allows plug-in extensions to an open caching
architecture.
Requests made to the open internet must first pass through an outbound proxy
filter. The web-filtering company provides a database of URL patterns (regular
expressions) with associated content attributes. This database is updated weekly by sitewide subscription, much like a virus filter subscription. The administrator instructs the
web filter to ban broad classes of content (such as sports, pornography, online shopping,
gambling, or social networking). Requests that match a banned URL pattern are rejected
immediately.
Assuming the requested URL is acceptable, the content is then fetched by the
proxy. At this point a dynamic filter may be applied on the return path. For example,
JPEG files could be blocked based on fleshtone matches, or language filters could
dynamically detect unwanted language. If the content is rejected then an HTTP fetch
error is returned and nothing is cached.
Most web filtering companies use an internet-wide crawling robot that assesses
the likelihood that a content is a certain type (i.e. "This content is 70% chance of porn,
40% chance of sports, and 30% chance of news" could be the outcome for one web
page). The resultant database is then corrected by manual labor based on complaints or
known flaws in the content-matching algorithms.
Web filtering proxies are not able to peer inside secure sockets HTTP transactions. As a
result, users wanting to bypass web filtering will typically search the internet for an open
and anonymous HTTPS transparent proxy. They will then program their browser to proxy
all requests through the web filter to this anonymous proxy. Those requests will be
encrypted with https. The web filter cannot distinguish these transactions from, say, a
legitimate access to a financial website. Thus, content filters are only effective against
unsophisticated users.
44
A special case of web proxies is "CGI proxies". These are web sites that allow a
user to access a site through them. They generally use PHP or CGI to implement the
proxy functionality. These types of proxies are frequently used to gain access to web sites
blocked by corporate or school proxies. Since they also hide the user's own IP address
from the web sites they access through the proxy, they are sometimes also used to gain a
degree of anonymity, called "Proxy Avoidance".
Firewall
.
45
46
1. Packet filter: Looks at each packet entering or leaving the network and accepts or
rejects it based on user-defined rules. Packet filtering is fairly effective and
transparent to users, but it is difficult to configure. In addition, it is susceptible to
IP spoofing.
2. Application gateway: Applies security mechanisms to specific applications, such
as FTP and Telnet servers. This is very effective, but can impose a performance
degradation.
3. Circuit-level gateway: Applies security mechanisms when a TCP or UDP
connection is established. Once the connection has been made, packets can flow
between the hosts without further checking.
4. Proxy server: Intercepts all messages entering and leaving the network. The proxy
server effectively hides the true network addresses.
Function
A firewall is a dedicated appliance, or software running on a computer, which
inspects network traffic passing through it, and denies or permits passage based on a set
of rules.
A firewall's basic task is to regulate some of the flow of traffic between computer
networks of different trust levels. Typical examples are the Internet which is a zone with
no trust and an internal network which is a zone of higher trust. A zone with an
intermediate trust level, situated between the Internet and a trusted internal network, is
often referred to as a "perimeter network" or Demilitarized zone (DMZ).
A firewall's function within a network is similar to physical firewalls with fire
doors in building construction. In the former case, it is used to prevent network intrusion
to the private network. In the latter case, it is intended to contain and delay structural fire
from spreading to adjacent structures.
Without proper configuration, a firewall can often become worthless. Standard
security practices dictate a "default-deny" firewall ruleset, in which the only network
connections which are allowed are the ones that have been explicitly allowed.
Unfortunately, such a configuration requires detailed understanding of the network
applications and endpoints required for the organization's day-to-day operation. Many
businesses lack such understanding, and therefore implement a "default-allow" ruleset, in
which all traffic is allowed unless it has been specifically blocked. This configuration
makes inadvertent network connections and system compromise much more likely.
47
Internet standard
In computer network engineering, an Internet Standard (STD) is a normative
specification of a technology or methodology applicable to the Internet. Internet
Standards are created and published by the Internet Engineering Task Force (IETF).
Overview
An Internet Standard is a special Request for Comments (RFC) or set of RFCs.
An RFC that is to become a Standard or part of a Standard begins as an Internet Draft,
and is later (usually after several revisions) accepted and published by the RFC Editor as
a RFC and labeled a Proposed Standard. Later, an RFC is labelled a Draft Standard, and
finally a Standard. Collectively, these stages are known as the standards track, and are
defined in RFC 2026. The label Historic (sic) is applied to deprecated standards-track
documents or obsolete RFCs that were published before the standards track was
established.
Only the IETF, represented by the Internet Engineering Steering Group (IESG),
can approve standards-track RFCs. The definitive list of Internet Standards is maintained
in Internet Standards document STD 1: Internet Official Protocol Standards.[1]
Standardization process
Becoming a standard is a three step process within the IETF called Proposed
Standards, Draft Standards and finally Internet Standards. If an RFC is part of a proposal
that is on the standard track, then at the first stage, the standard is proposed and
subsequently organizations decide whether to implement this Proposed Standard. After
three separate implementations, more review and corrections are made to the RFC, and a
Draft Standard is created. At the final stage, the RFC becomes a Standard.
Proposed Standard
A Proposed Standard (PS) is generally stable, has resolved known design choices,
is believed to be well-understood, has received significant community review, and
appears to enjoy enough community interest to be considered valuable. However, further
experience might result in a change or even retraction of the specification before it
advances. Usually, neither implementation nor operational experience is required.
Draft Standard
A specification from which at least two independent and interoperable
implementations from different code bases have been developed, and for which sufficient
successful operational experience has been obtained, may be elevated to the Draft
Standard (DS) level.
48
Standard
A specification for which significant implementation and successful operational
experience has been obtained may be elevated to the Internet Standard (STD) level. An
Internet Standard, which may simply be referred to as a Standard, is characterized by a
high degree of technical maturity and by a generally held belief that the specified
protocol or service provides significant benefit to the Internet community.
Generally Internet Standards cover interoperability of systems on the internet
through defining protocols, messages formats, schemas, and languages. The most
fundamental of the Standards are the ones defining the Internet Protocol.
All Internet Standards are given a number in the STD series - The first document
in this series, STD 1, describes the remaining documents in the series, and has a list of
Proposed Standards.
Each RFC is static; if the document is changed, it is submitted again and assigned
a new RFC number. If an RFC becomes an Internet Standard (STD), it is assigned an
STD number but retains its RFC number. When an Internet Standard is updated, its
number stays the same and it simply refers to a different RFC or set of RFCs. A given
Internet Standard, STD n, may be RFCs x and y at a given time, but later the same
standard may be updated to be RFC z instead. For example, in 2007 RFC 3700 was an
Internet StandardSTD 1and in May 2008 it was replaced with RFC 5000, so RFC
3700 changed to Historic status, and now STD 1 is RFC 5000. When STD 1 is updated
again, it will simply refer to a newer RFC, but it will still be STD 1. Note that not all
RFCs are standards-track documents, but all Internet Standards and other standards-track
documents are RFCs.
49
Today, the Web and the Internet allow connectivity from literally everywhere on earth
even ships at sea and in outer space.
The World Wide Web ("WWW" or simply the "Web") is a global information
medium which users can read and write via computers connected to the Internet. The
term is often mistakenly used as a synonym for the Internet itself, but the Web is a service
that operates over the Internet, as e-mail does. The history of the Internet dates back
significantly further than that of the World Wide Web.
The hypertext portion of the Web in particular has an intricate intellectual history;
notable influences and precursors include Vannevar Bush's Memex, IBM's Generalized
Markup Language, and Ted Nelson's Project Xanadu.
The concept of a home-based global information system goes at least as far back
as "A Logic Named Joe", a 1946 short story by Murray Leinster, in which computer
terminals, called "logics," were in every home. Although the computer system in the story
is centralized, the story captures some of the feeling of the ubiquitous information
explosion driven by the Web.
An early CERN-related contribution to the Web was the parody band Les
Horribles Cernettes, whose promotional image is believed to be among the Web's first
five pictures[3].
51
Web server
The term web server or webserver can mean one of two things:
1. A computer program that is responsible for accepting HTTP requests from clients
(user agents such as web browsers), and serving them HTTP responses along with
optional data contents, which usually are web pages such as HTML documents
and linked objects (images, etc.).
2. A computer that runs a computer program as described above.
Common features
Although web server programs differ in detail, they all share some basic common
features.
1. HTTP: every web server program operates by accepting HTTP requests from the
client, and providing an HTTP response to the client. The HTTP response usually
consists of an HTML or XHTML document, but can also be a raw file, an image,
or some other type of document (defined by MIME-types). If some error is found
in client request or while trying to serve it, a web server has to send an error
response which may include some custom HTML or text messages to better
explain the problem to end users.
2. Logging: usually web servers have also the capability of logging some detailed
information, about client requests and server responses, to log files; this allows
the webmaster to collect statistics by running log analyzers on these files.
In practice many web servers also implement the following features:
1. Authentication, optional authorization request (request of user name and
password) before allowing access to some or all kind of resources.
2. Handling of static content (file content recorded in server's filesystem(s)) and
dynamic content by supporting one or more related interfaces (SSI, CGI, SCGI,
FastCGI, JSP,ColdFusion, PHP, ASP, WhizBase, ASP.NET, Server API such as
NSAPI, ISAPI, etc.).
3. HTTPS support (by SSL or TLS) to allow secure (encrypted) connections to the
server on the standard port 443 instead of usual port 80.
4. Content compression (i.e. by gzip encoding) to reduce the size of the responses
(to lower bandwidth usage, etc.).
5. Virtual hosting to serve many web sites using one IP address.
6. Large file support to be able to serve files whose size is greater than 2 GB on 32
bit OS.
7. Bandwidth throttling to limit the speed of responses in order to not saturate the
network and to be able to serve more clients.
52
Vendor
Apache
Product
Apache
Microsoft IIS
GWS
nginx
nginx
lighttpd
lighttpd
53
54
A name for the object. The name should be unique among all
other objects on the page.
CLASSID=
CODEBASE=
PARAM NAME="x"
VALUE="y"
DATA=
Close the object tag using the (</OBJECT>) tag after the parameter list.
55
UNIT II
What is VBScript?
The HTML <script> tag is used to insert a VBScript into an HTML page.
The example below shows how to add HTML tags to the VBScript:
Example Explained
To insert a VBScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the type attribute to define
the scripting language.
56
<html>
<body>
<script type="text/vbscript">
...
</script>
</body>
</html>
The document.write command is a standard VBScript command for writing output to a page.
By entering the document.write command between the <script> and </script> tags, the browser will recognize it as a VBScript
command and execute the code line. In this case the browser will write Hello World! to the page:
<html>
<body>
<script type="text/vbscript">
document.write("Hello World!")
</script>
</body>
</html>
<html>
<body>
<script type="text/vbscript">
<!-document.write("Hello World!")
-->-->
</script>
</body>
</html
Scripts in <head>
57
Scripts in <body>
Scripts to be executed when the page loads go in the body section.
If you place a script in the body section, it generates the content of a page.
<html>
<head>
<script type="text/vbscript">
....
</script>
</head>
<body>
58
VBScript Variables
As with algebra, VBScript variables are used to hold values or expressions.
A variable can have a short name, like x, or a more descriptive name, like carname.
Rules for VBScript variable names:
In VBScript, all variables are of type variant, that can store different types of data.
Dim x;
Dim carname;
Now you have created two variables. The name of the variables are "x" and "carname".
You can also declare variables by using its name in a script. Like this:
carname=some value
Now you have also created a variable. The name of the variable is "carname". However, this method is not a good practice,
because you can misspell the variable name later in your script, and that can cause strange results when your script is running.
If you misspell for example the "carname" variable to "carnime", the script will automatically create a new variable called
"carnime". To prevent your script from doing this, you can use the Option Explicit statement. This statement forces you to
declare all your variables with the dim, public or private statement.
Put the Option Explicit statement on the top of your script. Like this:
Option Explicit
Dim carname
carname=some value
59
carname="Volvo"
x=10
The variable name is on the left side of the expression and the value you want to assign to the variable is on the right. Now the
variable "carname" has the value of "Volvo", and the variable "x" has the value of "10".
Lifetime of Variables
How long a variable exists is its lifetime.
When you declare a variable within a procedure, the variable can only be accessed within that procedure. When the procedure
exits, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in
different procedures, because each is recognized only by the procedure in which it is declared.
If you declare a variable outside a procedure, all the procedures on your page can access it. The lifetime of these variables
starts when they are declared, and ends when the page is closed.
Dim names(2)
The number shown in the parentheses is 2. We start at zero so this array contains 3 elements. This is a fixed-size array. You
assign data to each of the elements of the array like this:
names(0)="Tove"
names(1)="Jani"
names(2)="Stale"
Similarly, the data can be retrieved from any element using the index of the particular array element you want. Like this:
60
Dim table(4,6)
VBScript Procedures
In VBScript, there are two kinds of procedures:
Sub procedure
Function procedure
Sub mysub()
some statements
End Sub
or
Sub mysub(argument1,argument2)
some statements
End Sub
Function myfunction()
61
carname=findname()
Here you call a Function called "findname", the Function returns a value that will be stored in the variable "carname".
Or, you can do like this:
Call MyProc(argument)
Or, you can omit the Call statement, like this:
MyProc argument
Conditional Statements
Conditional statements are used to perform different actions for different decisions.
In VBScript we have four conditional statements:
62
If...Then...Else
Use the If...Then...Else statement if you want to
If you want to execute only one statement when a condition is true, you can write the code on one line:
If i=10 Then
msgbox "Hello"
i = i+1
End If
There is no ..Else.. in the example above either. You just tell the code to perform multiple actions if the condition is true.
If you want to execute a statement if a condition is true and execute another statement if the condition is not true, you must
add the "Else" keyword:
63
In the example above, the first block of code will be executed if the condition is true, and the other block will be executed
otherwise (if i is greater than 10).
If...Then...ElseIf
You can use the If...Then...ElseIf statement if you want to select one of many blocks of code to execute:
64
Select Case
You can also use the "Select Case" statement if you want to select one of many blocks of code to execute:
65
Looping Statements
Looping statements are used to run the same block of code a specified number of times.
In VBScript we have four looping statements:
For...Next Loop
Use the For...Next statement to run a block of code a specified number of times.
The For statement specifies the counter variable (i), and its start and end values. The Next statement increases the counter
variable (i) by one.
66
Exit a For...Next
You can exit a For...Next statement with the Exit For keyword.
67
Do...Loop
If you don't know how many repetitions you want, use a Do...Loop statement.
The Do...Loop statement repeats a block of code while a condition is true, or until a condition becomes true.
Do While i>10
some code
Loop
If i equals 9, the code inside the loop above will never be executed.
Do
some code
Loop While i>10
The code inside this loop will be executed at least one time, even if i is less than 10.
Do Until i=10
some code
Loop
If i equals 10, the code inside the loop will never be executed.
Do
68
Exit a Do...Loop
You can exit a Do...Loop statement with the Exit Do keyword.
Do Until i=10
i=i-1
If i<10 Then Exit Do
Loop
The code inside this loop will be executed as long as i is different from 10, and as long as i is greater than 10.
Date/Time Functions
Function
Description
CDate
Date
DateAdd
DateDiff
DatePart
DateSerial
DateValue
Returns a date
Day
FormatDateTime
Hour
IsDate
Minute
Month
MonthName
Now
Second
Time
Timer
TimeSerial
TimeValue
Returns a time
Weekday
69
Year
Conversion Functions
Function
Description
Asc
CBool
CByte
CCur
CDate
CDbl
Chr
CInt
CLng
CSng
CStr
Hex
Oct
Format Functions
Function
Description
FormatCurrency
FormatDateTime
FormatNumber
FormatPercent
Math Functions
Function
Description
Abs
Atn
Cos
Exp
Hex
Int
Fix
Log
Oct
70
Sgn
Sin
Sqr
Tan
Array Functions
Function
Description
Array
Filter
IsArray
Join
LBound
Split
UBound
String Functions
Function
Description
InStr
InStrRev
LCase
Left
Len
LTrim
RTrim
Trim
Removes spaces on both the left and the right side of a string
Mid
Replace
Right
Space
StrComp
Compares two strings and returns a value that represents the result
of the comparison
String
StrReverse
Reverses a string
71
Other Functions
Function
Description
CreateObject
Eval
GetLocale
GetObject
GetRef
InputBox
Displays a dialog box, where the user can write some input and/or
click on a button, and returns the contents
IsEmpty
IsNull
IsNumeric
IsObject
LoadPicture
MsgBox
Displays a message box, waits for the user to click a button, and
returns a value that indicates which button the user clicked
RGB
Round
Rounds a number
ScriptEngine
ScriptEngineBuildVersion
ScriptEngineMajorVersion
ScriptEngineMinorVersion
SetLocale
TypeName
VarType
72
EXAMPLES
Examples For Procedure
<html>
<head>
<script type="text/vbscript">
Sub mySub()
msgbox("This is a Sub procedure")
End Sub
</script>
</head>
<body>
<script type="text/vbscript">
Call mySub()
</script>
<p>A Sub procedure does not return a result.</p>
</body>
</html>
<html>
Examples For Procedure
<head>
<script type="text/vbscript">
Function myFunction()
myFunction = "BLUE"
End Function
</script>
</head>
<body>
<script type="text/vbscript">
document.write("My favorite color is " & myFunction())
</script>
<p>A Function procedure can return a result.</p>
</body>
</html>
73
Weekday Example
<html>
<body>
<p>VBScripts' function <b>WeekdayName</b> is used to get a weekday:</p>
<script type="text/vbscript">
document.write("<p>")
document.write(WeekDayName(1))
document.write("<br />")
document.write(WeekDayName(2))
document.write("</p><p>")
document.write("Get the abbreviated name of a weekday:")
document.write("<br />")
document.write(WeekDayName(1,True))
document.write("<br />")
document.write(WeekDayName(2,True))
document.write("</p><p>")
document.write("Get the current weekday:")
document.write("<br />")
document.write(WeekdayName(weekday(Date)))
document.write("<br />")
document.write(WeekdayName(weekday(Date), True))
document.write("</p>")
</script>
</body>
</html>
Example for Format Date, time
<html>
<body>
<script type="text/vbscript">
document.write(FormatDateTime(Date(),vbGeneralDate))
document.write("<br />")
74
document.write(FormatDateTime(Date(),vbLongDate))
document.write("<br />")
document.write(FormatDateTime(Date(),vbShortDate))
document.write("<br />")
document.write(FormatDateTime(Now(),vbLongTime))
document.write("<br />")
document.write(FormatDateTime(Now(),vbShortTime))
</script>
<p>Syntax for FormatDateTime: FormatDateTime(Date,namedformat).</p>
</body>
</html>
Return a Specified number of Char from String
<html>
<body>
<script type="text/vbscript">
sometext="Welcome to our Web Site!!"
document.write(Mid(sometext, 9, 2))
</script>
</body>
</html>
Replace String
<html>
<body>
<script type="text/vbscript">
sometext="Welcome to this Web!!"
document.write(Replace(sometext, "Web", "Page"))
</script>
</body>
</html>
Unit III
Define a Format
Pass the data that will be displayed on the format
Invoke the Format
Define a Format
Following is the syntax to define a Perl format
format FormatName =
fieldline
value_one, value_two, value_three
fieldline
value_one, value_two
.
FormatName represents the name of the format. The fieldline is the specific way the data should be formatted. The
values lines represent the values that will be entered into the field line. You end the format with a single period.
fieldline can contain any text or fieldholders. Fieldholders hold space for data that will be placed there at a later date.
A fieldholder has the format:
@<<<<
This fieldholder is left-justified, with a field space of 5. You must count the @ sign and the < signs to know the number of
spaces in the field. Other field holders include:
@>>>> right-justified
@|||| centered
@####.## numeric field holder
@* multiline field holder
An example format would be:
format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
===================================
.
In this example $name would be written as left justify within 22 character spaces and after that age will be written in two
spaces.
76
select(STDOUT);
We would then associate EMPLOYEE with STDOUT by setting the new format name with STDOUT, using the special
variable $~
$~ = "EMPLOYEE";
When we now do a write(), the data would be sent to STDOUT. Remember: if you didn't have STDOUT set as your default
file handle, you could revert back to the original file handle by assigning the return value of select to a scalar value, and using
select along with this scalar variable after the special variable is assigned the format name, to be associated with STDOUT.
The above example will generate a report in the following format
Kirsten
Mohammad
Suhi
Namrat
12
35
15
10
format EMPLOYEE_TOP =
-----------------------Name
Age
-----------------------.
Now your report will look like
-----------------------Name
Age
-----------------------Kirsten
12
Mohammad
35
Suhi
15
77
10
format EMPLOYEE_TOP =
-----------------------Name
Age
-----------------------.
Page @<
$%
-----------------------Name
Age
-----------------------Kirsten
12
Mohammad
35
Suhi
15
Namrat
10
Page 1
You can set the number of lines per page using special variable $= ( or $FORMAT_LINES_PER_PAGE ) By default $= will
be 60
format EMPLOYEE_BOTTOM =
End of Page @<
$%
.
This will give you following result
-----------------------Name
Age
-----------------------Kirsten
12
Mohammad
35
Suhi
15
Namrat
10
End of Page 1
Page 1
78
References
A reference is, exactly as the name suggests, a reference or pointer to another object.
There are two types of references: symbolic and hard.
A symbolic reference enables you to refer to a variable by name, using the value of another variable. For example, if
the variable $foo contains the string "bar", the symbolic reference to $foo refers to the variable $bar.
$foo = 'Bill';
$fooref = \$foo;
The $fooref variable now contains a hard reference to the $foo variable. You can do the same with other variables:
$array = \@ARGV;
$hash = \%ENV;
$glob = \*STDOUT;
To create a reference to a subroutine:
Anonymous Arrays
When you create a reference to an array directly - that is, without creating an intervening named array - you are creating an
anonymous array.
Creating an anonymous array is easy:
79
Anonymous Hashes
Anonymous hashes are similarly easy to create, except you use braces instead of square brackets:
Dereferencing
The most direct way of dereferencing a reference is to prepend the corresponding data type character ($ for scalars, @ for
arrays, % for hashes, and & for subroutines) that you are expecting in front of the scalar variable containing the reference. For
example, to dereference a scalar reference $foo, you would access the data as $$foo. Other examples are:
$array = \@ARGV;
# Create reference
$hash = \%ENV;
# Create reference
$glob = \*STDOUT;
# Create reference
$foosub = \&foo;
# Create reference
push (@$array, "From humans");
$$array[0] = 'Hello'
$$hash{'Hello'} = 'World';
&$foosub;
print $glob "Hello World!\n";
to
to
to
to
array
hash
typeglob
subroutine
Object Basics
There are three main terms, explained from the point of view of how Perl handles objects. The terms are object, class, and
method.
Within Perl, an object is merely a reference to a data type that knows what class it belongs to. The object is stored as
a reference in a scalar variable. Because a scalar only contains a reference to the object, the same scalar can hold
different objects in different classes.
A class within Perl is a package that contains the corresponding methods required to create and manipulate objects.
A method within Perl is a subroutine, defined with the package. The first argument to the method is an object
reference or a package name, depending on whether the method affects the current object or the class.
Perl provides a bless() function which is used to return a reference and which becomes an object.
Defining a Class
Its very simple to define a class. In Perl, a class is corresponds to a Package.To create a class in Perl, we first build a package.
A package is a self-contained unit of user-defined variables and subroutines, which can be re-used over and over again. They
provide a separate namespace within a Perl program that keeps subroutines and variables from conflicting with those in other
packages.
80
package Person;
The scope of the package definition extends to the end of the file, or until another package keyword is encountered.
package Person;
sub new
{
my $class = shift;
my $self = {
_firstName => shift,
_lastName => shift,
_ssn
=> shift,
};
# Print all the values just for clarification.
print "First Name is $self->{_firstName}\n";
print "Last Name is $self->{_lastName}\n";
print "SSN is $self->{_ssn}\n";
bless $self, $class;
return $self;
}
Every method of a class passes first argument as class name. So in the above example class name would be "Person". You can
try this out by printing value of $class. Next rest of the arguments will be rest of the arguments passed to the method.
Now Let us see how to create an Object
package Person;
sub new
{
my $class = shift;
my $self = {};
bless $self, $class;
return $self;
}
Defining Methods
81
sub getFirstName {
return $self->{_firstName};
}
Another helper function to set person first name:
sub setFirstName {
my ( $self, $firstName ) = @_;
$self->{_firstName} = $firstName if defined($firstName);
return $self->{_firstName};
}
Lets have a look into complete example: Keep Person package and helper functions into Person.pm file
#!/usr/bin/perl
package Person;
sub new
{
my $class = shift;
my $self = {
_firstName => shift,
_lastName => shift,
_ssn
=> shift,
};
# Print all the values just for clarification.
print "First Name is $self->{_firstName}\n";
print "Last Name is $self->{_lastName}\n";
print "SSN is $self->{_ssn}\n";
bless $self, $class;
return $self;
}
sub setFirstName {
my ( $self, $firstName ) = @_;
$self->{_firstName} = $firstName if defined($firstName);
return $self->{_firstName};
}
sub getFirstName {
my( $self ) = @_;
return $self->{_firstName};
}
1;
Now create Person object in mail.pl fileas follows
#!/usr/bin/perl
use Person;
82
Inheritance
Object-oriented programming sometimes involves inheritance. Inheritance simply means allowing one class called the Child
to inherit methods and attributes from another, called the Parent, so you don't have to write the same code again and again. For
example, we can have a class Employee which inherits from Person. This is referred to as an "isa" relationship because an
employee is a person. Perl has a special variable, @ISA, to help with this. @ISA governs (method) inheritance.
Following are noteable points while using inheritance
Perl searches the class of the specified object for the specified object.
Perl searches the classes defined in the object class's @ISA array.
If no method is found in steps 1 or 2, then Perl uses an AUTOLOAD subroutine, if one is found in the @ISA tree.
If a matching method still cannot be found, then Perl searches for the method within the UNIVERSAL class
(package) that comes as part of the standard Perl library.
If the method still hasn't been found, then Perl gives up and raises a runtime exception.
So to create a new Employee class that will inherit methods and attributes from our Person class, we simply code: Keep this
code into Employee.pm
#!/usr/bin/perl
package Employee;
use Person;
use strict;
our @ISA = qw(Person);
Now Employee Class has all the methods and attributes inherited from Person class and you can use it as follows: Use main.pl
file to test it
#!/usr/bin/perl
use Employee;
83
Method Overriding
The child class Employee inherits all the methods from parent class Person. But if you would like to override those methods in
your child class then you can do it by givig your implementation. You can add your additional functions in child class. It can
done as follows: modify Employee.pm file
#!/usr/bin/perl
package Employee;
use Person;
use strict;
our @ISA = qw(Person);
# Override constructor
sub new {
my ($class) = @_;
# Call the constructor of the parent class, Person.
my $self = $class->SUPER::new( $_[1], $_[2], $_[3] );
# Add few more attributes
$self->{_id}
= undef;
$self->{_title} = undef;
bless $self, $class;
return $self;
}
# Override helper function
sub getFirstName {
my( $self ) = @_;
# This is child class function.
print "This is child class helper function\n";
return $self->{_firstName};
}
# Add more methods
sub setLastName{
my ( $self, $lastName ) = @_;
$self->{_lastName} = $lastName if defined($lastName);
84
#!/usr/bin/perl
use Employee;
$object = new Employee( "Mohammad", "Saleem", 23234345);
# Get first name which is set using constructor.
$firstName = $object->getFirstName();
print "Before Setting First Name is : $firstName\n";
# Now Set first name using helper function.
$object->setFirstName( "Mohd." );
# Now get first name set by helper function.
$firstName = $object->getFirstName();
print "After Setting First Name is : $firstName\n";
This will produce following result
First Name is Mohammad
Last Name is Saleem
SSN is 23234345
This is child class helper function
Before Setting First Name is : Mohammad
This is child class helper function
After Setting First Name is : Mohd.
Default Autoloading
Perl offers a feature which you would not find any many other programming languages: a default subroutine.
If you define a function called AUTOLOAD() then any calls to undefined subroutines will call AUTOLOAD() function. The
name of the missing subroutine is accessible within this subroutine as $AUTOLOAD. This function is very useful for error
handling purpose. Here is an example to implement AUTOLOAD, you can implement this function in your way.
sub AUTOLOAD
{
my $self = shift;
my $type = ref ($self) || croak "$self is not an object";
my $field = $AUTOLOAD;
$field =~ s/.*://;
unless (exists $self->{$field})
{
croak "$field does not exist in object/class $type";
}
if (@_)
85
For Example:
package MyClass;
...
sub DESTROY
{
print "
MyClass::DESTROY called\n";
}
#!/usr/bin/perl
# Following is the implementation of simple Class.
package MyClass;
sub new
{
print "
MyClass::new called\n";
my $type = shift;
# The package/type name
my $self = {};
# Reference to empty hash
return bless $self, $type;
}
sub DESTROY
{
86
MyClass::DESTROY called\n";
}
sub MyMethod
{
print "
MyClass::MyMethod called!\n";
}
# Following is the implemnetation of Inheritance.
package MySubClass;
@ISA = qw( MyClass );
sub new
{
print "
MySubClass::new called\n";
my $type = shift;
# The package/type name
my $self = MyClass->new;
# Reference to empty hash
return bless $self, $type;
}
sub DESTROY
{
print "
}
MySubClass::DESTROY called\n";
sub MyMethod
{
my $self = shift;
$self->SUPER::MyMethod();
print "
MySubClass::MyMethod called!\n";
}
# Here is the main program using above classes.
package main;
print "Invoke MyClass method\n";
$myObject = MyClass->new();
$myObject->MyMethod();
print "Invoke MySubClass method\n";
$myObject2 = MySubClass->new();
$myObject2->MyMethod();
print "Create a scoped object\n";
{
my $myObject2 = MyClass->new();
}
# Destructor is called automatically here
print "Create and undef an object\n";
$myObject3 = MyClass->new();
undef $myObject3;
print "Fall off the end of the script...\n";
# Remaining destructors are called automatically here
87
What is CGI ?
The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between
the web server and a custom script.
The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows:
The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information
servers such as HTTP servers.
Your browser contacts the HTTP web server and demand for the URL ie. filename.
Web Server will parse the URL and will look for the filename in if it finds that file then sends back to the browser
otherwise sends an error message indicating that you have requested a wrong file.
Web browser takes response from web server and displays either the received file or error message.
However, it is possible to set up the HTTP server so that whenever a file in a certain directory is requested that file is not sent
back; instead it is executed as a program, and whatever that program outputs is sent back for your browser to display. This
function is called the Common Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can
be a PERL Script, Shell Script, C or C++ program etc.
88
#!/usr/bin/perl
print
print
print
print
print
print
print
print
print
"Content-type:text/html\r\n\r\n";
'<html>';
'<head>';
'<title>Hello Word - First CGI Program</title>';
'</head>';
'<body>';
'<h2>Hello Word! This is my first CGI program</h2>';
'</body>';
'</html>';
1;
If you click hello.cgi then this produces following output:
This hello.cgi script is a simple PERL script which is writing its output on STDOUT file ie. screen.
There is one important and extra feature available which is first line to be printed Contenttype:text/html\r\n\r\n. This line is sent back to the browser and specifiy the content type to be
displayed on the browser screen. Now you must have undertood basic concept of CGI and you can
write many complicated CGI programs using PERL. This script can interact with any other exertnal
system also to exchange information such as RDBMS.
HTTP Header
89
Header
Description
Content-type: String
A MIME string defining the format of the file being returned. Example is
Content-type:text/html
The date the information becomes invalid. This should be used by the
browser to decide when a page needs to be refreshed. A valid date string
should be in the format 01 Jan 1998 12:00:00 GMT.
The URL that should be returned instead of the URL requested. You can
use this filed to redirect a request to any file.
Last-modified: String
Content-length: String
The length, in bytes, of the data being returned. The browser uses this
value to report the estimated download time for a file.
Set-Cookie: String
Description
CONTENT_TYPE
The data type of the content. Used when the client is sending attached
content to the server. For example file upload etc.
CONTENT_LENGTH
The length of the query information. It's available only for POST requests
HTTP_COOKIE
Return the set cookies in the form of key & value pair.
HTTP_USER_AGENT
PATH_INFO
QUERY_STRING
REMOTE_ADDR
The IP address of the remote host making the request. This can be useful
for logging or for authentication purpose.
REMOTE_HOST
The fully qualified name of the host making the request. If this information
is not available then REMOTE_ADDR can be used to get IR address.
REQUEST_METHOD
The method used to make the request. The most common methods are GET
90
SCRIPT_NAME
SERVER_NAME
SERVER_SOFTWARE
Here is small CGI program to list out all the CGI variables. Click this link to see the result Get Environment
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "<font size=+1>Environment</font>\n";
foreach (sort keys %ENV)
{
print "<b>$_</b>: $ENV{$_}<br>\n";
}
1;
This HTTP header will be different from the header mentioned in previous section.
For example,if you want make a FileName file downloadable from a given link then its syntax will be as follows.
#!/usr/bin/perl
# HTTP Header
print "Content-Type:application/octet-stream; name=\"FileName\"\r\n";
print "Content-Disposition: attachment; filename=\"FileName\"\r\n\n";
# Actual File Content will go hear.
open( FILE, "<FileName" );
while(read(FILE, $buffer, 100) )
{
print("$buffer");
}
http://www.test.com/cgi-bin/hello.cgi?key1=value1&key2=value2
The GET method is the defualt method to pass information from browser to web server and it produces a long string that
appears in your browser's Location:box. Never use the GET method if you have password or other sensitive information to
pass to the server. The GET method has size limtation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible in your CGI Program through
QUERY_STRING environment variable
You can pass information by simply concatenating key and value pairs alongwith any URL or you can use HTML <FORM>
tags to pass information using GET method.
#!/usr/bin/perl
local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "GET")
{
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$first_name = $FORM{first_name};
$last_name = $FORM{last_name};
print
print
print
print
print
print
print
print
print
"Content-type:text/html\r\n\r\n";
"<html>";
"<head>";
"<title>Hello - Second CGI Program</title>";
"</head>";
"<body>";
"<h2>Hello $first_name $last_name - Second CGI Program</h2>";
"</body>";
"</html>";
1;
92
First Name:
Last Name:
Submit
#!/usr/bin/perl
local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$first_name = $FORM{first_name};
$last_name = $FORM{last_name};
print "Content-type:text/html\r\n\r\n";
print "<html>";
93
"<head>";
"<title>Hello - Second CGI Program</title>";
"</head>";
"<body>";
"<h2>Hello $first_name $last_name - Second CGI Program</h2>";
"</body>";
"</html>";
1;
Let us take again same examle as above, which passes two values using HTML FORM and submit button. We are going to use
CGI script hello_post.cgi to handle this imput.
First Name:
Submit
Last Name:
Maths
Physics
Select Subject
Below is checkbox.cgi script to handle input given by web browser for radio button.
#!/usr/bin/perl
94
"Content-type:text/html\r\n\r\n";
"<html>";
"<head>";
"<title>Checkbox - Third CGI Program</title>";
"</head>";
"<body>";
"<h2> CheckBox Maths is : $maths_flag</h2>";
"<h2> CheckBox Physics is : $physics_flag</h2>";
"</body>";
"</html>";
1;
Maths
Physics
Select Subject
95
#!/usr/bin/perl
local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$subject = $FORM{subject};
print
print
print
print
print
print
print
print
print
"Content-type:text/html\r\n\r\n";
"<html>";
"<head>";
"<title>Radio - Fourth CGI Program</title>";
"</head>";
"<body>";
"<h2> Selected Subject is $subject</h2>";
"</body>";
"</html>";
1;
96
Submit
#!/usr/bin/perl
local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$text_content = $FORM{textcontent};
print
print
print
print
print
print
print
print
print
"Content-type:text/html\r\n\r\n";
"<html>";
"<head>";
"<title>Text Area - Fifth CGI Program</title>";
"</head>";
"<body>";
"<h2> Entered Text Content is $text_content</h2>";
"</body>";
"</html>";
1;
97
#!/usr/bin/perl
local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$subject = $FORM{dropdown};
print
print
print
print
print
print
print
print
print
"Content-type:text/html\r\n\r\n";
"<html>";
"<head>";
"<title>Dropdown Box - Sixth CGI Program</title>";
"</head>";
"<body>";
"<h2> Selected Subject is $subject</h2>";
"</body>";
"</html>";
1;
How It Works
Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it
is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie
is available for retrieval. Once retrieved, your server knows/remembers what was stored.
Cookies are a plain text data record of 5 variable-length fields:
Expires : The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Domain : The domain name of your site.
98
Secure : If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this
field is blank, no such restriction exists.
Name=Value : Cookies are set and retrviewed in the form of key and value pairs.
Setting up Cookies
This is very easy to send cookies to browser. These cookies will be sent along with HTTP Header. Assuming you want to set
UserID and Password as cookies. So it will be done as follows
#!/usr/bin/perl
print "Set-Cookie:UserID=XYZ;\n";
print "Set-Cookie:Password=XYZ123;\n";
print "Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT";\n";
print "Set-Cookie:Domain=www.tutorialspoint.com;\n";
print "Set-Cookie:Path=/perl;\n";
print "Content-type:text/html\r\n\r\n";
...........Rest of the HTML Content....
From this example you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies.
Here it is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending
magic line "Content-type:text/html\r\n\r\n.
Retrieving Cookies
This is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will
have following form.
key1=value1;key2=value2;key3=value3....
Here is an example of how to retrieving cookies.
#!/usr/bin/perl
$rcvd_cookies = $ENV{'HTTP_COOKIE'};
@cookies = split /;/, $rcvd_cookies;
foreach $cookie ( @cookies ){
($key, $val) = split(/=/, $cookie); # splits on the first =.
$key =~ s/^\s+//;
$val =~ s/^\s+//;
$key =~ s/\s+$//;
$val =~ s/\s+$//;
if( $key eq "UserID" ){
$user_id = $val;
}elsif($key eq "Password"){
$password = $val;
}
}
print "User ID = $user_id\n";
print "Password = $password\n";
This will produce following result
99
Unit IV
Introduction to ASP
An ASP file can contain text, HTML tags and scripts. Scripts in an ASP file are executed
on the server
HTML / XHTML
A scripting language like JavaScript or VBScript
What is ASP?
ASP stands for Active Server Pages
ASP is a program that runs inside IIS
IIS stands for Internet Information Services
IIS comes as a free component with Windows 2000
IIS is also a part of the Windows NT 4.0 Option Pack
The Option Pack can be downloaded from Microsoft
PWS is a smaller - but fully functional - version of IIS
PWS can be found on your Windows 95/98 CD
ASP Compatibility
ASP is a Microsoft Technology
To run IIS you must have Windows NT 4.0 or later
100
Provide security since your ASP code can not be viewed from the browser
Clever ASP programming can minimize the network traffic
ASP Syntax
You cannot view the ASP source code by selecting "View source" in a browser, you will
only see the output from the ASP file, which is plain HTML. This is because the scripts
are executed on the server before the result is sent back to the browser.
In our ASP tutorial, every example displays the hidden ASP source code. This will make
it easier for you to understand how it works.
101
There is also a shorthand method for the response.write command. The following
example also sends the text "Hello World" to the browser:
<html>
<body>
<%="Hello World!"%>
</body>
</html>
VBScript: You can use several scripting languages in ASP. However, the default
scripting language is VBScript:
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>
The example above writes "Hello World!" into the body of the document.
JavaScript
To set JavaScript as the default scripting language for a particular page you must insert a
language specification at the top of the page:
<%@ language="javascript"%>
<html>
<body>
<%
Response.Write("Hello World!")
%>
</body>
</html>
Note: Unlike VBScript - JavaScript is case sensitive. You will have to write your ASP
code with uppercase letters and lowercase letters when the language requires it.
102
Examples
Write text with ASP
How to write some text with ASP.
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>
Output Result:
ASP Variables
A variable is used to store information.
If the variable is declared outside a procedure it can be changed by any script in the ASP
file. If the variable is declared inside a procedure, it is created and destroyed every time
the procedure is executed.
Lifetime of Variables
A variable declared outside a procedure can be accessed and changed by any script in the
ASP file.
A variable declared inside a procedure is created and destroyed every time the procedure
is executed. No scripts outside the procedure can access or change the variable.
103
To declare variables accessible to more than one ASP file, declare them as session
variables or application variables.
Session Variables
Session variables are used to store information about ONE single user, and are available
to all pages in one application. Typically information stored in session variables are
name, id, and preferences.
Application Variables
Application variables are also available to all pages in one application. Application
variables are used to store information about ALL users in a specific application.
Examples
Declare a variable
Variables are used to store information. This example demonstrates how to declare a
variable, assign a value to it, and use the value in a text.
<html>
<body>
<%
dim name
name="Senthil"
response.write("My name is: " & name)
%>
</body>
</html>
Output Result:
104
Header 1
Header 2
Header 3
Header 4
Header 5
Header 6
105
Output Result:
Thu Sep 6 05:59:12 EDT 2007 (Norwegian Time)
Good Morning!
ASP Procedures
In ASP you can call a JavaScript procedure from a VBScript and vice versa.
Procedures
The ASP source code can contain procedures and functions:
<html>
<head>
<%
sub vbproc(num1,num2)
response.write(num1*num2)
end sub
106
Insert the <%@ language="language" %> line above the <html> tag to write procedures
or functions in another scripting language than default:
<%@ language="javascript" %>
<html>
<head>
<%
function jsproc(num1,num2)
{
Response.Write(num1*num2)
}
%>
</head>
<body>
<p>Result: <%jsproc(3,4)%></p>
</body>
</html>
Examples
Call a procedure using VBScript
How to call a VBScript procedure from ASP.
<html>
<head>
<%
sub vbproc(num1,num2)
response.write(num1*num2)
end sub
%>
</head>
<body>
<p>
You can call a procedure like this:
</p>
<p>
Result: <%call vbproc(3,4)%>
</p>
107
Result: 12
Or, like this:
Result: 12
Call a procedure using JavaScript
How to call a JavaScript procedure from ASP.
<%@ language="javascript" %>
<html>
<head>
<%
function jsproc(num1,num2)
{
Response.Write(num1*num2)
}
%>
</head>
<body>
<p>
Result: <%jsproc(3,4)%>
</p>
</body>
</html>
Output Result:
Result: 12
Call procedures using VBScript
How to call both a JavaScript procedure and a VBScript procedure in an ASP file.
<html>
<head>
<%
sub vbproc(num1,num2)
Response.Write(num1*num2)
end sub
%>
<script language="javascript" runat="server">
function jsproc(num1,num2)
{
Response.Write(num1*num2)
}
</script>
108
Output Result:
Result: 12
Result: 12
User Input
The Request object may be used to retrieve user information from forms.
Form example:
<form method="get" action="simpleform.asp">
First Name: <input type="text" name="fname" />
<br />
Last Name: <input type="text" name="lname" />
<br /><br />
<input type="submit" value="Submit" />
</form>
Request.QueryString
The Request.QueryString command is used to collect values in a form with
method="get". Information sent from a form with the GET method is visible to everyone
(it will be displayed in the browser's address bar) and has limits on the amount of
information to send.
If a user typed "Bill" and "Gates" in the form example above, the URL sent to the server
would look like this:
http://www.w3schools.com/simpleform.asp?fname=Bill&lname=Gates
Assume that the ASP file "simpleform.asp" contains the following script:
<body>
Welcome
<%
response.write(request.querystring("fname"))
response.write(" " & request.querystring("lname"))
%>
</body>
The browser will display the following in the body of the document:
109
Request.Form
The Request.Form command is used to collect values in a form with method="post".
Information sent from a form with the POST method is invisible to others and has no
limits on the amount of information to send.
If a user typed "Bill" and "Gates" in the form example above, the URL sent to the server
would look like this:
http://www.w3schools.com/simpleform.asp
Assume that the ASP file "simpleform.asp" contains the following script:
<body>
Welcome
<%
response.write(request.form("fname"))
response.write(" " & request.form("lname"))
%>
</body>
The browser will display the following in the body of the document:
Welcome Bill Gates
Form Validation
User input should be validated on the browser whenever possible (by client scripts).
Browser validation is faster and you reduce the server load.
You should consider using server validation if the user input will be inserted into a
database. A good way to validate a form on the server is to post the form to itself, instead
of jumping to a different page. The user will then get the error messages on the same
page as the form. This makes it easier to discover the error.
Examples
A form with method="get"
How to interact with the user, with the Request.QueryString command.
<html>
<body>
<form action="demo_reqquery.asp" method="get">
Your name: <input type="text" name="fname" size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.QueryString("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>
</body>
</html>
110
ASP Cookies
111
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.
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,2002#
%>
Output:
Firstname=Alex
112
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
113
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:
Examples
Welcome cookie
How to create a Welcome cookie.
<%
dim numvisits
response.cookies("NumVisits").Expires=date+365
numvisits=request.cookies("NumVisits")
if numvisits="" then
response.cookies("NumVisits")=1
response.write("Welcome! This is the first time you are visiting this Web page.")
else
response.cookies("NumVisits")=numvisits+1
response.write("You have visited this ")
response.write("Web page " & numvisits)
if numvisits=1 then
response.write " time before!"
else
response.write " times before!"
end if
114
Welcome! This is the first time you are visiting this Web page.
A new user requests an ASP file, and the Global.asa file includes a
Session_OnStart procedure
A user requests an ASP file, and the Global.asa file uses the <object> tag to
instantiate an object with session scope
115
Note: The main problem with sessions is WHEN they should end. We do not know if the
user's last request was the final one or not. So we do not know how long we should keep
the session "alive". Waiting too long for an idle session uses up resources on the server,
but if the session is deleted too soon the user has to start all over again because the server
has deleted all the information. Finding the right timeout interval can be difficult!
Tip: If you are using session variables, store SMALL amounts of data in them.
When the value is stored in a session variable it can be reached from ANY page in the
ASP application:
Welcome <%Response.Write(Session("username"))%>
116
Result:
username
age
If you do not know the number of items in the Contents collection, you can use the Count
property:
<%
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
%>
Result:
Session variables: 2
Donald Duck
50
Application Object
An application on the Web may be a group of ASP files. The ASP files work together to
perform some purpose. The Application object in ASP is used to tie these files together.
The Application object is used to store and access variables from any page, just like the
Session object. The difference is that ALL users share one Application object, while with
Sessions there is one Session object for EACH user.
The Application object should hold information that will be used by many pages in the
application (like database connection information). This means that you can access the
information from any page. It also means that you can change the information in one
place and the changes will automatically be reflected on all pages.
In the example above we have created two Application variables: "vartime" and "users".
You can access the value of an Application variable like this:
There are
<%
Response.Write(Application("users"))
%>
active connections.
If you do not know the number of items in the Contents collection, you can use the Count
property:
<%
dim i
dim j
j=Application.Contents.Count
For i=1 to j
118
Application events
Session events
<object> declarations
TypeLibrary declarations
Note: The Global.asa file must be stored in the root directory of the ASP application, and
each application can only have one Global.asa file.
Events in Global.asa
In Global.asa you can tell the application and session objects what to do when the
application/session starts and what to do when the application/session ends. The code for
this is placed in event handlers. The Global.asa file can contain four types of events:
Application_OnStart - This event occurs when the FIRST user calls the first page from
an ASP application. This event occurs after the Web server is restarted or after the
Global.asa file is edited. The "Session_OnStart" event occurs immediately after this
event.
Session_OnStart - This event occurs EVERY time a NEW user requests his or her first
page in the ASP application.
Session_OnEnd - This event occurs EVERY time a user ends a session. A user ends a
session after a page has not been requested by the user for a specified time (by default
this is 20 minutes).
Application_OnEnd - This event occurs after the LAST user has ended the session.
Typically, this event occurs when a Web server stops. This procedure is used to clean up
settings after the Application stops, like delete records or write information to text files.
A Global.asa file could look something like this:
<script language="vbscript" runat="server">
sub Application_OnStart
'some code
end sub
sub Application_OnEnd
'some code
end sub
sub Session_OnStart
'some code
end sub
sub Session_OnEnd
'some code
end sub
</script>
Note: Because we cannot use the ASP script delimiters (<% and %>) to insert scripts in
the Global.asa file, we put subroutines inside an HTML <script> element.
<object> Declarations
It is possible to create objects with session or application scope in Global.asa by using the
<object> tag.
Note: The <object> tag should be outside the <script> tag!
Syntax
<object runat="server" scope="scope" id="id"
{progid="progID"|classid="classID"}>
....
</object>
120
Parameter
Description
scope
id
ProgID
ClassID
Examples
The first example creates an object of session scope named "MyAd" by using the ProgID
parameter:
<object runat="server" scope="session" id="MyAd"
progid="MSWC.AdRotator">
</object>
The objects declared in the Global.asa file can be used by any script in the application:
GLOBAL.ASA:
<object runat="server" scope="session" id="MyAd"
progid="MSWC.AdRotator">
</object>
You could reference the object "MyAd" from any page in the ASP application:
SOME .ASP FILE:
<%=MyAd.GetAdvertisement("/banners/adrot.txt")%>
TypeLibrary Declarations
A TypeLibrary is a container for the contents of a DLL file corresponding to a COM
object. By including a call to the TypeLibrary in the Global.asa file, the constants of the
COM object can be accessed, and errors can be better reported by the ASP code. If your
Web application relies on COM objects that have declared data types in type libraries,
you can declare the type libraries in Global.asa.
Syntax
<!--METADATA TYPE="TypeLib"
file="filename"
uuid="typelibraryuuid"
version="versionnumber"
lcid="localeid"
121
Parameter
file
Description
Specifies an absolute path to a type library.
Either the file parameter or the uuid parameter is required
uuid
version
Optional. Used for selecting version. If the requested version is not found,
then the most recent version is used
lcid
Error Values
The server can return one of the following error messages:
Error Code
Description
ASP 0222
ASP 0223
ASP 0224
ASP 0225
Note: METADATA tags can appear anywhere in the Global.asa file (both inside and
outside <script> tags). However, it is recommended that METADATA tags appear near
the top of the Global.asa file.
Restrictions
Restrictions on what you can include in the Global.asa file:
You can not display text that is written in the Global.asa file. This file can't
display information
You can only use Server and Application objects in the Application_OnStart and
Application_OnEnd subroutines. In the Session_OnEnd subroutine, you can use
Server, Application, and Session objects. In the Session_OnStart subroutine you
can use any built-in object
122
Global.asa Example
In this example we will create a Global.asa file that counts the number of current visitors.
The Session_OnStart subroutine adds one to the variable "visitors" every time a
new visitor arrives
The Session_OnEnd subroutine subtracts one from "visitors" each time this
subroutine is triggered
123
124
Sending an HTML e-mail that sends a webpage from a file on your computer:
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.CreateMHTMLBody "file://c:/mydocuments/test.htm"
myMail.Send
set myMail=nothing
125
Response Object
The ASP Response object is used to send output to the user from the server. Its
collections, properties, and methods are described below:
Collections
Collection
Cookies
Description
Sets a cookie value. If the cookie does not exist, it will be created, and
take the value that is specified
Properties
Property
Description
126
Buffer
CacheControl
Sets whether a proxy server can cache the output generated by ASP or
not
Charset
ContentType
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
Pics
Status
Methods
Method
Description
AddHeader
AppendToLog
BinaryWrite
Clear
End
Flush
Redirect
Write
Examples
Write text with ASP
This example demonstrates how to write text with ASP.
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>
127
128
output Result:
Refsnesdata.no!
This example demonstrates a link, each time you load the page, it will display one of two
links: W3Schools.com! OR Refsnesdata.no! There is a 50% chance for each of them.
Controlling the buffer
This example demonstrates how you can control the buffer.
<%
Response.Buffer=true
%>
<html>
<body>
<p>
This text will be sent to your browser when my response buffer is flushed.
</p>
<%
Response.Flush
%>
</body>
</html>
129
Set how many minutes a page will be cached in a browser before it expires
This example demonstrates how to specify how many minutes a page will be cached in a
browser before it expires.
<%Response.Expires=-1%>
<html>
<body>
<p>This page will be refreshed with each access!</p>
</body>
</html>
The ASP Request object is used to get information from the user.
Request Object
When a browser asks for a page from a server, it is called a request. The ASP Request
object is used to get information from the user. Its collections, properties, and methods
are described below:
Collections
Collection
Description
ClientCertificate
Cookies
Form
Contains all the form (input) values from a form that uses the post
method
QueryString
ServerVariables
Properties
Property
TotalBytes
Description
Returns the total number of bytes the client sent in the body of the
request
Methods
Method
BinaryRead
Description
Retrieves the data sent to the server from the client as part of a post
request and stores it in a safe array
Syntax
Request.Form(element)[(index)|.Count]
Parameter
Description
131
element
Required. The name of the form element from which the collection is to
retrieve values
index
Examples
Example 1
You can loop through all the values in a form request. If a user filled out a form by specifying
two values - Blue and Green - for the color element, you could retrieve those values like this:
<%
for i=1 to Request.Form("color").Count
Response.Write(Request.Form("color")(i) & "<br />")
next
%>
Output:
Blue
Green
Example 2
Consider the following form:
<form action="submit.asp" method="post">
<p>First name: <input name="firstname"></p>
<p>Last name: <input name="lastname"></p>
<p>Your favorite color:
<select name="color">
<option>Blue</option>
<option>Green</option>
<option>Red</option>
<option>Yellow</option>
<option>Pink</option>
</select>
</p>
<p><input type="submit"></p>
</form>
Output:
Hi, John. Your favorite color is Red.
132
Syntax
Request.QueryString(variable)[(index)|.Count]
Parameter
Description
variable
Required. The name of the variable in the HTTP query string to retrieve
index
Examples
Example 1
To loop through all the n variable values in a Query String:
The following request is sent:
http://www.w3schools.com/test/names.asp?n=John&n=Susan
Example 2
The following string might be sent:
http://www.w3schools.com/test/names.asp?name=John&age=30
Output:
133
134
135
The form uses the POST method, which means that the information sent is invisible to
others, and it has no limits (you can send a large amount of information).
<html>
<body>
<form action="demo_simpleform1.asp" method="post">
First name:
<input type="text" name="fname" value="Donald" />
<br />
Last name:
<input type="text" name="lname" value="Duck" />
<br />
<input type="submit" value="Submit" />
</form>
<%
Response.Write(Request.Form)
%>
</body>
</html>
136
137
Other Examples
Get the server variables
This example demonstrates how to find out the visitors (yours) browser type, IP address,
and more with the ServerVariables collection.
<html>
<body>
<p>
<b>You are browsing this site with:</b>
<%Response.Write(Request.ServerVariables("http_user_agent"))%>
</p>
<p>
<b>Your IP address is:</b>
<%Response.Write(Request.ServerVariables("remote_addr"))%>
</p>
<p>
<b>The DNS lookup of the IP address is:</b>
<%Response.Write(Request.ServerVariables("remote_host"))%>
</p>
138
You are browsing this site with: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;
SV1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; MEGAUPLOAD
2.0)
Your IP address is: 59.92.8.182
The DNS lookup of the IP address is: 59.92.8.182
The method used to call the page: GET
The server's domain name: www.w3schools.com
The server's port: 80
The server's software: Microsoft-IIS/6.0
Create a welcome cookie
This example demonstrates how to create a Welcome Cookie with the Cookies
Collection.
<%
dim numvisits
response.cookies("NumVisits").Expires=date+365
numvisits=request.cookies("NumVisits")
if numvisits="" then
response.cookies("NumVisits")=1
response.write("Welcome! This is the first time you are visiting this Web page.")
else
response.cookies("NumVisits")=numvisits+1
response.write("You have visited this ")
response.write("Web page " & numvisits)
if numvisits=1 then
response.write " time before!"
else
response.write " times before!"
end if
end if
139
Server Object
The ASP Server object is used to access properties and methods on the server. Its
properties and methods are described below:
Properties
Property
ScriptTimeout
Description
Sets or returns the maximum number of seconds a script can run before
it is terminated
Methods
Method
CreateObject
Description
Creates an instance of an object
140
Execute
GetLastError()
HTMLEncode
MapPath
Transfer
Sends (transfers) all the information created in one ASP file to a second
ASP file
URLEncode
Syntax
Server.ScriptTimeout[=NumSeconds]
Parameter
NumSeconds
Description
The maximum number of seconds a script can run before the server
terminates it. Default is 90 seconds
Examples
Example 1
Set the script timeout:
<%
Server.ScriptTimeout=200
%>
Example 2
Retrieve the current value of the ScriptTimeout property:
<%
response.write(Server.ScriptTimeout)
%>
141
application scope, you can either use the <object> tag in the Global.asa file, or store the
object in a session or application variable.
Syntax
Server.CreateObject(progID)
Part
progID
Description
Required. The type of object to create
Example
Example 1
This example creates an instance of the server component MSWC.AdRotator:
<%
Set adrot=Server.CreateObject("MSWC.AdRotator")
%>
Example 2
An object stored in a session variable is destroyed when the session ends. However, you can
also destroy the object by setting the variable to Nothing or to a new value:
<%
Session("ad")=Nothing
%>
or
<%
Session("ad")="a new value"
%>
Example 3
You cannot create an instance of an object with the same name as a built-in object:
<%
Set Application=Server.CreateObject("Application")
Syntax
Server.Execute(path)
Parameter
path
Description
Required. The location of the ASP file to execute
Example
File1.asp:
142
File2.asp:
<%
response.write("I am in File 2!<br />")
%>
Output:
I am in File 1!
I am in File 2!
I am back in File 1!
Also look at the Server.Transfer method to see the difference between the Server.Execute
and Server.Transfer methods.
Examples
When was a file last modified?
Checks 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>
143
144
can manipulate files, folders, and directory paths. It is also possible to retrieve file system
information with this object.
The following code creates a text file (c:\test.txt) and then writes some text to the file:
<%
dim fs,fname
set fs=Server.CreateObject("Scripting.FileSystemObject")
set fname=fs.CreateTextFile("c:\test.txt",true)
fname.WriteLine("Hello World!")
fname.Close
set fname=nothing
set fs=nothing
%>
Properties
Property
Drives
Description
Returns a collection of all Drive objects on the computer
Methods
Method
Description
BuildPath
CopyFile
CopyFolder
CreateFolder
CreateTextFile
DeleteFile
DeleteFolder
DriveExists
FileExists
FolderExists
GetAbsolutePathName
Returns the complete path from the root of the drive for the
specified path
145
GetBaseName
GetDrive
GetDriveName
GetExtensionName
GetFile
GetFileName
Returns the file name or folder name for the last component in a
specified path
GetFolder
GetParentFolderName
GetSpecialFolder
GetTempName
MoveFile
MoveFolder
OpenTextFile
Examples
Does a specified file exist?
This example demonstrates how to first create a FileSystemObject Object, and then use
the FileExists method to check if the file exists.
<html>
<body>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
If (fs.FileExists("c:\winnt\cursors\3dgarro.cur"))=true Then
Response.Write("File c:\winnt\cursors\3dgarro.cur exists.")
Else
Response.Write("File c:\winnt\cursors\3dgarro.cur does not exist.")
End If
set fs=nothing
%>
</body>
</html>
146
148
3dgarro
cursors
winnt
Syntax
FileSystemObject.OpenTextFile(fname,mode,create,format)
Parameter
Description
fname
mode
create
Optional. Sets whether a new file can be created if the filename does not
exist. True indicates that a new file can be created, and False indicates that a
new file will not be created. False is default
format
Example
<%
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.OpenTextFile(Server.MapPath("testread.txt"),8,true)
f.WriteLine("This text will be added to the end of file")
f.Close
set f=Nothing
set fs=Nothing
%>
149
Syntax
FileSystemObject.CreateTextFile(filename[,overwrite[,unicode]])
FolderObject.CreateTextFile(filename[,overwrite[,unicode]])
Parameter
Description
filename
overwrite
unicode
150
To create an instance of the TextStream object you can use the CreateTextFile or
OpenTextFile methods of the FileSystemObject object, or you can use the
OpenAsTextStream method of the File object.
The TextStream object's properties and methods are described below:
Properties
Property
Description
AtEndOfLine
Returns true if the file pointer is positioned immediately before the endof-line marker in a TextStream file, and false if not
AtEndOfStream
Returns true if the file pointer is at the end of a TextStream file, and
false if not
Column
Line
Methods
Method
Description
Close
Read
ReadAll
ReadLine
Reads one line from a TextStream file and returns the result
Skip
SkipLine
Write
WriteLine
WriteBlankLines
151
Examples
Read textfile
This example demonstrates how to use the OpenTextFile method of the FileSystemObject
to create a TextStream Object. The ReadAll method of the TextStream Object reads from
the opened text file.
<html>
<body>
<p>This is the text in the text file:</p>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.OpenTextFile(Server.MapPath("testread.txt"), 1)
Response.Write(f.ReadAll)
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>
152
153
Return line-number
This example demonstrates how to return the current line number in a TextStream file.
<html>
<body>
<p>This is all the lines in the text file (with line numbers):</p>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.OpenTextFile(Server.MapPath("testread.txt"), 1)
154
This is all the lines in the text file (with line numbers):
Line:1 Hello!
Line:2 How are you today?
He
The cursor is now standing in position 3 in the text file.
155
Syntax
TextStreamObject.WriteLine(text)
Parameter
text
Description
Optional. The text to write to the file. If you do not specify this parameter, a
new-line character will be written to the file
Example
<%
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.CreateTextFile("c:\test.txt",true)
f.WriteLine("Hello World!")
f.WriteLine("How are you today?")
f.WriteLine("Goodbye!")
f.close
set f=nothing
set fs=nothing
%>
The file test.txt will look like this after executing the code above:
Hello World!
How are you today?
Goodbye!
Syntax
TextStreamObject.Write(text)
Parameter
text
Description
Required. The text to write to the file
156
Example
<%
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.CreateTextFile("c:\test.txt",true)
f.write("Hello World!")
f.write("How are you today?")
f.close
set f=nothing
set fs=nothing
%>
The file test.txt will look like this after executing the code above:
Hello World!How are you today?
Syntax
TextStreamObject.WriteBlankLines(numlines)
Parameter
numlines
Description
Required. The number of new-line characters to write to the file
Example
<%
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.CreateTextFile("c:\test.txt",true)
f.WriteLine("Hello World!")
f.WriteBlankLines(2)
f.WriteLine("How are you today?")
f.close
set f=nothing
set fs=nothing
%>
The file test.txt will look like this after executing the code above:
Hello World!
How are you today?
157
Introduction to ADO
ADO can be used to access databases from your web pages.
What is ADO?
ADO is a Microsoft technology
ADO stands for ActiveX Data Objects
ADO is a Microsoft Active-X component
ADO is automatically installed with Microsoft IIS
ADO is a programming interface to access data in a database
Properties
Property
Description
Attributes
CommandTimeout
ConnectionString
ConnectionTimeout
159
to open
CursorLocation
DefaultDatabase
IsolationLevel
Mode
Provider
State
Version
Methods
Method
Description
BeginTrans
Cancel
Cancels an execution
Close
Closes a connection
CommitTrans
Execute
Open
Opens a connection
OpenSchema
RollbackTrans
Events
Note: You cannot handle events using VBScript or JScript (only Visual Basic,
Visual C++, and Visual J++ languages can handle events).
Event
Description
BeginTransComplete
CommitTransComplete
ConnectComplete
Disconnect
ExecuteComplete
InfoMessage
RollbackTransComplete
WillConnect
WillExecute
Collections
Collection
Description
Errors
Properties
additions by other users, and it prevents access to records that other users
have deleted. Data changes by other users will still be visible.
Static cursor - Provides a static copy of a recordset for you to use to find
data or generate reports. Additions, changes, or deletions by other users will
not be visible. This is the only type of cursor allowed when you open a
client-side Recordset object.
Forward-only cursor - Allows you to only scroll forward through the
Recordset. Additions, changes, or deletions by other users will not be
visible.
The cursor type can be set by the CursorType property or by the CursorType
parameter in the Open method.
Note: Not all providers support all methods or properties of the Recordset object.
Properties
Property
Description
AbsolutePage
AbsolutePosition
ActiveCommand
ActiveConnection
BOF
Bookmark
CacheSize
CursorLocation
CursorType
DataMember
162
DataSource
EditMode
EOF
Filter
Index
LockType
MarshalOptions
MaxRecords
PageCount
PageSize
RecordCount
Sort
Source
State
Status
StayInSync
Methods
Method
Description
163
AddNew
Cancel
Cancels an execution
CancelBatch
CancelUpdate
Clone
Close
Closes a Recordset
CompareBookmarks
Delete
Find
GetRows
GetString
Move
MoveFirst
MoveLast
MoveNext
MovePrevious
NextRecordset
Open
Requery
Resync
Save
164
Seek
Supports
Update
UpdateBatch
Events
Note: You cannot handle events using VBScript or JScript (only Visual Basic,
Visual C++, and Visual J++ languages can handle events).
Event
Description
EndOfRecordset
FetchComplete
FetchProgress
FieldChangeComplete
MoveComplete
RecordChangeComplete
RecordsetChangeComplete
WillChangeField
WillChangeRecord
WillChangeRecordset
WillMove
Collections
Collection
Description
165
Fields
Properties
Description
Returns the number of items in the fields collection.
Starts at zero.
Example:
countfields = rs.Fields.Count
Item(named_item/number)
Description
Returns the number of items in the properties collection.
Starts at zero.
Example:
countprop = rs.Properties.Count
Item(named_item/number)
Examples
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
166
set rs = Server.CreateObject("ADODB.recordset")
rs.Open "Select * from Customers", conn
'The first number indicates how many records to copy
'The second number indicates what recordnumber to start on
p=rs.GetRows(2,0)
response.write("<p>This example returns the value of the first
column in the first two records:</p>")
response.write(p(0,0))
response.write("<br>")
response.write(p(0,1))
response.write("<p>This example returns the value of the first
three columns in the first record:</p>")
response.write(p(0,0))
response.write("<br>")
response.write(p(1,0))
response.write("<br>")
response.write(p(2,0))
rs.close
conn.close
%>
</body>
</html>
<td><input name="custid"></td>
</tr><tr>
<td>Company Name:</td>
<td><input name="compname"></td>
</tr><tr>
<td>Contact Name:</td>
<td><input name="contname"></td>
</tr><tr>
<td>Address:</td>
<td><input name="address"></td>
</tr><tr>
<td>City:</td>
<td><input name="city"></td>
</tr><tr>
<td>Postal Code:</td>
<td><input name="postcode"></td>
</tr><tr>
<td>Country:</td>
<td><input name="country"></td>
</tr>
</table>
<br /><br />
<input type="submit" value="Add New">
<input type="reset" value="Cancel">
</form>
</body>
</html>
When the user presses the submit button the form is sent to a file called
"demo_add.asp". The "demo_add.asp" file contains the code that will add a new
record to the Customers table:
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
sql="INSERT INTO customers (customerID,companyname,"
sql=sql & "contactname,address,city,postalcode,country)"
sql=sql & " VALUES "
sql=sql & "('" & Request.Form("custid") & "',"
sql=sql & "'" & Request.Form("compname") & "',"
sql=sql & "'" & Request.Form("contname") & "',"
sql=sql & "'" & Request.Form("address") & "',"
sql=sql & "'" & Request.Form("city") & "',"
168
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers",conn
%>
<h2>List Database</h2>
<table border="1" width="100%">
<tr>
<%
for each x in rs.Fields
response.write("<th>" & ucase(x.name) & "</th>")
next
%>
</tr>
<% do until rs.EOF %>
<tr>
<form method="post" action="demo_update.asp">
<%
for each x in rs.Fields
if lcase(x.name)="customerid" then%>
<td>
<input type="submit" name="customerID" value="<
%=x.value%>">
</td>
<%else%>
<td><%Response.Write(x.value)%></td>
<%end if
next
%>
</form>
<%rs.MoveNext%>
</tr>
<%
loop
conn.close
%>
</table>
</body>
</html>
If the user clicks on the button in the "customerID" column he or she will be taken
to a new file called "demo_update.asp". The "demo_update.asp" file contains the
source code on how to create input fields based on the fields from one record in
170
the database table. It also contains a "Update record" button that will save your
changes:
<html>
<body>
<h2>Update Record</h2>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
cid=Request.Form("customerID")
if Request.form("companyname")="" then
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers WHERE customerID='" &
cid & "'",conn
%>
<form method="post" action="demo_update.asp">
<table>
<%for each x in rs.Fields%>
<tr>
<td><%=x.name%></td>
<td><input name="<%=x.name%>" value="<%=x.value%>"></td>
<%next%>
</tr>
</table>
<br /><br />
<input type="submit" value="Update record">
</form>
<%
else
sql="UPDATE customers SET "
sql=sql & "companyname='" & Request.Form("companyname") &
"',"
sql=sql & "contactname='" & Request.Form("contactname") &
"',"
sql=sql & "address='" & Request.Form("address") & "',"
sql=sql & "city='" & Request.Form("city") & "',"
sql=sql & "postalcode='" & Request.Form("postalcode") &
"',"
sql=sql & "country='" & Request.Form("country") & "'"
sql=sql & " WHERE customerID='" & cid & "'"
on error resume next
conn.Execute sql
if err<>0 then
response.write("No update permissions!")
else
171
172
</td>
<%else%>
<td><%Response.Write(x.value)%></td>
<%end if
next
%>
</form>
<%rs.MoveNext%>
</tr>
<%
loop
conn.close
%>
</table>
</body>
</html>
If the user clicks on the button in the "customerID" column he or she will be taken
to a new file called "demo_delete.asp". The "demo_delete.asp" file contains the
source code on how to create input fields based on the fields from one record in
the database table. It also contains a "Delete record" button that will delete the
current record:
<html>
<body>
<h2>Delete Record</h2>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
cid=Request.Form("customerID")
if Request.form("companyname")="" then
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers WHERE customerID='" &
cid & "'",conn
%>
<form method="post" action="demo_delete.asp">
<table>
<%for each x in rs.Fields%>
<tr>
<td><%=x.name%></td>
<td><input name="<%=x.name%>" value="<%=x.value%>"></td>
<%next%>
</tr>
</table>
<br /><br />
173
<%
else
sql="DELETE FROM customers"
sql=sql & " WHERE customerID='" & cid & "'"
on error resume next
conn.Execute sql
if err<>0 then
response.write("No update permissions!")
else
response.write("Record " & cid & " was deleted!")
end if
end if
conn.close
%>
</body>
Display the Records
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs = Server.CreateObject("ADODB.recordset")
rs.Open "Select * from Customers", conn
do until rs.EOF
for each x in rs.Fields
Response.Write(x.name)
Response.Write(" = ")
Response.Write(x.value & "<br />")
next
Response.Write("<br />")
rs.MoveNext
loop
rs.close
conn.close
%>
</body>
174
</html>
175
Components
ASP AdRotator Component
The ASP AdRotator component creates an AdRotator object that displays a
different image each time a user enters or refreshes a page. A text file includes
information about the images.
Syntax
<%
set adrotator=server.createobject("MSWC.AdRotator")
adrotator.GetAdvertisement("textfile.txt")
%>
Example
Assume we have a file called "banners.asp". It looks like this:
<html>
<body>
<%
set adrotator=Server.CreateObject("MSWC.AdRotator")
response.write(adrotator.GetAdvertisement("ads.txt"))
%>
</body>
</html>
The file "ads.txt" looks like this:
*
w3schools.gif
http://www.w3schools.com/
Visit W3Schools
80
microsoft.gif
http://www.microsoft.com/
Visit Microsoft
20
The lines below the asterisk in the file "ads.txt" specifies the images to be
displayed, the hyperlink addresses, the alternate text (for the images), and the
display rates in percent of the hits. We see that the W3Schools image will be
176
displayed for 80 % of the hits and the Microsoft image will be displayed for 20 %
of the hits in the text file above.
Note: To get the links to work when a user clicks on them, we will have to modify
the file "ads.txt" a bit:
REDIRECT banners.asp
*
w3schools.gif
http://www.w3schools.com/
Visit W3Schools
80
microsoft.gif
http://www.microsoft.com/
Visit Microsoft
20
The redirection page (banners.asp) will now receive a querystring with a variable
named URL containing the URL to redirect to.
Note: To specify the height, width, and border of the image, you can insert the
following lines under REDIRECT:
REDIRECT banners.asp
WIDTH 468
HEIGHT 60
BORDER 0
*
w3schools.gif
...
...
The last thing to do is to add some lines of code to the "banners.asp" file:
<%
url=Request.QueryString("url")
If url<>"" then Response.Redirect(url)
%>
<html>
<body>
<%
set adrotator=Server.CreateObject("MSWC.AdRotator")
response.write(adrotator.GetAdvertisement("textfile.txt"))
%>
</body>
</html>
177
That's all!!
Properties
Property
Description
Example
Border
<%
set
adrot=Server.CreateObject("MSWC.AdRotator"
Specifies the size of
)
the borders around
adrot.Border="2"
the advertisement
Response.Write(adrot.GetAdvertisement("ads.tx
t"))
%>
Clickable
<%
set
adrot=Server.CreateObject("MSWC.AdRotator"
Specifies whether the
)
advertisement is a
adrot.Clickable=false
hyperlink
Response.Write(adrot.GetAdvertisement("ads.tx
t"))
%>
TargetFrame
Methods
Method
GetAdvertisement
Description
Example
<%
set
Returns HTML
adrot=Server.CreateObject("MSWC.AdRotator"
that displays the
)
advertisement in
Response.Write(adrot.GetAdvertisement("ads.tx
the page
t"))
%>
178
Examples
Simple AdRotator Example
This example shows how to use the AdRotator component to display a different
advertisement image, each time a user visits or refreshes the page.
<html>
<body>
<%
set adrotator=Server.CreateObject("MSWC.AdRotator")
adrotator.Border="2"
Response.Write(adrotator.GetAdvertisement("text/advertisement
s.txt"))
%>
<p>
NOTE: Because images are changed randomly, and because this
page has few images to choose from, it will often display the
same advertisement twice in a row.
</p>
<p>
<a href="text/advertisements.txt">
<img border="0" src="/images/btn_view_text.gif">
</a>
</p>
</body>
</html>
179
Syntax
<%
Set MyBrow=Server.CreateObject("MSWC.BrowserType")
%>
The example below creates a BrowserType object in an ASP file, and displays a
table showing some of the capabilities of the current browser:
<html>
<body>
<%
Set MyBrow=Server.CreateObject("MSWC.BrowserType")
%>
<table border="1" width="100%">
<tr>
<th>Client OS</th>
<th><%=MyBrow.platform%></th>
</tr><tr>
<td >Web Browser</td>
<td ><%=MyBrow.browser%></td>
</tr><tr>
<td>Browser version</td>
<td><%=MyBrow.version%></td>
</tr><tr>
<td>Frame support?</td>
<td><%=MyBrow.frames%></td>
</tr><tr>
<td>Table support?</td>
<td><%=MyBrow.tables%></td>
</tr><tr>
<td>Sound support?</td>
<td><%=MyBrow.backgroundsounds%></td>
</tr><tr>
<td>Cookies support?</td>
<td><%=MyBrow.cookies%></td>
</tr><tr>
<td>VBScript support?</td>
<td><%=MyBrow.vbscript%></td>
</tr><tr>
<td>JavaScript support?</td>
<td><%=MyBrow.javascript%></td>
</tr>
</table>
</body>
</html>
180
Output:
Client OS
WinNT
Web Browser
IE
Browser version
5.0
Frame support?
True
Table support?
True
Sound support?
True
Cookies support?
True
VBScript support?
True
JavaScript support?
True
Description
Optional. Any line that starts with a semicolon are ignored by the
BrowserType object
Optional. Specifies the HTTP User Agent header to associate with the
HTTPUserA
browser-property value statements specified in propertyN. Wildcard
gentHeader
characters are allowed
browserDefi Optional. Specifies the HTTP User Agent header-string of a browser to use
nition
as the parent browser. The current browser's definition will inherit all of
181
valueN
182
vbscript=TRUE
javascript=TRUE
javaapplets=TRUE
ActiveXControls=TRUE
beta=False
;DEFAULT BROWSER
[*]
browser=Default
frames=FALSE
tables=TRUE
cookies=FALSE
backgroundsounds=FALSE
vbscript=FALSE
javascript=FALSE
Examples
<html>
<body>
<%
Set MyBrow=Server.CreateObject("MSWC.BrowserType")
%>
<table border="1" width="65%">
<tr>
<td width="52%">Client OS</td>
<td width="48%"><%=MyBrow.platform%></td>
</tr>
<tr>
<td >Web Browser</td>
<td ><%=MyBrow.browser%></td>
</tr>
<tr>
<td>Browser version</td>
<td><%=MyBrow.version%></td>
</tr>
<tr>
<td>Frame support?</td>
<td><%=MyBrow.frames%></td>
</tr>
<tr>
<td>Table support?</td>
<td><%=MyBrow.tables%></td>
</tr>
<tr>
183
<td>Sound support?</td>
<td><%=MyBrow.backgroundsounds%></td>
</tr>
<tr>
<td>Cookies support?</td>
<td><%=MyBrow.cookies%></td>
</tr>
<tr>
<td>VBScript support?</td>
<td><%=MyBrow.vbscript%></td>
</tr>
<tr>
<td>JavaScript support?</td>
<td><%=MyBrow.javascript%></td>
</tr>
</table>
</body>
</html>
file="nlcode.inc"-->. This line will include the code below on every page listed in
"links.txt" and the navigation will work.
"nlcode.inc":
<%
'Use the Content Linking Component
'to navigate between the pages listed
'in links.txt
dim nl
Set nl=Server.CreateObject("MSWC.NextLink")
if (nl.GetListIndex("links.txt")>1) then
Response.Write("<a href='" &
nl.GetPreviousURL("links.txt"))
Response.Write("'>Previous Page</a>")
end if
Response.Write("<a href='" & nl.GetNextURL("links.txt"))
Response.Write("'>Next Page</a>")
%>
The ASP Content Linking Component's methods are described below:
Methods
Met
hod
Description
Example
<%
dim nl,c
Set
nl=Server.CreateObject("MSWC.NextLink"
)
Get
List Returns the number of items listed in c=nl.GetListCount("links.txt")
Response.Write("There are ")
Cou the Content Linking List file
Response.Write(c)
nt
Response.Write(" items in the list")
%>
Output:
There are 4 items in the list
Get Returns the index number of the
ListI current item in the Content Linking
ndex List file. The index number of the
first item is 1. 0 is returned if the
current page is not in the Content
Linking List file
185
<%
dim nl,c
Set
nl=Server.CreateObject("MSWC.NextLink"
)
c=nl.GetListIndex("links.txt")
Response.Write("Item number ")
Response.Write(c)
%>
Output:
Item number 3
Get
Next
Desc
ripti
on
<%
dim nl,c
Set
nl=Server.CreateObject("MSWC.NextLink"
)
c=nl.GetNextDescription("links.txt")
Response.Write("Next ")
Response.Write("description is: ")
Response.Write(c)
%>
Next description is: ASP Variables
<%
dim nl,c
Set
nl=Server.CreateObject("MSWC.NextLink"
Returns the URL of the next item
Get listed in the Content Linking List file. )
Next If the current page is not found in the c=nl.GetNextURL("links.txt")
URL list file it returns the URL of the last Response.Write("Next ")
Response.Write("URL is: ")
page on the list
Response.Write(c)
%>
Next URL is: asp_variables.asp
Get
Nth Returns the description of the Nth
Desc page listed in the Content Linking
ripti List file
on
<%
dim nl,c
Set
nl=Server.CreateObject("MSWC.NextLink"
)
c=nl.GetNthDescription("links.txt",3)
Response.Write("Third ")
Response.Write("description is: ")
Response.Write(c)
%>
Third description is: ASP Variables
nl=Server.CreateObject("MSWC.NextLink"
)
c=nl.GetNthURL("links.txt",3)
Response.Write("Third ")
Response.Write("URL is: ")
Response.Write(c)
%>
Third URL is: asp_variables.asp
GetP
revi
ous
Desc
ripti
on
<%
dim nl,c
Set
nl=Server.CreateObject("MSWC.NextLink"
)
c=nl.GetPreviousDescription("links.txt")
Response.Write("Previous ")
Response.Write("description is: ")
Response.Write(c)
%>
Previous description is: ASP Variables
<%
dim nl,c
Set
nl=Server.CreateObject("MSWC.NextLink"
)
c=nl.GetPreviousURL("links.txt")
Response.Write("Previous ")
Response.Write("URL is: ")
Response.Write(c)
%>
Previous URL is: asp_variables.asp
Example
<html>
<body>
<p>
The example below builds a table of contents.
</p>
<%
187
dim c
dim i
set nl=server.createobject("MSWC.Nextlink")
c = nl.GetListCount("text\links.txt")
i=1
%>
<ul>
<%do while (i <= c) %>
<li><a href="<%=nl.GetNthURL("text\links.txt", i)%>">
<%=nl.GetNthDescription("text\links.txt", i)%></a>
<%
i = (i + 1)
loop
%>
</ul>
<p>
The text file contains a list of page urls
and link descriptions. It contains one line of text for each page.
Note that the url and
description MUST be separated by the TAB character.
</p>
<p>
<a href="text/links.txt"><img border="0"
src="/images/btn_view_text.gif"></a>
</p>
</body>
Output Result:
The example below builds a table of contents.
ASP Intro
ASP Syntax
ASP Variables
ASP Procedures
The text file contains a list of page urls and link descriptions. It contains one line
of text for each page. Note that the url and description MUST be separated by the
TAB character.
Text file content
188
asp_intro.asp
ASP
asp_syntax.asp
ASP
asp_variables.asp ASP
asp_procedures.asp ASP
Intro
Syntax
Variables
Procedures
"textads.txt":
%% #1
This is a great day!!
%% #2
<h1>Smile</h1>
%% #3
<img src="smiley.gif">
%% #4
Here's a <a href="http://www.w3schools.com">link.</a>
Notice the #number at the beginning of each content string. This number is an
189
optional parameter that indicates the relative weight of the HTML content string.
In this example, the Content Rotator will display the first content string one-tenth
of the time, the second string two-tenths of the time, the third string three-tenths of
the time, and the fourth string four-tenths of the time.
Then, create an ASP file, and insert the following code:
<html>
<body>
<%
set cr=server.createobject("MSWC.ContentRotator")
response.write(cr.ChooseContent("text/textads.txt"))
%>
</body>
</html>
Description
Example
<%
dim cr
Set
cr=Server.CreateObject("MSWC.ContentR
otator")
response.write(cr.ChooseContent("text/text
ads.txt"))
%>
Output:
190
ile y
Here's a link.
191