views:

98

answers:

1

I have an internal app used to edit XML files on disk. The XML files are loaded into an object model which is stored in ApplicationState.

I need to save this data. The one option is to do this every time the user changes some data. However, this seems a bit inefficient - writing the data out to disk each time a change is made.

Instead, is it possible to be notified whenever the user closes their browser, plus just before the web server exits? Thus, the data would be saved each time a session ends, plus when the computer shuts down, etc. I thought that Application_End(), Application_Error() and Session_End() in Global.asax would provide this, but these methods don't seem to be called.

A: 

Session_End should get called.

What version of IIS are you running on, or are you hosting in the Visual Studio development server?

Steps to get Session_End to fire:

  1. Create a new web site in VS 2008

  2. Edit web.config:

    Add <sessionState mode="InProc" cookieless="true" timeout="1"/> to <system.web>

  3. Add a Global.asax file with the code shown below.

    void Session_End(object sender, EventArgs e)

    {

    Console.WriteLine( "Session_End" );

    }

  4. Set a breakpoint on the Console.WriteLine call.

  5. Press F5 and see the page load in IE or Firefox.

  6. Wait 1 minute or so.

  7. The breakpoint should be highlighted in red in the IDE.

Liam
Note that Session_End is only called when using InProc session management, and won't be called at all if the application restarts for any reason, so isn't all that reliable.
Zhaph - Ben Duguid
If the application restarts, you might get a chance to do the save in the Application_End method.
Liam
As Zhaph pointed out:The Session_End event is raised only when the sessionstate mode is set to InProc in the Web.config file. If session mode is set to StateServer or SQLServer, the event is not raised.
Liam
If those changes are important, keep in mind that increasing the latency of writing to disk also increases the risk of losing those changes if the server suffers a hard failure (e.g. power outage, bugs making the app unresponsive, etc).
gWiz