Session deleting a subset the session Variables
When using the Sessions to store variables in, I use a naming convention-for example, for all Customer related info I prefix The session variable with the substring Customer. (So for the CustomerID it would is customer.id, the Customer username would be customer.name, etc.) This is very useful when viewing the session objects as and you can to the related objects off.
The problem I had the other day is that I wanted to remove only those items from the session which were SW. So-I-used the following code:
'---------------------------------------
Session ("sw.1") = "Test 1"
Session ("sw.2") = "Test 2"
Session (' other ') = "other"
For each sessionitem in session.contents
If Left (sessionitem,3) = "SW." Then
Session.Contents.Remove (Sessionitem)
End If
Next
'---------------------------------------
This seems fine, but when it's run, what happens is-is-sw.1, removed but is-not sw.2. Why? I ' m not exactly sure, but I guess that the index is then reset so that sw.2 be now where sw.1 be, and seeing as we have I Terated past that item in the For each ... Next statement, the loop just moves to, and missing out sw.2 altogether! eek!
This I wrote the following function, which'll properly delete all sessions variables that begin with SP round Ecified substring:
'---------------------------------------
function sessionremoveselected (sitemprefix)
'/////////////////////////////////////////////////
' Remove Selected Items starting with Sitemprefix
' From the session. e.g. SS. 'll remove Ss.id and
' Ss.name but not CustomerID Returns True or False
' Depending on whether the any items where removed.
'---------------------------------------
' Sitemprefix [string]: Item Prefix
'/////////////////////////////////////////////////
Dim arysession ()
Dim lcount, Lprefixlength
Dim Sessionitem
Dim Blnresult
Lcount =-1
Lprefixlength = Len (sitemprefix)
Blnresult = False
' Temporarily store in array items to remove
For each sessionitem in session.contents
If left (sessionitem,lprefixlength) = Sitemprefix Then
Lcount = lcount + 1
ReDim Preserve Arysession (Lcount)
Arysession (lcount) = Sessionitem
End If
Next
' Remove items
If IsArray (arysession) and lcount >= 0 Then
For lcount = LBound (arysession) to UBound (arysession)
Session.Contents.Remove (Arysession (lcount))
Next
Blnresult=true
End If
sessionremoveselected = Blnresult
End Function
'-------------------------------------------------