Why isn't Session available on page load? - asp.net

I have an ascx. In this ascx, I have any number of controls that I can interact with and set a session variable and it works as expected.
However, when (in the same control), I try to set session in page load, I get a different error depending on how I implement it:
System.Web.HttpContext.Current.Session("Test") = "Test"
It says that, summarized, the Session object is nothing.
If, instead, I say:
Session("Test") = "Test"
It then tells me that I need to enable session state in either the page or web.config. I have indeed checked and session is enabled in the web.config and furthermore, those session statements that are called in response to a click on a runat="server" control works fine.
At this point, I'm almost certain that my issue is because I lack knowledge on the lifecycle of the page and session object. So I therefore have two questions:
Why isn't this working as I expect? I suspect that I'm trying to call Session before some other code which makes it available is executing but what might that be?
How can I make it work so that I can store information in a session variable on page load (and subsequently clear it on page unload)? If I cannot make this work as I hope, how can I do something similar server-side?

The problem was caused by having multiple tabs in the same browser open.
To clarify...
Say maybe tab 1 is open to the page before where I tried to set session because I'm debugging and lazy and didn't close other tabs.
And then maybe tab 2 is the current tab that just opened when I started debugging. The only code change is where I'm trying to set a session variable.
There are now two tabs open with conflicting session state data. When the current code tries to set session, it is in conflict with what is being sent back and forth to "wherever sessions live". Or maybe it doesn't really work that way but closing the old tabs opened with "older code" and having only tabs opened that face the "new code" solves the problem.

Related

Persist selected values of control(s) from the Layout file across the MVC application

I have a Layout page which sets up the list of Projects in the application using Telerik's ComboBox as shown. The combobox allows user to select a project he/she wants to work on.
Once a selection is made, I want all subsequent actions in the application should correspond to the selected Project. I can preserve the Project information in a Session but then if user chooses to open this in a new tab and in 2nd tab users switches to a different Project and comes back to the first tab and refreshes the page then the session information (Project) would have changed which will create issues in my application.
So, what is the best way for me to persist Project information of the Layout.cshtml controls so that I can use it in my application such that every page that is rendered uses the currently/correctly selected values.
Tempdata / QueryStrings came to my mind but i don't know whether they will be reasonable solution to my problem. If yes, then how should I use them generically (specially querystrings) without complicating my solution?
localStroage and sessionStorage also seems like relevant solutions but then how do I use them in scenario where user opens a new tab from existing page? How will the Project # will persist on the newly opened page/window/tab?
something like this is achievable, if you make sure the url changes when a selection is made.
So let's say you select project C-1379 in your dropdown box, at that point your url could become http://localhost:58692/pid=C-1379.
from now onwards, your page can load the desired data, retrieving its required information from the query string. Do not use session or localstorage or anything like that as it won't work.
This way, you can still load your list of projects in your layout page, and you can select one based on the query string value and then load some default values via api calls to the back end.
If all your work from now on is done based on api calls, for example, you have some properties that you change and then you issue a POST to update said details then this is very easily done as well.
telerik controls usually have some events associated with them. the one you are using should have an onChange or something like that. This where where you would update the query string with the value of the project selected and then you can proceed to do what you need
I can preserve the Project information in a Session but then if user
chooses to open this in a new tab and in 2nd tab users switches to a
different Project and comes back to the first tab and refreshes the
page then the session information (Project) would have changed which
will create issues in my application.
I would have thought this is the desired behavior... take stackoverflow.com as an example, if I change my username in one browser-tab, I would expect my username to be updated in other browser-tabs as well... and that's what happens if I refresh my other tab.
There is no built in solution for maintaining user info in different browser tabs separately... the only way to achieve this, is by sending project name back and forth in the URL... but then you would loose this info if user changes the URL... In my opinion, this is an ad hoc solution and does not worth the effort of development, because it's a very uncommon scenario.
Getting to your options:
Storing user info is a very typical use case for session variable.
TempData is stored in Session by default. Though you can write
your own custom TempDataProvider and store it somewhere else (e.g.
database, cookie, etc). See Brok Allen's Cookie TempDataProvider
as an example. One advantage of using Cookie is that you send your
session variable back and forth with the request so you don't need to
worry about Sticky Sessions.
You can of course use a permanent storage, such as DB/Disk.
If the project name is not a sensitive info then I don't see any issue in passing it in Query String.

Internet Explorer - losing HttpSessionState

I have an intranet website. Within this is some code which stores a few variables within an HttpSessionState object. For all but one user this works. However for reasons unknown, on this one person's machine, it doesn't appear to be saving it.
The reason I know this is that basically its an asp.net wizard. On step 1 the user makes a selection and that gets stored. When attempting to move to the next step, the session gets checked for a valid value. In this case, the user is making the selection but it never gets remembered.
Very odd as it should be a standard build. I also see the same problem whether IE or Chrome.
Any high level things I could check to help diagnose?
Thanks.
If they have their browser privacy settings set to a high level this could prevent the session cookie from being accepted. Just a stab in the dark.

asp.net only occasionally calling Page_Load

Report updated with new information.
My initial report concerned an asp.net site / app, with vb.net codefiles, that only seems to work properly when debug is set to true in web.config. When debug=false the search function and the links to create a new search (which simply hyperlinks that reload the page) will occasionally not work, leaving the page partially loaded or not loaded at all.
From further investigation, it appears as though Page_Load is only being occasionally called, as I have a search object defined there that is occasionally found to be null (leading to the problems I've seen) in my button_click event (the first method that I find called when I refresh the page after a search).
Not really sure what to make of this or how to begin solving it. Have not found much of anything that suggests others have had the same problem. Any help appreciated!
I thought it might have been caching. Tried the suggestions here to no avail. I also discovered the setting of the debug flag is a red herring... having it set to true only masks the problem for a while, whereas setting it to false makes it appear almost immediately.
Check whether the user running the web page is having administrator rights .If not see whether the issue existing when running as an admin.
Try to run from a different browser .

How to Track F5/Refresh in ASP.Net

I am using VS 2005, C# 2, ASP.Net 2.0
I am unable to find out how to track that user pressed F5/Ctrl+F5/ Open a new Window(Ctrl + N) in ASP.Net.
I know that there is a Page.IsPostBack property, which tells that a page is loaded in response to an action taken by user.
I am just curious to know, that why isn't there a property as IsRefresh or Page.IsRefresh in ASP.Net, which will return true,
whenever user takes any of the above actions.
Is there a way to know this?
Actually my problem is that i have a DLL using which all of my aspx pages are inherited, I have to
insert some values in a table whenever the page is opened for the first time that's it, if user just opens the page or do not take any action,
an entry should be inserted into the database, but as far as I have tried, I controlled it anyhow using the Page.IsPostBack property, but I got stuck
in the refresh case, as it is inserting records unconditionally.
Similar to using a function in Global.asax (as others have suggested) you could use a session variable "flag". When the page first loads set a session variable and then just check against it in your page load function:
if (Session("visited") != "true"
//page has not been visited, log visit to DB
Just make sure you set the session flag sometime after the above check during the page load.
It won't be exact (sessions can timeout while a page is active, users can completely leave the site and come back in the same browser and the session stays alive, etc) but for your tracking it is much better than counting every page hit in the DB.
Perhaps you want the Session_Start method in the Global.asax file, which will be triggered once at the start of each user session?
In your Global.asax file, add or edit the method:
void Session_Start(object sender, EventArgs e)
{
}
why isn't there a property as IsRefresh or Page.IsRefresh in ASP.Net
Because ASP.NET cannot possibly know. The browser does not send any information that could allow it to determine whether the page is being requested due to a refresh or normal load. You will need to reconsider your requirements: what is the actual purpose of the database logging?
Session_Start method in Global.asax file is fired every time when a browser session is started. You can use this method to count number of unique users on your website.
Session_End method in Global.asax is fired when a session ends (explicitly or timedout). So you can decrement the count here.
Hope the above to example uses of these methods helps you understand how you can use them.
Because of the stateless nature of HTTP protocol there is no way to tell apart the initial load from the refresh
As has already been said. This isn't possible. A request issued due to a refresh is no different to a request issued the first time the page is loaded.
It sounds to me like you are trying to track page views somehow. This is certainly possible though it will require some work on your part. Your best bet is probably to log the URL of the page. You may also want to include the query string in order to differentiate between page loads for different pieces of data (if this happens in your application). You will also want to log the ID of the current user, and the ID of their session.
You can then make sure that you don't insert two page views for the same user for the same page in the same session, effectively filtering out any reloads of a page.
You do need to be aware that this isn't the same as detecting a refresh, what you are detecting is two page views in the same session, this could be a refresh, or it could be use of the back button, or just reloading from the address bar.
My suggestion would be to create a cookie on very first load, then on Page_Load check to see if the cookie exists. If it does, don't insert the record. You can use Session_End to destroy or create the cookie as someone suggested if that works with your application's architecture.

Why does my session variable appear to empty itself in ASP.NET?

I have user control on a ASP.NET web page, which contains a GridView and a radio button selector.
In the underlying middle tier I have a thread which goes to the database and then raises an event to say "I have some data" my User control handles this event and sets a Session Variable.
This works and I can see the event being handled and the Session variable gets the new data.
However when i go to use this session variable when the selected index of the Radio button selector changes the Session variable reports as "Nothing"
I have ensured that the obvious (i.e. spelling, Sessions switched on etc) are correct.
The GridView and radio button selector are encapsulated in the same Update panel.
Check that if your UpdatePanel - updatemode is set to 'Conditional'? also Child as triggers? I would first start by putting a stop in your page load, see whats happening from there. Do a search for all places where you populate that session variable and put a stop. You may be surprised, I have often found that page lifecycle gets confusing even though I thought I understood it. Alt - post some code and we can step through.
Yeah, sounds almost like a problem with order of operations or not checking for postback on a page load or something?
Like JamesM suggested, running your website in debug mode should really help identify the problem. You can bring up your watch window and set it for the Session variable you're looking for, then set breakpoints all over and check the value at each stop to divide and conquer the code.

Resources