Monday, April 20, 2009

Sorting in Classic ASP

For the past 2 weeks I have been supporting and maintaining a client website, which is huge, but mostly in ASP.

There was one emergency client work order – requesting an ASP page that should provide options to download some error log files located in a virtual directory.
The request was very clear in mentioning that the error log files should be shown in a dropdown, and the files should be sorted chronologically, the recently modified to be on top.

Getting the list of files is easy, using the FileSystemObject. Also getting the modified date is simple, we have the DateLastModified property of the file object. The only additional thing pending was to sort them by this date.

This has to be developed in classic ASP. .Net was not an option – How I miss coding in .Net! This whole thing could have been done in just a couple minutes. Still building this in ASP page only took a few minutes extra. Wanted to share the Sort method for reference to others (and myself too).

Fetch the list of files into an array:

Dim fso
Dim errorDir
Dim file
Dim filesArr()
Dim sortedFiles
Dim cnt
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set errorDir = fso.GetFolder(Server.MapPath(ErrorLog_Dir))
cnt = 0
For Each file in errorDir.Files
cnt = cnt + 1
Next
Redim filesArr(cnt,1)
cnt = 0
For Each file in errorDir.Files
filesArr(cnt,0) = file.Name
filesArr(cnt,1) = file.DateLastModified
cnt = cnt + 1
Next

Call the Sort function

SortByDate filesArr, 1

Definition of the SortByDate function:


Function SortByDate(arrToSort, intAsc)
Dim temp1
Dim temp2
Dim i, j
For i = 0 To UBound(arrToSort) - 1
For j = i To UBound(arrToSort)-1
'Sort Ascending
If intAsc = 1 Then
If datediff("n",arrToSort(i,1) , arrToSort(j,1)) >= 0 Then
temp1 = arrToSort(i,0)
temp2 = arrToSort(i,1)
arrToSort(i,0) = arrToSort(j,0)
arrToSort(i,1) = arrToSort(j,1)
arrToSort(j,0) = temp1
arrToSort(j,1) = temp2
End If
'Sort Descending
Else
If datediff("n",arrToSort(i,1) , arrToSort(j,1)) <= 0 Then
temp1 = arrToSort(i,0)
temp2 = arrToSort(i,1)
arrToSort(i,0) = arrToSort(j,0)
arrToSort(i,1) = arrToSort(j,1)
arrToSort(j,0) = temp1
arrToSort(j,1) = temp2
End If
End If
Next
Next
fnSort = arrToSort
End Function

Post a Comment