session variable object gets deleted on postback - ASP.NET - asp.net

I have made something like the following code:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Session["loginid"].ToString();
}
protected void delete_click(object sender, EventArgs e)
{
delete("mail1",Session["loginid"]);
}
private int delete(string mailid, string user)
{
System.IO.Directory.Delete(Server.MapPath(#"~\files\" + user + #"\" + mailid), true);
}
When i press the delete button, everything works fine and the folder gets deleted.
but after that when page postbacks again then a
NullRefrenceException is raised at
Label1.Text = Session["loginid"].ToString();
why is it happening...??
When I am not using this Directory.Delete() method everything is working fine and session variables are not set to null.
When I traced my application I found that After Directory.Delete() method Session variables were intact and I was able to use those session variables in the processing after Directory.Delete().
But as soon as the page postbacks all session variables are set to null.
And this problem doesn't appear when i m not using this delete() method.
The folder I m deleting is in my project's folder.
I m running this website using Visual Studio.
Please help.

Just another guess here but maybe it's because your modifying something in your applications directory (a hunch since your using Server.MapPath with the ~). IIS maybe thinks the app has changed and recycles the application and as a result wipes out all sessions.
This is similar to if you modify your web.config file while someone is using the app and it drops all sessions and recycles the app. Are you deleting a directory that may contain information that IIS is using for the application?
You said it only happens when you include that line of code and a session will really only get wiped out consistently (unless you are doing it yourself manually) when the application is recycled by IIS or times out. It is obviously not timing out so the recycle must be what is happening.

Is your 'files' folder in your web application folder? Maybe application restarting itself when you deleting the files. Try to use sessionStateServer. Its keep sessions alive.
Web.config:
<configuration>
<system.web>
<sessionState mode="StateServer"></sessionState>
</system.web>
</configuration>

Deleting a folder in your virtual directory may cause your application to re-start, thus loosing all session data. To prevent this, either delete individual files (not folders) or use the StateServer to maintain your sessions.

Since the page loads correctly before you press the delete button, the problem is presumably with the Session["loginid"].ToString() reference. Do you have any other code that references Session["loginid"]? The code you have shown here won't do anything that removes loginid from the Session.
However, if this application is running on a server cluster and you're using the default session mode of in-process, you may be losing access to your session between HTTP requests because they're handled by different servers. See here for more information.

If I remove the directory.delete()
function from the code then the whole
application is running so fine without
any exception
Ok, seems that we found your problem. Your project does not have the necessary privileges to delete the direcotry (even if the directory is deleted.nevertheless: there are privilege problems)
I guess that you're application is throwing an exception while performing this file operation and a new session begins. I have a similiar situation on one of my projects, but I still haven't figured out how to solve it.
I'm pretty sure you will concur with description if you create the Global.asax and set breakpoints on Application_OnError and Session_OnStart (or however these methods are spelled correctly). You will see that the an error is raised and afterwards a new Session is started.

First, a couple of sanity checks:
Does session work as expected on other pages?
Is your Delete method deleting files in a special ASP.NET folder, like App_Data or App_Code, which may be causing the application to restart?
Here's what I would try to debug this issue, after checking the above:
Set a breakpoint on the delete method and have the session variable in a watch window. See what the value of the session variable is before the call to Directory.Delete is and what it is afterward. Is it at that point when you're losing session, or is not until the next page visit?
Use a tool like Fiddler to examine the cookies exchanged between the browser and web server on postbacks. Check that when the browser first visits a new session cookie is created and stored on the browser. Then, when deleting the folder, see if the web server is sending a new session cookie on the response of that postback. This would indicate that a new session has been created.
Thanks

Related

Session being reset inadvertently

I have a legacy ASP.NET application. It was converted from NET 2 to net 4.
It uses state server session.
At some point, the app opens a new page (in a new browser tab: link target = "_blank")
But after returning to calling page (tab), I discovered the session is reset, so current user is no longer used and app redirects to login page. Actually, SessionID remains unchanged, but IsSessionNew is set to true, and session has no variables set in it.
The app doesn't use Session.Abort or Session.Clear.
Even if I change session to InProc, and change the target for the links to _top, or _self, or remove entirely, the same thing happens - session got reset.
This is session setting in web.config (alternatively I used StateServer, but with same result)
<sessionState timeout="432000" cookieless="UseCookies" mode="InProc"/>
Any idea what can cause this?
Thank you.
I finally fixed the problem.
However, I didn't found the actual cause, but I found the module which caused the issue.
It was a aspx page which did 1001 things (it's basic functionality plus another approximatively 80 other things based on ajax calls (!!!). I didn't made that page !!!
But the part that caused the problem was a functionality that served an image file.
So I rewrite that part as an ASHX handler, and then the code worked ok - the session remained open.

Session state enableSessionState issues in asp.net application

I get the following error in the production environment
Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the configuration\system.web\httpModules section in the application configuration.
The following things I have tried as of now
Checked machine.config and web.config, both have enableSessionState="true"
Added enableSessionState="true" to pages in web.config
State module is also added in <httpmodules> section
Even tried setting enableSessionState="true" in page directive
Note: When I try to debug the code in Dev environment, everything works fine as it should.
Can anyone help me out getting over this issue, I just can't figure out a way out of it.
What does your session state config look like? You probably want to be set up to use inproc session handling.
http://msdn.microsoft.com/en-us/library/ms178586.aspx
I know this is a late response but I just want to add how I fixed the same problem.
First I want to emphasize that I'm using web forms, not MVC - this may not work for MVC.
I created a web form that contained the class ContactUser and I created my own constructor so it looked like:
public ContactUser(String to, bool isUser)
{
...
}
And in this I tried to access a session variable:
String user = Session["username"]
It turns out that you CANNOT use the session state in the constructor of a class, but you can use it in other functions that you write and in the protected void Page_Load(object sender, EventArgs e) procedure. So once I moved session state out of the constructor into the page load procedure everything worked :)!
Hope this helps anyone that runs into the same problem :D!

Session_Start firing multiple times on default ASP.NET MVC3 project

I think I may have found a problem with ASP.NET MVC and it's event pipeline. In particular, I am finding that Session_Start is being called multiple times, each containing a new SessionID.
Here's the step-by-step process:
Open VS2010
File | New Project
ASP.NET MVC 3 Web Application, accept default name, click OK
Select Internet Application (although I don't think it matters really), click OK
When finished creating, edit the Global.asax.cs file
Add the following method (yes it's empty):
protected void Session_Start()
{
}
Set a breakpoint in the method
Debug
Notice that the breakpoint is caught twice before displaying the page. If you watch "Session.SessionID" when the breakpoints are caught, you will see that the session id is new each time.
Once you get to the home page, click on the "Home" or "About" tab link.
Session_Start will be fired again, this time with a new SessionID.
Continue execution, and any subsequent actions will no longer fire Session_Start.
I tried the same thing on a standard ASP.NET Web Application (not MVC), and Session_Start only fired once.
I'm pretty sure I'm not doing something wrong here, as I am using the default project templates, and the only code that is being modified is the Global.asax.cs file, to add the Session_Start method.
I am using IIS Express, but I've repeated the above steps using the "Cassini" web server (Visual Studio Development Server), with the same result.
Any advice?
UPDATE
I decided to use Fiddler to inspect the HTTP traffic during my debug session. It seems that:
The first Session_Start is fired when I am requesting the "/" URL. This seems reasonable. The SessionID generated at that time is then written in the response to the browser. Again, seems reasonable.
Fiddler then shows requests/responses for the *.js and *.css files. All successes. None of those fire off Session_Start. Good so far.
Then Fiddler shows that a request has been made for "/favicon.ico". At this time, Session_Start fires, and generates a new SessionID... I continue.
On Fiddler, it shows that the "/favicon.ico" file was not found (404). The webpage is displayed. I click on the "Home" link.
The URL "/" is requested and response is OK in Fiddler. But then, another "/favicon.ico" file is requested, and again Session_Start fires with a new SessionID... I continue.
All subsequent requests have responses, and the browser stops asking for "/favicon.ico".
I made note of each of the three SessionID's generated, and it seems the one that the browser holds on to is the first one. So when we get to step 6 above, and everything seems to work, it's actually using the very first SessionID that was generated.
So... I decided to host a "favicon.ico" file. I placed the ico file in the root of the project, and started my debug session again. This time, Session_Start only fires once. "/favicon.ico" was served successfully (200).
So... I guess it is working the way it should in a sense... But why do calls to "/favicon.ico" fire off the Session_Start event???? Shouldn't I have the choice to NOT host a favicon?
ASIDE: I tried all the above in an ASP.NET (not mvc) project, and it did not have the same problem, even though there was no favicon.ico file hosted by a default "ASP.NET Web Application" project.
I kinda had this problem for a while, and finally I realised that it was because there was some http/https shenanigans going on... looks like it destroys and recreates your session if you flip the ssl around like that and you have
<sessionState mode="InProc" sqlCommandTimeout="3600" timeout="120" cookieless="false" />
<httpCookies httpOnlyCookies="true" requireSSL="true" />
Possibly a trap for new players or people who are really tired and not paying attention! :)
Just FYI in case this helps anyone...
I think I've come to a point where I have a couple of solutions (albeit both seem 'hacky' to me), so I think I'll accept these and move on.
Got a comment from #Tz_ above that mentioned I should ignore the route for the favicon file. That's essentially what I'll be doing. (kudos #Tz_!)
Came across the following post, (among others). It describes a problem that when the browser requests a "/favicon.ico" file from an ASP.NET MVC site, the MVC stack is mistakingly trying to look for and instantiate a controller. I'm wasn't sure if that was true or not for my situation, but the answer suggested adding the following route entry:
routes.IgnoreRoute("favicon.ico");
I gave it a shot (added the above), and that fixed it!
So, I still don't know why "/favicon.ico" request has a mistaken identity in MVC, but I know how to fix it in my situation. Either:
Host a favicon,
or add an ignore route entry.
Again, both seem like hacks to me, as I think this is something controller factories should be capable of handling gracefully. IMHO
Reason you are getting Session_Start firing each time is because you have <httpCookies requireSSL="true" /> in <system.web> in your Web.Config remove this and you are good to go.
I can't reproduce this problem. I've tested on ASP.NET MVC 3/Tool Update, Win08/R2/SP1 and Win7/SP1 using IIS 7.5, Cassini and IIS Express. I see the 404 favicon request in Fiddler, but the break point is not hit for favicon. I tested with IE9, the current FF and Chrome. Each time I hit the site with a new browser, Session_Start() is called and I see the new session ID. I work for Microsoft so I'd like to know how to reproduce this problem.
This happened to me when I had some <img> in my pages with a wrong "src" attribute. Putting a valid path in "src" solved my problem.

ASP.NET - Disappearing session variables

I am working a current web application for a client and I am having some trouble with session variables disappearing on me. I will try and set up a good description of the scenario as best I can. It does not happen on any page other than the page I created to allow users to modify the strings stored in a resource file.
It shows up WHEN:
Users navigate to the page, select a resource file from a list and click edit a first time. The page loads the file into a gridview and allows them to edit it. At this point the session variables are being saved a reloaded correctly upon all postbacks. NOW, they click the save button at the bottom to write the resource file to the filesystem (App_LocalResources). They select a new file from the list, attempt to load it and this time the session variables are cleared out and it redirects them to the login page because it does not know there user information.
Additinal details:
It only happens when they click a save button which in turn calls my procedure to write to the resource file.
I am not really doing much in the save function besides writing to a resource file located in App_LocalResources and for some reason this clears out my session variables.
The session variable in question is there user information, which I attempt to get as the very first thing in a page_load method.
This session information is also executed upon every postback via the page_load method.
Thanks everyone, I hope I described this well enough.
The IIS will reset the application when you change files in the directory associated with the application. Resetting the application will make you lose memory-sessions.
You could put the resource file outside the directory. Or use a stateserver for sessions.

Editing Web.config programmatically

What is a good way to edit a Web.config file programmatically?
I looked into System.Xml but couldn't find any obvious answers.
This fellow shows sample code if you still want to do it after all the caveats:
protected void EditConfigButton(object sender, EventArgs e)
{
Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
//Edit
if (objAppsettings != null)
{
objAppsettings.Settings["test"].Value = "newvalueFromCode";
objConfig.Save();
}
}
One valid reason for editing a web.config is to encrypt it, which is what that article is about.
You can use the WebConfigurationManager to read specific configuration sections. This will return a ConfigurationSection object. You can use this to read/modify the ConfigurationElements in the section. Once you have updated them, you can Save the ConfigurationSection and it will update the file with your changes.
I use this to automatically encrypt the appSettings and connectionStrings on Application_Start if they aren't already encrypted. I haven't actually changed any settings this way, but it seems like you ought to be able to do so.
Saving the updated configuration file may cause the app to recycle depending on how it is built.
Depending on what you are doing, the method is really a bit different in each situation. However the most robust method is to load it as an XmlDocument and modify it as needed via that method, but you MUST be careful to only modify it in the needed manner.
In theory; you could just generate a web config file programmatically and with some templating to make it easy.
However, if you're trying to edit your web.config from within the site; it's highly recommended you don't. At the very least; you'd trigger an app reset every time you updated it; which would be especially bad if you're using in-process sessions.
As Anders asked, what is it you're trying to do?
Yes I agree with Josh. I have tried this before and I've had two negative effects:
Slow loading if the current page after postback because ASP.NET is loading the web.config and all related resources
If you change the web.config early enough in the load cycle (e.g. global.asax events) the site may never load or fail in unpredictable ways
Agree with others, editing the webconfig is achievable, but has knock on effects are just to dangerous / risk involved
If its a value that is application specific, then it should be in an application specific config file
Lot of time you want to modify application specific settings after deployment like say when something is wrong e.g. switching the database connection in case current DB goes down. Moreover sometimes you want to create your own XML based configuration file which you want o modify programatically.
Try XML Webpad - http://xmlwebpad.codeplex.com/
Its a framework to view an edit XML files. Once you integrate it with your web app, editing web.config ill be as simple as viewing the web.config page, making the required changes and hitting the save button (all from within your application).

Resources