HAL-PC Web Technolgies SIG

Mail List | SIG Leader

Page Name

HAL-PC Web Technologies SIG

extra stuff

Description

Tip

A caveat when using ASP's Response.Redirect method When ASP encounters the Response or End methods, it immediately halts script execution in both the GLOBAL.ASA file and in the application page. As a result, ASP won't execute any script that follows the Redirect method. Instead, it either ends the session or begins processing the new page. For this reason, you should always make the Redirect method the last call in any script.
Avoid boolean comparison errors in ASP Often in VBScript, you'll want to determine if a numeric value is greater than zero then perform some action based on the results. For example, you'll often want to know if a recordset contains records. To do so, you can simply use the results in a boolean expression, like so

If rst.RecordCount Then
'Do something
End If

This works because VBScript, like VB and VBA, considers any non-zero number (negative or positive) a True boolean value.

Be warned, however, that bugs can occur when you try to use Not with this same expression, as in

If Not rst.RecordCount Then

You might think this test would determine if the recordset didn't contain records. It does when the RecordCount property returns -1 ((Not -1) = 0). However, if the property returns the actual number of records, then this condition statement returns True. That's because when you use Not on a number, VBScript returns the opposite
value of that number minus one. For instance, the expression Not 15 returns -16, which as you know VBScript interprets as True. With regard to the record count test, if the property returns -1, then there's no problem, since the result is (1-1) or 0. However, when the property contains an actual value, then Not rst.RecordCount
evaluates to a non-zero number, which again VBScript evaluates as True.

To get around this minor glitch, you can use one of the following statments:

If Not Cbool(rst.RecordCount) Then

or

If Not (rst.RecordCount<>0) Then

or simply

If rst.RecordCount = 0 Then
Create Visual InterDev 6.0 ASP code templates Instead of retyping the same code lines on virtually every ASP page that you create in Visual InterDev 6.0, simply open Program Files | Microsoft Visual Studio | VIntDev98 | Templates | Web Project Items | New ASP Page.asp file, and then enter the code that you want duplicated, i.e. included files, titles, metatags. Save your work, and any new ASP page that you create will contain the new code.

Submitted by: Will Smith [will@newtweb.com ]
Determine browser capabilities in an ASP page When you use the Browser Capabilities component in an ASP page, you can determine client browser attributes: such as if the calling browser supports frames, VBScript, or javascript. You can also determine the browser's version and type, such as Internet Explorer 5.0, or Netscape Navigator 4.6. For example, to determine if a browser supports frames, you could use code similar to:

<%
Dim objBrowsCap
Dim blnAllowsFrames

Set objBrowsCap = Server.CreateObject ("MSWC.BrowserType")
blnAllowFrames = objBrowsCap.frames
If blnAllowFrames Then
'Code for frames goes here
Else
'Code for non-frames goes here
End If

Set objBrowsCap = Nothing
%>

Unfortunately, this component relies upon the server's browscap.ini file to determine the latest information on client browser. The Browser Capabilities component simply reads the INI file and returns the values contained therein. If the browscap.ini file is out of date and doesn't have information on the requesting browser, the component uses the INI file's default values, which may or may not contain the correct capablilities.

To avoid having to constantly update the INI file yourself, you can check out Cyscape, Inc.'s Web site at http://www.cyscape.com/browscap . They offer a continually updated INI file. In addition, they've developed a utility called BrowserHawk that, among other features, automatically detects new browsers and updates the appropriate files.
Eliminate default page renaming Have you ever experience the annoying problem where Copy Web copies the Web to the appropriate server but renames the default.asp page to default.htm? The problem is really caused by a bug in the Microsoft FrontPage extensions. Any Web application that contains a Default.asp in the root will rename the file when copied using the "Copy Web Application" command to default.htm in the destination Web application. To eliminate the problem, simply add a page named default.htm to the existing Web site.
Ensure accurate string comparisons in ASP pages As you probably know, the StrComp() function provides a quick way to compare two strings. It takes the following syntax:

StrComp( string1, string2, comparemode)

VBScript compares the two strings according to either the comparemode argument, or the default setting on the server. This function returns 1 if the first string is greater than the second string, 0 if the two are equal, and -1 if the first string is less than the second. However, if you want to compare strings taken from user input, to ensure that the results are accurate, remove any extra spaces from the two strings. For example, you could use something like:

StrComp( Trim(str1), Trim(str2))

Strings with extra spaces will provide inaccurate results. To illustrate, create the following ASP page, and then view it in Internet Explorer.

<html>
<head>
<script language="VBScript">
sub mySort()
Dim str1, str2, ary, sCompare

str1 = document.all.txt1.value
str2 = document.all.txt2.value

Select Case StrComp(trim(str1), trim(str2))
Case 1: sCompare = "greater than"
Case 0: sCompare = "equal to"
Case -1: sCompare = "less than"
End Select

MsgBox str1 & " is " & sCompare & " " & str2
end sub
</script>

<body>
<form>
<input type="text" id="txt1" /><br /><br />
<input type="text" id="txt2" /><br /><br />
<input type="button" value="Compare" onclick="mySort" />
</form>
</body>
</html>

First, enter an A; into the first field and a Z; into the second, then click the Compare button. When you do, VBScript informs you that A is less than Z, as you would expect. Now, enter a space before the Z and click the button again. This time the message box inaccurately claims that A is greater than Z.
Ensure proper remote scripting parameter types in ASP As you probably know, remote scripting is a great way to access server-side functions and procedures from client-side scripting. However, when you use parameters in a server-side function intended for client-side use, remember that IIS converts all parameter values into strings. As a result, if necessary, you'll want to
convert these values back into their proper data type within the server-side function. Also, keep in mind that for security reasons, IIS doesn't let you pass structured data (objects or arrays) as remote scripting parameters.
Generate accurate ADO RecordCount values in ASP As you know, the ADO RecordCount property returns the number of records in an ADO recordset. Of course, in several instances, this property also returns a -1 instead. The value RecordCount returns depends on the recordset's cursor type: -1 for a forward- only cursor; the actual count for a static or keyset cursor; and either -1 or the actual count for a dynamic cursor, depending on the data source.

You may be surprised to learn that RecordCount will be -1 for recordsets created with the Execute method from a Connection or Command object. That's because this method generates a forward-only recordset, which, as we mentioned earlier, returns -1.

As an example, enter and run the following procedure in a standard ASP page. When you open it, the page displays -1 for the recordset based on myConRst, and 6246 for myKeyRst.

<%
Dim myConn, myComm, myConRst, myKeyRst
Dim sConnection
sConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=D:\Microsoft Visual Studio\VB98\Biblio.mdb"

Set myConn = Server.CreateObject("ADODB.Connection")
Set myKeyRst = Server.CreateObject("ADODB.Recordset")

myConn.Open sConnection
myComm = "Select * From Authors"
Set myConRst = myConn.Execute(myComm, , 1)

myKeyRst.Open myComm, myConn, 1
%>

RecCount <BR/>
From Connection: <%=myConRst.RecordCount %><BR/>
From Recordset: <%=myKeyRst.RecordCount%>

<%
Set myKeyRst = Nothing
Set myConRst = Nothing
Set myConn = Nothing
%>
Globally replace text using just 5 lines of VBScript If you've ever tried to implement a text search and replace
function in an ASP page, you probably resorted to lengthy parsing
loops that used Instr() and an entire host of string functions.
If so, you'll be glad to know that there's a much easier way.

With the advent of VBScript 5.0, (IIS 5.0) Microsoft introduced
the Regular Expression engine. If you've used Perl or javascript,
you may be familiar with these pattern-matching powerhouses. In a
nutshell, regular expressions let you define a pattern, literal
or representative, which you can then match against a second
string. For example, the literal pattern 'abc' as a regular
expression would find a match in 'dabcef', 'abcdef', or 'defabc'.
To further refine a regular expression, the Regular Expression
engine offers a host of special metacharacters, similar to wildcard
characters. For example, using these metacharacters, you could
search for any word that began with a letter and ended in a digit.
To view these metacharacters and their uses, visit

http://msdn.microsoft.com/scripting/default.htm

then search in the VBScript documentation for the RegExp object's
Pattern property. (If you don't have IIS 5.0, all you really need
is the latest version of VBScript, which you can download from
http://www.microsoft.com/msdownload/vbscript/scripting.asp )

To create a simple find and replace subroutine with client-side
VBScript, first create a RegExp object, like so

<script language="VBScript">
Sub GoReplace()
Set myReg = new RegExp

Next, set the object's properties.

myReg.IgnoreCase = True
myReg.Global = True
myReg.Pattern = "abc"

Here, we've used a literal string to create a global, case-
insensitive pattern. Finally, you execute the object's Replace
method on a target string, as in

document.all.myTextArea.value = myReg.Replace(document.all.myTextArea,
"def")
End Sub
</script>

That's *all* there is to it! This example would replace "abc" with
"def" wherever it occurred within myTextArea. To execute the replace
on the first matching string only, set the Global property to False.
How to Increase the Speed of Large Uploads If you anticipate large uploads, increase Internet Information Server's (IIS) UploadReadAhead value to enable faster transfers. UploadReadAhead is an IIS parameter that contains the amount of data that the server will read before passing control to the application. The application is then responsible for reading the rest of the data. The default UploadReadAhead is 48kb. With a higher UploadReadAhead, transfers will be faster, but uploading will utilize more physical memory. If you increase the UploadReadAhead value, increase the amount of RAM on the server as well.

To increase the UploadReadAhead value,

1. Go to Start\Run
2. Enter regedt32 to open the registry
3. Open,
HKEY_LOCAL_MACHINE\
SYSTEM\
CurrentControlSet\
Services\
W3SVC\
Parameters\
UploadReadAhead
4. Highlight the UploadReadAhead value (in the right frame)
5. Open Edit and select DWORD
6. Enter a new value in the Data window

If the UploadReadAhead parameter does not exist in your registry, you can add it. To add the parameter,

1. Open the Edit menu
2. Select Add Value
3. Enter "UploadReadAhead" in Value Name
4. Enter REG_DWORD in Data Type
5. Click Ok

Enter the value in kb
Include VBScript variables in ASP SQL statements Often, you'll no doubt want to include a VBScript variable in an ASP SQL statement. For example, suppose you want to let a user search a table for names that begin with a letter they specify. To use a variable in a SQL statement, simply concatenate the various parts of the statement together. To see how this works, create an ASP page with the following code:

<HTML>
<BODY>
<FORM Name="test" Action="SQLVars.asp" Method="POST" >
<INPUT Name="txtSearch" TYPE="TEXT" Size=15
VALUE="SearchForMe">
<INPUT Type="SUBMIT" VALUE="Submit">
</FORM>
<%
Dim strSQL1
Dim strSQL2
Dim strSearch

strSearch = Request.Form("txtSearch")
If Len(strSearch) Then
strSQL1 = "Select From Customer(MyField) Where " _
& "Name(Col.Name) Like 'strSearch%'"

strSQL2 = "Select From Customer(MyField) Where " _
& "Name(Col.Name) Like '" & strSearch & "%'"
End If
%>
<UL>
<LI>Before concatenation: <%=strSQL1%>
<LI>After concatenation: <%=strSQL2%>
</UL>
</BODY>
</HTML>

When you run the page, only strSQL2 contains the variable's actual value, which can then be sent on to SQL Server, or any other database that processes SQL statements. Also, notice the use of the single quote before the double quote and after the percent sign. This ensures that the database interprets the variable's value
as a string.
Let the Scripting type library verify a file's existence The FileSystemObject offers a great way to manipulate a server's directory structure. With the FileExists method, you can determine if a file exists at runtime. This method conforms to the following syntax:

object.FileExists(filespec)

where object is a FileSystemObject variable and filespec is the file's path (absolute or relative). If you expect the file to be in the same folder as the ASP page running the script, then you only need to specify the filename. This method follows the same syntax in both VBScript and javascript. So, suppose you wanted to use this handy method to search for a file in an images folder. To do so, use code similar to

blnExists = fso.FileExists(Server.MapPath("/images/Some.gif")

Here, the code searches the server's root directory for the Some.gif file. It returns True if the file exists, and False if not.

In addition to the FileExists method, the FileSystemObject also exposes FolderExists and DriveExists methods, both of which follow the same syntax.
Obtain a header list with ASP's ServerVariables collection The SeverVariables collection contains all kinds of information about the calling client and the server. For instance, you can determine a visitor's browser type with the HTTP_USER_AGENT variable. Or, you can use HTTP_REFERER to determine the referring Internet address. Not all browsers support the same headers, however. To see a quick list of the headers supported within a browser, run the following code.

<HTML>
<BODY>
<TABLE BORDER=1>
<TH COLSPAN=2>ServerVariables</TH>
<%
For Each var in Request.ServerVariables
With Response
.Write("<TR>")
.Write("<TD><B>" & var & "</B>:</TD>")
.Write("<TD>" & Request.ServerVariables(var) _
& "</TD>")
.Write("</TR>")
End With
Next
%>
</TABLE>
</BODY>
</HTML>
Parsing multiple selected options in server-side ASP In a previous tip, we showed you how to gather multiple selections from an HTML Select element on the client side. However, when you obtain these values after a Get or Post request, you need to use a different technique. That's because these multiple values get passed as a comma-delimited string. So, say you had a Select element named "Lst1" on a form. If you selected three options with values 5, 6, and 7, and submitted the form, then

Request.Form("Lst1")

would contain the string "5, 6, 7". As a result, you'll need to parse this string to get the individual values. To do so, you have two options. First, you can use the Split() function to place the values into an array. Or, if you don't have a version of IIS that supports the Split() function, you can use the Instr() function and search for the comma character within the string. As an example, create an HTML page named GetOptions.html and add the following form to it:

<form id="frm1" action="GetOptions.asp" method="post">
<select size=10 multiple="multiple" name="Lst1" id="Lst1">
<option value="1">Sunday</option>
<option value="2">Monday</option>
<option value="3">Tuesday</option>
<option value="4">Wednesday</option>
<option value="5">Thursday</option>
<option value="6">Friday</option>
<option value="7">Saturday</option>
</select>
<br /><br /><input type="submit">
</form>

Next, create an ASP page named GetOptions.asp and add the following code:

<%
' Parse request string using Split()
Dim sSelected, arySelected, x
sSelected = Request.Form("Lst1")
Response.Write("You selected: " & sSelected & "<br />")

Response.Write("<br /><b>Split()</b><br />")
arySelected = Split(sSelected, ",")
For x = 0 to Ubound(arySelected)
Response.Write("Choice " & x & ": " & arySelected(x) & "<br />")
Next

Response.Write("<br /><b>Instr()</b><br />")

' Parse request string using Instr()
Dim subString
x = 0
sSelected = sSelected & ","

Do Until Instr(sSelected,",") = 0
Response.Write("Choice " & x & ": " & Left(sSelected, _
instr(sSelected,",") -1) & "<br />")
sSelected = Mid(sSelected, instr(sSelected,",") + 1)
x=x+1
Loop
%>

Note, that the same techniques would work with Response.QueryString("Lst1") as well.
Prevent spam before it starts with our Jscript If you're like us, then you're getting really, *really* tired of
all the spam mail piling up in your in box. While we can't tell
you how to get rid of it entirely, we can give you a tip that
will help cut down on spam.

As you may know, most spam list generators work by browsing the
Web and gleaning email addresses from Web sites. Because of an
email address' distinct format, it's pretty easy to find one in a
page. Well, you'll be happy to know there's a technique that lets
your email addresses show up in a page, but still defeats the spam
list spiders. The trick is to use a javascript function, like the
one that follows, to generate the email addresses:

<script language="javascript">
<!-- Hide from old browsers
function ShowAddress(part1, part2)
{
var addr = part1 + "@" + part2;
var result = ("<a href='" + "mail" + "to:" + addr + "'>" + addr + "</a>")
return result;
}
//-->
</script>

To make an email address appear in the page, call the function like so:

<script language="javascript">
<!--
document.write(ShowAddress("wdv","zdjournals.com"));
//-->
</script>

Now, won't those spam list spiders be baffled!

Submitted by: Vik Nokhoudian, World Wide Web Associates [vik@wwwa.com ]
Register WSC scripts before using them in ASP The Windows Scripting Component is a great tool that let's you create COM components for use in ASP pages. What's more, you can use either VBScript or javascript to give them functionality. When you create a WSC component, however, you must register it before you can use it in an ASP page. To do so, open Windows Explorer and right-click on the WSC file you just created. Select Register from the shortcut menu. To create an object variable based on the new script object, use code similar to

Set objXMLCreate = Server.CreateObject("MyScriptObj.WSC")

At this point, you're free to access any of the object's methods and properties.
Setting checkbox values from an Access database Often you'll want to display a checkbox value stored in an Access database in an ASP page. Depending on the setting in your Access table, Access may display Yes/No, On/Off, or True/False in the field when you view the table in the database. As a result, you may think to use ASP similar to

<input type="checkbox" name="chk1" value="Yes" <% if rs("checkfield")="yes"
then %>
checked="checked" <% end if %> />

However, this doesn't actually work. That's because even though Access displays the field contents as a Yes or No, it stores the contents as True or False, (-1 and 0 respectively). To get an accurate checkbox setting in ASP, use

<input type="checkbox" name="chk1" value="Yes" <% if rs("checkfield")=True
then %>
checked="checked" <% end if %> />
Simplify loading stored values via ASP When loading an <OPTIONS> list from a database table, it's much easier to call a procedure that uses process parameters. This way, you can use the same procedure for several different operations. For example, suppose you want to fill a Listbox with a list of animals. In addition, you've set up several checkboxes on a Web page that let the user simply view the list, or load the list with one of the animals already selected. The following example shows how you might process the resulting page. (To save space, we hard-coded the two parameters.)

<!-- #include File="DBConnect.Asp" -->
<HTML>
<BODY>
<FORM>
<SELECT name=Atype size= 5>

<%
Dim chkMode
chkMode = 2 'or Request.Form("chkMode")
fillOptionList chkMode,"Snake"
%>
</SELECT>

<%
Sub fillOptionList(myMode, optionValue)

Dim rsAnimal
Dim strSelected

set rsAnimal = CreateObject("ADODB.recordset")
With rsAnimal
.Open "tblAnimals", strDB, adOpenStatic,,adCmdTable

Do While Not .EOF
Select Case myMode
Case 1
strSelected = ""
Case Else
If optionValue = rsAnimal("Animal") Then
strSelected = " SELECTED"
Else
strSelected = ""
End if
End Select

Response.Write("<OPTION" & strSelected & " VALUE=" _
& rsAnimal("ID") & ">" & rsAnimal("Animal") & "</OPTION>")
.MoveNext
Loop

.Close
End With
Set rsAnimal = Nothing
End Sub

%>

</BODY>
</HTML>

For the OPTION elements, this code produces output HTML like this:

<SELECT name=Atype size= 5>

<OPTION Value=1>Cat</OPTION>
<OPTION Value=2>Cow</OPTION>
<OPTION Value=3>Dog</OPTION>
<OPTION SELECTED Value=4>Snake</OPTION>
<OPTION Value=5>Elephant</OPTION>
<OPTION Value=6>Fish</OPTION>

</SELECT>

Submitted by: Faisal Ladak [fladak@systech-inc.net]
Use a single ADO connection to reduce ASP server load If you need to execute multiple SQL statements on a single database in a single ASP page, it's often wise to open a single Connection and reuse it multiple times. Doing so reduces the number of times the server must open and close the same database, which can significantly increase the server's load. To use a single connection, create the database Connection at the beginning of the page, then destroy it at the end. When you Execute a SQL statement, whether it returns a Recordset or not, specify the active Connection. Here's an example.

<%
strDSN = "DSN=database;UID=username;PWD=password"

Set conn = Server.CreateObject("ADODB.Connection")
conn.Open strDSN

strSQL = "select column from table"

Set rsResults=conn.Execute(strSQL, , 1)

if not rsResults.eof then
temp = rsResults("column")
else
temp = "No Results"
end if

'close the Recordset, but leave the Connection open
rsResults.Close

strSQL = "delete from table where column=123"
conn.Execute strSQL, , 1

'Done executing SQL statements at this point, so close the Connection.
conn.Close

set rsResults = Nothing
set conn = Nothing
%>

Submitted by: Brian Coverstone [brian@pcioh.com]
Use ADO's native OLEDB drivers instead of ODBC When you create an connection string, ADO gives you a choice between indicating a data source driver as either a Driver, as in

Driver={SQL Server};DBQ=database_file

or a Provider, such as

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=database_name

However, when you use the first option, ADO uses older ODBC drivers to connect to the data source; whereas the second form uses OLEDB, which is ADO's native data access interface. For this reason, you should use the Provider option whenever possible. Such native OLEDB drivers exist for SQL Server, Index Server, Site Server Search, and Oracle, among others.
Use VBScript's RegExp object to validate email address syntax Nowadays, if your Web application requires a user to enter
specific company information, you probably have a field for
an email address. No doubt, you'll want to ensure that the
address not only contains the @ and dot, but that the remaining
characters contain only letters, numerals, or underscores (and
perhaps a dash or period). At first, this may seem like a daunting
task. And if you use standard VBScript's string functions alone,
it will be. Fortunately, the RegExp object provides an easier way.

The following code validates an email address in a textbox named Text1:

<head>
<script language="VBScript">
Sub checkEmail(sEmail)
Dim myReg
Set myReg = New RegExp
myReg.IgnoreCase = True
myReg.Pattern = "^[\w-\.]+@\w+\.\w+$"
msgbox myReg.Test(sEmail)
End Sub
</script>
</head>
<body>
<form>
<input type="text" id="txtEmail" name="txtEmail"></input>
<input type="button" onclick="checkEmail(document.forms(0).txtEmail.value)"
value="Verify"></input>
</form>
</body>

Here, the pattern accepts any number of numeric, underscore, letters,
periods, or dash characters before the @ character and only numerals,
underscores, or letters before and after the dot.
Why relative filespecs may not work in ASP Even though the helpfile states you can use relative directory paths with FileSystemObject objects, you probably encountered an error if you tried to use them in an ASP path. That's because the directory that contains the ASP page doesn't become the current directory, as far as the FileSystemObject is concerned. To illustrate, run the following VBScript code in an ASP page:

<%
Set FileObject = Server.CreateObject("Scripting.FileSystemObject")
filespec="\test.jpg"
CurrDir = FileObject.GetAbsolutePathName(".")
Response.Write "Using CurrDir: " & CurrDir & filespec & "<br>"
if FileObject.FileExists(filespec) then
Response.Write "[CurrDir] File Found<br>"
else
Response.Write "[CurrDir] No File found<br>"
end if

Response.Write "Using MapPath: " & Server.MapPath(filespec) & "<BR>"
if FileObject.FileExists(Server.MapPath(filespec)) then
Response.Write "[MapPath] File Found<br>"
else
Response.Write "[MapPath] No File found<br>"
end if

Set FileObject = Nothing
%>

About Us | Site Map | Advanced Search | Privacy Policy | Contact Us | ©1999-2006 HAL-PC Web Technologies SIG Leader Cheryl D. Wise