This web page has some survival notes on using ASP & VBScript.
Topic |
Notes |
General |
General
- ASP (Active Server Pages) is a Microsoft product.
- ASPX (Active Server Pages Extended) is a Microsoft product working
with MS's .Net technology.
- Web Servers that support ASP: MS IIS (maybe others)
- Basic Coding
- An ASP can have HTML & ASP code. HTML is processed by
the client (browser) and ASP code is processed by the server (MS
IIS).
- Simple ASP - ASP Scripting is in the <% %> tags.
- <h1><% = "Hello World" %></h1>
- <% Response.Write("<h1>Hello World</h1>");
%>
- Scripting (coding) - the scripting language supported by ASP
(code between the tags <% %>) is either VBScript or JScript.
VBScript - Like Microsoft's VB (Visual Basic).
JScript - Microsoft's implementation of JavaScript.
- Code Execution - Remember that any code (scripting) between the tags <% %>
is executed on the server side (web/application server), not the
client (browser).
|
Server Side Configuration
(For Developers) |
Server Side Configuration - (Win
XP Professional) Home Directory
- Launch MS IIS (Start, Control Panel, Administrative Tools, Internet
Information Services)
- Right click on "Default Web Site" and choose Properties.
- Click on the "Home Directory" tab.
- Click - Script Source Access
- Click - Read
- Click on "Configuration"
Home Directory - Configuration - Debugging - Turn on the to Debug
- Click the "Debugging" tab
- Check - Enable ASP server-side script debugging
Check - Enable ASP client-side script debugging
Check - Send detailed ASP error messages to client
Home Directory - Configuration - Options
- Click the "Options" tab.
- Click - Enable session state (Session time out: 20 min)
Click - Enable Buffering
Click - Enable parent paths
Default ASP language: VBScript
ASP Script timeout: 90 seconds
|
Server Directives |
Server Directives
- All server directives must be at the top of the ASP page.
- <%@ something %> - example of a Server directive.
- Script Language Directive
<%@ Language = VBScript %> - Default script is VBScript
<%@ Language = JavaScript %> - Default script is JavaScript
The default script language can be set at the Web Server.
|
Scripting Language |
Scripting Language
Defining the default script language:
(Make sure these server directives are at the top of your ASP page.)
- JavaScript - by Netscape. JScript is Microsoft's
implementation (IE) of JavaScript.
<%@ Language=JavaScript %>
- VBScript - by Microsoft
<%@ LANGUAGE = VBScript %>
<% Option Explicit %>
(Note: Option Explicit forces the declaration of variables.)
VBScript vs JavaScript
- Case Sensitivity - VBScript-NO, JavaScript-YES.
- There are many, many differences in the 2 languages. VBScript
is similar to MS Visual Basic and VBA (Visual Basic for
Applications). JavaScript was created by Netscape and has some
similarity to C and Java (created by Sun). JavaScript is NOT
Java.
|
VBScript Basics |
VBScript Basics
- Commenting (Comment / Comments)
- // - Single line comment
- ' - Single line comment
- <%= %> - Cannot have comments.
- In-line comments in multiple lines of code - DOES NOT WORK
(for me atleast)
- Example that DOES
NOT Work
strMsg = "Hello" & _ //Test Comment.
"World"
- Example that DOES Works
strMsg = "Hello" & _
"World" //Test Comment.
- Multi-line comments (VBScript) - DOES NOT WORK
- /* */ - does not work.
- The best work around is to close the ASP script and make an
HTML comment.
- Example that DOES work (Because the comment
becomes an HTML comment!)
<%
response.write( "Before" & "<br>")
%>
<!--
response.write( "Hello World" & "<br>")
response.write( "Session.SessionID = " & Session.SessionID )
-->
<%
response.write( "After" & "<br>")
%>
- Example that DOES NOT
work.
<%
response.write( "Before" & "<br>")
<!--
response.write( "Hello World" & "<br>")
response.write( "Session.SessionID = " & Session.SessionID )
-->
response.write( "After" & "<br>")
%>
- Creating multiple lines of code. Use the "_"
character.
MyVar = "This is test line 1" _
& "This is test line 2"
- Declaring a variable
- <% Option Explicit %> - Forces declaration of variables.
- Dim strSql ' As String - Declare a variable.
- Conditional
- Or - don't use: ||
- And - don't use: &&
- String Values
- Assign a string value: Use a double quote ( " ).
- DOES NOT WORK
- Single quote ( ' ) doesn't work!
- Adding strings (&): "String 1" & "String
2"
- Insert a quote (") in a string. Escape the quote by
using 2 quotes.
sText = "<font size=""3"">Hello World</font>" Returns: <font size="3">Hello World</font>
- Misc Items
- Count vs Length
VBScript: objMy.Count
JScript: objMy.length
- Other gotchas
- Equality in conditional statement, use "=" and NOT "==".
- NULL
VBScript: NULL (notes: isNull(NULL) returns true. isNull("")
returns false. )
JScript: null
- "&" vs "+" with Strings. Use the "&" to add string values.
- Escaping a Quote
JScript: Escape Quote: \"
VBScript Escape Quote: "" (2 Quotes)
- += Doesn't exist !!!
Use intLoop = intLoop + 1
- not vs !
Example #2:
JScript: intMyVar != 1
VBScript: not ( intMyVar = 1 )
Example #1:
JScript: if ( ! blnMyVar )
VBScript: if ( not blnMyVar )
Example #2:
JScript: if ( intEx != 0 ) (<> is an error)
VBScript: if ( intEx <> 0 ) (!= is an error)
- Arrays start with 0.
JScript Arrays start with: 0, columns with 0
VBScript Arrays start with: 0, But columns with 1
|
JScript Basics |
JScript Basics
- Commenting
- // - Single line comment.
- /* */
|
ASP to HTML |
ASP to HTML
- <% <ASP Server side script %>
- <%= <value or function that returns a value> %>
- <% Response.Write ( <value> ) %>
|
Debugging Tips |
Debugging Tips
- If you want to stop processing the .ASP page and return the results
use: (Very useful to me!)
<%
If ( false ) then
Response.Clear
Response.Write("query = " & query)
Response.End
End if
%>
Note:
If Response.Buffer has been set to TRUE, calling Response.End
will flush the buffer. If you do not want output returned to the user,
you should call Response.Clear first.
|
Variable Visibility |
Variable Visibility
- Visibility of Variables
- Web Server Variables (IIS)
- Session - Store the variable in the Session Object.
Visible by all ASP pages requested by one user (user
specific).
Example: <% Session("FirstName") = "John" Session("LastName") = "Doe" %>
- Application - Store the variable in the Application Object.
Visible by all ASP pages requested by any user (application
specific). "... an Application is a group of ASP files within
as single directory, including any subdirectories"
<% Application("AppName") = "ABC
Reporting" %>
- Global - A variable declared outside of a procedure (VBScript)
or a function.
- Local - A variable declared inside of a procedure (VBScript) or
a function.
|
DB Connections |
DB Connections
Example ASP Code to Connect to a DB:
- x
- MS Access 2000 MDB example.
<%
//Example of connecting to a Database.
Dim dbcnUsers ' As ADODB.Connection
Dim strDbPathname ' As String
Dim strConnection ' As String
strDbPathname = Server.MapPath("MyDbBasics.mdb")
strConnection = _
"Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & strDbPathname
Set dbcnUsers = Server.CreateObject("ADODB.Connection")
dbcnUsers.Open(strConnection)
%>
Provider attributes:
- MS Access 2000: Provider=Microsoft.Jet.OLEDB.4.0;
- MS Access 97: Provider=Microsoft.Jet.OLEDB.3.51;
- DSN (Data Source Name)
DB2 Example:
dbcnUsers.Open("DSN=Sample;UID=db2admin;PWD=<password>")
Resources
|
Create a Table of Data Based on
a SQL Query |
Create an HTML Table based all the
fields of a Query: Dim dbcnUsers ' As
ADODB.Connection
Dim strOpenDBInfo ' As String
strOpenDBInfo = "DSN=MyDbAsp;UID=mydbasp;PWD=mydbasp;"
Set dbcnUsers = Server.CreateObject("ADODB.Connection")
dbcnUsers.open(strOpenDBInfo)
Dim rsUsers ' As ADODB.Recordset
Dim strSql ' As String
strSql = "select * from users order by username"
Set rsUsers = dbcnUsers.Execute( strSql ) //Returns a RecordSet
response.write( "<table border='1'>" )
' Create the column titles.
Dim itemColumn
Response.Write("<tr>" & vbCrLf )
For Each itemColumn in rsUsers.Fields
Response.Write("<td>" & itemColumn.name & "</td>" & vbCrLf )
Next
Response.Write("</tr>" & vbCrLf )
Do While Not rsUsers.EOF
' Create the rows of data.
Response.Write("<tr>" & vbCrLf )
For Each itemColumn in rsUsers.Fields
Response.Write("<td>" & rsUsers(itemColumn.name) & "</td>" &
vbCrLf )
Next
Response.Write("</tr>" & vbCrLf )
rsUsers.MoveNext
Loop
response.write( "</table>" )
Load an Array With the Results
arrUsers = rsUsers.GetRows
|
Database Permissions |
Permissions is granted at the
Database server, not in ASP. You can log into the database from ASP at
connection time.
- MS Access Database
- The default is to give permissions to the Group "Users"
- To view permissions, open the database then: Tools,
Security, Users & Group Permissions.
|
Basic ASP Objects |
Basic ASP Objects
- Response - object that returns data to the browser.
- Response object - is used to send the output back to the client
(browser) (HTTP variables, cookies, and other info about the content).
- Response.Cookies (collection) - specify the values of cookies which
will be sent back to the client browser.
- Response.Buffer (property) A boolean value indicating
whether page output is buffered or not. (true = output from the page will not be sent to the client until all the
script in that page is processed). IIS 5 default is true.
- Response.CacheControl (property) - A string specifying that the output from the ASP should
be cached or not. (Pulbic = proxy server to cache the output of
your ASP, Private = no)
- Response.Charset (property) - A string which appends the name of character set to be used
to HTTP-content-type header.
- Response.ContentType (property) - A string which specifies the HTTP content type for the
response. (default = MIME-type "text/html")
- Response.Expires (property) - An integer specifying the duration of time in minutes after
which the page expires in the client browser cache.
- Response.ExpiresAbsolute (property) - Date/Time after which the page cached in the
client browser expires and is no longer valid. (ex: Response.ExpiresAbsolute = #March 31, 2001 12:00:00#
)
- Response.IsClientConnected (property) - A boolean value indicating whether the client is
still connected to this particular page. If this property returns
false then the page's script processing can be stopped by using
Response.End method.
- Response.Pics (property) - create a PICS header (content
rating)
- Response.Status (property) - A string which specifies the value of status line of the
server. (ex: "404 File Not Found".)
- Response.AddHeader (method) - Adds a custom new HTTP header to the response. Must be
used before any text or HTML is sent to the client. Does not replace
a HTTP header of the same name e.g. Response.AddHeader
"AUTHENTICATED", "You are now logged on."
- Response.AppendToLog (method) - A string which is added to the end of the web server log
entry for this page. (ex: Response.AppendToLog "Your custom log
info.".
- Response.BinaryWrite (method) - writes binary data
(images, etc...)
- Response.Clear (method) - Clears the buffered output html
(ex: aborting, etc....)
- Response.End (method) - Abort the processing of the
script and send page to client.
- Response.Flush (method) - Sends the buffered output
immediately to the client. Is used to send parts of long pages to the client
when Response.Buffer is set to true.
- Response.Redirect (method) - Redirects the browser to another page (URL)
(ie: Response.Redirect( "http://www.google.com"
).
(ie: Response.Redirect( "http://<yourpage>?parm1=hello&parm2=world"
).
- Response.Write (method) - Writes the specified string to the web page
(ie: Response.Write( "Hello World!") )
- Request - object that contains data sent by the browser (html
parms, forms, cookies, client certificates (if SSL) etc...).
- Request.ServerVariables (collection) - Contains a collection of predetermined environment
variables plus a collection of all the HTTP header values sent from
the client browser to the server.
Request.ServerVariables("SERVER_NAME") - returns the server name.
Request.ServerVariables("QUERY_STRING") - returns the complete URL
parm string as a string.
Request.ServerVariables("selSearchCities") - returns the URL parm
value for "selSearchCities".
(Note: You can do the following also: Request("selSearchCities")
)
- Request.QueryString (collection) - Collection of variables which
are stored in the HTTP query string.
Ex: Request.QueryString("myurlparm")
(Note: You can do the following also: Request("myurlparm") )
- Request.Form (collection) - Collection of all the values of Form element in the HTTP
request.
Ex: Request.Form("selSearchCities")
- Request.ClientCertificate (collection) - Makes us available a
collection of values stored in the client certificate that is sent
to the HTTP request.
- Request.Cookies (collection) - cookies stored in the client
browser for this domain.
- Request.TotalBytes (property) total number
of bytes in this request.
- Request.BinaryRead (method) - Retrieves data sent to the server from the client in raw
format as part of the POST request. It saves all this data in a
SafeArray.
- Server - the methods and properties of our server ( IIS ).
- Server.ScriptTimeout (property) - script timeout abort value in seconds.
ex: Server.ScriptTimeout = 90 'In Seconds
Warning: Requires an IIS reset (restart) before the ASP pages
will use the new value if it is changed from the IIS Manager screen
(ASP Script timeout).
- Server.CreateObject (method) - Creates an instance of the object ( a
component, application or a scripting object ).
- Server.Execute (method) - Executes the given .asp page and then returns
the control to the page who called the method.
- Server.HTMLEncode (method) - Provides HTML encoding to a given string.
- Server.MapPath (method) - Maps the specified virtual or relative path
into physical path of the server.
- Server.Transfer (method) - Transfers the control of the page to another
page specified in the URL.
- Server.URLEncode (method) - Provides URL encoding .
- Application
- The Application object is created when the first .asp page is
requested after starting the IIS and remains there until the server
shuts down. All the variables created with application object have
application level scope meaning there by that they are accessible to
all the users. All .asp pages in a virtual directory and its
subdirectories come under the application scope. So application
level variables are shared by more than one user at a time.
- Application.Contents (collection) - all application objects.
- Application.StaticObjects (collection)
- Contents.Remove (method) - removes item from
Application.Contents.
- Contents.RemoveAll (method) - removes all item from
Application.Contents.
- Application.Lock (method) - lock so one user at a time can
modify the values.
- Application.UnLock (method)
- Application_OnEnd (event) - This event occurs when the IIS is shut down after
Session_OnEnd event. All the variables are destroyed after that.
- Application_OnStart (event) - This event occurs when the first .asp page is
called after starting the IIS. Application level variables can be
declared here.
- Session - user specific object that has persistence across
web pages and is stored by IIS.
- Session(<session name>) = <value>
- Session object - created every time client browser access pages
from your web site. Session object is specific for every user and
varies from user to user. It can be used to store variables specific
for a user and IIS will maintain these variables when the client
moves across pages within your site.
- Session.Contents (collection) - Contains all the items which have been added
to the Session object. You can iterate through the Contents
collection and retrieve a list of all the items added or you can
retrieve a specific item. Note that it contains all the Session
items except the ones created using <object> element.
- Session.StaticObjects (collection) - Contains all the items which have
Session scope created using <object> element.
- Session.CodePage (property) - An integer which defines the code page to be
used to display content to the client browser (1252= American
English)
- Session.LCID (property) - locale identifier.
- Session.SessionID (property) - session identifier for this client browser.
- Session.Timeout (property) - time out period in minutes. If the client
doesn't refresh or request any page of your site within this time
out period then the server ends the current session. (default - 20
minutes).
Ex: Session.Timeout = 120 'In Minutes
- ASPError - (starting in IIS v5)
- ASPError.ASPCode (property) - A string which contains the error code
generated by the server .
- ASPError.Number (property) - A long integer which contains the error code
returned by the COM component. A standard COM error code.
- ASPError.Source (property) - A string which contains the actual source code
which caused the error, if available.
- ASPError.Category (property) - A string which indicates if the error was
caused by IIS, scripting language or some component.
- ASPError.File (property) - A string, name of the .asp page which caused the
error.
- ASPError.Line (property) - An integer which indicates the number of line in
.asp page that caused the error.
- ASPError.Column (property) - An integer indicating the column position
within the .asp page which caused the error.
- ASPError.Description (property) - A string , short description of the
error.
- ASPError.ASPDescription (property) - Detailed description of the error if
it is ASP related.
- ObjectContext - objects for Transaction processing.
- SetAbort (method) - Aborts the transaction initiated by
the ASP script.
- SetComplete (method) - if all components report complete then
the transaction will complete.
- OnTransactionAbort (event) - This event occurs when the
transaction is aborted.
- OnTransactionCommit (event) - This event occurs when the
transactional script's transaction is committed.
|
Error Handling |
Error Handling in VBScript
On Error Resume Next - will resume
process if there is an error. Then you can trap for it.
On error goto 0 - Resets error handling.
(Note: There is No "On Error Function()" in VBScript like there is in VB)
Example #1:
On Error Resume Next
Set rsMyResultSet = mydatabase.execute(strSql)
if ( Err.Number = 0 ) Then
mydatabase.Close()
Response.redirect("mypage_confirm.asp")
else
mydatabase.Close()
Response.redirect("mypage_error.asp")
End if
Example #2:
Sub HandleError
If Err.Number = 0 then Exit Sub
Response.Clear Response.Write("<hr>" & vbCrLf) Response.Write("Err.Number = " & Err.Number & "<br>" & vbCrLf) Response.Write("Err.Description = " & Err.Description & "<br>" & vbCrLf)
Response.End
End Sub
On Error Resume Next
Set rsMyResultSet = mydatabase.execute(strSql)
HandleError()
Example #3:
dim rsUsers
dim strSql strSql = "select * zzz from MyTable"
On Error Resume Next Set rsUsers = mydbconnection.execute(strSql) if ( Err.Number <> 0 ) Then Response.Clear Response.Write("<hr>" & vbCrLf) Response.Write("Err.Number = " & Err.Number & "<br>" & vbCrLf) Response.Write("Err.Description = " & Err.Description & "<br>" & vbCrLf)
Response.Write("Err.HelpContext = " & Err.HelpContext & "<br>" & vbCrLf)
Response.Write("Err.Source = " & Err.Source & "<br>" & vbCrLf) Response.Write("Err.HelpFile = " & Err.HelpFile & "<br>" & vbCrLf) Response.Write("<hr>" & vbCrLf) ' This error object has no data for SQL errors!!! Dim objASPError Set objASPError = Server.GetLastError() Response.Write("ASPCode = " & objASPError.ASPCode & "<br>" & vbCrLf) Response.Write("ASPDescription = " & objASPError.ASPDescription & "<br>" & vbCrLf) Response.Write("Category = " & objASPError.Category & "<br>" & vbCrLf) Response.Write("Column = " & objASPError.Column & "<br>" & vbCrLf) Response.Write("Description = " & objASPError.Description & "<br>" & vbCrLf)
Response.Write("File = " & objASPError.File & "<br>" & vbCrLf) Response.Write("Line = " & objASPError.Line & "<br>" & vbCrLf) Response.Write("Number = " & objASPError.Number & "<br>" & vbCrLf) Response.Write("Source = " & objASPError.Source & "<br>" & vbCrLf) Response.Write("<hr>" & vbCrLf)
Response.Write("URL = " & Request.ServerVariables("URL") & "<br>" & vbCrLf)
Response.Write("Filename = " & Request.ServerVariables("PATH_TRANSLATED") & "<br>" & vbCrLf) Response.Write("Remote User = " & Request.ServerVariables("REMOTE_USER") & "<br>" & vbCrLf) Response.Write("Remote Host = " & Request.ServerVariables("REMOTE_HOST") & "<br>" & vbCrLf) Response.Write("Server Name = " & Request.ServerVariables("SERVER_NAME") & "<br>" & vbCrLf) Response.Write("Local Addr = " & Request.ServerVariables("LOCAL_ADDR") & "<br>" & vbCrLf) ' Response.redirect("database_example.asp") 'Endless error loop! Response.End End If
Other Items
|
Invoking a Stored Procedure
from ASP | Example Code (ASP-VBScript): (to
run a Stored Procedure from MSSQL )
dim strOpenDBInfo
dim database
strOpenDBInfo = "DSN=mydb; UID=sa; PWD=mypswd;"
Set database = Server.CreateObject("ADODB.Connection")
database.open(strOpenDBInfo)
dim cmdSaveUser
dim strSql
Set cmdSaveUser = Server.CreateObject("ADODB.Command")
Set cmdSaveUser.ActiveConnection = database
cmdSaveUser.CommandText = "spCustomSaveUser"
cmdSaveUser.CommandType = &H0004 ' &H0004 Value for a Stored Procedure (aka:
adCmdStoredProc if you have that const variable.)
cmdSaveUser.Parameters.Refresh
cmdSaveUser.Parameters(1) = Session("User.userid") ' @userId int
cmdSaveUser.Parameters(2) = Request.Form("elmPhone") ' @phone varchar(30)
cmdSaveUser.Parameters(3) = Request.Form("elmEmail") ' @email varchar(128)
'Output returned. (See the Stored Procedure and look for Parms with OUTPUT.
'cmdSaveUser.Parameters(4) @errorCode int OUTPUT
'cmdSaveUser.Parameters(5) @errorText varchar(255) OUTPUT
cmdSaveUser.Execute
If cmdSaveUser.Parameters(4) <> 0 Then '@errorCode
response.redirect("creditcard_confirm.asp?errorcode=" &
cmdSaveUser.Parameters(4) & "&errortext=" & cmdSaveUser.Parameters(5)) '@errorText
End If
Microsoft's resources:
http://support.microsoft.com/kb/164485 |
Email using CDONTS.NewMail | Email using CDONTS.NewMail
FYI - I was not successful in getting CDONTS working on a server that
emailed using a relay server.
Warning: I don't think there is a way to specify the SMTP Server. (Win2000
IISv5)
Microsoft's resources:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdo/html/2ce1c7e3-4354-4f7d-b41d-5348c3435efc.asp |
Email using CDO.Message | Tested on a Win 2000 Server with
IIS v5 These metadata tags have
the cdo... variable values. Place these tags towards the top but below
the Server Language tag. <!--METADATA TYPE="typelib" UUID="CD000000-8B95-11D1-82DB-00C04FB1625D"
NAME="CDO for Windows 2000 Library" -->
<!--METADATA TYPE="typelib" UUID="00000205-0000-0010-8000-00AA006D2EA4"
NAME="ADODB Type Library" --> Here is the cdo values for the variables if you don't want to place the
metadata tags in your code:
cdoSendUsingPort = 2
cdoBasic = 1
cdoSendUsingMethod = http://schemas.microsoft.com/cdo/configuration/sendusing
cdoSMTPServer = http://schemas.microsoft.com/cdo/configuration/smtpserver
cdoSMTPServerPort = http://schemas.microsoft.com/cdo/configuration/smtpserverport
cdoSMTPAuthenticate = http://schemas.microsoft.com/cdo/configuration/smtpauthenticate Microsoft Resource:
http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q286431&ID=KB;EN-US;Q286431& |
IIS and ASP pages hanging | I've seen the following: (Win 2000
& IIS v5)
(Note: I could NOT duplicate this problem on Win XP Prof IIS web server.
All ASP pages would server out even during the script timeout period.)Problem #1:
In a MSSQL DB environment, if a script that generates a SQL error is not
Error Trapped then all ASP pages appear to hang until the script times out.
(Ex SQL: select * zzz from MyTable ) Problem #2:
All ASP pages appear to hang (the script doesn't time out from the server
side). It is possible that the client's web browse could time out.
Other files work fine (ie: html, images, etc....).
To create this problem, setup problem #1 (SQL select error) and have 2 users
hit the ASP page at the same time that has a SQL select error.
How to un-hang IIS:
Win 2000 & Win XP Prof
| IIS Option #1:
In IIS Manager, right click on the web site (ie: Default Web Site) and
choose Properties
Click on "Home Directory"
In the Application Setting section, notice the Application Name setting
(ie: Default Application)
Click "Remove" accross from Application Name and then click Create.
Now any new hits to ASP pages will be served out. |
IIS Option #2: (This will stop and start the web server). | IIS Reset (Restart):
from the command line do: c:\ IISReset |
Solution to Problem #1 and #2: (also consider global.asa etc...) Place error trapping around the calls to execute when creating the
results set.
Example:
' Note: You do not have to create the "Err" object.
On Error Resume Next
Set rsUsers = docentlms.execute(strSql)
if ( Err.Number <> 0 ) Then
Response.Clear
Response.Write("Err.Number = " & Err.Number & "<br>" & vbCrLf)
Response.Write("Err.Description = " & Err.Description & "<br>" & vbCrLf)
Response.Write("Err.HelpContext = " & Err.HelpContext & "<br>" & vbCrLf)
Response.Write("Err.Source = " & Err.Source & "<br>" & vbCrLf)
Response.Write("Err.HelpFile = " & Err.HelpFile & "<br>" & vbCrLf)
Response.End
End If
|
Global.asa | Global.asa
- Placement of the file - IIS will use the Global.asa file if it is
placed in the root directory of the Web Site or a Virtual Web Site.
With that statement in mind, the closest Global.asa file will override
any Global.asa file in a parent directory. If there is no
Global.asa in the current virtual Web Site then the web server will use
the closest Global.asa in a parent Web Site. The closest
Global.asa will completely replace any Global.asa in a parent Web Site.
- In my testing of Win XP Pro and Win 2000 Server changes to the
Global.asa seem to be read immediately without a web server reset (or
restart) or without the user closing his browser and creating another
connection. This includes changes to the Application_xxx and
Session_xxx subs.
|
ASP & Server Name
(Network Server Name vs the HostName from the Client's URL) | Network Server Name vs the HostName from the Client's URL
This is the HostName from the client's URL:
Request.ServerVariables("SERVER_NAME")
Get The Network Server Name:
' (FYI - this will work in the Global.asa's Application_OnStart sub.)
Dim strNetworkServerName
Dim objWScriptNetwork
Set objWScriptNetwork = CreateObject("WScript.Network")
strNetworkServerName = objWScriptNetwork.ComputerName
Application("strNetworkServerName") = strNetworkServerName
|
WSH (Windows Script Host) | Windows Script Host Network Server Name:
Dim strNetworkServerName
Dim objWScriptNetwork
Set objWScriptNetwork = CreateObject("WScript.Network")
strNetworkServerName = objWScriptNetwork.ComputerName
|
File System | File System Example of creating a text file on the server and appending
text.
Dim objFileSystemObject
Dim objFile
Dim objFileStream
Set objFileSystemObject = Server.CreateObject("Scripting.FileSystemObject")
If ( objFileSystemObject.FileExists( Application("strLogFileLocation") ) )
Then
Set objFile = objFileSystemObject.GetFile(
Application("strLogFileLocation") )
' 8=ForAppending, -2 System Default 0 = ASCII
Set objFileStream = objFile.OpenAsTextStream(8, 0)
Else
Set objFileStream = objFileSystemObject.CreateTextFile(
Application("strLogFileLocation") )
End If
objFileStream.Write( strLogFileMsg )
objFileStream.Close In Download
zip file - see MyTextFileA.asp. |
Creating an Excel file. | Creating an Excel file: Dim strFileName
strFileName = "MyFile_" & _
DatePart("yyyy",Date) & _
right("0" & DatePart("m",Date), 2) & _
right("0" & DatePart("d",Date), 2) & _
".xls"
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "content-disposition","attachment; filename=" &
strFileName
Example of ASP code that will use the
Excel Sum function:
<td bgcolor="#808080">=SUM(B4:B6)</td>
Then add your normal html code. Be aware that some tags may have
conversion issues. Note: I have an example .asp page in my download
zip: MyExcelSpreadSheet.asp |
ASP (VBScript) - running from a
Windows Scheduled Task. |
ASP
VBScript - Running from a Windows Scheduled Task - see information on
trying to run ASP from a windows scheduled task. |
Running an ASP page from a batch
file. |
In Download zip file - see
MyTextFileA_batchfile_run_asp_via_ie.bat Example Batch file:
c:
cd "C:\_data\webs\A\michael-thomas.com\tech\asp\myaspexamples"
set strLogFile=MyTextFileA_batchfile_run_asp_via_ie.log
echo ************************************ >> %strLogFile%
echo Start: %date% %time% >> %strLogFile%
"C:\Program Files\Internet Explorer\IExplore.exe" "http://localhost/michael-thomas/tech/asp/myaspexamples/MyTextFileA.asp?loopcount=10000&closebrowser=no"
echo Stop: %date% %time% >> %strLogFile% |
VBScript Resources |
http://www.w3schools.com/asp/asp_globalasa.asp
http://support.microsoft.com/kb/164485 http://support.microsoft.com/kb/300883/en-us http://www.faqts.com |
Category |
Functions |
Variable Types |
TypeName, VarType
CBool, CByte, CCur, CDate, CDbl, CInt, CLng, CInt, CLng, Csng, CStr
IsArray, IsDate, IsEmpty, IsNull, IsNumeric, IsObjectNote: Use
the c... functions to convert a string to numeric.
Ex:
intMyVar = cInt( "123" )
lngMyVar = cLng( "123.99" ) |
Strings |
Asc, Chr, InStr, InStrRev,
LCase, Left, Len, LTrim, Mid, Replace, Right, RTrim, Space, StrComp,
String, StrReverse, Trim, UCase
FormatCurrency, FormatDateTime, FormatNumber, FormatPercent |
Numbers |
Abs, Atn, Cos, Exp, Fix, Hex, Int,
IsNumeric, Log, Oct,
Rnd, Round, Sgn, Sin, Sqr, Tan |
Date/Time |
Date, DateAdd,
DateDiff, DatePart, DateSerial, DateValue, Day,
Hour, IsDate, Minute,
Month, MonthName, Now, Second,
Time, TimeSerial, TimeValue, Weekday, WeekDayName, Year |
Arrays |
Array, Filter, IsArray,
Join, Split, IsArray, UBound |
Objects |
CreateObject, GetObject,
IsObject |
Scripting |
ScriptEngine,
ScriptEngineBuildVersion, ScriptEngineMajorVersion
|
Function | Info |
Abs
|
Abs(number)
Returns the absolute value of the number. (Converts all negative values
to positive values).
|
Array
|
Array(size,[dimensions])
Creates an array.
Notes:
Rows start from: 0
Columns start from: 1<ArrayName>(3) - Single dimensional
<ArrayName>(3, 5) - Multi-dimensional
Example: Single Dimensional Array created with Array()
Dim intDay
Dim arrDaysOfWeek
arrDaysOfWeek =
Array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
strMsg = strMsg & "Array created by Array()." & "<br>" & vbCrLf
For intDay = 0 to UBound(arrDaysOfWeek)-1 Step 1
strMsg = strMsg & intDay & " - " & arrDaysOfWeek(intDay) & "<br>" &
vbCrLf
Next
Response.Write( strMsg ) Example: Single Dimensional Array
Dim strMsg
Dim arrItems(4)
arrItems(0) = "January"
arrItems(1) = "February"
arrItems(2) = "March"
arrItems(3) = "April"
Dim intCounter
strMsg = strMsg & "Step through an array: Bottom up" & "<br>" &
vbCrLf
For intCounter = 0 to UBound(arrItems)-1 Step 1
strMsg = strMsg & intCounter & " - " & arrItems(intCounter) & "<br>" &
vbCrLf
Next
strMsg = strMsg & "<br>" & vbCrLf
strMsg = strMsg & "Step through an array: Top down (reverse)." &
"<br>" & vbCrLf
For intCounter = UBound(arrItems)-1 to 0 Step -1
strMsg = strMsg & intCounter & " - " & arrItems(intCounter) & "<br>" &
vbCrLf
Next
Response.Write( strMsg )
Example: Multi-Dimensional Array
Dim strMsgMulti
Dim intCounterMulti
Dim arrItemsMulti(3,2)
Const COL1MULTI = 1
Const COL2MULTI = 2
arrItemsMulti(0, COL1MULTI) = "Row #0 - Col #1"
arrItemsMulti(0, COL2MULTI) = "Row #0 - Col #2"
arrItemsMulti(1, COL1MULTI) = "Row #1 - Col #1"
arrItemsMulti(1, COL2MULTI) = "Row #1 - Col #2"
arrItemsMulti(2, COL1MULTI) = "Row #2 - Col #1"
arrItemsMulti(2, COL2MULTI) = "Row #2 - Col #2"
strMsgMulti = strMsgMulti & "Step through an Multi-Dimensional array:
Bottom up" & "<br>" & vbCrLf
For intCounterMulti = 0 to UBound(arrItemsMulti)-1 Step 1
strMsgMulti = strMsgMulti & intCounterMulti & " - " &
arrItemsMulti(intCounterMulti,COL1MULTI) & " : " &
arrItemsMulti(intCounterMulti,COL2MULTI) & "<br>" & vbCrLf
Next
Response.Write( strMsgMulti )
|
Asc | Asc(string)
Returns the ANSI code for the first letter in the string.
Each letter in the alphabet (and some special characthers) has got it's
own numeric value. To find this value use the Asc() function. The
reverse function is Chr().
|
Atn | Atn(number)
Returns the arctangent.
|
CBool | CBool(expression)
Converts to variant of subtype Boolean
|
CByte | CByte(expression)
Converts to variant of subtype Byte
|
CCur | CCur(expression)
Converts to variant of subtype Currency
|
CDate | CDate(expression)
Converts to variant of subtype Date
|
CDbl | CDbl(expression)
Converts to variant of subtype Double
|
Chr | Chr(expression)
Converts ANSI code to the corresponding keyboard character
Common Uses:chr(13) Carriage return
chr(13)&chr(10) Combination carriage return and line feed
chr(12) Form feed
chr(10) Line feed
chr(9) Horizontal tab
chr(11) Vertical tab
|
CInt | CInt(expression)
Converts to variant of subtype Integer
|
CLng | CLng(expression)
Converts to variant of subtype Long
|
Cos | Cos(number)
Returns the cosine
|
CreateObject | CreateObject(servername.typename)
Creates an server object. |
Csng | Csng(expression)
Converts to variant of subtype Single
|
CStr | CStr(expression)
Converts to variant of subtype String
|
Date | Date
Returns the date according to the system.
ex: date() returns: 5/31/2007
Note: This is the time of the server in the time zone of the server.
This is not GMT time.
Warning: This value is only the Date and does not include the
time.Also see: Now(), Time() |
DateAdd | DateAdd(interval,number,date)
Adds the time interval to date. The interval argument accepts the
following values:
Interval options:
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week of year
h Hour
n Minute
s Second
Examples:
DateAdd("d",1,Now()) - adds one day.
|
DateDiff | DateDiff(interval,date1,date2[,firstdayofweek[,firstweekofyear]])
Returns the number of intervals between two dates. The interval argument
accepts the following values:
Interval options:
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week of year
h Hour
n Minute
s Second
Examples:
date1="01.01.2001"
date2="01.02.2001"
DateDiff("d",date1,date2) -> 31
|
DatePart | DatePart(interval,date[,firstdayofweek[,firstweekofyear]])
Returns the designated part of the time. The interval argument accepts
the following values:
Interval: Description:
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week of year
h Hour
n Minute
s Second
|
DateSerial | DateSerial(year,month,day)
Converts to subtype Date
|
DateValue | DateValue(date)
Converts to subtype Date
Examples:
Dim dateRegStartDate
dateRegStartDate = DateValue("31-Jan-02")
' You may want to use this to convert a SQL results set value to a
Date.
' This value does NOT accept a time value. |
Day | Day(date)
Returns the day of the month according to the argument
|
Exp | Exp(number)
Raises e to the number of number.
|
Filter | Filter(InputStrings,Value[,Include[,Compare]])
Creates a new array according to the filter criteria. |
Fix | Fix(number)
Converts to integer (rounds up for negative numbers)
|
FormatCurrency | FormatCurrency(Expression [,NumDigitsAfterDecimal
[,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])
Formats currency according to the settings of the server and the
parameters given.
|
FormatDateTime | FormatDateTime(Date[,NamedFormat])
Formats dates and times.
Default format: mm/dd/yyyy
Default time: hh:mm:ss AM/PM
<% =FormatDateTime("4/17/07") %> 4/17/2007
<% =FormatDateTime("17:30") %> Results: 5:30:00 PM
<% =FormatDateTime(Now()) %> Results: 5/7/2007 12:41:28 PM
<%= FormatDateTime(Now(), 0) %> Results: 5/7/2007 12:37:47 PM
<%= FormatDateTime(Now(), 1) %> Results: Monday, May 07, 2007
<%= FormatDateTime(Now(), 2) %> Results: 06/01/2007
<%= FormatDateTime(Now(), 3) %> Results: 5:30:00 PM
<%= FormatDateTime(Now(), 4) %> Results: 17:30 Note:
24 hr clock
Constant | Value | Description |
VBGeneralDate | 0 | Display the date and time using system settings |
VBLongDate | 1 | Display the date in long date format
Tuesday, April 17, 2007 |
VBShortDate | 2 | Display the date in short date format
04/17/07 |
VBLongTime | 3 | Display the time in long time format
5:00:00 PM |
VBShortTime | 4 | Display the time in short time format (24 hour clock)
17:00 |
|
FormatNumber | FormatNumber(Expression [,NumDigitsAfterDecimal
[,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])
Formats numbers.
|
FormatPercent | FormatPercent(Expression [,NumDigitsAfterDecimal
[,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])
Formats percentages.
|
GetObject | GetObject([pathname][,class])
Returns the specified Automation object from the specified file. |
Hex | Hex(number)
Returns the hexadecimal value of number.
|
Hour | Hour(time)
Returns the hour according to the time argument.
|
InStr | InStr([start,]string1,string2[,compare])
Returns the first appearance of string2 within string1.Return of 0 =
not found. start (optional) integer - The starting position for the search
compare (optional) integer - The type of string comparison. (0=Binary
(default), 1 = Text (case insensitive))
|
InStrRev | InStrRev(string1,string2[,start[,compare]])
Returns the last appearance of string2 within string1.
|
Int | Int(number)
Returns an integer (rounds down for a negative number).
|
IsArray | IsArray(varname)
Determines whether a variable is an array
Example:
DIM myarray(1,2)
DIM myvariable
IsArray(myarray) = True
IsArray(myvariable) = False
|
IsDate | IsDate(expression)
Determines whether a expression can be converted to date format
|
IsEmpty | IsEmpty(expression)
Determines whether the variable has been initialized.
|
IsNull | IsNull(expression)
Determines whether expression is null.
|
IsNumeric | IsNumeric(expression)
Determines whether expression is a number.
|
IsObject | IsObject(expression)
Determines whether expression is an object.
|
Join | Join(list[,delimiter])
Joins substrings in an array separated by the charcather indicated by
delimiter.
|
LCase | LCase(string)
Changes the string to lowercase.
|
Left | Left(string,length)
Returns the left string portion of the designated length.
|
Len | Len(string[,varname])
Returns the length of the string or the byte size of the variable.
|
Log | Log(number)
Returns the natural logarithm of the number.
|
LTrim | LTrim(string)
Removes extra spaces to the left of the string.
|
Mid | Mid(string,start[,length])
Returns a string portion of the designated length starting from the
argument start.
|
Minute | Minute(time)
Returns the minute according to the time argument.
|
Month | Month(date)
Returns the month represented by the number.
|
MonthName | MonthName(month[,abbreviate])
Returns the month represented by the name.
|
Now | Now()
Returns the current date and time according to the system.
Response.Write( Now() )
Ex: 5/31/2007 3:33:50 PM (Date/Time of the server's time zone (not
GMT) )Also see: Date(), Time() |
Oct | Oct(number)
Returns the octal value of number. |
Replace | Replace(expression,find,replacewith[,start[,count[compare]]])
Replaces the designated substring <find> with the substring <replacewith> the designated number of times.
Example:
strExample = Replace("Hello World example of remove spaces"," ","") -
this will remove the spaces. |
Right | Right(string,length)
Returns the right string portion of the designated length. |
Rnd | Rnd([number])
Generates a pseudo-random number.
Example:
Randomize ' Needed for Rnd() to generate a true random number.
Response.write(Rnd()) |
Round | Round(number[,numdecimalplaces])
Rounds number to the specified number of decimal places.
|
RTrim | RTrim(string)
Removes extra spaces at the right.
|
ScriptEngine | ScriptEngine()
Reurns the name of the scripting language in use
|
ScriptEngineBuildVersion | ScriptEngineBuildVersion()
Reurns the build version of the scriptengine in use.
|
ScriptEngineMajorVersion | ScriptEngineMajorVersion
Returns the major version number of the script engine.
|
Second | Second(time)
Returns the second according to the time argument.
|
Sgn | Sgn(number)
Returns the sign of the number.
|
Sin | Sin(number)
Returns the sine of the number
|
Space | Space(number)
Creates a string with the specified number of spaces. |
Split | Split(expression[,delimiter[,count[,compare]]])
Splits a string and converts it into an array.
|
Sqr | Sqr(number)
Returns the square root of the number.
|
StrComp | StrComp(string1,string2[,compare])
String comparison.
|
String | String(number,character)
Creates a string with character repeated the specified number of times.
|
StrReverse | StrReverse(string)
Reverses the charcters of a string.
|
Tan | Tan(number)
Returns the tangent of the number.
|
Time | Time
Returns the current time according to the server clock
Also see: Date(), Time() |
TimeSerial | TimeSerial(hour,minute,second)
Returns Date Variant.
|
TimeValue | TimeValue(time)
Returns Date Variant containing time.
|
Trim | Trim(String)
Removes extra spaces at each side of a string
|
TypeName | TypeName(varname)
Returns the subtype by name.
|
UBound | UBound(arrayname[,dimension])
Returns the upper bound of the array dimension. If no dimension is
specified, the first dimension is used.
|
UCase | UCase(string)
Changes the string to uppercase.
|
VarType | VarType(varname)
Returns subtype by value.
Value Description
0 Uninitalized (default)
1 Contains no valid data
2 Integer subtype
3 Long subtype
4 Single subtype
5 Double subtype
6 Currencey subtype
7 Date subtype
8 String subtype
9 Object
10 Error subtype
11 Boolean subtype
12 Variant (only used for arrays of variants)
13 Data acces object
14 Decimal subtype
17 Byte subtype
8192 Array
|
Weekday | Weekday(date[,firstdayofweek])
Returns the day of the week by number. |
WeekdayName | WeekdayName(weekday[,abbreviate[,firstdayofweek]])
Returns the day of the week by name. |
Year | Year(date)
Returns the year according to the argument |
|
|