Web Technologies
Web Technologies
Web Technologies
Lecture 1-9
Definitions
1. A web browser is a software application that enables a user to display and interact
with text, images, videos, music and other information typically located on a Web page at
a website on the World Wide Web or a local area network. Text and images on a Web
page can contain hyperlinks to other Web pages at the same or different website. Web
browsers allow a user to quickly and easily access information provided on many Web
pages at many websites by traversing these links. Web browsers format HTML
information for display, so the appearance of a Web page may differ between browsers.
Some of the Web browsers available for personal computers include Internet Explorer,
Mozilla Firefox, Safari, Opera, and Netscape
2. A Web page or webpage is a resource of information that is suitable for the World
Wide Web and can be accessed through a web browser. This information is usually in
HTML or XHTML format, and may provide navigation to other web pages via hypertext
links.
Web pages may be retrieved from a local computer or from a remote web server. The
web server may restrict access only to a private network, e.g. a corporate intranet, or it
may publish pages on the World Wide Web. Web pages are requested and served from
web servers using Hypertext Transfer Protocol (HTTP).
Web pages may consist of files of static text stored within the web server's file system
(static web pages), or the web server may construct the (X)HTML for each web page
when it is requested by a browser (dynamic web pages). Client-side scripting can make
web pages more responsive to user input once in the client browser.
3. Web site (alternatively, website or web site) is a collection of Web pages, images,
videos or other digital assets that is hosted on one or several Web server(s), usually
accessible via the Internet, cell phone or a LAN.
A Web page is a document, typically written in HTML, that is almost always accessible
via HTTP, a protocol that transfers information from the Web server to display in the
user's Web browser.
All publicly accessible websites are seen collectively as constituting the "World Wide
Web".
The pages of websites can usually be accessed from a common root URL called the
homepage, and usually reside on the same physical server. The URLs of the pages
organize them into a hierarchy, although the hyperlinks between them control how the
reader perceives the overall structure and how the traffic flows between the different
parts of the sites.
Some websites require a subscription to access some or all of their content. Examples of
subscription sites include many business sites, parts of many news sites, academic journal
sites, gaming sites, message boards, Web-based e-mail, services, social networking
website, and sites providing real-time stock market data.
(2) A computer that is connected to a TCP/IP network, including the Internet. Each host
has a unique IP address.
(3) To provide the infrastructure for a computer service. For example, there are many
companies that host files, programs, applications or even a Web server for companies and
individuals. In the case of a Web server, it means that they provide the hardware,
software, and communications lines required by the server, but the content on the server
may be controlled by someone else.
WEB SERVER
1. A computer program that is responsible for accepting HTTP requests from clients,
which are known 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 which provides the functionality
described in the first sense of the term.
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 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 the request, 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 log files.
Bandwidth throttling to limit the speed of responses in order to not saturate the
network and to be able to serve more clients.
HEAD
Asks for the response identical to the one that would correspond to a GET
request, but without the response body. This is useful for retrieving meta-
information written in response headers, without having to transport the entire
content.
GET
Requests a representation of the specified resource. By far the most common
method used on the Web today. Should not be used for operations that cause side-
effects (using it for actions in web applications is a common misuse). See 'safe
methods' below.
POST
Submits data to be processed (e.g. from an HTML form) to the identified
resource. The data is included in the body of the request. This may result in the
creation of a new resource or the updates of existing resources or both.
PUT
Uploads a representation of the specified resource.
DELETE
Deletes the specified resource.
TRACE
Echoes back the received request, so that a client can see what intermediate
servers are adding or changing in the request.
OPTIONS
Returns the HTTP methods that the server supports. This can be used to check the
functionality of a web server.
CONNECT
Converts the request connection to a transparent TCP/IP tunnel, usually to
facilitate SSL-encrypted communication (HTTPS) through an unencrypted HTTP
proxy.[1]
Introduction to Microsoft IIS
IIS 6.0 includes new features designed to help businesses, IT professionals, and Web
administrators achieve their goals of performance, reliability, scalability, and security for
potentially thousands of Web sites either on a single IIS server or on multiple servers.
This section describes new and notable features in IIS 6.0.
Reliability Features: Describes new modes of operation and World Wide Web
Publishing Service (WWW service) processes.
Security Features: Describes new features designed to secure your Web sites, data, and
your IIS server.
Performance Features: Describes performance and scalability features.
Web Application Technologies: Describes the IIS 6.0 implementation of Microsoft®
ASP.NET, ASP, and the ADSI provider.
Administrative Tools and Features: Describes metabase changes and new administrative
tools.
Internet Standards: Describes support for Web and Internet standard protocols.
Internet Protocol Version 6 Features: Describes the IIS 6.0 functionality that supports
Internet Protocol Version 6 (Ipv6).
Virtual Directories
A sub-directory of a web-site in IIS can be either a physical sub-directory, or it can be a Virtual Directory
that is logically mapped to that location. It really should not matter whether the directory is a physical
sub-directory or a Virtual Directory, just like the location of the web-root isn't exposed. In most production
cases, especially with shared web-hosts, you will only be able to create physical sub-directories, probably
using FTP or similar tools.
If you open up the Internet Services Manager in your Administrative Tools, also called IIS Manager, and
drill down you will see the logical structures. Physical directories are shown with a folder icon, while Virtual
Directories are shown with a special folder icon that has a globe as part of the icon. You may also see
another icon, either a box around a globe icon (Win 2K/XP) or a gear icon (W2003), which indicates the
directory is an IIS Application.
IIS Applications
An IIS Application is a directory, physical or virtual, that has been setup in a manner that makes it
logically independent from the rest of the web-site. Its purpose is basically to make sub-directories act
just like real web-sites, which is very useful on Win 2K/XP Pro, but not really necessary on a Server. Its
important to understand that you cannot create an IIS Application simply using FTP or similar tools -- and
this is the cause of many ASP.NET problems.
So how do you create an IIS Application? First, VS.NET automatically makes all new web projects into IIS
Applications, whether you want it to be or not. Otherwise, you need to use IIS Manager to create or setup
an IIS Application, or get your web-host to do it for you (WebHost4Life.com has a tool for this). The
easiest technique is to use IIS Manager to create a new Virtual Directory -- it will also be an IIS
Application by default, which adds to the confusion.
In most cases, the content you publish to your Web or FTP site is located in a root or
home directory on your computer, such as C:\Inetpub\Wwwroot\. However, there might
be instances when the content is located somewhere else, or even on a remote computer.
To publish from any directory not contained within your home or root directory, you can
create a virtual directory. A virtual directory is a directory that is not contained in the
home directory but appears to client browsers as though it were.
You can create a virtual directory through IIS Manager or by using Windows Explorer.
1. From the Start menu, point to Administrative Tools, and then click Internet
Information Services (IIS) Manager.
You can also access IIS from the Computer Management window. Accessing IIS in this
way does not give you the range of administration options offered by IIS Manager;
however, it does offer quick access and limited management options for your Web sites.
HTML 4.0
With HTML 4.0 all formatting can be moved out of the HTML document and into a
separate style sheet. Because HTML 4.0 separates the presentation of the document from
its structure, we have total control of presentation layout without messing up the
document content.
With CSS we have a style and layout model for HTML documents.
CSS was a breakthrough in Web design because it allowed developers to control the style
and layout of multiple Web pages all at once. As a Web developer you can define a style
for each HTML element and apply it to as many Web pages as you want. To make a
global change, simply change the style, and all elements in the Web are updated
automatically.
JavaScript
Required Fields
The function below checks if a required field has been left empty. If the required field is
blank, an alert box alerts a message and the function returns false. If a value is entered,
the function returns true (means that data is OK):
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{alert(alerttxt);return false}
else {return true}
}
}
The entire script, with the HTML form could look something like this:
<html>
<head>
<script type="text/javascript">
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{alert(alerttxt);return false}
else {return true}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(email,"Email must be filled out!")==false)
{email.focus();return false}
}
}
</script>
</head>
<body>
<form action="submitpage.htm"
onsubmit="return validate_form(this)"
method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit">
</form>
</body>
</html>
E-mail Validation
The function below checks if the content has the general syntax of an email.
This means that the input data must contain at least an @ sign and a dot (.). Also, the @
must not be the first character of the email address, and the last dot must at least be one
character after the @ sign:
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@")
dotpos=value.lastIndexOf(".")
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false}
else {return true}
}
}
The entire script, with the HTML form could look something like this:
<html>
<head>
<script type="text/javascript">
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@")
dotpos=value.lastIndexOf(".")
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false}
else {return true}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_email(email,"Not a valid e-mail address!")==false)
{email.focus();return false}
}
}
</script>
</head>
<body>
<form action="submitpage.htm"
onsubmit="return validate_form(this);"
method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit">
</form>
</body>
</html>
What is CSS?
CSS Syntax
Syntax
The CSS syntax is made up of three parts: a selector, a property and a value:
The selector is normally the HTML element/tag you wish to define, the property is the
attribute you wish to change, and each property can take a value. The property and value
are separated by a colon, and surrounded by curly braces:
Note: If the value is multiple words, put quotes around the value:
p {text-align:center;color:red}
To make the style definitions more readable, you can describe one property on each line,
like this:
p
{
text-align: center;
color: black;
font-family: arial
}
Grouping
You can group selectors. Separate each selector with a comma. In the example below we
have grouped all the header elements. All header elements will be displayed in green text
color:
h1,h2,h3,h4,h5,h6
{
color: green
}
<p class="right">
This paragraph will be right-aligned.
</p>
<p class="center">
This paragraph will be center-aligned.
</p>
Note: To apply more than one class per given element, the syntax is:
The paragraph above will be styled by the class "center" AND the class "bold".
You can also omit the tag name in the selector to define a style that will be used by all
HTML elements that have a certain class. In the example below, all HTML elements with
class="center" will be center-aligned:
In the code below both the h1 element and the p element have class="center". This means
that both elements will follow the rules in the ".center" selector:
<h1 class="center">
This heading will be center-aligned
</h1>
<p class="center">
This paragraph will also be center-aligned.
</p>
The id Selector
You can also define styles for HTML elements with the id selector. The id selector is
defined as a #.
The style rule below will match the element that has an id attribute with a value of
"green":
#green {color: green}
The style rule below will match the p element that has an id with a value of "para1":
p#para1
{
text-align: center;
color: red
}
CSS Comments
Comments are used to explain your code, and may help you when you edit the source
code at a later date. Browsers will ignore a comment. A CSS comment begins with "/*",
and ends with "*/", like this:
/* This is a comment */
p
{
text-align: center;
/* This is another comment */
color: black;
font-family: arial
}
An external style sheet is ideal when the style is applied to many pages. With an external
style sheet, you can change the look of an entire Web site by changing one file. Each
page must link to the style sheet using the <link> tag. The <link> tag goes inside the head
section:
<head>
<link rel="stylesheet" type="text/css"
href="mystyle.css" />
</head>
The browser will read the style definitions from the file mystyle.css, and format the
document according to it.
An external style sheet can be written in any text editor. The file should not contain any
html tags. Your style sheet should be saved with a .css extension. An example of a style
sheet file is shown below:
hr {color: sienna}
p {margin-left: 20px}
body {background-image: url("images/back40.gif")}
Internal Style Sheet
An internal style sheet should be used when a single document has a unique style. You
define internal styles in the head section by using the <style> tag, like this:
<head>
<style type="text/css">
hr {color: sienna}
p {margin-left: 20px}
body {background-image: url("images/back40.gif")}
</style>
</head>
The browser will now read the style definitions, and format the document according to it.
Inline Styles
An inline style loses many of the advantages of style sheets by mixing content with
presentation. Use this method sparingly, such as when a style is to be applied to a single
occurrence of an element.
To use inline styles you use the style attribute in the relevant tag. The style attribute can
contain any CSS property. The example shows how to change the color and the left
margin of a paragraph:
<p style="color: sienna; margin-left: 20px">
This is a paragraph
</p>
h3
{
color: red;
text-align: left;
font-size: 8pt
}
And an internal style sheet has these properties for the h3 selector:
h3
{
text-align: right;
font-size: 20pt
}
If the page with the internal style sheet also links to the external style sheet the properties
for h3 will be:
color: red;
text-align: right;
font-size: 20pt
The color is inherited from the external style sheet and the text-alignment and the font-
size is replaced by the internal style sheet.
Lecture 10-27
Active Server Pages: Working with ASP Pages, ASP Objects, File System Objects,
Session Tracking and Cookies, ActiveX Data Objects, Accessing a Database from Active
Server Page.
Working with ASP Pages
An ASP file can contain text, HTML tags and scripts. Scripts in an ASP file are executed
on the server.
What is ASP?
ASP Source:
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>
Output Result
Hello World!
ASP Source:
<html>
<body>
<%
response.write("<h2>You can use HTML tags to format the text!</h2>")
%>
<%
response.write("<p style='color:#0000ff'>This text is styled with the style attribute!
</p>")
%>
</body>
</html>
Output Result:
You can use HTML tags to format the text!
The response.write command is used to write output to a browser. The following example
sends the text "Hello World" to the browser:
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>
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>
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.
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.
ASP Source:
<html>
<body>
<%
dim name
name="Donald Duck"
response.write("My name is: " & name)
%>
</body>
</html>
Output Result:
My name is: Donald Duck
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.
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.
Declare an array
Arrays are used to store a series of related data items. This example demonstrates how to
declare an array that stores names.
ASP Source:
<html>
<body>
<%
Dim famname(6),i
famname(1) = "Jan Egil"
famname(2) = "Tove"
famname(3) = "Hege"
famname(4) = "Stale"
famname(5) = "Kai Jim"
famname(6) = "Borge"
For i = 1 to 6
response.write(famname(i) & "<br />")
Next
%>
</body>
</html>
Output Result:
Jan Egil
Tove
Hege
Stale
Kai Jim
Borge
<html>
<body>
<%
dim i
for i=1 to 6
response.write("<h" & i & ">Header " & i & "</h" & i & ">")
next
%>
</body>
</html>
Output Result:
Header 1
Header 2
Header 3
Header 4
Header 5
Header 6
Examples
ASP Source:
<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>
<p>
Or, like this:
</p>
<p>
Result: <%vbproc 3,4%>
</p>
</body>
</html>
Output Result:
Result: 12
Result: 12
ASP Source:
Output Result:
Result: 12
Call procedures using VBScript
How to call both a JavaScript procedure and a VBScript procedure in an ASP file.
ASP Source:
<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>
</head>
<body>
<p>Result: <%call vbproc(3,4)%></p>
<p>Result: <%call jsproc(3,4)%></p>
</body>
</html>
Output Result:
Result: 12
Result: 12
Procedures
<html>
<head>
<%
sub vbproc(num1,num2)
response.write(num1*num2)
end sub
%>
</head>
<body>
<p>Result: <%call vbproc(3,4)%></p>
</body>
</html>
Insert the <%@ language="language" %> line above the <html> tag to write procedures
or functions in another scripting language than default:
Examples
ASP Source:
<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>
Output Result:
Submit
Your name:
ASP Source:
<html>
<body>
<form action="demo_simpleform.asp" method="post">
Your name: <input type="text" name="fname" size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.Form("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>
</body>
</html>
Output Result:
Submit
Your name:
ASP Source:
<html>
<%
dim cars
cars=Request.Form("cars")
%>
<body>
<form action="demo_radiob.asp" method="post">
<p>Please select your favorite car:</p>
Output Result:
Volvo
Saab
BMW
Submit
User Input
The Request object may be used to retrieve user information from forms.
Form example:
Request.QueryString
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:
Request.Form
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:
ASP Cookies
A cookie is often used to identify a user.
Examples
Welcome cookie
How to create a Welcome cookie.
ASP Source:
<%
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
%>
<html>
<body>
</body>
</html>
Output Result:
Welcome! This is the first time you are visiting this Web page.
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.
Note: The Response.Cookies command must appear BEFORE the <html> tag.
In the example below, we will create a cookie named "firstname" and assign the value
"Alex" to it:
<%
Response.Cookies("firstname")="Alex"
%>
It is also possible to assign properties to a cookie, like setting a date when the cookie
should expire:
<%
Response.Cookies("firstname")="Alex"
Response.Cookies("firstname").Expires=#May 10,2002#
%>
<%
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>
Output:
Firstname=Alex
If a cookie contains a collection of multiple values, we say that the cookie has Keys.
In the example below, we will create a cookie collection named "user". The "user" cookie
has Keys that contains information about a user:
<%
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>
<%
Response.Cookies("firstname")="Alex"
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>
Assume that your server has sent all the cookies above to a user.
Now we want to read all the cookies sent to a user. The example below shows how to do
it (note that the code below checks if a cookie has Keys with the HasKeys property):
<html>
<body>
<%
dim x,y
for each x in Request.Cookies
response.write("<p>")
if Request.Cookies(x).HasKeys then
for each y in Request.Cookies(x)
response.write(x & ":" & y & "=" & Request.Cookies(x)(y))
response.write("<br />")
next
else
Response.Write(x & "=" & Request.Cookies(x) & "<br />")
end if
response.write "</p>"
next
%>
</body>
</html>
Output:
firstname=Alex
user:firstname=John
user:lastname=Smith
user:country=Norway
user:age=25
When you are working with an application, you open it, do some changes and then you
close it. This is much like a Session. The computer knows who you are. It knows when
you start the application and when you end. But on the internet there is one problem: the
web server does not know who you are and what you do because the HTTP address
doesn't maintain state.
ASP solves this problem by creating a unique cookie for each user. The cookie is sent to
the client and it contains information that identifies the user. This interface is called the
Session object.
The Session object is used to store information about, or change settings for a user
session. Variables stored in the Session object hold information about one single user,
and are available to all pages in one application. Common information stored in session
variables are name, id, and preferences. The server creates a new Session object for each
new user, and destroys the Session object when the session expires.
• A new user requests an ASP file, and the Global.asa file includes a
Session_OnStart procedure
• A value is stored in a Session variable
• A user requests an ASP file, and the Global.asa file uses the <object> tag to
instantiate an object with session scope
A session ends if a user has not requested or refreshed a page in the application for a
specified period. By default, this is 20 minutes.
If you want to set a timeout interval that is shorter or longer than the default, you can set
the Timeout property.
<%
Session.Timeout=5
%>
<%
Session.Abandon
%>
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.
Store and Retrieve Session Variables
The most important thing about the Session object is that you can store variables in it.
The example below will set the Session variable username to "Donald Duck" and the
Session variable age to "50":
<%
Session("username")="Donald Duck"
Session("age")=50
%>
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"))%>
You can also store user preferences in the Session object, and then access that preference
to choose what page to return to the user.
The example below specifies a text-only version of the page if the user has a low screen
resolution:
The example below removes the session variable "sale" if the value of the session
variable "age" is lower than 18:
<%
If Session.Contents("age")<18 then
Session.Contents.Remove("sale")
End If
%>
<%
Session.Contents.RemoveAll()
%>
The Contents collection contains all session variables. You can loop through the Contents
collection, to see what's stored in it:
<%
Session("username")="Donald Duck"
Session("age")=50
dim i
For Each i in Session.Contents
Response.Write(i & "<br />")
Next
%>
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
You can loop through the StaticObjects collection, to see the values of all objects stored
in the Session object:
<%
dim i
For Each i in Session.StaticObjects
Response.Write(i & "<br />")
Next
%>
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.
Application variables can be accessed and changed by any page in the application.
Sub Application_OnStart
application("vartime")=""
application("users")=1
End Sub
</script>
In the example above we have created two Application variables: "vartime" and "users".
There are
<%
Response.Write(Application("users"))
%>
active connections.
ASP Response Object
The ASP Response object is used to send output to the user from the server.
The ASP Response object is used to send output to the user from the server. It has
collections, properties, and methods.
Methods like
Method Description
Redirect Redirects the user to a different URL
Write Writes a specified string to the output
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:
QueryString Collection Examples
ASP Source:
<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>
Output Result:
Submit
Your name:
ASP Source
<html>
<body>
<%
Response.Write(Request.QueryString)
%>
</body>
</html>
Output Result:
First name:
Last name:
Submit
Form Collection Examples
This example demonstrates how the Form collection retrieves the values from a
form. 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>
<%
Response.Write(Request.Form)
%>
</body>
</html>
Output Result:
First name:
Last name:
Submit
fname=Donald&lname=Duck
This example demonstrates how to use the values retrieved from a form. We use
the Form collection. The form uses the post method.
ASP Source:
<html>
<body>
<form action="demo_simpleform.asp" method="post">
Your name: <input type="text" name="fname" size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.Form("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>
</body>
</html>
Output Result:
Submit
Your name:
Collections
Collection Description
Contents Contains all the items appended to the application through a
script command
StaticObjects Contains all the objects appended to the application with the
HTML <object> tag
Methods
Method Description
Contents.Remove Deletes an item from the Contents collection
Contents.RemoveAll() Deletes all items from the Contents collection
Lock Prevents other users from modifying the variables in the
Application object
Unlock Enables other users to modify the variables in the Application
object (after it has been locked using the Lock method)
Events
Event Description
Application_OnEnd Occurs when all user sessions are over, and the application
ends
Application_OnStart Occurs before the first new session is created (when the
Application object is first referenced)
Application_OnStart Event
The Application_OnStart event occurs before the first new session is created (when the
Application object is first referenced).
Application_OnEnd Event
The Application_OnEnd event occurs when the application ends (when the web server
stops).
Syntax
Examples
Global.asa:
<script language="vbscript" runat="server">
Sub Application_OnEnd()
Application("totvisitors")=Application("visitors")
End Sub
Sub Application_OnStart
Application("visitors")=0
End Sub
Sub Session_OnStart
Application.Lock
Application("visitors")=Application("visitors")+1
Application.UnLock
End Sub
Sub Session_OnEnd
Application.Lock
Application("visitors")=Application("visitors")-1
Application.UnLock
End Sub
</script>
<html>
<head>
</head>
<body>
<p>
There are <%response.write(Application("visitors"))%>
online now!
</p>
</body>
</html>
When you are working with an application, you open it, do some changes and then you
close it. This is much like a Session. The computer knows who you are. It knows when
you start the application and when you end. But on the internet there is one problem: the
web server does not know who you are and what you do because the HTTP address
doesn't maintain state.
ASP solves this problem by creating a unique cookie for each user. The cookie is sent to
the client and it contains information that identifies the user. This interface is called the
Session object.
The Session object is used to store information about, or change settings for a user
session. Variables stored in the Session object hold information about one single user,
and are available to all pages in one application. Common information stored in session
variables are name, id, and preferences. The server creates a new Session object for each
new user, and destroys the Session object when the session expires.
The Session object's collections, properties, methods, and events are described below:
Collections
Collection Description
Contents Contains all the items appended to the session through a
script command
StaticObjects Contains all the objects appended to the session with the
HTML <object> tag
Properties
Property Description
CodePage Specifies the character set that will be used when displaying
dynamic content
LCID Sets or returns an integer that specifies a location or region.
Contents like date, time, and currency will be displayed
according to that location or region
SessionID Returns a unique id for each user. The unique id is generated
by the server
Timeout Sets or returns the timeout period (in minutes) for the Session
object in this application
Methods
Method Description
Abandon Destroys a user session
Contents.Remove Deletes an item from the Contents collection
Contents.RemoveAll() Deletes all items from the Contents collection
Events
Event Description
Session_OnEnd Occurs when a session ends
Session_OnStart Occurs when a session starts
Session_OnStart Event
Session_OnEnd Event
The Session_OnEnd event occurs when the session ends (abandoned or times out).
Syntax
Examples
Global.asa:
<script language="vbscript" runat="server">
Sub Application_OnEnd()
Application("totvisitors")=Application("visitors")
End Sub
Sub Application_OnStart
Application("visitors")=0
End Sub
Sub Session_OnStart
Application.Lock
Application("visitors")=Application("visitors")+1
Application.UnLock
End Sub
Sub Session_OnEnd
Application.Lock
Application("visitors")=Application("visitors")-1
Application.UnLock
End Sub
</script>
<html>
<head>
</head>
<body>
<p>
There are <%response.write(Application("visitors"))%>
online now!
</p>
</body>
</html>
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 Description
ScriptTimeout Sets or returns the maximum number of seconds a script can run
before it is terminated
Methods
Method Description
CreateObject Creates an instance of an object
Execute Executes an ASP file from inside another ASP file
GetLastError() Returns an ASPError object that describes the error condition that
occurred
The ASPError object was implemented in ASP 3.0 and is available in IIS5 and later.
The ASPError object is used to display detailed information of any error that occurs in
scripts in an ASP page. The ASPError object is created when Server.GetLastError is
called, so the error information can only be accessed by using the Server.GetLastError
method.
The FileSystemObject object is used to access the file system on the server. This object
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
%>
ActiveX Data Objects, Accessing a Database from Active Server Page.
The common way to access a database from inside an ASP page is to:
What is ADO?
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
%>
Note, from the example above, that you have to specify the Microsoft Access database
driver (Provider) and the physical path to the database on your computer.
Create an ODBC Database Connection
If you have an ODBC database called "northwind" you can connect to the database with
the following ASP code:
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Open "northwind"
%>
With an ODBC connection, you can connect to any database, on any computer in your
network, as long as an ODBC connection is available.
Note that this configuration has to be done on the computer where your web site is
located. If you are running Personal Web Server (PWS) or Internet Information Server
(IIS) on your own computer, the instructions above will work, but if your web site is
located on a remote server, you have to have physical access to that server, or ask your
web host to do this for you.
Connection Object
If you want to access a database multiple times, you should establish a connection using
the Connection object. You can also make a connection to a database by passing a
connection string via a Command or Recordset object. However, this type of connection
is only good for one specific, single query.
ProgID
set objConnection=Server.CreateObject("ADODB.connection")
ADO Recordset
To be able to read database data, the data must first be loaded into a recordset.
After an ADO Database Connection has been created, as demonstrated in the previous
chapter, it is possible to create an ADO Recordset.
Suppose we have a database named "Northwind", we can get access to the "Customers"
table inside the database with the following lines:
<%
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 "Customers", conn
%>
We can also get access to the data in the "Customers" table using SQL:
<%
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
%>
<%
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
for each x in rs.fields
response.write(x.name)
response.write(" = ")
response.write(x.value)
next
%>
The ADO Recordset object is used to hold a set of records from a database table.
ADO Display
The most common way to display data from a recordset, is to display the data in an
HTML table.
We have a database named "Northwind" and we want to display the data from the
"Customers" table (remember to save the file with an .asp extension):
<html>
<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
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>
</html>
CustomerID = ALFKI
CompanyName = Alfreds Futterkiste
ContactName = Maria Anders
ContactTitle = Sales Representative
Address = Obere Str. 57
City = Berlin
PostalCode = 12209
Country = Germany
CustomerID = BERGS
CompanyName = Berglunds snabbköp
ContactName = Christina Berglund
ContactTitle = Order Administrator
Address = Berguvsvägen 8
City = Luleå
PostalCode = S-958 22
Country = Sweden
CustomerID = CENTC
CompanyName = Centro comercial Moctezuma
ContactName = Francisco Chang
ContactTitle = Marketing Manager
Address = Sierras de Granada 9993
City = México D.F.
PostalCode = 05022
Country = Mexico
....
....
....
Display the Field Names and Field Values in an HTML Table
We can also display the data from the "Customers" table inside an HTML table with the
following lines (remember to save the file with an .asp extension):
<html>
<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 Companyname, Contactname FROM Customers", conn
%>
<table border="1" width="100%">
<%do until rs.EOF%>
<tr>
<%for each x in rs.Fields%>
<td><%Response.Write(x.value)%></td>
<%next
rs.MoveNext%>
</tr>
<%loop
rs.close
conn.close
%>
</table>
</body>
</html>
We want to add headers to the HTML table to make it more readable (remember to save
the file with an .asp extension):
<html>
<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")
sql="SELECT Companyname, Contactname FROM Customers"
rs.Open sql, conn
%>
<table border="1" width="100%">
<tr>
<%for each x in rs.Fields
response.write("<th>" & x.name & "</th>")
next%>
</tr>
<%do until rs.EOF%>
<tr>
<%for each x in rs.Fields%>
<td><%Response.Write(x.value)%></td>
<%next
rs.MoveNext%>
</tr>
<%loop
rs.close
conn.close
%>
</table>
</body>
</html>
Companyname Contactname
Alfreds Futterkiste Maria Anders
Berglunds snabbköp Christina Berglund
Centro comercial Moctezuma Francisco Chang
ADO Queries
We may use SQL to create queries to specify only a selected set of records and fields
to view.
Display Selected Data
We want to display only the records from the "Customers" table that have a
"Companyname" that starts with an A (remember to save the file with an .asp extension):
<html>
<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")
sql="SELECT Companyname, Contactname FROM Customers
WHERE CompanyName LIKE 'A%'"
rs.Open sql, conn
%>
<table border="1" width="100%">
<tr>
<%for each x in rs.Fields
response.write("<th>" & x.name & "</th>")
next%>
</tr>
<%do until rs.EOF%>
<tr>
<%for each x in rs.Fields%>
<td><%Response.Write(x.value)%></td>
<%next
rs.MoveNext%>
</tr>
<%loop
rs.close
conn.close%>
</table>
</body>
</html>
Companyname Contactname
Alfreds Futterkiste Maria Anders
Display records where "Companyname" starts with an A
How to display only the records from the "Customers" table that have a "Companyname"
that starts with an A.
ASP Source:
<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")
sql="SELECT Companyname, Contactname FROM Customers WHERE CompanyName
LIKE 'A%'"
rs.Open sql, conn
%>
</body>
</html>
Output Result:
Companyname Contactname
Alfreds Futterkiste Maria Anders
Let the user choose filter
Let the user choose which country to show customers from.
ASP Source:
<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")
sql="SELECT DISTINCT Country FROM Customers ORDER BY Country"
rs.Open sql,conn
country=request.form("country")
%>
<form method="post">
Choose Country <select name="country">
<% do until rs.EOF
response.write("<option")
if rs.fields("country")=country then
response.write(" selected")
end if
response.write(">")
response.write(rs.fields("Country"))
rs.MoveNext
loop
rs.Close
set rs=Nothing %>
</select>
<input type="submit" value="Show customers">
</form>
<%
if country<>"" then
sql="SELECT Companyname,Contactname,Country FROM Customers WHERE
country='" & country & "'"
set rs=Server.CreateObject("ADODB.Recordset")
rs.Open sql,conn
%>
<table width="100%" cellspacing="0" cellpadding="2" border="1">
<tr>
<th>Companyname</th>
<th>Contactname</th>
<th>Country</th>
</tr>
<%
do until rs.EOF
response.write("<tr>")
response.write("<td>" & rs.fields("companyname") & "</td>")
response.write("<td>" & rs.fields("contactname") & "</td>")
response.write("<td>" & rs.fields("country") & "</td>")
response.write("</tr>")
rs.MoveNext
loop
rs.close
conn.Close
set rs=Nothing
set conn=Nothing%>
</table>
<% end if %>
</body>
</html>
Output Result:
Show customers
Choose Country
DO Add Records
We may use the SQL INSERT INTO command to add a record to a table in a
database.
We want to add a new record to the Customers table in the Northwind database. We first
create a form that contains the fields we want to collect data from:
<html>
<body>
<form method="post" action="demo_add.asp">
<table>
<tr>
<td>CustomerID:</td>
<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") & "',"
sql=sql & "'" & Request.Form("postcode") & "',"
sql=sql & "'" & Request.Form("country") & "')"
on error resume next
conn.Execute sql,recaffected
if err<>0 then
Response.Write("No update permissions!")
else
Response.Write("<h3>" & recaffected & " record added</h3>")
end if
conn.close
%>
</body>
</html>
Important
• If the table contains a primary key, make sure to append a unique, non-Null value
to the primary key field (if not, the provider may not append the record, or an
error occurs)
• If the table contains an AutoNumber field, do not include this field in the SQL
INSERT command (the value of this field will be taken care of automatically by
the provider)
In a MS Access database, you can enter zero-length strings ("") in Text, Hyperlink, and
Memo fields IF you set the AllowZeroLength property to Yes.
Note: Not all databases support zero-length strings and may cause an error when a record
with blank fields is added. It is important to check what data types your database
supports.
We want to update a record in the Customers table in the Northwind database. We first
create a table that lists all records in the Customers table:
<html>
<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 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
response.write("Record " & cid & " was updated!")
end if
end if
conn.close
%>
</body>
</html>
We want to delete a record in the Customers table in the Northwind database. We first
create a table that lists all records in the Customers table:
<html>
<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_delete.asp">
<%
for each x in rs.Fields
if 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_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 />
<input type="submit" value="Delete record">
</form>
<%
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>
</html>
7/11/2000
17 Jan Refsnes 66 77 88 [email protected] http:/www.w3schools.com 1:01:56 PM
4/26/2000
39 Torleif Rasmussen 77 88 99 N/A N/A 3:46:41 AM
4/25/2000
46 anton chek 83833 [email protected] www.yahoo.com 7:17:45 AM
5/31/2000
555-
48 stale refsnes [email protected] http://www.w3schools.com 11:14:33 AM
12234
1/18/2001
98410-
52 hari prawin [email protected] www.hari.com 7:47:58 AM
95897
3/22/2001
53 Hege Refsnes N/A [email protected] N/A 1:35:01 PM
<%option explicit%>
<html>
<head><title>ADO - List Database Records</title></head>
<body>
<%
dim conn,rs,x
set conn=Server.CreateObject("ADODB.Connection")
conn.provider="Microsoft.Jet.OLEDB.4.0"
conn.open(server.mappath("/db/database.mdb"))
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM tblGuestBook",conn
%>
<h2>List Database Table</h2>
<p>Click on a button to modify a record.</p>
Save Delete
View source on how to create input fields based on the fields from one record in the
database table.
Note: If you click on "Save" or "Delete" a new page will open. On the new page you may
look at the source on how to submit changes to, or delete from a database table.
<%
no=Request.Form("no")
if no="" then response.end
set conn=Server.CreateObject("ADODB.Connection")
conn.provider="Microsoft.Jet.OLEDB.4.0"
conn.open(server.mappath("/db/database.mdb"))
set rs = Server.CreateObject("ADODB.Recordset")
rs.Open "Select * from tblGuestBook where tblGuestBook.[no]=" & no , conn
%>
<html>
<head>
<title>ADO - Edit DataBase Record</title>
</head>
<body>
<h2>Edit Database Table</h2>
<form method="post" action="demo_db_submit.asp" target="_blank">
<input name="no" type="hidden" value=<%=no%>>
<table bgcolor="#b0c4de">
<%
for each x in rs.Fields
if x.name <> "no" and x.name <> "dateadded" then%>
<tr>
<td><%=x.name%> </td>
<td><input name="<%=x.name%>" value="<%=x.value%>" size="20"></td>
<%end if
next
rs.close
conn.close
%>
</tr>
</table>
<br />
<input type="submit" name="action" value="Save">
<input type="submit" name="action" value="Delete">
</form>
Adding a Record
Fname
Lname
Phone
Email
homepage
Add Record
View source on how to create input fields based on the fields in the database table.
Note: If you click on "Add Record" a new page will open. On the new page you may
look at the source on how to add a record to a database table. <html>
<head>
<title>ADO - Add DataBase Record</title>
</head>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.mappath("/db/database.mdb"))
set rs = Server.CreateObject("ADODB.Recordset")
rs.Open "select * from tblGuestBook", conn
%>
<h2>Adding a Record</h2>
<form method="post" action="demo_db_new.asp" target="_blank">
<table bgcolor="#b0c4de">
<%
for each x in rs.Fields
if x.name <> "no" and x.name <> "dateadded" then%>
<tr>
<td><%=x.name%></td>
<td><input name="<%=x.name%>" value="N/A" size="20"></td>
<%
end if
next
rs.close
conn.close
%>
</tr></table>
<br />
<input type="submit" name="action" value="Add Record">
</form>
Lecture 28-35
Introducing Visual InterDev and the World Wide Web
During the first day, the context for Visual InterDev will be set, and
you'll be introduce to some of the latest developments concerning the
Internet and the WWW. You will learn about the importance of the
Internet. You also will learn about the rising number of intranets, or
private internets, that are growing within many companies. You will
see how the WWW has become ubiquitous and the implications that it
has for individuals and businesses. In discussing the WWW, you will
discover the differences between static and dynamic web pages and
what you should focus on for the future. You will then be introduced to
the reasons for having an application development tool for the Web.
Finally, you will get a glimpse of Visual InterDev.
We are truly living in the Information Age, and the Internet has
become the primary means for expanding our horizons. The Internet
has opened up any number of possibilities for applications by providing
a ready-made network for businesses to use. Growth in the Internet
has also forced us to rethink the way we approach life. A student in
California can communicate with his parents in Florida via e-mail
instead of building up a hefty, long distance telephone bill. In fact, now
most families can conduct conversations over the Internet, thereby
skirting the phone companies.
Many companies are realizing the benefits of the Internet from within
their companies. These organizations are creating intranets, which are
private, or internal, internets. These intranets have been established
initially as an internal communication tool. Employees can send e-mail
to other employees within the company. Intranets enable private and
sensitive corporate information to be distributed and shared within the
organization. This new medium of communication has become a very
cost-effective solution, especially for geographically dispersed
businesses that have employees all over the world. The time to
communicate new policies, procedures, and information is immediately
reduced along with postage and paper costs.
An intranet also can be used for software distribution and for providing
access to vital applications. Companies are now starting to put
applications like survey forms and employee benefit registration forms
on their intranets to simplify basic processes. Businesses also are
starting to consider replacing or enhancing their mission-critical
applications (like accounting, sales order entry, oil and gas trading,
and so on) with applications that are secured within an intranet.
Intranets are usually protected and secured by means of a firewall that
prevents outside intruders from accessing the internal network. To the
user, there is no difference between accessing the Internet and the
company's intranet. Figure 1.1 depicts a typical configuration for an
intranet.
Figure 1.1.
The most recent numbers estimate that more than 45 million people
have visited the Web at least once. When sports figures, music
celebrities, and news anchors are touting the Web, you know it has
become ubiquitous. The Web provides an alternate delivery channel for
all types of information as well as graphically robust applications.
Major software vendors are totally revamping their products to make
them Internet-enabled. Banks are having to rethink their strategy of
targeting and servicing their customers by providing online banking.
Businesses are establishing a presence on the Web to offer products
and services electronically. The Web is everywhere, and we must learn
how to properly and constructively use its capabilities.
Figure 1.2.
Figure 1.3.
A more in-depth discussion concerning how the web client and server
interact is warranted here. Historically, Web applications have been
based on HTML and common gateway interface (CGI) programs on the
server. The Web browser interprets the HTML tags and appropriately
formats the page for the user. A web page can be a combination of
formatted text, images and graphics, audio, and video. HTML also
allows for the creation of basic forms that contain text fields, radio
buttons, checkboxes, push buttons, and listboxes. These objects are
discussed in more detail on Day 12, "Using Basic and Advanced HTML
Form Controls."
CGI programs have typically been used for processing requests on the
server and distributing information to the client machine. CGI
programs, or scripts, are executable files that can be built using
languages such as UNIX shell script, Perl, C, and so on. As information
is updated on your database, the CGI script can handle accessing the
data and passing the information back down to the client browser. The
advantage is that you don't have to write new HTML code for every
new document or database update. The CGI server program provides
a reusable component that saves development time.
Table 1.1. The most popular APIs, their respective vendors, and supported server
platforms.
Dynamic web pages are those pages that provide true user interaction.
In this model, users interact through the use of server-side programs
that provide for an enhanced experience. Instead of just reading about
the latest human resource benefits, employees can register and
update their benefits. Dynamic web pages support the building of true
interactive applications. Once you have read the published flight
schedules, you can make airline reservations electronically over the
Internet. Stock brokerage houses can publish the hottest stock tips
and then enable you to capitalize on the investment through online
stock trading. Dynamic web pages provide a world of new possibilities
over static pages.
Visual InterDev also supports the use of Active Server Pages. Active
Server Pages are a new feature included with Internet Information
Server 3.0; they provide a framework for creating dynamic Web
pages.
Active Server Pages are based on the ActiveX Scripting engine and
enable you to include server-side executable script directly into an
HTML document. You can create Active Server Pages using any of the
popular scripting languages, including VBScript, JavaScript, Perl, and
so on. Figure 1.4 illustrates how an Active Server Page interacts with a
client machine.
Figure 1.4.
You will notice from the diagram that the web clients communicate
with the web server through the HTTP protocol. The web server can be
on the Internet or within an intranet. The web server is comprised of
Internet Information Server 3.0, which includes the ActiveX Server
Scripting engine. The diagram shows the Active Server pages, or .asp
files, where the server-side script resides. These files are simply HTML
pages that contain scripting code. This scripting code extends basic
HTML and provides additional functionality for your application.
There are many extensive and powerful technologies for creating Web
applications, but most tools only focus on a single, specific need. Other
tools are being developed to address a few needs. Developers have
been dreaming of the day when they can use a comprehensive,
integrated development environment to build their applications. Why,
you ask, do you need an integrated tool? Take a walk through a typical
Web development effort and look at the many different types of tools
that you can use to build a Web-based application.
First you need an HTML editor. Many people have created a new
function for an old product and made Notepad the HTML editor of
choice. Table 1.2 outlines some of the more robust and popular
products on the market.
Microsoft also has created add-in products for its Office suite of
products that enable HTML conversion. For example, a user who is
familiar with Microsoft Word can use the Internet Assistant for Word to
convert a document to HTML format for display in a browser.
The point in this example is that you could spend a lot of time and
effort using a number of tools to implement a robust, Web-based
application. Compatibility between the tools becomes a debugging
nightmare. Also, you spend a lot of time switching between the
development environments, thereby diminishing your productivity.
Due to these limitations, Microsoft created Visual InterDev to address
the many needs for today's Web-based application developer.
Developer productivity was a major design goal for Microsoft, and they
have accomplished it by providing Visual InterDev with many wizards
and visual tools, as well as database development features. Powerful
database integration and connectivity were clearly of paramount
importance for its design. Visual InterDev even supports developers in
deploying their sites once they have been built by integrating
comprehensive tools to create and maintain a web site into Visual
InterDev.
Now that you have been introduced to the features and benefits of the
integrated development environment, it's time for a brief look at some
of the specific features of Visual InterDev. This discussion sets the
context for Day 2, in which you will get to meet Visual InterDev up
close and personal.
Visual InterDev also includes two tools for spicing up your web pages.
These tools focus on multimedia creation and management. The
Microsoft Image Composer and Microsoft Music Producer enable you to
create graphical images, music, and sounds for your web site. You can
use the Microsoft Image Composer to create engaging images for your
web pages. The Image Composer supports the Adobe Photoshop file
format as well as GIF and JPG formats. The Image Composer is simple
to use, and you don't have to be a graphic artist to master it. The
Music Producer enables you to create music and sound effects for your
web site. You pick from over 100 pre-defined styles of music and can
modify the arrangement of instruments as well as the tempo.
Now consider some of the key features for building robust server
applications. Visual InterDev enables you to create dynamic web pages
through the use of Active Server Pages. The concept of Active Server
Pages was touched on earlier in the day. As a refresher, Active Server
Pages are HTML pages that contain server-side script. The script code
can be either VBScript, JavaScript, or some other scripting language.
The Active Server Page, or .asp file, resides on the server machine and
executes before being downloaded to the browser.
Database Integration
Visual InterDev provides some very robust database tools. The Visual
Data Tools included with Visual InterDev are easy to use and
significantly reduce the time and effort for adding database capability
into your application. Some of the features include the following:
• Data View. Visual InterDev project window that enables you to view all of your
database objects including tables, views, stored procedures, and triggers.
• Query Designer A tool that enables you to visually build your SQL database
queries and test the results.
• Database Designer A tool that enables you to design, create, and maintain your
SQL database.
• Stored Procedure/Trigger Editor A tool for editing stored procedures and
triggers for Microsoft SQL Server 6.x and Oracle 7.x.
The World Wide Web (WWW) has made the Internet come alive for
many new users. In the initial stages, users realized that they could
view numerous documents on various topics from all over the world.
Through the WWW, people have access to a plethora of knowledge.
Not only can you read about many interesting topics on the Web, but
you also can find information about your favorite products and
services.
Once you have gained this knowledge, you will invariably want to act
on it. Some companies have built Web-based applications, enabling
you to buy their products and services electronically over the Internet.
Other companies enable you to fill out registration information to begin
receiving certain services. The point is, applications enable the user to
act on the knowledge they have gained. Businesses can capitalize on
opportunities sooner by becoming closer to the customer through a
virtual marketplace. Visual InterDev provides all the necessary tools to
build these vital applications for the Web.
Figure 2.1.
Visual InterDev provides the tool to take advantage of the new Web-
based model of computing. Some development tools focus on
supporting a single Internet technology. Others support several
technologies for Web-based development but don't provide visual tools
to accomplish these tasks. Visual InterDev exceeds existing Web
development tools by providing a way to integrate multiple
technologies and supplies visual tools to greatly enhance a developer's
productivity. Visual InterDev also surpasses and extends the reach of
client-server tools to the Internet and the Web.
The Essence of Integration
"1. To make into a whole; unify. 2. To join with something else; unite."
Truly, Visual InterDev unifies and unites the technologies of the Web
through its integrated development environment. You can use the
environment to rapidly build a robust application. You have at your
disposal all of the tools necessary for Web-based application
development in one integrated package. In this sense, the whole really
is greater than the sum of its parts.
Figure 2.3.
Figure 2.3 shows the Visual InterDev File Open Project dialog window.
Notice the ability to open multiple types of projects from within the
environment.
When you open your Visual InterDev project, you're viewing your
actual web site. The Visual InterDev development environment uses
the Explorer interface to view and manage your web site files and
folders. This interface simplifies the task of creating and maintaining
your web site files and folders. Also, the interface enables you to fully
organize the construction of your Web-based application. The
integrated development environment enables easy site creation
through the use of wizards, and enables developers to reuse files from
other sites.
Visual InterDev enables you to easily import existing files into your
web site structure. The Explorer interface enables you to accomplish
this task through a point-and-click metaphor, just as you copy and
paste files and folders on your PC. Figure 2.4 shows a Visual InterDev
project using File View.
Figure 2.4.
The File View is the default view for a typical Visual InterDev project.
Notice the tabs at the bottom of the pane on the left-hand side of the
workspace. File View enables you to see the structure of your web site
including files and folders. This view displays the entire contents of
your site, including HTML pages, images, controls, applets, and other
files. The pane to the right of this workspace displays the object that is
selected based upon its file type. For example, if you selected an HTML
page from the list on the left, the HTML code would be displayed in the
window on the right.
DataView is the other tab located next to the FileView tab. This view
shows all of your database objects, including tables, views, stored
procedures, and triggers. The Data View provides a direct connection
to your ODBC datasource to enable remote configuration and
maintenance as well as interaction. Figure 2.5 demonstrates the Data
View showing a sample Access database.
Figure 2.5.
NOTE: The Data View only appears as an option for web projects after
you have inserted a database connection. The Data View also is displayed
for Database Projects.
Browser Integration
You do have the capability to use the Browse With function to view
your web site from within the browser's native window. For example,
you could configure Internet Explorer or Netscape Navigator and view
the site from within the production browser environment. You probably
will want to use this feature during final testing of your web site. If
you're deploying your site for use with the Netscape Navigator
browser, you have to use this feature.
You can use either of these features by selecting an HTML file and
right-clicking the mouse to display the shortcut menu. Figure 2.6
shows the Preview in Browser and Browse With menu options on the
shortcut menu for an HTML file.
Figure 2.6.
Using this editor, you can create and edit your HTML code, which is
color-coded, providing a visually appealing syntax. You can incorporate
many objects and controls, such as HTML layouts and controls, ActiveX
controls, and Design-time ActiveX controls. The editor also supports
the use of script with your HTML web page. Figure 2.7 highlights
standard HTML code using the HTML Source Editor.
Figure 2.7.
The HTML Source Editor.
Figure 2.8.
The HTML Layout Editor is the same editor that was first included with
the ActiveX Control Pad from Microsoft. This editor provides a way to
accurately position all of your ActiveX controls on your web page. The
interface is very similar to tools like Visual Basic, which enable you to
position your objects on forms. With this layout editor, you can drag
and drop controls onto the layout and establish their properties and
exact position within the web page. When the form is displayed by the
browser at runtime, the controls are positioned at the exact
coordinates that were specified at design time. The toolbox enables
you to add and delete controls. You also can use the Script Wizard to
automatically add scripting code for use with your controls. Figure 2.9
displays the HTML Layout Editor.
Figure 2.9.
The HTML Layout Editor.
Object Editor
The Object Editor enables you to establish the properties for your
ActiveX and Design-time ActiveX controls as well as Java applets and
Netscape plug-ins. The Object Editor is activated after you insert an
object into your HTML source code. For example, to position an
ActiveX control on your web page, you would right-click the mouse
where you wanted the object to be placed within your HTML code.
NOTE: You must click between the <HTML> and </HTML> tags that signify
the beginning and ending of your code.
You can then choose between regular and Design-time controls. Once
you have chosen a control, the Object Editor is displayed, enabling you
to set the properties for the given control. Figure 2.10 exhibits the
Object Editor for a typical ActiveX control.
Figure 2.10.
As you can see, there are several editors that you can choose, based
on the task that you're trying to accomplish. These editors are covered
in-depth later in the week. You also will get a chance to use each of
these editors to experience their features during the first week.