Using EndRequest Event to close NHibernate Session with IIS 7 - asp.net

I am using NHibernate on a new ASP.NET project, and am running into what I believe to be strange behavior. I am attempting to manage my session by using an HttpModule to catch the EndRequest event and close the session. This is working fine, however, after the EndRequest event fires, I am getting an exception in the OnLoad event of one of my custom controls that is attempting to read a Property from my object that is lazy loaded. I get an exception stating 'failed to lazily initialize a collection, no session or session was closed'. Turning lazy load off for these properties does fix the problem, and is an acceptable solution. But this seems to be going against what I always thought to be true.
I would assume that the OnLoad event and all server side processing would be done at the point that EndRequest is fired. This is also the first time that I have used IIS 7 on a project. Is this a reason for the behavior? What is the expected behavior?

I just had a 'palm slaps forehead' moment. Despite the fact that I am in fact deploying to an IIS 7 server, I have been debugging using the VS 2008 Built in Web server (Casini). Casini passes all requests through the ASP.NET pipeline, IIS does not. This was causing a request for an image file or javascript file (or any other static resource) to close my NHibernate session before I was actually thinking it should close.
Thanks for the list of resources, I will certainly look into them.

If your object is lazy-init and no session is open, resolving the properties will fail.
Remember that lazy exceptions will most probably appear when you have some relationship with another entity that hasn't been initialized.
http://forum.springframework.org/showthread.php?t=13474
I would also recommend using something like the HTTP Module in Rhino Commons to manage your NHibernate Sessions.

You should use a shrinkwrapped package for dealing with this.
I like to use Autofac with ASP.NET/MVC integration. You simply ask the RequestContainer for an ISession whenever you need it and, because the ISession is IDisposable, the RequestContainer automatically knows to dispose of the ISession when the current request ends. Everything is taken care of for you.

use HttpModule if you need lazy loading. Inherit your class from it and then you'd have two methods you can override (can't remember their names). First one is called each time any page is requested. Open the session there and put the session in viewstate. The other method is called when page is posted back, close your session there.

Related

Webmethod authentication not passed

I'm new to this AJAX approach when you're not supposed to use UpdatePanel but rather go with WebMethods and WebServices. My main problem is authentication.
When page is entered or postback request is created, everything works fine. Authentication is passed correctly and I can access Thread.CurrentPrincipal.Identity and get my user identity object from there.
However this changes when I try to call WebMethod on my page. Call is passed correctly to server and everything seems to work just fine until i try to get user identity from thread. Then I get just Anonymous user instead of real one. Enabling session on webmethod didn't seem to help much.
Any ideas what might cause this problem and how to solve it? Someone mentioned that authentication cookie needs to be passed along with the request, but how am I supposed to do it?
Any help will be appreciated.
Edit:
Some clarification and code:
My application is written in standard asp.net. After some deeper research in legacy code I've found out, that all authentications are done in some base class from wchich all other pages inherit. Each time page is loaded, user principal are obtained from HttpContext.Current.Session("..."). I think this is far from good solution, but I'll need to stick with it right now. Problem was, WebMethod is not firing whole page lifecycle since it's static. I've fixed it right now by calling method that obtains user data from session.
I would like to get some ideas how this could be created correctly and what problems might be result of session based authentication.
PageMethods.SomeMethod(parameter, SuccessDelegate, FailureDelegate);
This is how I'm calling WebMethods right now. I assume it's passing all required cookies, am I right?
It depends on how you're calling the method and in what manner?
Jquery for instance with its Post method should push all cookies (including your FormsAuth / Session cookie) up with the request that should still authenticate as appropriate. Bare metal techniques might be making lightweight calls that simply do not push the cookie up...One way to monitor this is by using Fiddler to observe the request and a browser based development plugin like Firebug and see what is occuring and amend your JS code as appropriate.
Personally, if you are starting a brand new project and there is no pressing need to expose your services beyond your web application then I would suggest looking at ASP.NET MVC where you can make Jquery / client-side up to the controller and get your authentication wrapped up for free. I've recently created something simliar using WCF JSON endpoints and some inevitable pain, I then saw MVC and kinda kicked myself...
As noted in comment above, the issue lies in legacy code that handles users. It is needed to make call to special function that assigns appropriate user data to handling thread. Not a best solution, but that's how it sometimes is with legacy code. What you gonna do?

Attaching an event listener to all URLRequest's

We have a flex application that connects to a proxy server which handles authentication. If the authentication has timeout out the proxy server returns a json formatted error string. What I would like to do is inspect every URLRequest response and check if there's an error message and display it in the flex client then redirect back to login screen.
So I'm wondering if its possible to create an event listener to all URLRequests in a global fashion. Without having to search through the project and add some method to each URLRequest. Any ideas if this is possible?
Unless you're only using one service, there is no way to set a global URLRequest handler. If I were you, I'd think more about architecting your application properly by using a delegate and always checking the result through a particular service which is used throughout the app.
J_A_X has some good suggestions, but I'd take it a bit farther. Let me make some assumptions based on the limited information you've provided.
The services are scattered all over your application means that they're actually embedded in multiple Views.
If your services can all be handled by the same handler, you notionally have one service, copied many times.
Despite what you see in the Adobe examples showing their new Service generation code, it's incredibly bad practice to call services directly from Views, in part because of the very problem you are seeing--you can wind up with lots of copies of the same service code littered all over your application.
Depending on how tightly interwoven your application is (believe me, I've inherited some pretty nasty stuff, so I know this might be easier said than done), you may find that the easiest thing is to remove all of those various services and replace them by having all your Views dispatch a bubbling event that gets caught at the top level. At the top level, you respond to that event by calling one instance of your service, which is again handled in one place.
You may or may not choose to wrap that single service in a delegate, but once you have your application archtected in a way where the service is decoupled from your Views, you can make that choice at any time.
Would you be able to extend the class and add an event listener in the object's constructor? I don't like this approach but it could work.
You would just have to search/replace the whole project.

Does the SessionState attribute in MVC 3 work properly?

I'm managing a rather large project, written in asp.net webforms + mvc3, with a large user base, and a pretty high daily visitor count. Basically, there are a lot of requests at any given moment.
One of my controllers in MVC that handles / resizes images on the fly has the following attribute applied to it:
[SessionState(SessionStateBehavior.Disabled)]
Now, if an action in the controller tries to access the session - it obviously throws an exception - so we're good so far.
The problem is: if I go to the IIS Worker Processes window (Win Server 2008 R2, IIS 7.5), and check the current requests for this site, I can sometimes see the requests to an action in this controller. Their current state is locked in State: RequestAcquireState, Module Name: Session. Sometimes these locks go over a second or two in this state.
Wasn't the whole point of the attribute in the first place to make the requests to the controller ignore the state, and not waste time (and possibly being locked) trying to acquire the state?
If this is so - am I doing something wrong here, or does the problem lie elsewhere?
[migrated from comments]
If you're using a custom controller factory or route handler, make sure that they're aware of the controller's session state behavior. Marking a controller as not requiring session state requires cooperation from both of these components. Out-of-box, the DefaultControllerFactory and MvcRouteHandler are designed to work with this. See DefaultControllerFactory.GetControllerSessionBehavior and MvcRouteHandler.GetHttpHandler for more information. If you're writing custom components, you can use those methods as inspiration.

What code whould be placed in the application_start and the session_start events in global.asax?

Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?
I know when each subroutine is called.
Application_Start when the first user first accesses the web application.
Session_Start when a user opens a session with the application.
But what code belongs in each of these subroutines. What should the code in each subroutine do?
Just any examples? Well, in an MVC site the routes are registered in Application_Start. That's also a good place to initialize an IoC container such as StructureMap. Maybe initialize some singletons you have in your application if you want them to be readily available rather than late-bound when a user accesses them (like if they have a high initialization cost and you'd rather do one slow initial hit on the website yourself than bother a customer or two with it).
Session_Start is generally used less often, but could be a good place for per-user (or per-session, realistically) tracking of some kind.
Application_Start is often used to initialize application wide settings which need to be done once per application domain like registering object containers, reading some config initialization values, ... In Session_Start you could place some code which is tied to the specific user who started the session.
Be careful with exception handling in Application_Start. In IIS7 Integrated mode you won't have the response object or HTTPContext. See this thread: Request is not available in this context

detecting undisposed web service calls (ASP.NET)

I'm inheriting a legacy project, and there's a page that calls a method that makes a web service call. Load and performance testing has detected that this page sometimes takes a really long time to close, but usually it's fine, and if there is one hanging, all other requests for that page hang until the first one resolves, and then they all resolve.
I think this might have something to do with the web service being instantiated and not disposed, but I don't know how I can be more sure. I tried to add a delegate to the Dispose method but that doesn't seem to ever fire. (I'm not sure it would without Dispose being called explicitly, but that doesn't really matter.)
So what can I look for on the production server or any deployed environment to watch those requests pile up and go out (or get handled in an orderly manner, if they aren't the problem)?
You might consider using a tool like .NET Memory Profiler. You can use it to attach to your running application, and it can find and report all undisposed objects.
I think they have a free two week trial.
In your web app code, you could write to a log (event log, text file) right before you send a request, and again right after you get the response. Include some identifying information about the request. Add timestamps.
If you only want to use this while debugging, wrap it in #debug.
Or if you want to test in release mode, you could put a boolean in appSettings in web.config so you could turn the logging off and on.

Resources