Selecting a Random File from a Directory and Outputting its Contents Demo

This demo illustrates how to have a random text file read from a directory and have its contents displayed. Below you will see the output of a random text file from the directory of (very) old WebWeekly issues.


WebWeekly: Your weekly source for Web Technology Tips and Tricks! -Forward this email and subscription information to a fellow developer!********************************************************************** Developers Can Now Deploy ASP Applications Anywhere! Halcyon Software will release this month an Active Server Frameworkthat gives developers the ability to deploy Active Server Pages (ASP)applications on any Web Server, Application Server, or Operating Systemplatform. Instant ASP (iASP) not only provides standard Microsoft ASP compatibility on non-Microsoft platforms, it extends basic ASPcapabilities to provide support for Java, JavaServer Pages (JSP), andCORBA components as well. Instant ASP is $495 SRLP per deployment server.Developer editions of iASP are free! *** http://www.halcyonsoft.com ***-- Please support our sponsors, they make WebWeekly possible! --******************************************************************************************************************************************** Explicitly ReAllocating Memory**********************************************************************One of life's few truisms is that programmers are inherently lazy. Thisfact gets us into trouble more often than not, and can get us intoextremely hot water when dealing with database connectivity with ASP. In ASP, we create connections to databases and capture the results ofdatabase queries using ADO; we use ADODB.Connection and ADODB.Recordset,most frequently. Let's look at a quick example of how we might use thesetwo: Dim objConn Set objConn = Server.CreateObject("ADODB.Connection") objConn.ConnectionString = "DSN=Northwind" objConn.Open Dim objRS Set objRS = Server.CreateObject("ADODB.Recordset") objRS.Open "SELECT * FROM Table1", objConn We'd then go along our merry way, iterating through objRS. Once we'redone using objRS, what do we do? Most often, developers do nothing, theylet ASP "clean up." When the Server.CreateObject calls are made, resourcesare allocated on the server to handle new instances of these objects. Ifwe don't explicitly inform the server that we're done with these allocatedresources, ASP *should* do it for us. Putting all of our faith into ASPis a bit of a risk. It's much safer and much more reliable to*explicitly* close and clean up the instances of our recordset andconnection objects. So, how do we explictly close our objects and free the memory associatedwith them? All we need to do is invoke these following four lines whenwe're finished utilizing our two objects: objRS.Close Set objRS = Nothing objConn.Close Set objConn = Nothing This will force the cleanup, rather than relying on the automated,implicit cleanup. Now, you may be wondering how important it is to dothis. Who wants to have to write four extra lines of code for each ASPpage that utilizes database connectivity? Well, the advantages to doing itfar outweigh the disadvantages of having to do it. To make my point, letme quote Charles Carroll, webmaster of ActiveServerPages.com: "You must close recordset, set to nothing, close connections and set to nothing in that sequence. The standard garbage collection is incomplete and unreliable. [By garbage collection, Charles is referring to the implicit cleanup of allocated resources on the server.] "DataReturn[, an ASP webhosting company,] has many sites that fail horribly if they let IIS do automatic garbage collection. Adding Close/Set Nothing makes the sites work like champs again. It is mandatory in any high volume site." If Charles's words didn't convince you, let me discuss a real worldproblem that was caused by a lack of explicit memory reallocation calls. Brian Fairchild runs a high-volume ASP site that uses Access as thedatabase backend. He noted after a while, ASP pages would simply stopresponding! HTML pages would display fine, but all ASP pages would simplynot process; a reboot of the server was needed. Eventually, Brian foundout that by explicitly closing and freeing all of his recordset andconnection objects, the problems stopped. (Seehttp://www.aspmessageboard.com/forum/performance.asp?M=1321&P=1&F=23 toread Brian's posts to the messageboard regarding this issue.)Another tip from Charles Carroll for those using Access is to increase thedefault number of threads. Here's what Charles had to say: "The default threads of 4 in the registry bites for Access. Increasing it to 20 will do wonders for all aspects of the server, but specifically Access.Our server was 100% CPU solid from 8-5pm but this simple change made it calm down so I have tested this tweak." To learn more about increasing the threads, be sure to visit:http://www.aspmagazine.com/aspmagazine/issue10kb.aspWell, lazy coders out there, I hope this article has convinced you tospend the extra few seconds to explicitly close your ADO objects. I havetrouble myself, taking the few moments and writing those needed lines! Happy Programming!*************************************************************************************************************************************************************************************************************** ------ HOT ASP COMPONENT MAKES BROWSER COMPATIBILITY EASY! ------Did you know? BrowserHawk 2.0 allows you to easily create web sites that work consistently for the wide variety of browsers in use today.It recognizes all IE and NN browsers, providing info on more than 40capabilities including DHTML, FileUpload, StyleSheets, SSLKeySize, andeven detects disabled cookies!Visit http://www.cyscape.com?q=4gn now to download your FREE evaluation!-- Please support our sponsors, they make WebWeekly possible! --*************************************************************************************************************************************************************************************************************** OTHER ARTICLES*********************************************************************Search the Internet From Your Site!http://www.4guysfromrolla.com/webtech/060699-1.shtmlThis article, by Christopher Miller, demonstrates how to add a form toyour webpage to search many of the Internet's popular search engines, suchas Yahoo!, AltaVista, Excite, and others. Christopher provides full code,and a working example of his scripts! *********************************************************************Creating an Event Calendarhttp://www.4guysfromrolla.com/webtech/060599-2.shtmlThis article, by Christopher Miller, demonstrates how to use ASP and ADOto create an event calendar. Users can add events, which will thendynamically appear in the calendar. Christopher provides a thoroughexplanation of his code, a working example you can check out, and fullsource code, including the database files he used! An interesting read! *********************************************************************Error Handling in ASPhttp://www.4guysfromrolla.com/webtech/060399-1.shtmlDon't you hate it when you get those nasty ADO errors? There's nothingworse than an end user seeing those. This article discusses how toimplement error handling in ASP so that errors are trapped, error messagesformatted, and an informative explanation is presented to the user ratherthan a nasty ADO error! *********************************************************************ASP Messageboard, the place to get answers!http://www.ASPMessageboard.comThe ASP Messageboad site has been growing at an incredible rate!Tons ofnew questions are getting asked and answered each day! Ifyou've got anASP-related question, or would like to help others solvetheir ASPdilemmas, drop on by and puruse the questions! *********************************************************************Win Free Books from WROX!http://www.4GuysFromRolla.com/webtech/raffleFrom now until 6/12 we will be raffling off five FREE copies of Wrox'sIE5 & Dynamic HTML! Drop on by to sign up for your chance to win afree copy of this book!You can also check out http://4guysfromrolla.com/freestuff.shtml to seewhat free stuff we're currently giving away! Have a great day!*********************************************************************4GuysFromRolla.com Humor Sectionhttp://www.4GuysFromRolla.com/humorThe humor section has been consistently growing, and we recently wonan award for it! I know this is a little off-topic for the WebWeekly,so I don't want to go into it; just wanted to invite you all to checkout our collection of jokes, original humor, and spoof sites!*********************************************************************I hope you enjoyed this WebWeekly. If you have any ideas, comments,suggestions, rants, or raves, please let me know by replying to thisemail. If you are not familiar with 4GuysFromRolla.com, be sure tocheck out http://www.4GuysFromRolla.com/new, to view our sitemap.Happy Programming!****************************************************************************************************************************************** To subscribe to WebWeekly, point your browser to: http://www.4GuysFromRolla.com/webtech/webdaily To unsubscribe from WebWeekly, reply to this email with the following subject: UNSUBSCRIBE WEBWEEKLY******************************************************************************************************************************************Thank you for subscribing to WebWeekly!If you know someone who could benefit from a wealth of web developmenttechnology, invite them to visit http://www.4GuysFromRolla.com/new


Source Code
<%
Option Explicit

Function ReadDir(FolderName)
	On Error Resume Next
	Dim objFSO
	Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
		
	'Make sure the specified folder exists
	If Not objFSO.FolderExists(FolderName) Then
		ReadDir = "Folder does not exist. <br><b>This can be changed to " & _
				"a default message or nothing.</b>"
		Exit Function
	End If

	Dim objFolder
	Set objFolder = objFSO.GetFolder(FolderName)

	Dim I : I = -1
	ReDim arrFile(20)
	Dim objFile
	For Each objFile In objFolder.Files
		If Right(objFile, 4) = ".txt" Then
  			I = I + 1
			
			if I > UBound(arrFile) then ReDim Preserve arrFile(I + 20)
						
			arrFile(I) = objFile.Path
		End If
	Next
	
	'Make sure arrFile is the right size
	Redim Preserve arrFile(I)

    If I = -1 Then
		ReadDir = "No text files in this directory. <br><b>This can be " & _
		          "changed to a default message or nothing.</b>"
		Exit Function
	End If

	Randomize
	Dim RanFile : RanFile = Int((UBound(arrFile) - 1 + 1) * Rnd + 1)
	Dim strOutput : strOutput = ""
	Dim strFileName : strFileName = arrFile(RanFile)
	If objFSO.FileExists(strFileName) Then
		Dim objTextStream
		Set objTextStream = objFSO.OpenTextFile(strFileName, 1)
			Do While Not objTextStream.AtEndOfStream
				strOutput = strOutput & objTextStream.ReadLine
			Loop
		objTextStream.Close
	Else
		ReadDir = "File does not exist. <br><b>This can be changed to a " & _
		          "default message or nothing.</b>"
		Exit Function
	End If
 
	
    ReadDir = strOutput
 
 Set objTextStream = Nothing
 Set objFolder = Nothing
 Set objFile = Nothing
 Set objFSO = Nothing
End Function
%>

<h1>Selecting a Random File from a Directory and Outputting its Contents Demo</h1>
...

<%
  Response.Write(ReadDir(Server.MapPath("/webtech/WebDaily")))
%>


[Return to the User Tip]