ASP Classic Code Snippets Page
These Code Snippets are contributed by you (our online community members). They are organized by our knowledge base topics. Specifically, by the ASP Classic sub-topics.
|
53 ASP Classic Coding Code Snippets
Group: ASP Classic Coding
Topic: ASP Classic
|
1. ASP Classic Array (x = Array()) |
|
Arrays in ASP Classic use a 0-based indice.
Use UBound to get the number of elements. UBound returns -1 if the array has no elements, 0 if it has 1, 1 if it has 2, etc.
Dim MyArray, i
MyArray = Array("Mike", "Lisa", "Felicia", "Nathan")
If UBound(MyArray) > -1 Then For i = 0 to UBound(MyArray)
Response.Write MyArray(i)
Next
End If
|
|
2. ASP Classic Case Sensitivity (No) |
|
ASP Classic is not case sensitive. My preference for all languages where case sensitivity does not matter is to use camel caps as in the first example above. Many developers coming from a case sensitive language prefer to use all lowercase.
You can use any of the following: Response.Write "Hello" response.write "Hello" RESPONSE.WRITE "Hello" REsponse.WritE "Hello"
|
|
3. ASP Classic Edit Record (AddNew, Update, Delete) |
|
In ASP, using ADO, you use RecordSet.AddNew to add a new record, Recordset.Update to post the record, and RecordSet.Delete to delete it. To edit a record, you open the RecordSet using an editable cursor.
The following code snippet adds a record to a given editable RecordSet with FullName and Created fields:
objRS.AddNew
objRS.Fields("FullName") = "Barack Obama"
objRS.Fields("Created") = Now
objRS.Update
|
|
4. ASP Classic Empty String Check (Len(s&vbNullString)) |
|
In ASP Classic, you have to add an empty string to the value being compared in order to get consistent results. For example, add &"" to your string varilable or it's code equivalent &vbNullString. Then compare to an empty string or verify it's length to 0 with Len.
All these will work for variables unassigned, set to "", or set to Null: If s&"" = "" Then Response.Write("<br>Quotes with &'' say null is empty") End If If Len(s&"") = 0 Then Response.Write("<br>Len with &'' says null is empty") End If If Len(s&vbNullString) = 0 Then Response.Write("<br>Using vbNullString also works!") End If
|
|
5. ASP Classic Exception Trapping (On Error) |
|
Languages Focus: Exception TrappingA common usage of exception handling is to obtain and use resources in a "try-it" block, deal with any exceptions in an "exceptions" block, and release the resources in some kind of "final" block which executes whether or not any exceptions are trapped. ASP Classic Exception Trapping
On Error Resume Next Response.Write FormatDateTime(f_CurrentActualDate, vbShortDate) If ErrNumber <> 0 Then Break(f_CurrentActualDate) End If On Error Goto 0
|
|
6. ASP Classic File Extensions (.ASP) |
|
.asp is the default extension for Active Server Pages (ASP) although some developers will change the default extension in an effort to add an additional security level. Although there is no clear standard for include files, using .INC is common but you must make sure that .INC files are not executed nor displayed.
|
|
7. ASP Classic Filter Records (Filter) |
|
In ASP, using ADO, you filter a set of records using Filter.
objRecordSet.Filter = "ExtEmpType='P'"
|
|
8. ASP Classic Find Record (Find, Seek) |
|
In ASP, using ADO, you use Find and Seek to move a cursor of a RecordSet to a matching record.
Given a valid ADO recordset, the following code snippet finds a specific user and prints out their age: TC.Find " UserID='mprestwood' " Response.Write TC.Fields("Age")
|
|
9. ASP Classic Parameters (ByRef, ByVal) |
|
By Reference or Value For parameters, you can optionally specify ByVal or ByRef. ByRef is the default if you don't specify.
Function SomeRoutine(ByRef pPerson, ByVal pName, Age)
|
|
10. ASP Classic Record Movement (MoveFirst, MoveLast, MoveNext) |
|
ASP uses MoveFirst, MoveLast, MoveNext, and MovePrevious to move a database cursor (a RecordSet). objRecordSet.MoveNext
The following snippet moves to the second to last record of a given RecordSet object:
objRecordSet.MoveLast
objRecordSet.MovePrevious
|
|
11. ASP Classic Sort Records (Sort) |
|
In ASP, using ADO, you sort a set of records using the Sort property.
objMembersRS.Sort = "FirstName"
|
|
12. ASP Classic Yes/No Function |
|
The following function demonstrates one technique for coding a Yes/No dropdown. It uses a for loop which can be expanded to handle more than the 3 states (Y, N, and blank).
Example of calling the function: Do you fish? <%=YesNoDropDown("ynFish", "")%>
Function YesNoDropDown(strName, strSelected) Dim i Dim strSelectedString Dim YesNoName Dim YesNoCode YesNoName = Array("Yes","No") YesNoCode = Array("Y","N") YesNoDropDown = "<select name='" & strName & "'>" & vbcrlf YesNoDropDown = YesNoDropDown & "<option>" & "--" & "</option>" For i = 0 To UBound(YesNoName) If strSelected = YesNoCode(i) Then strSelectedString = "Selected" Else strSelectedString = "" End If YesNoDropDown = YesNoDropDown & "<option value='" & YesNoCode(i) & "' " & _ strSelectedString & " >" & YesNoName(i) & "</option>" & vbcrlf Next YesNoDropDown = YesNoDropDown & "</select>" & vbcrlf End Function
|
|
13. DateDiff vbMonday ww Week of Year |
|
This code returns the current week of the current year with a week starting on Monday.
DateDiff("ww", CDate("1/1/" & Year(Now)), Now, vbMonday)
|
|
14. How do I determine which version of IIS I am running? |
|
The following ASP Classic code displays the version of the Internet Information Services (IIS) you are running in the form of a text string (i.e. Microsoft-IIS/6.0).
response.write(Request.ServerVariables("SERVER_SOFTWARE"))
|
Topic: Tool Basics
|
15. ASP Classic Assignment (=) |
|
ASP Classic uses = for it's assignment operator.
FullName = "Randy Spitz" Age = 38
|
|
16. ASP Classic Code Blocks (End Xxx) |
|
In .ASPhtml pages, you embed ASP code between <% and %>.
ASP Classic code blocks are surrounded by statement ending keywords that all use End such as End Sub, End If, and WEnd.
<% Sub x End Sub If x Then End If While x WEnd %>
|
|
17. ASP Classic Comments (' or REM) |
|
Commenting Code ASP Classic, like all the VB-based languages, uses a single quote (') or the original class-style basic "REM" (most developers just use a quote). ASP Classic does NOT have a multiple line comment.
Preprocessor Directives - @ and # An @ is used for preprocessor directives within ASP code (within <% %>) and a # is used for HTML-style preprocessor directives.
Note: ASP Classic does not support VB Classic's #If directive.
'Single line comment. REM Old school single line comment.
Common Preprocessor Directives include:
<%@LANGUAGE=VBScript%> <!-- #Include File="includes.inc" -->
|
|
18. ASP Classic Comparison Operators (=, <>) |
|
//Does ASP evaluate the math correctly? No! If .1 + .1 + .1 = .3 Then Response.Write "correct" Else Response.Write "not correct" End If
|
|
19. ASP Classic Deployment Overview |
|
With ASP Classic, you simply copy your files to a web server that is capable of running ASP pages. This includes your .ASP pages along with supporting files such as images, include files, and database files.
Optionally, you can also deploy a global.asa file which is used to code certain events like application start, application end, session start, and session end.
|
|
20. ASP Classic Development Tools |
|
Languages Focus: Development ToolsPrimary development tool(s) used to develop and debug code.
ASP Classic Development ToolsMicrosoft Visual Interdev was popular for several years but isn't used as much any more. Any good editor such as Microsoft Expression Web, etc. will work but debugging is left up to interactive skills.
|
|
21. ASP Classic End of Statement (Return) |
|
Languages Focus: End of StatementIn coding languages, common End of statement specifiers include a semicolon and return (others exist too). Also of concern when studying a language is can you put two statements on a single code line and can you break a single statement into two or more code lines.
ASP Classic End of StatementA return marks the end of a statement and you cannot combine statements on a single line of code. You can break a single statement into two or more code lines by using a space and underscore " _".
Response.Write("Hello1") Response.Write("Hello2") Response.Write("Hello3") 'The following commented code on a single line does not work... ' Response.Write("Hello4") Response.Write("Hello5") 'Two or more lines works too with a space+underscore: Response.Write _ ("Hello6")
|
|
22. ASP Classic Literals (quote) |
|
Literals are quoted as in "Prestwood". If you need to embed a quote use two quotes in a row.
Response.Write "Hello" Response.Write "Hello ""Mike""." 'Does ASP evaluate this simple 'floating point math correctly? No! If (.1 + .1 + .1) = .3 Then Response.Write "Correct" Else Response.Write "Not correct" End If
|
|
23. ASP Classic Overview and History |
|
Language Overview: Class-based language. Although you can create classes, ASP is not fully OOP. It is a traditional language with a few OOP extensions. You code in a traditional approach using functions, procedures, and global data, and you can make use of simple classes to help organize your reusable code.
Target Platforms: ASP Classic is most suitable for creating websites targeting any browser (IIS Web Server with ASP Classic installed or equivalent).
|
|
24. ASP Classic Report Tools Overview |
|
Because ASP Classic targets a client browser (a document interfaced GUI), a common solution is to simply output an HTML formatted page with black text and a white background (not much control but it does work for some situations).
|
|
25. ASP Classic String Concatenation (& or +) |
|
Although you can use either a & or a + to concatenate values, my preference is to use a + because more languages use it. However, if you use & then some type conversions are done for you. If you use + you will sometimes have to cast a value to concatenate it. For example, you will have to use CStr to cast a number to a string if you use the + operator as a concatenation operator.
Dim FirstName Dim LastName FirstName = "Mike" LastName = "Prestwood" Response.Write "Full name: " & FirstName & " " + LastName Response.Write "2+2=" + CStr(2+2)
|
|
26. ASP Classic Unary Operators |
|
An operation with only one operand (a single input) such as + and -.
|
|
27. ASP Classic Variables (Dim x) |
|
ASP Classic is a loosely typed language. No variable types in ASP (all variables are variants). Declaring variables is even optional unless you use the Option Explicit statement to force explicit declaration of all variables with Dim in that script. Using Option Explicit is strongly recommended to avoid incorrectly typing an existing variable and to avoid any confusion about variable scope.
For example, at the top of my common include file, I have the following:
<%@LANGUAGE=VBScript%> <% Option Explicit '...more code here. %>
Dim Fullname Dim Age Dim Weight FullName = "Mike Prestwood" Age = 32 Weight = 154.4 'Declaritive assignment not supported: ''Dim Married = "Y" '>>>Not supported.
|
|
28. Response.Write Assignment Operator |
|
This is a simple example of passing a value to a JavaScript function. You can pass values to JavaScript the same way you pass values to HTML.
<% Dim MyName MyName = "Mr Paradiddle" %> <script language="javascript"> <!-- function ShowYourName() { document.write('Your name is <%=MyName%>.') } ShowYourName() --> </script>
|
Topic: Language Basics
|
29. ASP Classic Constants (Const kPI = 3.1459) |
|
Scope can be Public or Private. Public Const is the same as just specifying Const. As with variables, all constants are variants. You do not specify the type, it's implied.
Const kPI = 3.1459 Const kName = "Mike" //Public variable: Public Const kFeetToMeter=3.28, kMeterToFeet=.3
|
|
30. ASP Classic If Statement (If..ElseIf..Else..End If) |
|
The End If is optional if you put your code on a single line.
//Single line example. If X = True Then Response.Write "hello" //Complete example. If X = True Then '>>>do something. ElseIf Y = "ABC" Then '>>>do something. Else '>>>do something. End If
|
|
31. ASP Classic Left |
|
Dim LeftString LeftString = Left("Prestwood", 3) Response.Write LeftString
|
|
32. ASP Classic Logical Operators (and, or, not) |
|
Same as VB. ASP Classic logical operators:
and |
and, as in this and that |
or |
or, as in this or that |
Not |
Not, as in Not This |
'Given expressions a, b, c, and d: If Not (a and b) and (c or d) Then 'Do something. End If
|
|
33. ASP redirect http to https |
|
To redirect from http to https, check the Request.ServerVariables HTTPS field and then use Response.Redirect if set to "off".
Here's a code snippet: If Request.ServerVariables("HTTPS") = "off" Then Response.Redirect https://store.prestwood.com End If
Obviously this code works only for "specific" implementations. You could make this non-domain specific pretty easily by "constructing" the https://www.prestwood.com portion.
|
|
34. CBool(ANumber Mod 2) |
|
The following function returns true if the integer portion of a number passed in is odd; otherwise, it returns false.
Function IsOdd(byVal ANumber) ''Non numbers always return false. If Not IsNumeric(ANumber) Then IsOdd = False Exit Function End If ANumber = Fix(ANumber) '>>>Strip to integer. IsOdd = CBool(ANumber Mod 2) End Function
|
|
35. GetStringCount with Split and UBound |
|
This function uses Split to count the number of strings within a string.
Function GetStringCount(AString, AChar) Dim MyArray Dim ArrayCount MyArray = Split(AString, AChar) GetStringCount = UBound(MyArray) End Function
|
|
36. Random Numbers with Rnd and Randomize |
|
Call randomize then call Rnd to generate a random number between 0 and 1. The following generates a random number from the low to high number including the low and high numbers:
Function GetRandomInt(LowNumber, HighNumber) RANDOMIZE GetRandomInt = Round(((HighNumber-1) - LowNumber+1) * Rnd+LowNumber) End Function Response.Write GetRandomInt(10, 100)
|
|
37. Scripting.FileSystemObject |
|
The following function uses the Scripting.FileSystemObject to check for the existence of a file.
Function IsFileExists(AFileName) Dim objFSO Dim TempFileName TempFileName = Server.MapPath(TempFileName) Set objFSO = Server.CreateObject("Scripting.FileSystemObject") If (objFSO.FileExists( TempFileName ) = True) Then IsFileExists = True Else IsFileExists = False End If Set objFSO = Nothing End Function
|
|
38. Scripting.FileSystemObject |
|
The following function uses the FileSystemObject to delete a file.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' DeleteFile '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function DeleteFile(AFileName) Dim objFSO Dim TempFileName TempFileName = AFileName Set objFSO = Server.CreateObject("Scripting.FileSystemObject") Call objFSO.DeleteFile(Server.MapPath(TempFileName), True) Set objFSO = Nothing End Function
|
Topic: Language Details
|
39. ASP Classic Associative Array (Scripting.Dictionary) |
|
Use the scriptiing dictionary object which is available on later versions of ASP Classic (all still commonly in use). Both Access VBA and VB Classic use a collection for this but collections are not supported in ASP Classic. Dim StateList Set StateList = Server.CreateObject("Scripting.Dictionary") StateList.Add "CA", "California" StateList.Add "NV", "Nevada" Response.Write "I live in " & StateList.Item("CA")
Dim StateList set StateList = Server.CreateObject("Scripting.Dictionary") StateList.Add "CA", "California" StateList.Add "NV", "Nevada" Response.Write "I live in " & StateList.Item("CA")
|
|
40. ASP Classic Custom Routines (Sub, Function) |
|
ASP Classic is a non-OOP language with some OOP features. It offers both Subs and Functions. A Sub does not return a value while a Function does. When Subs and Functions are used in a defined class, they become the methods of the class.
Sub SayHello(ByVal pName) Response.Write "Hello " + pName + "!<br>" End Sub Function Add(ByRef pN1, ByRef pN2) Add = pN1 + pN2 End Function
|
|
41. ASP Classic Overloading (Not Supported) |
|
ASP Classic does not support any type of overloading.
- Operator - No.
- Method - No.
Some developers like to pass in an array and then handle the array for a pseudo technique. Although not overloading, it's useful.
|
|
42. ASP Classic Self Keyword (me) |
|
Same as VB. The Me keyword is a built-in variable that refers to the class where the code is executing.
Class Cyborg Public CyborgName
Public Function IntroduceYourself() 'Using Me. Prints Cameron. Response.Write("Hi, my name is " & Me.CyborgName & ".") 'The above is just a demo. You could also not include "Me." 'in this case because we are in context of Me now. Using Me 'makes more sense when you start to pass Me as a parameter 'to a method. End Function End Class
|
Topic: OOP
|
43. ASP Classic Class..Object (Class..Set..New) |
|
Ultra-primitive (no inheritance) but useful and encourages you to think and design using objects.
'Declare class. Class Cyborg Public Function IntroduceYourself() Response.Write("Hi, I do not have a name yet.") End Function End Class 'Create object from class. Set T1 = new Cyborg T1.IntroduceYourself() Set T1 = Nothing 'Be sure to clean up!
|
|
44. ASP Classic Constructors (Class_Initialize) |
|
When an object instance is created from a class, ASP calls a special parameter-less sub named Class_Initialize. Since you cannot specify parameters for this sub, you also cannot overload it.
When a class is destroyed, ASP calls a special sub called Class_Terminate.
Class Cyborg Public CyborgName Public Sub Class_Initialize Response.Write "<br>Class created" CyborgName = "Cameron" End Sub End Class
|
|
45. ASP Classic Destructor (Class_Terminate) |
|
When an object instance is destroyed, ASP calls a special parameter-less sub named Class_Terminate. For example, when the variable falls out of scope. Since you cannot specify parameters for this sub, you also cannot overload it.
When an object instance is created from a class, ASP calls a special sub called Class_Initialize.
Class Cyborg
Public Sub Class_Terminate Response.Write "<br>Class destroyed" End Sub End Class
|
|
46. ASP Classic Inheritance (Not Supported) |
|
The concept of a class makes it possible to define subclasses that share some or all of the main class characteristics. This is called inheritance. Inheritance also allows you to reuse code more efficiently. In a class tree, inheritance is used to design classes vertically. (You can use Interfaces to design classes horizontally within a class tree.) With inheritance, you are defining an "is-a" relationship (i.e. a chow is-a dog). Analysts using UML call this generalization where you generalize specific classes into general parent classes. ASP Classic Inheritance
|
|
47. ASP Classic Interfaces (Not Supported) |
|
Although ASP Classic does support simple classes, it does not support interfaces.
|
|
48. ASP Classic Member Field |
|
ASP Classic does support member fields, but, as usual, you cannot initialize the type nor value of a member field. The type is implied by usage.
Class Cyborg Private FSerialNumber Public FCyborgName Public FCyborgAge Public FSeriesID End Class
|
|
49. ASP Classic Member Method (Sub, Function) |
|
ASP classic uses the keywords sub and function. A sub does not return a value and a function does. Many programmers like to use the optional call keyword when calling a sub to indicate the call is to a procedure.
'Declare class. Class Cyborg Public Function IntroduceYourself() Response.Write("Hi, I do not have a name yet.") End Function End Class 'Create object from class. Set T1 = new Cyborg T1.IntroduceYourself()
|
|
50. ASP Classic Member Modifiers (Default) |
|
Other than visibility modifiers Public and Private, the only other member modifier available in ASP Classic is Default which is used only with the Public keyword in a class block. It indicates that the sub, function, or property is the default method for the class. You can have only one Default per class.
|
|
51. ASP Classic Member Property (Property..Get..Let) |
|
ASP classic uses the property keyword and special Get and Let methods to both get and set the values of properties.
Class Cyborg Private FCyborgName Public Property Get CyborgName() CyborgName = FCyborgName End Property Public Property Let CyborgName(pCyborgName) FCyborgName = pCyborgName End Property End Class
|
|
52. ASP Classic Member Visibility (Private, Public) |
|
The member visibility modifiers are Private and Public. If not specified, the default is Public. Private and Public have the usual meaning. Private members are visible only within the class block. Public members are visible within the class and outside of the class.
Class Cyborg Private FSerialNumber Public FCyborgName Public Function IntroduceYourself() Response.Write("Hi, I do not have a name yet.") End Function
End Class
|
|
53. ASP Classic Static Members (Not Supported) |
|
Although ASP Classic supports the creation of simple classes, it does not support static methods.
|
|
|