ASP Classic Flashcards Library
These FlashCards are contributed by you (our online community members). They are organized by our knowledge base topics. Specifically, by the ASP Classic sub-topics.
|
61 ASP Classic Coding FlashCards
Group: ASP Classic Coding
Topic: ASP Classic
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
|
|
|
|
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"
|
|
|
|
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
|
|
|
|
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
|
|
|
|
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
|
|
|
|
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.
|
|
|
|
|
objRecordSet.Filter = "ExtEmpType='P'"
|
|
|
|
|
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")
|
|
|
|
|
Function SomeRoutine(ByRef pPerson, ByVal pName, Age)
|
|
|
|
|
The following snippet moves to the second to last record of a given RecordSet object:
objRecordSet.MoveLast
objRecordSet.MovePrevious
|
|
|
|
|
objMembersRS.Sort = "FirstName"
|
|
|
|
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
|
|
|
|
Tip: ASP Constant Naming Convention
|
When naming constants, Microsoft suggests you prefix each constant with "con" as in conYourConstant. Although, they also say the older all caps with words separated by an underscore is still acceptable (i.e. YOUR_CONSTANT).
|
|
|
|
|
|
DateDiff("ww", CDate("1/1/" & Year(Now)), Now, vbMonday)
|
|
|
|
Q&A: Find Last Day of Week
|
Question:
How do you find last Monday? I want to return a date for last Monday or today if today is Monday.
|
|
|
Answer:
While Weekday(ADate) <> vbMonday ADate = DateAdd("d", -1, ADate) WEnd
You could wrap this up in a function as follows: Function SU_GetLastDOW(ADate, AWeekDayConst) While Weekday(ADate) <> AWeekDayConst ADate = DateAdd("d", -1, ADate) WEnd SU_GetLastDOW = ADate End Function
|
|
|
|
|
response.write(Request.ServerVariables("SERVER_SOFTWARE"))
|
|
|
|
|
Answer:
VBScript is short for Visual Basic Scripting. VBScript brings scripting to a wide variety of environments, including Web client scripting in Microsoft Internet Explorer and Web server scripting in Microsoft Internet Information Service. It is used in Visual Basic, Access, Word, Excel, ASP, etc.
|
|
|
|
Topic: Tool Basics
|
FullName = "Randy Spitz" Age = 38
|
|
|
|
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 %>
|
|
|
|
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" -->
|
|
|
|
|
//Does ASP evaluate the math correctly? No! If .1 + .1 + .1 = .3 Then Response.Write "correct" Else Response.Write "not correct" End If
|
|
|
|
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.
|
|
|
|
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.
|
|
|
|
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")
|
|
|
|
|
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
|
|
|
|
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).
|
|
|
|
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).
|
|
|
|
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)
|
|
|
|
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.
|
|
|
|
|
Answer:
Although this question really depends on the provider, in general, the answer is no to MS Access views and yes to MS SQL Server views so long as you open the RecordSet editable.
|
|
|
|
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
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
|
|
|
|
|
//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
|
|
|
|
|
Dim LeftString LeftString = Left("Prestwood", 3) Response.Write LeftString
|
|
|
|
|
'Given expressions a, b, c, and d: If Not (a and b) and (c or d) Then 'Do something. End If
|
|
|
|
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.
|
|
|
|
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
|
|
|
|
|
Function GetStringCount(AString, AChar) Dim MyArray Dim ArrayCount MyArray = Split(AString, AChar) GetStringCount = UBound(MyArray) End Function
|
|
|
|
Tip: If Statement: No Short Circuit
|
Short-circuit evaluation is a feature of most languages where once an evaluation evaluates to False, the compiler evaluates the whole expression to False, exits and moves on to the next code execution line. The ASP Classic if statement does not support short-circuit evaluation but you can mimic it. Use either an if..else if..else if statement or nested if statements. ASP code that makes use of this technique is frequenlty clearer and easier to maintain than the short-circuit equivalent.
|
|
|
|
|
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)
|
|
|
|
|
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
|
|
|
|
|
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' 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
Tip: ASP Application.Lock Method
|
Call Application.Lock to freeze ASP code while you set IIS application variables the Application.Unlock to unfreeze. No actions take place on the server while locked. Application.Lock
Application(YourAppVar) = AValue Application.Unlock
|
|
|
|
|
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")
|
|
|
|
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
|
|
|
|
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.
|
|
|
|
|
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
|
|
|
|
|
Answer:
Use a dictionary: Dim StateList set StateList = Server.CreateObject("Scripting.Dictionary") StateList.Add "CA", "California" Response.Write "NV is " & StateList("NV") For more examples, refer to our ASP Classic Associative Array (Scripting.Dictionary) article.
|
|
|
|
Tip: Using Request.QueryString
|
Although you can use the generic request collection, as in Request("SomeValue"), for either Request.Form("SomeValue") or Request.QueryString("SomeValue"), it's best to avoid the generic request collection until it's really needed. Use a For Each loop to loop through elements.
|
|
|
|
|
Topic: OOP
|
'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!
|
|
|
|
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
|
|
|
|
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
|
|
|
|
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
|
|
|
|
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
|
|
|
|
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()
|
|
|
|
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.
|
|
|
|
|
Class Cyborg Private FCyborgName Public Property Get CyborgName() CyborgName = FCyborgName End Property Public Property Let CyborgName(pCyborgName) FCyborgName = pCyborgName End Property End Class
|
|
|
|
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
|
|
|
|
|
|