home *** CD-ROM | disk | FTP | other *** search
/ H4CK3R 4 / hacker04 / 04_HACK04.ISO / src / ASP / quiz.asp < prev    next >
Encoding:
Text File  |  2001-06-08  |  15.8 KB  |  445 lines

  1. <%
  2. '*******************************************************
  3. '*     ASP 101 Sample Code - http://www.asp101.com     *
  4. '*                                                     *
  5. '*   This code is made available as a service to our   *
  6. '*      visitors and is provided strictly for the      *
  7. '*               purpose of illustration.              *
  8. '*                                                     *
  9. '* Please direct all inquiries to webmaster@asp101.com *
  10. '*******************************************************
  11. %>
  12.  
  13. <%
  14. ' Takes a integer parameter and converts it to the appropriate letter
  15. Function GetLetterFromAnswerNumber(iInput)
  16. Dim strTemp
  17.     Select Case iInput
  18.         Case 0
  19.             strTemp = "A"
  20.         Case 1
  21.             strTemp = "B"
  22.         Case 2
  23.             strTemp = "C"
  24.         Case 3
  25.             strTemp = "D"
  26.         Case 4
  27.             strTemp = "E"
  28.         Case 5
  29.             strTemp = "F"
  30.     End Select
  31. GetLetterFromAnswerNumber = strTemp
  32. End Function
  33.  
  34. ' To simplify and streamline the code I split this line into many parts,
  35. ' wrapped it into a function and commented it so you'd have a better
  36. ' chance of figuring out what I'm doing since I usually can't!
  37. Function GetAnswerFromAnswerString(iQuestionNumber, strAnswers)
  38. Dim strTemp
  39. Dim iOffset
  40.     ' I use InStrRev since I want to retrieve the last entered value
  41.     ' in case they went back and changed their mind. 
  42.     
  43.     ' Find the location of the question number we want to use
  44.     iOffset = InStrRev(strAnswers, "|" & iQuestionNumber & "|", -1, 1)
  45.     
  46.     ' Get our answer by using the offset we just found and then moving
  47.     ' right the length of the question indicator to arrive at the
  48.     ' appropriate letter
  49.     strTemp = Mid(strAnswers, iOffset + Len("|" & iQuestionNumber & "|"), 1)
  50.  
  51.     ' There's no way it should be anything else, but to be sure we
  52.     ' convert it to a string and make sure it's uppercase
  53. GetAnswerFromAnswerString = UCase(CStr(strTemp))
  54. End Function
  55. %>
  56.  
  57. <%
  58. ' This code works with either a DB or hard coded in values.  I developed
  59. ' it using the DB connection and our sample DB, but switched to the hard
  60. ' coded to increase the speed for our site.  Using the DB allows for better
  61. ' data encapsulation and easier updates.  It all comes down to your specific
  62. ' needs so I gave you both options.
  63.  
  64. ' Set this to True to use the Db.  False to use hard coded values
  65. Const USE_DB_FOR_INFO = False
  66.  
  67. ' These 2 things only apply if you use the DB
  68. ' If you're not then they're values are irrelevant
  69. Dim DB_CONN_STRING
  70. DB_CONN_STRING = "DBQ=" & Server.MapPath("quiz.mdb") & ";"
  71. DB_CONN_STRING = DB_CONN_STRING & "Driver={Microsoft Access Driver (*.mdb)};"
  72. DB_CONN_STRING = DB_CONN_STRING & "DriverId=25;FIL=MS Access;"
  73. ' Lets you run multiple quizzes from one DB by separating by QUIZ_ID!
  74. Const QUIZ_ID = 1
  75.  
  76.  
  77. ' Now to all our other variables!
  78. Dim cnnQuiz, rsQuiz     'DB objects if we use the DB for the info
  79.  
  80. Dim I                   'our standard (improperly named) looping variable
  81. Dim iNumberOfQuestions  'the number of questions in the test
  82. Dim iQuestionNumber     'the question we're currently on
  83. Dim strQuestionText     'text of the question to be asked
  84. Dim aAnswers            'array of choices for the question to be asked
  85.                         'if we hard code, then I also use it for the
  86.                         'correct answers when I go to grade the quiz
  87. Dim strAnswers          'stores the question numbers and response choices
  88.                         'seperated by |'s
  89. Dim iScore              'so we know how well the user did
  90. Dim bAbort              'added after I had finished to account for closed sessions
  91. Dim strResults          'another late addition for the each question breakdown!
  92.  
  93. bAbort = False          'set it to false since we only want to abort in certain cases
  94.  
  95.  
  96.  
  97. ' If this is the first call to the quiz then init everything
  98. ' o/w retrieve values we need.  We check by looking for the
  99. ' Question ID from the querystring.
  100. If Request.QueryString("qid") = "" Then
  101.     ' Retrieve and Set the Quiz Info
  102.     If USE_DB_FOR_INFO Then
  103.         ' Code to use DB!
  104.         ' Create DB connection and connect to the DB
  105.         Set cnnQuiz = Server.CreateObject("ADODB.Connection")
  106.         cnnQuiz.Open DB_CONN_STRING
  107.         
  108.         ' Create RS and query DB for quiz info
  109.         Set rsQuiz = Server.CreateObject("ADODB.Recordset")
  110.         rsQuiz.Open "SELECT * FROM quizzes WHERE quiz_id=" & QUIZ_ID & ";", cnnQuiz
  111.         
  112.         ' Set our session vars
  113.         Session("QuizName") = CStr(rsQuiz.Fields("quiz_name").Value)
  114.         Session("NumberOfQuestions") = CInt(rsQuiz.Fields("number_of_questions").Value)
  115.         Session("PercentageToPass") = CInt(rsQuiz.Fields("percentage_to_pass").Value)
  116.         
  117.         ' Close and dispose of our DB objects
  118.         rsQuiz.Close
  119.         Set rsQuiz = Nothing
  120.         cnnQuiz.Close
  121.         Set cnnQuiz = Nothing
  122.     Else
  123.         ' If we're not going to the DB, hard code in values here!
  124.         ' BEGIN HARD CODE
  125.         Session("QuizName") = "ASP 101 Quiz"
  126.         Session("NumberOfQuestions") = 10
  127.         Session("PercentageToPass") = 70
  128.         ' END HARD CODE
  129.     End If
  130.  
  131.     ' Set our question indicator to 1 and init our answer string
  132.     iQuestionNumber = 1
  133.     Session("AnswerString") = "|"
  134. Else
  135.     'Check to be sure we've still got a session!
  136.     If Session("AnswerString") = "" Then
  137.         Response.Write "I'm sorry, but you've taken too long.  You can start over by "
  138.         Response.Write "clicking <A HREF=""" & Request.ServerVariables("URL") & """>here</A>."
  139.         ' I'd normally just do a response.end, but I can't because I'm inside of our
  140.         ' site template.  I need the script to complete so I've declared and set a Flag
  141.         'Response.End
  142.         bAbort = True
  143.     End If
  144.     
  145.     ' Get the number of the question we're processing
  146.     iQuestionNumber = CInt(Request.QueryString("qid"))
  147.         
  148.     ' Log selected answer to last question
  149.     Session("AnswerString") = Session("AnswerString") & iQuestionNumber & "|" & _
  150.         GetLetterFromAnswerNumber(CInt(Request.QueryString("sa"))) & "|"
  151.     
  152.     ' Increment question identifier
  153.     iQuestionNumber = iQuestionNumber + 1
  154. End If
  155.  
  156. ' If session has expired then skip all the code.
  157. ' Equivalently, only run all the code if it hasn't!
  158. If Not bAbort Then
  159.  
  160.     ' Set this to a local variable to avoid accessing the collection each time
  161.     ' This isn't required, but makes it easier for me to access and
  162.     ' supposedly speeds it up... I'm not sure how much, but it can't hurt!
  163.     iNumberOfQuestions = Session("NumberOfQuestions")
  164.  
  165.     ' Check to see it the quiz is over.  If so then show results, o/w
  166.     ' ask the next question
  167.     If iQuestionNumber > iNumberOfQuestions Then
  168.         ' Process results and show end quiz status report
  169.         
  170.         ' Done for the same reason as for iNumberOfQuestions a few lines above
  171.         strAnswers = Session("AnswerString")
  172.         
  173.         ' Useful for debugging
  174.         'Response.Write strAnswers & "<BR>" & vbCrLf & "<BR>" & vbCrLf
  175.  
  176.         ' Bug hunting once again... I didn't even come across any real bugs on this trip!
  177.         ' Could you imagine the ammo I'd take if it was real hunting I was doing!
  178.         'For I = 1 to iNumberOfQuestions
  179.         '    Response.Write GetAnswerFromAnswerString(I, strAnswers) & "<BR>" & vbCrLf
  180.         'Next 'I
  181.  
  182.         ' Retrieve Correct Answers and compare to the entered ones
  183.         If USE_DB_FOR_INFO Then
  184.             ' Code to use DB!
  185.             ' Create DB connection and connect to the DB
  186.             Set cnnQuiz = Server.CreateObject("ADODB.Connection")
  187.             cnnQuiz.Open DB_CONN_STRING
  188.                 
  189.             ' Create RS and query DB for quiz info
  190.             Set rsQuiz = Server.CreateObject("ADODB.Recordset")
  191.             ' Specify 3, 1 (Static, Read Only)
  192.             rsQuiz.Open "SELECT * FROM questions WHERE quiz_id=" & QUIZ_ID & _
  193.                 " ORDER BY question_number;", cnnQuiz, 3, 1
  194.                 
  195.             iScore = 0
  196.             I = 1
  197.             Do While Not rsQuiz.EOF
  198.                 If UCase(CStr(rsQuiz.Fields("correct_answer").Value)) = _
  199.                     GetAnswerFromAnswerString(I, strAnswers) Then
  200.                     
  201.                     iScore = iScore + 1
  202.                     ' This and the Else could be used to output a
  203.                     ' correctness status for each question
  204.                     ' Also useful for bug hunting!
  205.                     'Response.Write "Right" & "<BR>" & vbCrLf
  206.                 Else
  207.                     'Response.Write "Wrong" & "<BR>" & vbCrLf
  208.                     strResults = strResults & I & ", "
  209.                 End If
  210.                 I = I + 1
  211.                 rsQuiz.MoveNext
  212.             Loop
  213.  
  214.             ' Close and dispose of our DB objects
  215.             rsQuiz.Close
  216.             Set rsQuiz = Nothing
  217.             cnnQuiz.Close
  218.             Set cnnQuiz = Nothing
  219.         Else
  220.             ' If we're not going to the DB, hard code in answer values here!
  221.             ' BEGIN HARD CODE
  222.             aAnswers = Array("A", "A", "A", "E", "D", "A", "E", "E", "A", "A")
  223.             ' END HARD CODE
  224.             
  225.             iScore = 0
  226.             For I = 1 to iNumberOfQuestions
  227.                 If UCase(CStr(aAnswers(I - 1))) = _
  228.                     GetAnswerFromAnswerString(I, strAnswers) Then
  229.                     
  230.                     iScore = iScore + 1
  231.                     ' This and the Else could be used to output a
  232.                     ' correctness status for each question
  233.                     ' Also useful for bug hunting!
  234.                     'Response.Write "Right" & "<BR>" & vbCrLf
  235.                 Else
  236.                     'Response.Write "Wrong" & "<BR>" & vbCrLf
  237.                     strResults = strResults & I & ", "
  238.                 End If
  239.             Next 'I
  240.         End If
  241.  
  242.         ' Convert score to a percentage rounded to the whole number
  243.         iScore = Round((iScore / iNumberOfQuestions) * 100)
  244.         %>
  245.         <FONT SIZE="+2"><B><%= Session("QuizName") %></B></FONT><BR>
  246.         <BR>
  247.         <%
  248.         If iScore >= Session("PercentageToPass") Then 
  249.             Response.Write "Congratulations!  You've passed the quiz with a score of "
  250.             Response.Write iScore & "%.<BR>" & vbCrLf
  251.         Else
  252.             Response.Write "Sorry!  You needed to achieve a score of "
  253.             Response.Write Session("PercentageToPass") & "% or higher to pass.  "
  254.             Response.Write "Unfortunately, your score was only " & iScore & "%.  "
  255.             Response.Write "You can take the test again by clicking <A HREF="""
  256.             Response.Write Request.ServerVariables("URL") & """>here</A>.<BR>" & vbCrLf
  257.         End If
  258.         Response.Write "<BR>" & vbCrLf
  259.         If Len(strResults) <> 0 Then
  260.             Response.Write "You missed the following questions: " & Left(strResults, Len(strResults) - 2)
  261.             Response.Write "<BR>" & vbCrLf
  262.         End If
  263.         'Response.Write iScore & "%"
  264.  
  265.         ' This is also where you could log the results if you wanted to.
  266.         ' In it's simplest form, you would simply log strAnswers to a file,
  267.         ' but you could format little "report cards" or log the result to a
  268.         ' separate data source.
  269.     Else
  270.         ' Retrieve and Set the Question Info
  271.         If USE_DB_FOR_INFO Then
  272.             ' Code to use DB!
  273.             ' Create DB connection and connect to the DB
  274.             Set cnnQuiz = Server.CreateObject("ADODB.Connection")
  275.             cnnQuiz.Open DB_CONN_STRING
  276.                 
  277.             ' Create RS and query DB for quiz info
  278.             Set rsQuiz = Server.CreateObject("ADODB.Recordset")
  279.             rsQuiz.Open "SELECT * FROM questions WHERE quiz_id=" _
  280.                 & QUIZ_ID & " AND question_number=" & iQuestionNumber & ";", cnnQuiz
  281.                 
  282.             ' Set our question info
  283.             strQuestionText = CStr(rsQuiz.Fields("question_text").Value)
  284.             
  285.             ' Get an array of answers
  286.             aAnswers = Array( _
  287.             CStr(rsQuiz.Fields("answer_a").Value & ""), _
  288.             CStr(rsQuiz.Fields("answer_b").Value & ""), _
  289.             CStr(rsQuiz.Fields("answer_c").Value & ""), _
  290.             CStr(rsQuiz.Fields("answer_d").Value & ""), _
  291.             CStr(rsQuiz.Fields("answer_e").Value & ""), _
  292.             CStr(rsQuiz.Fields("answer_f").Value & ""))
  293.                 
  294.             ' This is probably bad coding style, but too bad... it works!
  295.             For I = LBound(aAnswers) To UBound(aAnswers)
  296.                 If aAnswers(I) = "" Then
  297.                     ReDim Preserve aAnswers(I - 1)
  298.                     Exit For
  299.                 End If
  300.             Next ' I
  301.  
  302.             ' Close and dispose of our DB objects
  303.             rsQuiz.Close
  304.             Set rsQuiz = Nothing
  305.             cnnQuiz.Close
  306.             Set cnnQuiz = Nothing
  307.         Else
  308.             ' If we're not going to the DB, hard code in values here!
  309.             ' BEGIN HARD CODE
  310.             Select Case iQuestionNumber
  311.                 Case 1
  312.                     strQuestionText = "What does ASP stand for?"
  313.                     aAnswers = Array( _
  314.                         "Active Server Pages", _
  315.                         "Additional Sensory Perception", _
  316.                         "Accidental Script Problem", _
  317.                         "Altruistically Solving Problems", _
  318.                         "Additional Sleeping Preferred", _
  319.                         "Any Solution Possible")
  320.                 Case 2
  321.                     strQuestionText = "What command is <%= %> equivalent to?"
  322.                     aAnswers = Array( _
  323.                         "Response.Write", _
  324.                         "Request.Write", _
  325.                         "Referer.Write", _
  326.                         "Redirect.Write", _
  327.                         "Reasonably.Write", _
  328.                         "Damn It I'm Right!")
  329.                 Case 3
  330.                     strQuestionText = "What does "Option Explicit" do?"
  331.                     aAnswers = Array( _
  332.                         "Requires explicit variable declaration", _
  333.                         "Makes the computer give you additional errors", _
  334.                         "Converts a PG rated programming language into one rated NC-17")
  335.                 Case 4
  336.                     strQuestionText = "Which of the following is not a valid "
  337.                     strQuestionText = strQuestionText & "VBScript looping statement?"
  338.                     aAnswers = Array( _
  339.                         "Do...Loop", _
  340.                         "While...Wend", _
  341.                         "For...Next", _
  342.                         "For Each...Next", _
  343.                         "Just do this 10 times you stupid computer!")
  344.                 Case 5
  345.                     strQuestionText = "What language can you not use to write ASP?"
  346.                     aAnswers = Array( _
  347.                         "VBScript", _
  348.                         "JavaScript (JScript)", _
  349.                         "PerlScript", _
  350.                         "SuperScript")
  351.                 Case 6
  352.                     strQuestionText = "Where does ASP code execute?"
  353.                     aAnswers = Array( _
  354.                         "On the web server", _
  355.                         "In the client's browser", _
  356.                         "On any machine it wants to", _
  357.                         "Reportedly somewhere in Washington State")
  358.                 Case 7
  359.                     strQuestionText = "Which set of acronyms is not associated with ASP?"
  360.                     aAnswers = Array( _
  361.                         "CDO, CDONTS", _
  362.                         "ADO, RDS, DAO, ODBC", _
  363.                         "IIS, PWS, MMC", _
  364.                         "ADSI, XML", _
  365.                         "BÖC, OU812, GNR, BTO")
  366.                 Case 8
  367.                     strQuestionText = "Which of the following is not something you can get "
  368.                     strQuestionText = strQuestionText & "from the Request collection?"
  369.                     aAnswers = Array( _
  370.                         "Cookies", _
  371.                         "Form", _
  372.                         "QueryString", _
  373.                         "ServerVariables", _
  374.                         "Beer", _
  375.                         "ClientCertificate")
  376.                 Case 9
  377.                     strQuestionText = "What will this script output when run?<BR><BR><%<BR>"
  378.                     strQuestionText = strQuestionText & "Dim aTempArray<BR>Dim I<BR>"
  379.                     strQuestionText = strQuestionText & "aTempArray = Array(1, 2, 3)<BR>"
  380.                     strQuestionText = strQuestionText & "For I = LBound(aTempArray) To "
  381.                     strQuestionText = strQuestionText & "Ubound(aTempArray)<BR>"
  382.                     strQuestionText = strQuestionText & "     "
  383.                     strQuestionText = strQuestionText & "Response.Write I & " "<BR>"
  384.                     strQuestionText = strQuestionText & "Next 'I<BR>%><BR>"
  385.                     aAnswers = Array( _
  386.                         "0 1 2", _
  387.                         "1 2 3", _
  388.                         "0<BR>1<BR>2<BR>", _
  389.                         "1<BR>2<BR>3<BR>")
  390.                 Case 10
  391.                     strQuestionText = "What is the URL of the best ASP web site?"
  392.                     aAnswers = Array("http://www.asp101.com (yeah... like we'd put any other choices here!)")
  393.             End Select
  394.             ' END HARD CODE
  395.         End If
  396.  
  397.         ' Now that we've got the variables set...
  398.         ' show the appropriate question and choices
  399.         %>
  400.  
  401.         <FONT SIZE="+2"><B><%= Session("QuizName") %></B></FONT><BR>
  402.         
  403.         <BR>
  404.         
  405.         Progress Indicator:
  406.         <%
  407.         Const BAR_LENGTH = 160
  408.         If iQuestionNumber = 1 Then
  409.             ' Since a 0 width is ignored by the browsers we need to remove the image altogether!
  410.             Response.Write "<IMG SRC=""./images/spacer_red.gif"" HEIGHT=""10"" WIDTH="""
  411.             Response.Write BAR_LENGTH
  412.             Response.Write """><BR>"
  413.         Else
  414.             Response.Write "<IMG SRC=""./images/spacer_blue.gif"" HEIGHT=""10"" WIDTH="""
  415.             Response.Write (BAR_LENGTH / iNumberOfQuestions) * (iQuestionNumber - 1) 
  416.             Response.Write """>"
  417.             Response.Write "<IMG SRC=""./images/spacer_red.gif"" HEIGHT=""10"" WIDTH="""
  418.             Response.Write (BAR_LENGTH / iNumberOfQuestions) * (iNumberOfQuestions - (iQuestionNumber - 1))
  419.             Response.Write """><BR>"
  420.         End If
  421.         %>
  422.         Question <%= iQuestionNumber %> of <%= iNumberOfQuestions %><BR>
  423.         
  424.         <BR>
  425.  
  426.         <STRONG><%= iQuestionNumber %>.</STRONG>  <%= strQuestionText %><BR>
  427.  
  428.         <BR>
  429.  
  430.         <STRONG>Choices:</STRONG>
  431.  
  432.         <OL TYPE="A">
  433.         <%
  434.         For I = LBound(aAnswers) to UBound(aAnswers)
  435.             Response.Write "<LI><A HREF=""" & Request.ServerVariables("URL")
  436.             Response.Write "?qid=" & iQuestionNumber & "&sa=" & I & """>"
  437.             Response.Write aAnswers(I) & "</A></LI>" & vbCrLf
  438.         Next 'I
  439.         %>
  440.         </OL>
  441.         <%
  442.     End If
  443. End If 'bAbort
  444. %>
  445.