Sie sind auf Seite 1von 32

INTRODUCTION

• ASP stands for Active Server Pages


• ASP is a program that runs inside IIS (Internet Information Services)

• An ASP file can contain text, HTML, XML, and scripts


• Scripts in an ASP file are executed on the server

• When a browser requests an ASP file, IIS passes the request to the ASP engine.
The ASP engine reads the ASP file, line by line, and executes the scripts in the
file. Finally, the ASP file is returned to the browser as plain HTML

You can run ASP on your own PC without an external server. To do that, you must install
Microsoft's Personal Web Server (PWS) or Internet Information Services (IIS) on your
PC.

The default scripting language is VBScript. To set JavaScript as the default scripting
language for a particular page you must insert a language specification at the top of the
page. Like this: <%@ language="JavaScript"%>

Advantages of ASP:
• Minimizes network traffic by limiting the need for the browser and server to talk to
each other
• Makes for quicker loading time since HTML pages are only downloaded
• Allows to run programs in languages that are not supported by the browser
• Can provide the client with data that does not reside on the client’s machine
• Provides improved security measures since the script cannot be viewed by the browser

Difference between server side scripting and client side scripting:


Scripts executed only by the browser without contacting the
server is called client-side script. It is browser dependent. The scripting
code is visible to the user and hence not secure. Scripts executed by the
web server and processed by the server is called server-side script.

Order of execution for an ASP application:


1) Global.asa
2) Server-side Includes statements
3) Directives
4) Jscript scripts tagged within <SCRIPT> tags
5) HTML together with scripts tagged within <% … %> delimiters
6) VBScripts tagged within <SCRIPT> tags

In a simple way, order of scripts is defined as (points 4, 5, 6 above)


1. scripts in non-default language
2. scripts using <%%>
3. scripts in default language
ILLUSTRATION:
<%@language="vbscript"%>

<script language="VBscript" runat=server>


response.write("1<p>")
</script>

<script language="jscript" runat=server>


Response.Write("2<p>");
</script>

<%
Response.write("3<p>")
%>

<script language="jscript" runat=server>


Response.Write("4<p>");
</script>

<script language="VBscript" runat=server>


response.write("5<p>")
</script>
OUTPUT: 2 4 3 1 5

<%@language="JScript"%>

<script language="VBscript" runat=server>


response.write("1<p>")
</script>

<script language="jscript" runat=server>


Response.Write("2<p>");
</script>

<%
Response.Write("3<p>");
%>

<script language="jscript" runat=server>


Response.Write("4<p>");
</script>

<script language="VBscript" runat=server>


response.write("5<p>")
</script>
OUTPUT: 1 5 3 2 4

ASP PROCEDURES

Call a procedure using vbscript:

<%
sub vbproc(num1,num2)
response.write(num1*num2)
end sub
%>

<%call vbproc(3,4)%> OR <%vbproc 3,4%>

Call a procedure using javascript:

<%@ language="javascript" %>

<%
function jsproc(num1,num2)
{
Response.Write(num1*num2)
}
%>

<%jsproc(3,4)%>

Call both vbscript and javascript procedures in vbscript:

<%
sub vbproc(num1,num2)
Response.Write(num1*num2)
end sub
%>
<script language="javascript" runat="server">
function jsproc(num1,num2)
{
Response.Write(num1*num2)
}
</script>

<%call vbproc(3,4)%>

<%call jsproc(3,4)%>
Note: When calling a JavaScript or a VBScript procedure from an ASP file written in
JavaScript, always use parentheses after the procedure name. In vbscript, parentheses are
optional. If you omit the "call" keyword, the parameter list must not be enclosed in
parentheses.

ASP FORMS and INPUTS

Commands for information retrieval from forms:

1. Request.QueryString
2. Request.Form

Difference between GET and POST methods:

GET:

1. Limited data can be sent upto 255 characters.


2. Command used is Request.QueryString
3. Data is visible to the users.

POST:

1. Umlimited data can be sent.


2. Command used is Request.Form
3. Data is not visible to the users.

ASP COOKIES

A cookie is a temporary file 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.

Why is a cookie used?

A cookie (persistent) enables a website to remember you on subsequent visits, speeding


up or enhancing your experience of services or functions offered.

For example, a website may offer its contents in different languages. On your first visit,
you may choose to have the content delivered in French and the site may record that
preference in a persistent cookie set on your browser. When you revisit that site it will
use the cookie to ensure that the content is delivered in French.

Creating a Cookie:

<%Response.Cookies("firstname")="Alex"%>
Properties:

1. Domain: This is the domain that the cookie originated from. It is set by default to
the domain in which it was created but it can be altered.

Example: Response.Cookies("name").Domain = "www.cookiemonster.com"

2. Expires: There are 2 ways.


a) You can use the current date and add or subtract days

Response.Cookies("name").Expires = Date + 365

b) You can set it to a specific date

Response.Cookies("name").Expires = #May 10,2002#


Note: To expire the session enabled with cookies, Give current date.
Example: Response.Cookies("name").Expires = Date OR Date-1

3. Path: This specifies in more detail the exact path on the domain that can use the
cookie.

Response.Cookies("name").Path = "/this/is/the/path"

4. Secure: If set, the cookie will only be set if the browser is using secure sockets or
https:// to connect.

Response.Cookies("name").Secure = True

Dictionary Cookie OR Cookies with Keys: It is a cookie that can hold multiple values.

Example:

Response.Cookies("name")("first") = "John"
Response.Cookies("name")("last") = "Smith"

How to know if the cookie has keys?

Ans: With the Haskeys property.

Example:

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

Note: There are limits on how much data you can put on a clients browser. Most
browsers allow you to place 20 cookies per domain at a maximum of 4k each.

Types of cookies:

1. Persistent: Persistent cookies are stored on your computer hard disk. They stay
on your hard disk and can be accessed by web servers until they are deleted or
have expired. Persistent cookies are not affected by your browser setting that
deletes temporary files when you close your browser.
2. Non-Persistent: Non-persistent cookies are saved only while your web browser is
running. They can be used by a web server only until you close your browser.
They are not saved on your disk.

ASP OBJECTS

Response Object: Response object is used to display items on a web page.

Request Object: The ASP Request object is used to get information from the user.
Application Object: A group of ASP files that work together to perform some purpose is
called an application. The Application object in ASP is used to tie these files together.

Session Object: The Session object is used to store information about, or change settings
for a user session.
Server Object: The ASP Server object is used to access properties and methods on the
server.
ASPError Object: The ASPError object is used to display detailed information of any
error that occurs in scripts in an ASP page.

Object Context: The ObjectContext object can be used to commit or abort a


transaction.

Collections, Properties and Methods:


OBJECT COLLECTIONS PROPERTIES METHODS EVENTS
Response 1. Cookies 1. Buffer 1. Write
2. ContentType 2. Redirect
3. Expires 3. End
4. ExpiresAbsolute 4. Clear
5. Charset 5. Flush
6. CacheControl 6. BinaryWrite
7.IsClientConnected 7. AddHeader
8. Pics 8.AppendToLog
9. Status
Request 1. Cookies 1. TotalBytes 1. BinaryRead
2. Form
3. QueryString
4.ServerVariables
5.ClientCertificate
Application 1. Contents 1. Lock 1.
2. StaticObjects 2. UnLock Application_OnStart
3.Contents.Remove 2. Application_OnEnd
4.Contents.RemoveAll()
Session 1. Contents 1. CodePage 1. Abandon 1. Session_OnStart
2. StaticObjects 2. LCID 2. Contents.Remove 2. Session_OnEnd
3. SessionID 3.Contents.RemoveAll()
4. Timeout
Server 1. ScriptTimeOut 1. CreateObject
2. Execute
3. GetLastError()
4. Transfer
5. HTMLEncode
6. URLEncode
7. MapPath
Error 1. ASPCode
2. ASPDescription
3. Category
4. Column
5. Line
6. Source
7. Description
8. File
9. Number
Object 1. SetAbort 1.OnTransactionAbort
Context 2. SetComplete 2.OnTransaction
CommitEvent

RESPONSE:

Collections

Collection Description
Cookies Sets a cookie value. If the cookie does not exist, it will be created,
and take the value that is specified

Properties

Property Description
Buffer Specifies whether to buffer the page output or not
CacheControl Sets whether a proxy server can cache the output generated by ASP
or not
Charset Appends the name of a character-set to the content-type header in
the Response object
ContentType Sets the HTTP content type for the Response object
Expires Sets how long (in minutes) a page will be cached on a browser
before it expires
ExpiresAbsolute Sets a date and time when a page cached on a browser will expire
IsClientConnected Indicates if the client has disconnected from the server
Pics Appends a value to the PICS label response header
Status Specifies the value of the status line returned by the server

Methods

Method Description
AddHeader Adds a new HTTP header and a value to the HTTP response
AppendToLog Adds a string to the end of the server log entry
BinaryWrite Writes data directly to the output without any character conversion
Clear Clears any buffered HTML output
End Stops processing a script, and returns the current result
Flush Sends buffered HTML output immediately
Redirect Redirects the user to a different URL
Write Writes a specified string to the output

REQUEST:

Collections
Collection Description
ClientCertificate Contains all the field values stored in the client certificate
Cookies Contains all the cookie values sent in a HTTP request
Form Contains all the form (input) values from a form that uses the post
method
QueryString Contains all the variable values in a HTTP query string
ServerVariables Contains all the server variable values

Properties

Property Description
TotalBytes Returns the total number of bytes the client sent in the body of the
request

Methods

Method Description
BinaryRead Retrieves the data sent to the server from the client as part of a post
request and stores it in a safe array

APPLICATION:

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)

SESSION:

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

SERVER:

Properties
Property Description
ScriptTimeout Sets or returns the maximum number of seconds a script can run
before it is terminated

Methods

Method Description
CreateObject Creates an instance of an object
Execute Executes an ASP file from inside another ASP file
GetLastError() Returns an ASPError object that describes the error condition that
occurred
HTMLEncode Applies HTML encoding to a specified string
MapPath Maps a specified path to a physical path
Transfer Sends (transfers) all the information created in one ASP file to a
second ASP file
URLEncode Applies URL encoding rules to a specified string

ERROR:

Properties

Property Description
ASPCode Returns an error code generated by IIS
ASPDescription Returns a detailed description of the error (if the error is ASP-
related)
Category Returns the source of the error (was the error generated by ASP?
By a scripting language? By an object?)
Column Returns the column position within the file that generated the error
Description Returns a short description of the error
File Returns the name of the ASP file that generated the error
Line Returns the line number where the error was detected
Number Returns the standard COM error code for the error
Source Returns the actual source code of the line where the error occurred

ASP SESSION
The Session object is used to store information about a user session. 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.
Session is implemented by creating a unique cookie for each user.
Session Starts when a new user requests an ASP file, and the Global.asa file includes a
Session_OnStart procedure.

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.

To set the timeout interval, Timeout property is used.

<%Session.Timeout=5%>

To end the session immediately, Abandon method is used.


<%Session.Abandon%>

Store session variables:


<%Session("username")="Donald Duck"%>

Retrieve session variables:


<%Response.Write(Session("username"))%>

Remove session variables:


<%
If Session.Contents("age")<18 then
Session.Contents.Remove("sale")
End If
%>
The Contents collection contains all session variables. It is possible to remove a session
variable with the Remove method.

To remove all variables in a session, use the RemoveAll method:

<%Session.Contents.RemoveAll()%>

To know the number of items in the content collection: use Count property

<%Session.Contents.Count%>

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

What is the difference between session and cookie?


If you set the variable to "cookies", then your users will not have to log in each time they
enter your community.
The cookie will stay in place within the user’s browser until it is deleted by the user.
But Sessions are popularly used, as the there is a chance of your cookies getting blocked
if the user browser security setting is set high.
If you set the variable to "sessions", then user activity will be tracked using browser
sessions, and your users will have to log in each time they re-open their browser. The
Key difference would be cookies are stored in your hard disk whereas a session aren't
stored in your hard disk. Sessions are basically like tokens, which are generated at
authentication. A session is available as long as the browser is opened.

ASP APPLICATION

A group of ASP files that work together to perform some purpose is called an application.

Application variables are available to all pages in one application. Application variables
are used to store information about ALL users in a specific application.

To create application variables:

You can create Application variables in "Global.asa" like this:

<script language="vbscript" runat="server">

Sub Application_OnStart
application("vartime")=""
application("users")=1
End Sub

</script>

Lock and Unlock:

<%
Application.Lock
'do some application object operations
Application.Unlock
%>

ASP #INCLUDE

The #include directive is used to create functions, headers, footers, or elements that will
be reused on multiple pages.

Syntax:
<!--#include virtual="somefilename"-->
or
<!--#include file ="somefilename"-->

Virtual: to indicate a path beginning with a virtual directory


<!-- #include virtual ="/html/header.inc" -->
File: to indicate a relative path. A relative path begins with the directory that contains the
including file.
<!-- #include file ="headers\header.inc" -->

Note: Included files are processed and inserted before the scripts are executed.

GLOBAL.ASA FILE
The Global.asa file is an optional file (stored in the root directory of the application) that
can contain declarations of objects, variables, and methods that can be accessed by every
page in an ASP application.

The Global.asa file can contain only the following:

• Application events
• Session events
• <object> declarations
• TypeLibrary declarations
• the #include directive

Events in Global.asa

Application_OnStart: Occurs when

1. The FIRST user calls the first page from an ASP application.
2. after the Web server is restarted or after the Global.asa file is edited

Session_OnStart: Occurs

1. EVERY time a NEW user requests his or her first page in the ASP application.

Session_OnEnd: Occurs

1. EVERY time a user ends a session.


2. after a page has not been requested by the user for a specified time

Application_OnEnd: Occurs

1. after the LAST user has ended the session.


2. when a Web server stops
Note: we cannot use the ASP script delimiters (<% and %>) to insert scripts in the
Global.asa file

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>

Object Declaration:

Syntax:

<object runat="server" scope="scope" id="id"


{progid="progID"|classid="classID"}>
....
</object>

Parameters:
1. scope
2. id
3. ProgID
4. ClassID

Example:
<object runat="server" scope="session" id="MyAd"
progid="MSWC.AdRotator">
</object>

Difference between Object tag and Server.CreateObject:


object tag creates the object and initializes the memory only when the first
method/property of the object was accessed.
Server.CreateObject will immediately create the object and initialize the memory.
ASP COMPONENTS
1. AdRotator
2. Content Rotator
3. Content Linking
4. Browser Capabilities

1. ADROTATOR:
The ASP AdRotator component creates an AdRotator object that displays a different
image each time a user enters or refreshes a page.
Syntax:
<%
set adrotator=server.createobject("MSWC.AdRotator")
adrotator.GetAdvertisement("textfile.txt")
%>
//Here textfile.txt contains information about the images
Example:
ASP page looks like below:

/* code if images are hyperlinks

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

Txt file looks like below:


REDIRECT banners.asp //is used when images should be hyperlinks
WIDTH 468 //width, height and border are for the size of the image that is
displayed
HEIGHT 60
BORDER 0
*
w3schools.gif //image
http://www.w3schools.com/ //hyperlink address
Visit W3Schools Alt text
80 //percent of hits
microsoft.gif
http://www.microsoft.com/
Visit Microsoft
20
Methods:
1. GetAdvertisement

Properties:
1. Border
2. Clickable
3. TargetFrame

2. CONTENT ROTATOR:
The ASP Content Rotator component creates a ContentRotator object that displays a
different HTML content string each time a user enters or refreshes a page.
Syntax:
<%
Set cr=Server.CreateObject( "MSWC.ContentRotator" )
%>
Example:
//ASP File looks like this:
<html>
<body>

<%
set cr=server.createobject("MSWC.ContentRotator")
response.write(cr.ChooseContent("text/textads.txt"))
%>

</body>
</html>
//Txt file looks like this
%% #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>
Note: #Num indicates the relative weight of the HTML content string

Methods:
1. ChooseContent
2. GetAllContent

3. CONTENT LINKING:
The ASP Content Linking component is used to create a quick and easy navigation
system!
The Content Linking component returns a Nextlink object that is used to hold a list of
Web pages to be navigated.
Syntax:
<%
Set nl=Server.CreateObject( "MSWC.NextLink" )
%>
Example:
//txt file looks like this:
asp_intro.asp ASP Intro
asp_syntax.asp ASP Syntax
asp_variables.asp ASP Variables
asp_procedures.asp ASP Procedures

//On each of the pages listed above, put one line of code: <!-- #include file="nlcode.inc"--
>. This line will include the code below on every page listed in "links.txt" and the
navigation will work.

//nlcode.inc file looks like this:


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

Methods:
1. GetListCount
2. GetListIndex
3. GetNextDescription
4. GetNextURL
5. GetNthDescription
6. GetNthURL
7. GetPreviousDescription
8. GetPreviousURL

4. BROWSER CAPABILITIES:
The ASP Browser Capabilities component creates a BrowserType object that determines
the type, capabilities and version number of each browser that visits your site.

When a browser connects to a server, an HTTP User Agent Header is also sent to the
server. This header contains information about the browser (like browser type and
version number). The BrowserType object then compares the information in the header
with information in a file on the server called "Browscap.ini".

If there is a match between the browser type and version number sent in the header and
the information in the "Browsercap.ini" file, you can use the BrowserType object to list
the properties of the matching browser. If there is no match for the browser type and
version number in the Browscap.ini file, it will set every property to "UNKNOWN".

The "Browsercap.ini" file is used to declare properties and to set default values for
browsers.

Syntax:

<%
Set MyBrow=Server.CreateObject("MSWC.BrowserType")
%>

Example:

//browsercap.ini file on the server looks like this:

;IE 5.0
[IE 5.0]
browser=IE
Version=5.0
majorver=#5
minorver=#0
frames=TRUE
tables=TRUE
cookies=TRUE
backgroundsounds=TRUE
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

//ASP file looks like this:

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

ASP SCRIPTING OBJECTS


Objects that can enhance the application are known as scripting objects.
1. Dictionary Object
2. File System Object
3. Text Stream

FILE SYSTEM OBJECT:


The FileSystemObject object is used to access the file system on the server.
Types:
1. FileSystem
2. TextStream
3. Drive
4. File
5. Folder

FILESYSTEM:

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 Description
Drives Returns a collection of all Drive objects on the computer

Methods:
Method Description
BuildPath Appends a name to an existing path
CopyFile Copies one or more files from one location to another
CopyFolder Copies one or more folders from one location to another
CreateFolder Creates a new folder
CreateTextFile Creates a text file and returns a TextStream object that can
be used to read from, or write to the file
DeleteFile Deletes one or more specified files
DeleteFolder Deletes one or more specified folders
DriveExists Checks if a specified drive exists
FileExists Checks if a specified file exists
FolderExists Checks if a specified folder exists
GetAbsolutePathName Returns the complete path from the root of the drive for the
specified path
GetBaseName Returns the base name of a specified file or folder
GetDrive Returns a Drive object corresponding to the drive in a
specified path
GetDriveName Returns the drive name of a specified path
GetExtensionName Returns the file extension name for the last component in a
specified path
GetFile Returns a File object for a specified path
GetFileName Returns the file name or folder name for the last component
in a specified path
GetFolder Returns a Folder object for a specified path
GetParentFolderName Returns the name of the parent folder of the last component
in a specified path
GetSpecialFolder Returns the path to some of Windows' special folders
GetTempName Returns a randomly generated temporary file or folder
MoveFile Moves one or more files from one location to another
MoveFolder Moves one or more folders from one location to another
OpenTextFile Opens a file and returns a TextStream object that can be used
to access the file

TEXTSTREAM OBJECT:
The variable f is an instance of the TextStream object in the above example.

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.

Properties:
Property Description
AtEndOfLine Returns true if the file pointer is positioned immediately before the
end-of-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 Returns the column number of the current character position in an
input stream
Line Returns the current line number in a TextStream file

Methods:
Method Description
Close Closes an open TextStream file
Read Reads a specified number of characters from a TextStream file and
returns the result
ReadAll Reads an entire TextStream file and returns the result
ReadLine Reads one line from a TextStream file and returns the result
Skip Skips a specified number of characters when reading a TextStream
file
SkipLine Skips the next line when reading a TextStream file
Write Writes a specified text to a TextStream file
WriteLine Writes a specified text and a new-line character to a TextStream
file
WriteBlankLines Writes a specified number of new-line character to a TextStream
file

DRIVE:

The Drive object is used to return information about a local disk drive or a network share.
The Drive object can return information about a drive's type of file system, free space,
serial number, volume name, and more.

Example:

<%
Dim fs,d
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set d=fs.GetDrive("c:")
Response.Write("Drive " & d & ":")
Response.Write("Total size in bytes: " & d.TotalSize)
set d=nothing
set fs=nothing
%>

Output:

Drive c: Total size in bytes: 4293563392

Properties:
Property Description
AvailableSpace Returns the amount of available space to a user on a specified drive
or network share
DriveLetter Returns one uppercase letter that identifies the local drive or a
network share
DriveType Returns the type of a specified drive
FileSystem Returns the file system in use for a specified drive
FreeSpace Returns the amount of free space to a user on a specified drive or
network share
IsReady Returns true if the specified drive is ready and false if not
Path Returns an uppercase letter followed by a colon that indicates the
path name for a specified drive
RootFolder Returns a Folder object that represents the root folder of a specified
drive
SerialNumber Returns the serial number of a specified drive
ShareName Returns the network share name for a specified drive
TotalSize Returns the total size of a specified drive or network share
VolumeName Sets or returns the volume name of a specified drive

FILE:

The File object is used to return information about a specified file.

To work with the properties and methods of the File object, you will have to create an
instance of the File object through the FileSystemObject object. First; create a
FileSystemObject object and then instantiate the File object through the GetFile method
of the FileSystemObject object or through the Files property of the Folder object.

Example:
<%
Dim fs,f
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.GetFile("c:\test.txt")
Response.Write("File created: " & f.DateCreated)
set f=nothing
set fs=nothing
%>

Output:

File created: 9/19/2001 10:01:19 AM

Properties:
Property Description
Attributes Sets or returns the attributes of a specified file
DateCreated Returns the date and time when a specified file was created
DateLastAccessed Returns the date and time when a specified file was last accessed
DateLastModified Returns the date and time when a specified file was last
modified
Drive Returns the drive letter of the drive where a specified file or
folder resides
Name Sets or returns the name of a specified file
ParentFolder Returns the folder object for the parent of the specified file
Path Returns the path for a specified file
ShortName Returns the short name of a specified file (the 8.3 naming
convention)
ShortPath Returns the short path of a specified file (the 8.3 naming
convention)
Size Returns the size, in bytes, of a specified file
Type Returns the type of a specified file

Methods:
Method Description
Copy Copies a specified file from one location to another
Delete Deletes a specified file
Move Moves a specified file from one location to another
OpenAsTextStream Opens a specified file and returns a TextStream object to access
the file

FOLDER:

The Folder object is used to return information about a specified folder.

To work with the properties and methods of the Folder object, you will have to create an
instance of the Folder object through the FileSystemObject object. First; create a
FileSystemObject object and then instantiate the Folder object through the GetFolder
method of the FileSystemObject object.

Example:
<%
Dim fs,fo
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set fo=fs.GetFolder("c:\test")
Response.Write("Folder created: " & fo.DateCreated)
set fo=nothing
set fs=nothing
%>
Output:

Folder created: 10/22/2001 10:01:19 AM

Collections:
Collection Description
Files Returns a collection of all the files in a specified folder
SubFolders Returns a collection of all subfolders in a specified folder

Properties:
Property Description
Attributes Sets or returns the attributes of a specified folder
DateCreated Returns the date and time when a specified folder was created
DateLastAccessed Returns the date and time when a specified folder was last accessed
DateLastModified Returns the date and time when a specified folder was last
modified
Drive Returns the drive letter of the drive where the specified folder
resides
IsRootFolder Returns true if a folder is the root folder and false if not
Name Sets or returns the name of a specified folder
ParentFolder Returns the parent folder of a specified folder
Path Returns the path for a specified folder
ShortName Returns the short name of a specified folder (the 8.3 naming
convention)
ShortPath Returns the short path of a specified folder (the 8.3 naming
convention)
Size Returns the size of a specified folder
Type Returns the type of a specified folder

Methods:
Method Description
Copy Copies a specified folder from one location to another
Delete Deletes a specified folder
Move Moves a specified folder from one location to another
CreateTextFile Creates a new text file in the specified folder and returns a
TextStream object to access the file

DICTIONARY OBJECT: The Dictionary object is used to store information in


name/value pairs (referred to as key and item). The Dictionary object might seem similar
to Arrays, however, the Dictionary object is a more desirable solution to manipulate
related data.
Comparing Dictionaries and Arrays:

• Keys are used to identify the items in a Dictionary object


• You do not have to call ReDim to change the size of the Dictionary object
• When deleting an item from a Dictionary, the remaining items will automatically
shift up
• Dictionaries cannot be multidimensional, Arrays can
• Dictionaries have more built-in functions than Arrays
• Dictionaries work better than arrays on accessing random elements frequently
• Dictionaries work better than arrays on locating items by their content

Example:
<%
Dim d
Set d=Server.CreateObject("Scripting.Dictionary")
d.Add "re","Red"
d.Add "gr","Green"
d.Add "bl","Blue"
d.Add "pi","Pink"
Response.Write("The value of key gr is: " & d.Item("gr"))
%>

Output:

The value of key gr is: Green

Properties:
Property Description
CompareMode Sets or returns the comparison mode for comparing keys in a
Dictionary object
Count Returns the number of key/item pairs in a Dictionary object
Item Sets or returns the value of an item in a Dictionary object
Key Sets a new key value for an existing key value in a Dictionary object

Methods:
Method Description
Add Adds a new key/item pair to a Dictionary object
Exists Returns a Boolean value that indicates whether a specified key exists
in the Dictionary object
Items Returns an array of all the items in a Dictionary object
Keys Returns an array of all the keys in a Dictionary object
Remove Removes one specified key/item pair from the Dictionary object
RemoveAll Removes all the key/item pairs in the Dictionary object
VIRTUAL DIRECTORY
Allows you to create multiple website under one ip address. Allows you reference
another location (folder) to include additional functionality.
To create one
1) Open IIS Manager (Ctrl Panel->Admin Tools->Internet Service Manager)
2) Right click the default site and “New”>”Virtual Directory”.
3) Type the name of the virtual directory and then browse to the location you would like
to reference.

UPLOAD FILES
//Form tag in upload page
<form name="Ifrm" method="post" action="" action="" ENCTYPE="multipart/form-
data">

//To browse a file, give Type=”FILE”


Eg: <input type="file" class="mediumtext" name="File1">

Note: We use a third party component “Persits” to upload any file.

//Create Upload object


Set Upload=Server.CreateObject("Persits.Upload.1")

//If a file already exists with same name then we can give option whether to upload or not
to upload.
Upload.OverwriteFiles = False/True
Eg:
True:
If swetha.jpg already exists then also the file is uploaded as swetha[1].jpg
False:
If same name already exists then we cannot upload.

//If there is any error in uploading and we still want to move ahead then we give this. If
we want to see the error then we should remove this statement.
On Error Resume Next

//Set File Limit to upload


Upload.SetMaxSize 5242880

//We can also add code for creating the folder if the specified does not exist
Set fso=Server.CreateObject("Scripting.FileSystemObject")
if fso.FolderExists(server.mappath("./CoachImages"))=false then
Set fobj=fso.CreateFolder(server.mappath("./CoachImages"))
end if
Set fobj=nothing
Set fso=nothing
//To get the count of the uploaded files
Count = Upload.Save(server.mappath("./"&folder))

//To know if a file a uploaded or not. If not Show Error Message


if Count = 0 then
Error

// In Else part, we increment a loop for the uploaded Files


For Each File in Upload.Files

//Here we check the type of file. Suppose it is an image, then


If ucase(File.ImageType) = "GIF" or ucase(File.ImageType) = "JPG" …….then
//To get File Name
File.FileName
//To get Image Width
File.ImageWidth
//To get Image Height
File.ImageHeight
Else //If file type does not match then we can delete the file
File.Delete
End If

Next

//To delete an old uploaded file


Set fs=Server.CreateObject("Scripting.FileSystemObject")
if fs.FileExists(Server.MapPath("./BoardImages/"&IRs("photoname"))) then
fs.DeleteFile(Server.MapPath("./BoardImages/"&IRs("photoname")))
end if
set fs=nothing

After clicking SUBMIT, in Javascript


function SendBoardValues()
{
window.close();
window.opener.evntfrm.submit();
}
Here, opener is used to get the values in this window to the main page in the browser.

Export to Excel
// Mention below lines in the asp page
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "Content-Disposition", "attachment; filename=sheet1.xls"
After this, use an html table to write the desired data.

Send Mail
Note: We use a third party component “Persits” to send a mail.

//Declare mail object


Set objPersits = CreateObject("Persits.MailSender")

With objPersits
.From = "affiliates@sportskids.com" //From Email Id
.FromName = "SportsKids.com" //Name of the Sender
.Host = "mail.sportskids.com" //Mail Host
.Subject = "Invitation"
.AddAddress <mailTo>,<mailName>
.Body = mailbody
.isHTML = True //If html content exists in the mail body
on error resume next
.Send //To send mail finally
if err.number <> 0 then
response.write "Error " & err.number & " sending to " & mailTo & "
(" & mailName & ")<br>"

//To know the description of the error, we give


response.write err.description

err.clear
else
//Mail has been sent
end if
.RemoveAddress mailTo, mailName
End With

set objPersits = nothing

How to send an external html file through mail?


//Declare file system object to read from the file
set fso = Server.CreateObject("Scripting.FileSystemObject")

//Specify File location


fname = "/AffiliateEmails/skaffmail.htm"

//Open a file using above object and set it to a new object


set fObj = fso.openTextFile(server.mappath(fname))
//Read from the file and assign to a variable which is further assigned to the .Body of the
mail
mailBody = fObj.readAll

//Close the connection to the file


fObj.close

set fso = nothing

No Print
//Give the link in the html page to print
<a href="javascript:onclick=window.print()" class="navlinksareas">Print</a>
//On clicking, the entire page is printed

How to eliminate the unnecessary things from printing?


// Declare the style in a style sheet
.noprint
{
DISPLAY: none
}

//include the external style sheet in the page


<link rel="stylesheet" type="text/css" href="/noprint.css" media="print"></link>

//Put the div tags with class=”noprint” in the page wherever required
<div class="noprint">……..</div>

Paging

//execute the query and open the recordset


If not(Rs.eof and Rs.bof) then

//initialize paging requirements


Pagesize = 5 //set page size to a variable
Page = request(“page”) //get the current page no into a variable
If Page = “” then Page = 1 //if this variable is null that means it is first page
Recordcount = Rs.recordcount //get no. of records in Rs
Rs.pagesize = Pagesize //assign page size to Rs
Rs.absolutepage = Page //current page no. assigned to Rs
TotalPages = Rs.Pagecount //get count of total no. of pages
Prev = Page – 1 //Previous page no. set here
Next = Page + 1 //Next page no. set here
Count = 1 //initialize count variable to 1
//open the while loop of the result set
While not Rs.eof and Count <= Pagesize
//Here, looping is restricted to the page size that we have set
………………………..
//increment count variable
Count = Count + 1
//close loop
Wend

//At the bottom of the page, provide links for paging


<tr><td>
<%
dim Counter
if Prev <> 0 then //if previous pages are available then this link appears
%>
<a href="search.asp&page=<%=prev%>">Previous</a>
<%end if%>
<%
for i = 1 to Page //links of page no. from first page to current page are displayed
if i = cint(Page) then//if I is current page then just display the no. w/o hyper link
response.write i
else //pages other than current page are displayed as links
%>
<a href="search.asp?page=<%= i%>"><%= i%></a>
<% end if
Next

if Rs.AbsolutePage <> -3 then //if next pages are available


%>
<a href="search.asp?page=<%=next%>">Next</a>
<%end if %>
</td></tr>

Das könnte Ihnen auch gefallen