Session State persists across multiple computers - asp.net

Im sure it has nothing to do with persistance across Multiple Computers but seems quirky that a second website visit, would trigger a refresh of question & answers that are dynamically loaded to be displayed within a Ajax update panel.
Session Interaction and logging
Web.Config:
<sessionState mode="InProc" cookieless="UseCookies" timeout="20" cookieName="ASPNET_Quiz" />
Global.asax:
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Session("test") = "true" 'Used only to create a static Session ID for references.
If (Globals.Quiz(Session) Is Nothing) Then
Globals.Quiz(Session) = New classes.Quiz(WebConfigurationManager.OpenWebConfiguration("~"))
End If
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the session ends
Globals.Quiz(Session) = Nothing
Session.Remove("test")
Session.Abandon()
End Sub
Globals.vb
Module Globals
'Get/Set a Quiz object into the SessionState.
Public Property Quiz(sess As HttpSessionState) As Quiz
Get
Return CType(sess("quiz"), Quiz)
End Get
Set(value As Quiz)
sess("quiz") = value
End Set
End Property
End Module
I have a Master Page with an UpdatePanel that is used to countdown a number of minutes, based on a Database value, and is AsyncPostBack triggered off a Timer Tick event (Interval=1000)
The Content Page has a different UpdatePanel wrapped around the Question & Answers for the site, and also has a AsyncPostBack trigger registered (through the codebehind) to the built RadioButtonList's SelectedIndexChanged event.
If only one person is accessing the site, then there is no problem. As soon as another user accesses the site, is when the Questions & Answers get reshuffled in the Quiz object, which then reshuffles their display and basically causes Questions that have not been answered to be displayed either above the users current position or below. The Answers that have been selected already, do not change but the order of the Answers is reshuffled. The Randomization of the Q&A is rooted at the SQL Server side, via SProc.
Updated 2012-12-07
Changed all 3 of the code segments above to mirror my current design
Also, not sure if it matters but changed the Content Page UpdatePanel PostBackTrigger from AsyncPostBack to just a PostBack
Question:
Any suggestions for fixing this? If it matters any, i also incorporated PageRouting for the site.
Is there a better approach for storing .Net objects, so they survive postbacks? Key is that the Questions & Answers classes associated with the Quiz object, are dynamically ordered every time the Sproc is called. So i need to keep them in the same order as they are first presented.
Should i be initializing the Quiz object in Application_BeginRequest instead of Session_Start?

Related

IE Session.Abandon()

IE seems a bit buggy when it comes on Abondoning the session. This is the whole code thats get executed:
Protected Sub logout_OnClick(ByVal sender As Object, ByVal e As EventArgs)
Session.Abandon()
Response.Redirect("login.aspx")
End Sub
It redirects to login.aspx but when i change the url to default.aspx its get in without checking it. In all the other browsers it doesnt and get you redirected because of the following code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If (Session("Naam") Is Nothing) Then
Response.Redirect("login.aspx")
Else
Label1.Text = "Welkom " + Session("Naam").ToString()
End If
End Sub
Is there any reason that IE doesnt abandon the session?
note//
I am not using log-incontrol what so ever
Try disabling/removing the autopostback and then re-test your page. I would guess that the autopostback is somehow keeping your session data active,maybe its being used in the postback? therefore all instance's dont get abandoned?.
Edit
When the Abandon method is called, the current Session object is queued for deletion but is not actually deleted until all of the script commands on the current page have been processed. This means that you can access variables stored in the Session object on the same page as the call to the Abandon method but not in any subsequent Web pages.
For example, in the following script, the third line prints the value Mary. This is because the Session object is not destroyed until the server has finished processing the script.
<%
Session.Abandon
Session("MyName") = "Mary"
Reponse.Write(Session("MyName"))
%>
If you access the variable MyName on a subsequent Web page, it is empty. This is because MyName was destroyed with the previous Session object when the page containing the previous example finished processing.
The server creates a new Session object when you open a subsequent Web page, after abandoning a session. You can store variables and objects in this new Session object.
The above is from the MSDN website.
Which all means that somewhere your session object is being used AFTER you have abandoned it.
I normally use the same code block as you do to log a member out of a session.
Session.Abandon()
Response.Redirect("default.aspx")
with the same code in the global.asax or global.aspx file too.

.NET Master Page Session state variable not saving

I'm trying to store the session state in a master page to keep track of the previous URL. Here's what I'm doing
Public Property PreviousPage() As String
Get
Return Session("theprevpage")
End Get
Set(value As String)
Session("theprevpage") = value
End Set
End Property
Private Function HandleSiteNode(ByVal sender As Object, ByVal e As SiteMapResolveEventArgs) As SiteMapNode
Dim currNode As SiteMapNode = SiteMap.CurrentNode.Clone(True)
Dim tempNode As SiteMapNode = currNode
Dim strPrev As String = PreviousPage
' Append parent pages query string back onto the parent's node URL
If Not tempNode.ParentNode Is Nothing Then
If strPrev.Contains("?") Then
tempNode.ParentNode.Url = tempNode.ParentNode.Url + "?" + strPrev.Split("?")(1)
End If
End If
Return currNode
End Function
And in the master page load function
If Not IsPostBack Then
AddHandler SiteMap.SiteMapResolve, AddressOf HandleSiteNode
PreviousPage = Request.UrlReferrer.ToString()
End If
Now, here is where it gets strange.
The first page is a login page the master load doesn't get called on. After I log in it then going to the main.aspx page, and it successfully saves the "login.aspx" page in the session state.
Now, when I go to navigate the 2nd time after logging in, the session state is set successfully, but by the time it gets into the HandleSiteNode which is called after the session was set successfully, the session still says the url is "login.aspx" and not "main.aspx"
No where else in the code am I setting this session state, it just seems to revert back to its previous value on its own.
No matter how many links I click & how many times the session is set, the Session variable will never change to anything else besides "login.aspx"
Help!
edit: Another odd detail, when I move the AddHandler line from master page into a non-master page, the session state is saved properly. However, if I try to move the Addhandler code into the Master page MainContent.Load function, it still doesn't work
SiteMapResolve is a static event.
This means that it doesn't have access to the session object. You'll note this if you put a breakpoint in your HandleSiteNode code and inspect the Session.SessionId property.
The examples on MSDN about the event all target the global.asax file which means that handler is really geared towards a single use of the site. Note that the MSDN example I linked to is a little jacked in that it attaches a new event on every page load, which will eat memory. The event should only be attached to once.
Click here for more info on potential ways to get around the issues.
Apparently, my web project has at least 2 different session states.
I can access the session state that contains the value I want by using
e.Context.Session("theprevpage")
This seems like a bit of a hack but it's working for me.

Clearing a session in ASP.NET

I'm a new developer, and I've been assigned the task of figuring out why our log out function is not working. I've tried every possible method I can find. Below is the log I've kept that includes the methods I've used.
Added a log out button to the CommonHeader.ascx form
Have tried numerous methods in the logout.aspx.vb form to get it to end or clear the session but none of them work.
a. ClearSession sub routine defined in the logout.aspx.vb form:
Session("Variable") = ""
FormsAuthentication.SignOut()
Session.RemoveAll()
Session.Abandon()
Session.Clear()
b. Also added this to the top of the Page_Load sub routine:
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)
HttpContext.Current.Response.Cache.SetNoServerCaching()
HttpContext.Current.Response.Cache.SetNoStore()
c. Also changed the ClearSession sub routine to Session.Contents.Remove("Variable") from Session("Variable") = ""
None of these methods work. We use Siteminder, and I've been wondering if this is the root of the problem. I just can't find anything on clearing a Session that uses Siteminder. Also keep in mind this application is coded with Visual Studio 2003.
This is the code for the button I'm using in the ascx file:
athp:TopNavText Title="Log Out" NavigateUrl="logout.aspx" Target="_top"/
Then on the "logout.aspx" form I've tried just using one of the methods described above or a combination of each one. This is the code before I ever touch it:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ClearSession()
Response.Redirect("login.aspx")
End Sub
Public Sub ClearSession()
Session("Variable") = ""
End Sub
Finally figured out the solution, I originally did not define the domain upon deletion of the cookie which contained the siteminder session id. The code I used is as following:
Dim cookie3 As HttpCookie = New HttpCookie("SMSESSION", "NO")
cookie3.Expires = DateTime.Now.AddYears(-1)
cookie3.Domain = ".domain.com"
Response.Cookies.Add(cookie3)
Response.Redirect("login.aspx")
This question: formsauthentication-signout-does-not-log-the-user-out describes a problem with not clearing cookies even after calling FormsAuthentication.SignOut(). This sounds like your issue, they say it's a bug with .NET and as your using 1.1 this sounds distinctly possible.
HI friend please add the click event of the button in user control. And in the click event please add the following code and remove all the other code.
Session("Variable") = "";
look at this post
C# Clear Session
Whether its c sharp or vb the same rules still apply. You are calling session abandon then clear, but by the time you call clear the session should be gone anyway.
Clear keeps the session state along with the objects in it, so by calling it after abandon you could in fact be reinitializing a session for the user, but with cleared variables.
See this post for the order and proper way to kill the session and redirect to the login page if you have one
FormsAuthentication.SignOut() does not log the user out
The first thing to note is that, if you're using Forms Authentication, Session has absolutely nothing to do with whether or not a user is logged in.
Calling FormsAuthentication.SignOut will remove the forms-authentication ticket information from the cookie or the URL if CookiesSupported is false.
But it will have no effect on what is stored in Session.
UPDATE
Why do you think log out (FormsAuthentication.SignOut) is not working? What are you expecting to happen when you click on Sign Out, and what exactly is actually happening?
I'd get rid of all the code to clear Session and look at this. For example, look at the http traffic with a tool such as Fiddler: you should be able to see that the FormsAUthentication cookie is removed when you click on Log Out.

ASP.Net Session variables - struggling with the Cache

I'm using some session variables to store and pass data across several pages of an ASP.Net application. The behavior is a bit unpredictable though. I'm setting the session variable post page_load as follows
Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
If (Session.Item("ScholarshipID") = Nothing) Then
Session.Add("ScholarshipID", "Summer2011")
End If
Ok so far so good, on a normal page load. If the user completes the form action, hits the next page, and decides OH NO, i needed to change field xyz, and clicks back, corrects the data, then submits, the session variable is showing as NULL. Why would a cached session behave this way? I'm not destroying/clearing the variable, unless I fail to understand the scope of session variables.
try
If (IsNothing(Session("Scholarship"))) Then
Session("Scholarship") = "Summer2011"
End If

Add Multiple User Control of the Same Type to a Page

Similar questions to this one have been asked but none seem to address my exact situation here's what I am trying to do.
I have a user control that manages student info. i.e. FirstName, LastName, Address etc.
I have a webpage/form that has a button on it. "Add Student". What I want to accomplish is for a new StudentInfo control to be added to the webform after each click.
My current code looks something like this
Private Sub btnAddStudent_Click(sender as object, ByVal e As System.EventArgs)
Dim lStudentInfo as Control
LoadControl("~/StudentInfo.ascx")
Me.placeholder1.controls.add(lStudentInfo)
End Sub
With this code only one StudentInfo control is added and upon pressing the "Add" button again a new StudentInfo control isnt added below the first one and the text/data entered within the first control is cleared.
Thanks in advance for any assistance.
What is happening is that every time you do a postback your previous control was lost. Remember, every postback uses a brand new instance of your page class. The instance you added the control to last time was destroyed as soon as the http request finished — possibly before the browser even finished loading it's DOM.
If you want a control to exist for every postback you have to add it on every postback.
Additionally, if you want ViewState to work for the control you need to add it before the Load event for the page. This means either on Init or PreInit.
Private Sub btnAddStudent_Click(sender as object, ByVal e As System.EventArgs)
Me.placeholder1.controls.add(LoadControl("~/StudentInfo.ascx"))
Session("NewStudentControls") += 1
End Sub
Protected Sub Page_Init(sender as object, e as system.eventargs)
For i As Integer = 1 To Session("NewStudentControls")
Me.placeholder1.controls.add(LoadControl("~/StudentInfo.ascx"))
Next
End Sub

Resources