Stateful session with nhibernate and asp.net - nhibernate

Let's say I have a client who is filling up a data from a website. the underlying persistence used is Nhibernate.
Now the series of events goes like this
user fills up the form .
he submits the form .
the nhibernate sessionfactory is created and via customer object its is saved to database .
the database commits the session object using a native generator for nhibernate
but a mishap happens before the response from the server reaches the client . the connection to the client goes off .
the client gets to see a page not found error or request time out error . and has a dilemma that he isnt registered yet .
so he again presses the refresh button . and the same set of data (although that is committed to database ) has been send to server for database commit.
the server sees the data and again registers the same customer with different id .
so the problem goes like . now the same customer entry has been duplicated two times cause the connection has got cut off .
Now can someone tell me how to proceed into this scenario. So that even if the customer submits he just recognizes only one entry and submits it, even if the response has got cut off and he presses the refresh button?

Thoughts:
1) You don't want to create the NHibernate SessionFactory on every request. This should be created once and then used by all future requests. It's a heavy-weight operation. Only the Sessions need to be created each request.
2) Manage the transaction in a high level method - to reduce the likelihood of something going wrong AFTER you've committed the transaction, but BEFORE the client has a response.
3) Guard against the "Refresh" method resubmitting, by having the submit function return a different page which presents the information. This page should not submit anything.
4) Guard against a resubmit server side by validating the submission against previously submitted credentials. Inform the client if they've previously registered and provide them with a means to access the saved details (Password recovery for example.)
so for example if your users are keyed by email address then in the page load event perform the following steps:

Related

Session-id w/Serilog in Blazor ServerSide?

In aspnet, I can set a "session" log pr request using
using (LogContext.PushProperty("CorrelationId", "SomeUniqeSessionId"));
and then use the Disposal pattern to pop the property off again, so I have a id to track the users session.
In Blazor Serverside, how can I get the same functionality ? I want to have the log message from the same user session correlated, in order to track "ok, what did the user do to get to here and cause this error?"
A F5 refresh on the browser should then give a new session ID (afaicu), since its re-loading the entire page. Off course I can subclass the logger, or store it in a custom session object, but would like to use the "normal" Serilog constructs, where the logger is injected ect ect.

Capture start of long running POST VB.net MVC4

I have a subroutine in my Controller
<HttpPost>
Sub Index(Id, varLotsOfData)
'Point B.
'By the time it gets here - all the data has been accepted by server.
What I would like to do it capture the Id of the inbound POST and mark, for example, a database record to say "Id xx is receiving data"
The POST receive can take a long time as there is lots of data.
When execution gets to point B I can mark the record "All data received".
Where can I place this type of "pre-POST completed" code?
I should add - we are receiving the POST data from clients that we do not control - that is, it is most likely a client's server sending the data - not a webbrowser client that we have served up from our webserver.
UPDATE: This is looking more complex than I had imagined.
I'm thinking that a possible solution would be to inspect the worker processes in IIS programatically. Via the IIS Manager you can do this for example - How to use IIS Manager to get Worker Processes (w3wp.exe) details information ?
From your description, you want to display on the client page that the method is executing and you can show also a loading gif, and when the execution completed, you will show a message to the user that the execution is completed.
The answer is simply: use SignalR
here you can find some references
Getting started with signalR 1.x and Mvc4
Creating your first SignalR hub MVC project
Hope this will help you
If I understand your goal correctly, it sounds like HttpRequest.GetBufferlessInputStream might be worth a look. It allows you to begin acting on incoming post data immediately and in "pieces" rather than waiting until the entire post has been received.
An excerpt from Microsoft's documentation:
...provides an alternative to using the InputStream propertywhich waits until the whole request has been received. In contrast, the GetBufferlessInputStream method returns the Stream object immediately. You can use the method to begin processing the entity body before the complete contents of the body have been received and asynchronously read the request entity in chunks. This method can be useful if the request is uploading a large file and you want to begin accessing the file contents before the upload is finished.
So you could grab the beginning of the post, and provided your client-facing page sends the ID towards the beginning of its transmission, you may be able to pull that out. Of course, this would be reading raw byte data which would need to be decoded so you could grab the inbound post's ID. There's also a buffered one that will allow the stream to be read in pieces but will also build a complete request object for processing once it has been completely received.
Create a custom action filter,
Action Filters for executing filtering logic either before or after an action method is called. Action Filters are custom attributes that provide declarative means to add pre-action and post-action behavior to the controller's action methods.
Specifically you'll want to look at the
OnActionExecuted – This method is called after a controller action is executed.
Here are a couple of links:
http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2016/03/04/how-to-create-a-custom-action-filter-in-asp-net-mvc.aspx
http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-vb
Here is a lab, but I think it's C#
http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-custom-action-filters

Conditionally returning a custom response object to the client in Wep Api 2

I have a Web Api 2 service that will be deployed across 4 production servers. When a request doesn't pass validation a custom response object is generated and returned to the client.
A rudimentary example
if (!ModelState.IsValid)
{
var responseObject = responseGenerator.GetResponseForInvalidModelState(ModelState);
return Ok(responseObject);
}
Currently the responseGenerator is aware of what environment it is in and generates the response accordingly. For example, in development it'll return a lot detail but in production it'll only return a simple failure status.
How can I implement a "switch" that turns details on without requiring a round trip to the database each time?
Due to the nature of our environment using a config file isn't realistic. I've considered using a flag in the database and then caching it at the application layer but environmental constraints make refreshing the cache on all 4 servers very painful.
I ended up going with the parameter suggestion and then implementing a token system on the back end. If a Debug token is present in the request the service validates it against the database. If it's a valid and active token it returns the additional detail.
This allows us to control things from our end while keeping things simple for the vendors and only adds that extra round trip to the database during debugging.

ASPNET out-of-proc session is mysteriously reset

I'm facing a very peculiar issue with sessions being reset without any apparent reason. This happens randomly, once every few tens or hundreds of requests.
My web application is running on windows 2003, IIS 6.0, .NET 1.1. The application has a webpage which populates a bunch of Session variables during its Page_Load event. The data is stored out of process in ASPNET State Service.
After the Page_load event exits and the page is displayed, the user clicks on a button, which retrieves the session data and does some work with it.
And this Button_click is where the issue occurs. On some occasions, the session variable is null, raising a nullRefException.
Our traces show that the sessionID during the Button_click event is a brand new session, with a different ID than the session of the Page_Load event. Thus, the application fails to retrieve the data that was stored during Page_Load. Our event log shows that the session variables for the problematic requests are indeed populated during the Page_load event, and the response is sent without issue, which normally would persist the data.
We have ruled out session timeouts; although a timeout would still result in the same nullRefException, the same session ID from Page_load would be used to retrieve non-existing data. In this case, the sessionID is different than the original.
We are not messing with the ASPNET cookie in any way, we do not use session.abandon, nor do we inadvertedly remove items from the session.
My question is: what server-side factors could cause the cardholder's session to be reset like that? The Application event log does not contain any useful info.
Also, is there anything client-side (e.g. cookie tampering) that could force IIS to assign a new session upon subsequent postbacks of the page?
Many thanks in advance.
I'm not sure if this applies to your situation, but it might help others.
I was designing a website and I found out the hard way, meaning I had to redesign a portion of this site I was working on. When you create or delete a folder (from an asp.net page) within the active IIS folder it resets all sessions for the website. This means every user currently on the site gets their sessions instantly deleted.
If you have control of your the server, store files outside the IIS folder and stream them in as needed. If you don't have control of the server, you will have to remove any work with folders.

Securely storing variables without session in zope

I want to store values in variables to access form another page (a.k.a State management).
Now I cannot use sessions since I have multiple Zope instances & if one fails the user need to be redirected to another Zope instance and one session is valid only for one Zope instance.
Now my remaining options are
submit a Hidden input tag using POST method
Passing through URL with GET method
Using cookies
Using Database (which I think is 'making simple things complex'.)
I am not even considering the first 2 methods and I think using cookies is not secure.
So is there a commercial or open source module that can securely (encryption etc.) do cookie management.
If not I will have to use a database.
Please inform me, if I am missing something.
Version - Zope 2.11.1
The SESSION support built-in to Zope 2 actually keeps the session in a temporary partition of the ZODB so I think it actually is valid for multiple Zope clients connecting to the same ZEO server. The cost of this is that all session changes invoke the transaction machinery and result in a commit, so just make sure you're not using the SESSION in something very low-level like PAS auth or you'll have commits hitting your ZODB for every image, CSS file, and JS file.