ASP.Net Session variables - struggling with the Cache - asp.net

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

Related

Making combobox_selectedIndexChanged work

I have a web page that on page load loads data into drop down lists and the user has the option to change the values if they wish too. How do I make it so everytime they change the value it will save it and resend it to the database? So far all I have is this:
Private Sub cboCure_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboCure.SelectedIndexChanged
cboCure.SelectedItem.Text = CStr(sender)
...database functions using cboCure.SelectedItem.Text
End Sub
I don't know if this is enough information to help out at all, if it's not just lemme know... I don't really know what else to put in this one.
Set autopostback property of your combobox to true. So that, whenever a change happens; you can check if if(ispostback) and have your code to do the insertion of changed data in DB.

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.

Session State persists across multiple computers

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?

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.

How do I update an entity in EF across multiple ASP.NET requests without retrieving it again?

Sounds easy, right? Here's the scenario...
Private dbQuery As New ReefEntities
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
CurrentCoral = (From c In dbQuery.Corals Where c.CoralID = intCoralID).FirstOrDefault
txtCommonName.Text = CurrentCoral.CommonName
End If
End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
'how do I access the coral from the page load to update it?
CurrentCoral.CommonName = strName
dbQuery.SaveChanges()
End Sub
I don't want to re-query my result, I want to update the query from the page load and then save the changes, right? How do I access that original object to update it?
HTTP is a stateless protocol and as a result, every request you make to your server needs to rebuild your object graph unless you persist it somewhere. There are many ways to persist data across a web "session". In ASP.NET you can store data in cookies, server side session, viewstate, form variables, and more.
First you would detach your CurrentCoral from the object context when you're done with it in Page_Load
dbQuery.Detach(CurrentCoral)
Then put it in a data store like view state.
Me.ViewState.Add("CurrentCoral", CurrentCoral)
In the next web request when your save button is clicked, retrieve the entity from the view state and attach it to your new object context.
CurrentCoral = CType(Me.ViewState("CurrentCoral"), Coral)
dbQuery.Attach(CurrentCoral)
CurrentCoral.CommonName = strName
dbQuery.SaveChanges()
Please forgive any syntax errors. VB.NET is not my first language! For more details on attaching and detaching entities with Entity Framework see the following article.
Attaching and Detaching Objects
You could put your CurrentCoral object into the ViewState or Session, then retrieve it in the Click event.
Dim oCurrentCorral as Object = ViewState("CurrentCoral")
dbQuery.ObjectStateManager.ChangeObjectState(oCurrentCoral, System.Data.EntityState.Added)
dbQuery.SaveChanges()
If the request is a postback, the record isn't loaded in Page_Load at all – there's nothing to re-query since you haven't made a query in the request at all. I'd say to just re-query in the postback handler, chances are the overhead of hitting your database once to update is much smaller than the overhead of sending the whole entity serialised in ViewState all the time.

Resources