Error checking with ASP classic VbScript

Here is a handy snippet for those rare occasions when you bother to error check.

 

If Err.Number <> 0 Then
subject = "Error creating early alert"
email_message = "There was the following error while creating an early alert record: " & Err.Number & " : " & Err.Description
sendEmail adminEmail, email_message, from_email, subject
End If

Can deliver a helpful error message such as:

There was the following error while creating a record: -2147217900 : Unclosed quotation mark after the character string ‘Failed a quiz/test’.

Asp array from comma delimited list

This is a handy snipped to create an array from a list of items separated by a comma, like you would get submitted from a checkbox group. Its as easy as using the “Split” function as so:

MyString = "ItemOne, ItemTwo, ItemThree"
MyArray= Split(MyString , ",")

 

You could then access the elements using the standard array language MyArray(x)

For x = LBound(MyArray) to UBound(MyArray)
    Response.Write MyArray(x)
Next

Get ID of last record inserted – VBScript – SQL Server

Here is the technique to get the ID number of the last record inserted (right as you insert it)

Dim db,rcs,new_identity

‘Create a database connection
Set db = Server.CreateObject(“adodb.connection”)
db.Open “DSN=MyDSN”

‘Execute the INSERT statement and the SELECT @@IDENTITY
Set rcs = db.execute(“insert into tablename (fields,..) ” & _
“values (values,…);” & _
“select @@identity”).nextrecordset

‘Retrieve the @@IDENTITY value
new_identity = rcs(0)

Automation: open and close a form every year.

As complex paperless forms become full fledged web applications, there is a growing need for automation such as  having a form available to be used from a certain date/time range. For example,  a health insurance sign up that opens on December 1 at 9:00 AM and closes on December 24th at 5:00pm Pacific Time. We want these times to be hard coded for the server, in case the users  are from different time zones, we want everyone to be able to sign up at exactly the same server time, regardless of their location. So if they were from New York, they would be open to sign up at 3pm December 1st, etc….

We need a few variables.
open_date – the date / time that the form will open
close_date – the date / time that the form will close
today_date_server – the current date/time of the servertoday_date_user – the current date/time of the users machine.
user_time_difference – the difference between the users time and the servers time. this could be used to display correct messages about when the user can sign up.

openorclosed – this will be set by the logic then used to display the correct messages and ui views
closedmessage – this will be a spot for the special message that will display to the user when the form is closed.

So now that I have my variables set up, lets put them to use. I will compare the dates and make sure that today is within the form opening range. Then I will set the openorclosed variable to open or closed based on the results. The I will update the ui view according to the openorclosed variable.

Here is the final form opening and closing automation logic in VbScript:

open_date = "9/2/" & year(NOW) & " 09:00 AM"
close_date = "10/14/" & year(NOW) & " 05:00 PM"
today_date_server = NOW()
datediffopen = DateDiff("n",today_date_server, open_date)
datediffclosed = DateDiff("n", today_date_server, close_date)
If datediffopen < 0 and datediffclosed > 0 Then
openorclosed = "open"
Else
openorclosed = "closed"
End If

This will automatically open and close the form to the users every year. Hooray for Automation!

Now I can manipulate the ui view using the variables, so the user will know when the form is open and why its closed.

[code language=”vb”]
If datediffopen > 0 and datediffclosed > 0 Then
‘display message for before the form has opened for the year.
openorclosedmessage=”The nomination form will be open from ” & open_date & ” to ” & close_date & “. Please submit your nominations between this time period for them to be considered.”
ElseIf datediffopen < 0 and datediffclosed < 0  Then
‘display message for after form has closed for the year.
openorclosedmessage=”The nominations were due by ” & close_date & “. The nominations are over for the ” & year(NOW) & ”  year. The nomination form is closed.”
End If[/code]

To display the date and time in a user friendly format –  Tuesday, October 14, 2014 at 5:00:00 PMuse the FormatDateTime function:
[code language=”vb”]FormatDateTime(close_date, 1)  at FormatDateTime(close_date, 3)[/code]

To debug the automation code, use this snippet:

[code language=”vb”]

‘ this message is for de bugging the open / close  automation
closedmessage = closedmessage + “<p class=’redtext boldtext’>Today is ” & today_date_server & “. The form will open on ” & open_date & ” and close on ” & close_date & “. Is today inside the date range?” & isitopenorclose & “. The date dif open is ”  & datediffopen & “. the date diff closed is ” & datediffclosed & “</p>”

[/code]

Now I would like to take this a bit further, by having the form open on the first Monday of January, and close on the last Friday of January. Here is the algorithm I have come up with:

[code]
mydate = “1/1/” & year(NOW) & ” 9:00 AM”
dtmDate = CDate(mydate)
daycounter = 1
Do While daycounter <= 7
‘ response.write(Weekday(dtmDate) & ” is the weekday for  ” & dtmDate & “<br/>”)

If Weekday(dtmDate) = 2 Then
response.write(“<br>The form will open on ” & FormatDateTime(dtmDate, 1))
Exit Do
End If
daycounter = daycounter + 1
dtmDate = dtmDate + 1
Loop

daycounter = 1
Do While daycounter <= 31
‘response.write(“<br />” & Weekday(dtmDate) & ” is the weekday for  ” & dtmDate & “<br/>”)

If Weekday(dtmDate) = 6 Then
thelastfriday=dtmDate
End If
daycounter = daycounter + 1
dtmDate = dtmDate + 1
Loop
response.write(“<br>The form will close on ” & FormatDateTime(thelastfriday, 1))
[/code]

For the year 2014, the result will display:
The form will open on Monday, January 06, 2014
The form will close on Friday, January 31, 2014

Now I can drop this into my forms that will open in the pattern of first Monday, and close on last Friday of January.

Find text in a string, compare two strings for similar match VBScript ASP classic

According to the Microsoft Docs, The InStr(string1, string2)  function returns the position of the first occurrence of one string within another.

We can use this to find a string within another one. For example. I wish to see if an email address is from the Skagit.edu domain. I want to see if the address is firstname.lastname@skagit.edu so I can use the first and last name in a greeting.

string1=”@skagit.edu”
string2=”firstname.lastname@skagit.edu”

stringcount = InStr(string1, string2)

If stringcount>0 Then
response.write(“We have a skagit.edu domain address”)
Else
response.write(“This is not a skagit.edu email address”)
End If

Basic Email Validation With VBScript / ASP classic

I need a server side check for basic email address syntax. I will use a regular expression to match the pattern of xxxxx@yyyyy.zzz

 Function GetEmailValidator() 
      Set GetEmailValidator = New RegExp 
      GetEmailValidator.Pattern = "^((?:[A-Z0-9_%+-]+.?)+)@((?:[A-Z0-9-]+.)+[A-Z]{2,4})$" 
      GetEmailValidator.IgnoreCase = True 
End Function 

This is a great function, but how to use it? Well, you test it like so:

Dim EmailValidator : Set EmailValidator = GetEmailValidator()
If EmailValidator.Test(to_email) = False Then ..... execute code for when an invalid email is found

Working with date and time in ASP VBScript

Here is a sweet way to perform a function based on the date.

If DateDiff(“n”,Now(),”9/15/13 08:00:00″) <= 0 Then
openorclosed = “open”  ‘open form to public access.
Else
openorclosed = “closed”  ‘close form to public access.
End If

 

Lets break down the use of the DateDiff function. From the msdn docs I see DateDiff(interval, date1, date2 [,firstdayofweek[, firstweekofyear]])

Interval lets us decide how precise we want this function to be. If we want, we can call it as broad as a  year or down to the second we want to define.

For example, since its December and all the kids are freaking out, lets make a Christmas countdown timer to show how many days until Christmas.

today = Now()
christmas = “12/25/2013”
interval = “d” ‘ we use d since we want to count the days.
numberofdays = DateDiff(interval, today, christmas)
Response.Write(“<p>There are only ” &  numberofdays & ” days until Christmas.<p>”)

Screen shot of code display
Here is the output of the script.

 

To really automate the open and closing of a form, I need to see if the date is in the range of open and closed dates provided by administration.

opendate = “July 1, 2015″
closedate=”April 20, 2015”

If CDate(NOW()) > opendate and CDate(NOW()) < closedate Then
response.write(“<p>the form should be open</p>”)
Else
response.write(“<p>the form should be closed</p>”)
End If

 

How about if I want to format a date to look good for the user. In some cases we would want the date to look formal: Lets take Christmas:

 

christmas_date=”12/25/2015 24:00:00″

FormatDateTime(open_date, 1) // this would output “Wednesday, December 25th, 2015”

FormatDateTime(open_date, 3) // This would output “12:00 AM”

 

Response.write(date & “<hr>”)
Response.Write(MonthName(Month(Date)) & “<hr />”)
Response.Write(Day(Date) & “<hr>”)

Response.Write(Month(“8/10/2008”))

Response.Write(Month(“Aug 10, 2008”))

Response.Write(Month(“10 Aug, 2008”))

Response.Write(Month(“10 August, 2008”))

Response.Write(Month(“August 10, 2008”))

Response.Write(“<br />”)
scrn1

 

Filter text before it is displayed. Find and replace invalid charaters from cms content using JavaScript and ASP

The content for the website is generated by the staff and put into the site using the content management system. Much of this content is created in a Word Processing program such as Microsoft Word. In many cases, the content is not formatted correctly for the web. While the cms does a good job of filtering out the Word Document markup, there are still some charaters that get through the filter, but don’t display properly on the web. These  characters show up as odd symbols such as diamonds and squares. I have created a filter to run the content through before it is displayed, finding the invalid characters and replacing them with html character codes.

 

Due to the restraints of the system I am working in, I decided to go with a vbscript dictionary object to hold an array of characters that were not displaying properly in the browser. I created an api that could be included into any page, and used an algorithm to detect and replace the pesky invalid characters.

‘——————————
‘_____________________________
‘ function to replace extended asci chars with the html equivalent ‘***************************
Function replace_characters(inString)
newstring = inString
dim lamechars
Set lamechars = CreateObject _
(“Scripting.Dictionary”)
lamechars.Add “–”, “&#150;”
lamechars.Add “®”, “&#174;”
lamechars.Add “’”, “&#8217;”
lamechars.Add ““”, “&#8220;”
lamechars.Add “””, “&#8221;”
lamechars.Add “—”, “&#150;”
For Each character in lamechars
newstring=Replace(newstring, character, lamechars(character))

Next
Response.Write(newstring)
End Function
‘**************************
‘ end function to replace extended asci chars with the html equivalent ‘—————————

Web Form Security Practices

We have had a lot of attacks to our web forms here at SVC. I am the paperless applications developer, so the task of keeping them safe and secure falls into my daily operations. An un secure form can let an attacker do many things to ruin someones day, such as sending unsolicited emails to all the staff and students. Some of the common practices to keep the “bots” from breaking into a web form are:

CAPTCHA
This technique provides the user with a series of image “keys”  that they must “unlock” before they can submit the web form. This is a  good way to slow down the bots, but since they don’t get tired, and can hammer away at the form many times each second, they can eventually bypass this technique. Another problem with captcha, and a very important one, is regarding the user experience. Some captchas are impossible to read, and take several tries for a normal user to get correct. This can really damper the user experience and create a situation where the user will just leave instead of taking the time to keep trying to unlock the captcha keys. As stated by the w3, “This type of visual and textual verification comes at a huge price to users who are blind, visually impaired or dyslexic. Naturally, this image has no text equivalent accompanying it, as that would make it a giveaway to computerized systems. In many cases, these systems make it impossible for users with certain disabilities to create accounts, write comments, or make purchases on these sites, that is, CAPTCHAs fail to properly recognize users with disabilities as human.”

So, what else can I do to help keep the bots from submitting forms?

1: Try to make sure that the form is submitted from the form page, because the bots usually submit directly to the form action. Put some kind of trigger in the form submit actions that look for a referring address or a session variable.

In classic ASP we have the Request.ServerVariables collection that can get some important information, and if the form data has not come from the form page, we know its a bot, and can secretly send a security alert to the admin, while not letting the bot know its been busted.

Request.ServerVariables("URL"), SCRIPT_NAME, and PATH_INFO

should all contain the form’s address, and should show that the form was submitted from the proper location.

Request.ServerVariables("SERVER_NAME")

should be checked for the proper domain, indicating whether the form was properly posted from my server. I could create an include to be used before each form submission to check for coming from my server.

These could be put into hidden fields and submitted with the form, then checked for validity before processing and submitting the form. Also a session variable might be a good way to track these from form submit to data capture.

In the form capture logic, we could look for Request.ServerVariables(“HTTP_REFERER”) to ensure that the data has come from our form page.

So, lets try some of this junk and see if it helps out.
First, lets set a session of “formuser” with a value of Request.ServerVariables(“URL”) when the user accesses the form, and then check for that session in the form submit logic. If there is no session, then this data did not come from our form.

Capitalize first letter of a string vbscript classic asp

So Here we go, need to capitalize the first letter of a string. thats easy.

myString = “donald”

If myString <> “” Then ‘ this is important becuase if the string is empty it will create an error.
myString = ucase(left(myString , 1)) + right(myString, len(myString )-1)
End If

Response.Write(myString)

Donald