-Log in
-Register (free)


-RSS Feeds
-New MyDesk Module
-Update to Profile

Image Uploader Timeout - Flash Uploader?
POST form (browser remembering values)
Dynamically create a 3x2 html table




 Lesson 7: Add a quote of the day!
Lesson 7: Add a quote of the day!

Author: Alexander Haneng
Quotes supplied by Epcylon
Difficulty: Easy
Requires: ASP
Demo: Demo
Download: Lesson7.zip
Summary:
Learn to make a random quote of the day. View the demo to see the result.

Intro:
Since you now are an expert on using files after lesson 4 (the Guestbook), let's make something a little bit more fancy. I often see people having a "tip of the day", or a "quote of the day", and I thought I should try to make a VBScript variant. It reads the quotes from a text file (for easy maintenance), and displays it.

The code:
Let's start coding! First make a text file in a directory. Fill it with your quotes, one on each line. To make it easier later on, add the number of quotes (lines) on the first line (alone). Now your text file will look something like this:
3
A Computer Scientist Is Someone Who Fixes Things That Aren't Broken.
Any Sufficiently Advanced Bug Is Indistinguishable From A Feature. -- Kulawiec
Asking Whether Machines Can Think Is Like Asking Whether Submarines Can Swim.


Why the number? Well we are to pick a quote at random, and we therefore need to know how many quotes there are. We could just loop trough the file one time, counting home many lines there are. But to make it a little bit faster, we use a header.
And now to the script:
<%
'First we open the banner file, make sure you have the right path to the file
Set MyFileObj = Server.CreateObject("Scripting.FileSystemObject")
Set MyTextFile = MyFileObj.OpenTextFile("c:\quote.txt")
'Then we read the header
IF NOT MyTextFile.AtEndOfStream THEN
  header = CInt(MyTextFile.ReadLine)
END IF
'Then we make a random value based on the header, the RANDOMIZE
'statement is important to insure a random value.
RANDOMIZE
LowestNumber = 1
HighestNumber = header
RandomValue = INT((HighestNumber-LowestNumber+1)*Rnd+LowestNumber)
Count=0
'Loops until it comes to line number=random value
'And then it saves it in the variable quote
WHILE NOT MyTextFile.AtEndOfStream AND NOT Count = RandomValue
  quote = MyTextFile.ReadLine
  Count = Count + 1
WEND
'Closing up the text file
MyTextFile.Close
%>
<HTML><BODY>
Today's quote is: <%=quote%>
</BODY></HTML>

Download the code: Lesson7.zip

Modifications:
Use this script in an include file, and use:
<!--#INCLUDE FILE="quote.asp"-->
where you want the quote to appear. For more info on using INCLUDE, see lesson 6.

Where to go next:
Take a look at our lessons page to get an overview of all our lessons.


6: 5 tricks with VBScript!
8: Bake a cookie!
| Info |
© Copyright 1997-2008 Alexander Haneng