I am trying to use sessions for the first time and would like to know abt that in a better and easy way.
I am creating a session variable using GUID and creating a folder with that GUID and storing that value as shown below
If Session("tempDir") Is Nothing Then
Dim tempDir As String
tempDir = Path.GetRandomFileName()
tempDir = tempDir.Substring(0, tempDir.LastIndexOf("."))
IO.Directory.CreateDirectory(Server.MapPath("Uploads/" & tempDir))
IO.Directory.CreateDirectory(Server.MapPath("Downloads/" & tempDir))
Session.Add("tempDir", tempDir)
currentDirectory.Value = Session("tempDir").ToString
CopySession.Text = currentDirectory.Value
End If
This is the code for generating GUID:
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
if (!length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
I am using the below code to get that on page is postback but whenver I refreshes it deletes that value and gives me a NULL value.
If Page.IsPostBack Then
If Session("tempDir") Is Nothing Then
Dim tempDir As String
tempDir = Path.GetRandomFileName()
tempDir = tempDir.Substring(0, tempDir.LastIndexOf("."))
IO.Directory.CreateDirectory(Server.MapPath("Uploads/" & tempDir))
IO.Directory.CreateDirectory(Server.MapPath("Downloads/" & tempDir))
Session.Add("tempDir", tempDir)
currentDirectory.Value = Session("tempDir").ToString
CopySession.Text = currentDirectory.Value
End If
End If
How do I retrieve the tempDir value?Can anyone give me some detailed explanation regarding this as I am totally confusing.
Remove this 2 lines out of the IF
will be
What Is the different here, that if the session is not exist, then go and set it it. After the if the session for tempDir exist because ether you just set it, ether get it from previous or other call. I hope this give you what you wondering, or else tell me what you do not understand.
Session
The session is a Dictionary of values that is connected with each user for the time the session is active (eg for 20 minutes). As the user interacts with the site this data is follow this user and you can set them, read them or delete them using the session.
When a page loads the session data read at the start, you can used them on page, and on page unload the session data saved back to session keeper.