Session and Tabbed Browsing ASP.Net MVC - asp.net-mvc

I'm once again looking into the world of tabbed browsing and Sessions. Looking over a few google searches it seems that there isn't a nice way of supporting this.
Does anyone know of a method that allows Bookmarking without stealing a session (cookieless) (and this doesn't work in MVC2 for dataannotations).
Supporting tabs in such a way that it's per use case (like Windows Workflow), going through two workflows at once.
I'm thinking a url in the query string might support this, but I'm wondering if anybody else has done a similar implementation.
[Edit] Use Case: Say I'm writing an application that uses something like Windows Workflow. Each UI workflow may do an action such as collect settings of a page and execute some external process. I may wish to do two of these workflows at once (not necessarily the same UI workflow). As such if I saved in session I would get:
a) Different tabs interfering with the workflow
b) Previous/Next buttons would be extremely difficult to work out, due to a).
I would like it so either, a user cannot open another tab to a url (don't think there is a 100% method of preventing this), or allow a user to use a UI workflow in isolation without one affecting another (much like running two workflows in two different browsers).
Hopefully that gives an indication of what I'm attempting to do.
Regards,
J

It sounds like you might be trying to do the following:
For example, let's say you have a two page questionaire, the first page has first name on it and the second page has last name on it. You desire that the user can open two tabs, and be at different pages in the questionaire while entering different data in the questionaire in each tab.
So in Tab A, you have entered Mark as the first name and submitted and you are at page two now in Tab A. You decide you are going to do a questionairre for your friend also, so you open up a new Tab, Tab B. In Tab B you enter Tom and submit the page.
Currently in the browser you have Tab A, which is at page 2 of the questionaire with firstname = "Mark" and Tab B which is at page 2 of the questionaire with first name = "Tom". Assuming you wanted to maintain both of these in session on the server here is an approach that i think will work for you.
When a web browser requests page 1 of your form, on a GET request(no posted questionaire data to the server), you supply a hidden field in the the response html and generate a random number to store in that field. When this form is submitted you do the following on the server:
Look in session using the random number as a key "var questionaire = session[Request.Form["questionaire_rnumber"]]
if the questionaire is not in session you create a new questionaire and update it's properties and stick it in session
var questionaire = new Questionaire();
questionaire.FirstName = Request.Form["firstName"]
session[Request.Form["questionaire_rnumber"]] = questionaire;
if the questionaire was in the session you simply update the object, and display the next page, however when you display the next page you will want to supply the hidden random number field in the html again, using the same random number you used on page 1.
This way you can hold any number of questionaires in a single session. With MVC.NET it should be straight forward for you to add the random number field to your view model and add the logic for looking in session for an existing questionaire or creating a new one and I think you'll be good to go.
You should keep in mind the possible issues with the approach also, like back button issues, security issues, and performance issues.
One example of a security and a performance issue would be that an attacker realizes your application works like this and the attacker requests page 1 of your form 10,000 times and submit the page 1 each time. You would have 10,000 questionaire objects in that one user session. If the attacker deleted his session ID cookie 10,000 times and for each session id cookie he created 10,000 requests for page 1 and submitted the page 1 form, you would have 100,000 questionaire objects cumulatively across 10,000 sessions on your server. So you should put some constraints on it also to protect your application, for example:
Any individual session can only have X questionaires in session
Any individual IP address can only have Y concurrent sessions (this you would probably need to track in the Application object)
ADDITIONAL RESPONSE TO ADDED USE CASE
Thanks for the use case. My solution should still work for you. You have two options.
If you want to ensure there is only one tab working with your workflow, then when the random number is passed to the server from a new tab you will be able to detect that there is another workflow in progress and that the random number from the new tab does not match the random number from the first, so you will throw an exception and show the user some messaging that says they can't start a new workflow until they finish the first one, and ask if they want to cancel the first. You have to ask if they want to cancel it because if they close their browser on the first workflow they started they will be stuck until their session expires. Which won't happen if they keep trying to start a new workflow.
Secondly, you could allow them to do multiple, but segment the context of each workflow by the random number, as suggested in the first answer. The whole point is that you are making little mini-sessions in your session, but keyed of a value that is only stored in the client. So since each tab has a different random number when the form posts to the server, it's easy to correlate that random number with an entry in your session that has all the information about the workflow initiated from that tab.
Hope this helps.

You need to store wizard state information in the client in some way, via query string or form values. As you've intuited, Session will not work. Nor will anything else that relies solely on what is on the server.

Related

Temporary Persistence when Dealing with MVC and Entity Framework

Perhaps it is my lack of experience still with really stretching MVC and Entity Framework but I've run into a problem I can't really figure out.
Up until now my applications have been simple: I show and hide a few divs in a View, and when the user has entered all data they hit submit and I save it to the database using EF. The complication I have now is I have basically have to have a flow where:
Person Registers -> Register Another Person? If Yes -> Person Registers -> And So On...
EDIT* To Clarify: Person comes in to Register a group of people. The first screen is a form where they enter identification info, next is clicked, and then They are asked if they'd like to add someone else, if they click yes they repeat that process. I create a Registration Object each time this happens until they don't want to add anymore, after which they are directed to a "Confirmation" action that shows them their registrations and let's them submit their registrations.
I need to have a way to temporarily hold that data while the user jumps to different actions and ultimately submits it to be saved. I'd prefer not to hold a bunch of models in a Session variable.
Well, in your given example, you shouldn't be holding on to anything. After each person is registered, that data can be saved to the database immediately before redirecting back to the form to allow the user to register another person. At each step, you're dealing with a discrete unit, so there's no reason not to just save it immediately.
In a different scenario, perhaps something like a wizard, where you collect partial info in multiple steps, which culminate to produce one discrete unit, your only real option is to use something like TempData. TempData is still session-based, and uses the Session object under the hood, but it does have the advantage over traditional use of Session that the data is only persisted through the next request, whereas Session data is persisted for the life of the session, which can be anywhere from minutes to weeks based on configuration.

"State" management for asp.net mvc multi partial view + ajax app

I am trying to convert my asp.net mvc4 app, which had fairly heavy use of SessionState, into a stateless app. I understand that I can store this information in the DB, and intend to do so.
My question, though, is about my particular architecture. My app has a main 'page' consisting of a number of partial view panels, which each have actions in them that can affect the other panels. What i've been doing up to now is storing the entire state of the viewModel (lots of inter-related EF list collections and 'record' objects) in the session, and its been working great. Except when the session just randomly dies.
So, I need to get this data out of the session, and into the DB where I can rebuild the thing at need. My concern is that, if I store the info in the database, every single action done on screen might affect 3-5 different panels, each with their own State updates, thats a minimum of 10 round trips to the DB for every interaction!
What are some strategies I can use to make this idea more scalable?
EXTRA INFO
The view in question here is a sort of POS shopping cart system. There are panels for selecting events, selecting/adding items to the cart, editing cart items, selecting contacts, editing contacts, displaying the cart items, displaying the cart 'subtotals', and finally, a panel with a [checkout] button.
Selecting a new event will change the list of available items. Selecting an item to add to the cart will change the cart item list, subtotals, as well as the checkout panel. Same for editing a cart item.
The main concern is how to recover from a lost session, as I've found the built-in asp.net session code too unreliable. My testers have encountered issues with sessions timing out, and then my app not having any kind of recovery process. When its installed on 1500 sites, each with an average of 10 users, its going to be a plague of lost session issues, and I need to combat that before it becomes a real problem.
I agree that I'm not going stateless...wrong choice of words used in a rush. I'm just trying to move that state into a form that I can rely on past the session failure. My main idea presently is to continue using the session as the local cache for the viewModel data, but to have a fallback operation that can rebuild the viewModel from DB if the session one is lost somehow.
You shouldn't necessarily be using a database to store (what sounds like) data that only needs to be persisted in the short term.
If these changes to the other partials are only relevant in the context of the current "master view," then I would suggest using jQuery AJAX to send off the requests, parse the response JSON and update the other views. Tutorials on jQuery AJAX and ASP.NET MVC are easy to find, if you don't already have the knowledge:
http://www.codeproject.com/Articles/41828/JQuery-AJAX-with-ASP-NET-MVC
This way, you don't need to make a bunch of round trips. If the changes need to be persisted beyond the context of the current view, make ONE round trip to the database to perform the update and then simply update all of the other partials from the in-memory response from the AJAX call.
You don't need to read from secondary storage multiple times when you already have all of the information you need in-memory. Just do the reading and writing once.
I decided to go with a hybrid approach. I'm still using session, but I'm building out a DB 'recovery' option, so that if the session portion is lost, the DB will be able to provide the values needed to rebuild the session seamlessly.
Seems to be working well, so far.

Storing Product List through out session

Im using MVC ASP.NET C#, jQuery
I'm building what could be decribed as the simpliest shopping cart in the world.
Basically My Clients wants users to be able to browse the site, Click on a product they want and it be added to a "list" and then when they "Checkout" they simply fill in a form and it emails my client with the list of products they had chosen!
I was thinking of something like storing them in a cookie. So as the user browses they won't be lost, Then have a jQuery dialog appear when they choose to view/checkout their cart. and it can list all products and then they simply fill in a simple form..
Is this the best way to go about it. Its a cheap website and I would like the simplest way to do this? All i guess I would need to sort is the product Id's..
Any ideas of better ways or any opinions at all!
Using Session depends on whether you think the users will pick the products in one go. Or will they leave the page and come back in an hour? The problem being that if they come back in an hour, the Session State may have been garbage collected to free up resources on the server, or the session might have expired.
To get around this, if all the products are on one page, you could store the chosen products in a hidden field, encrypted and all, that will stay there until the user closes the app.
You just need to serialize the list of product Ids, pass that serialized string to the view and put it in a hidden field.
Another option would be to store it in the users session. A benefit of this is if the user has cookies turned off and the site caters for cookieless session state then they will still be able to select products and checkout.
The thing to look out for is how much you could potentially end up storing in session. From the sounds of it this will not be an issue but if this could potentially use up an unacceptable amount of memory then you would probably need to consider a database approach anyway rather than cookies.
I'd say to go for the Session object. You can always configure the location of Sessions at runtime
I think some may dislike this storage method (it breaks testing isolation, if i'm not mistaken), but it's there for free :)
If you're using jquery, you could store the basket as a json array inside the $('body').data() element (or actually as i do, under a div called '#storage'). this works as a fantastic local storage mechanism, tho' would only be relevant to the current page that the user was on and would be cleared on moving to subsequent 'new pages' unless of course, your design was such that the shopping page was ALWAYS the same page and only refreshed by ajax methods. this way, you could continually append/modify the json structure on the 'worksurface' page.
i use this technique for a different application of the logic, but virtually for the same reason.
here's a snippet of the kind of thing i do:
/* example of data params key*/
var keyParams = "Data-Search-type-" + $('#searchtype').val();
/* add json to body with key*/
$('#storage').data(keyParams, jsonData);
/* get same data back later */
var jsonData = $('#storage').data(keyParams);
When i 'save' the data to the server, i then clear the data() element back to null. There is of course the other option of localstorage itself which can be used well, especially in disconnected environments (such as mobile apps).
another way to skin the many skinned cat!!

How to pass context around in a ASP.NET MVC web app

Ok, I'm a newbie to ASP.NET web apps... and web apps in general. I'm just doing a bit of a play app for an internal tool at work.
given this tutorial...
http://www.asp.net/learn/mvc-videos/video-395.aspx
The example basically has a global tasklist.
So if I wanted to do the same thing, but now I want to maintain tasks for projects. So I now select a project and I get the task list for that project. How do I keep the context of what project I have selected as I interact with the tasks? Do I encode it into the link somehow? or do you keep it in some kind of session data? or some other way?
As it sounds like you are having multiple projects with a number of tasks each, it would be best practise to let the project be set in the URL. This would require a route such as "/projects/{project}/tasks". It follows the RESTful URL principle (i.e. the URL describes the content).
Using session state will not work if a user possibly have different projects open in multiple browser windows. Let's say I am logging into your system and a selecting two projects opening in two tabs. First the session is set to the project of the first opened tab, but as soon the second tab has loaded, the session will be overwritten to this project. If I then do anything in the first tab, it will be recorded for the second project.
I use:
Session state for state that should last for multiple requests, e.g. when using wizards. I'd be careful not to put too much data here though as it can lead to scalability problems.
TempData for scenarios where you only want the state to be available for the next request (e.g. when you are redirecting to another action and you want that action to have access to the state, but you don't want it to hang around after that)
Hidden form fields [input type="hidden"] for state that pertains to the form data and that I want the the controller to know about, but I don't want that data displayed. Also can be used to push state to the client so as not to overburden server resources.
ok, From what I can tell, the best option seems to be to save it into the Session data
RESTful URLs, hidden fields, and session cookies are your friends.

Preventing double HTTP POST

I have made a little app for signing up for an event. User input their data and click "sign me in".
Now sometimes people are double in the database, the exact same data that got inserted 2 times very quickly after each other. This can only mean someone clicked the button twice, which caused two posts to happen.
This is common web problem, as credit card apps and forum apps often say: "Clicking once is enough!".
I guess you could solve it by checking for the exact same data to see if the post is unique, but I wonder if there are other methods.
This ofcourse does not count for ASP.NET webforms, because POST doesn't matter as much.
While JavaScript solutions can disable the submit button after it has been clicked, this will have no effect on those people who have JavaScript disabled. You should always make things work correctly without JavaScript before adding it in, otherwise there's no point as users will still be able to bypass the checks by just disabling JavaScript.
If the page where the form appears is dynamically generated, you can add a hidden field which contains some sort of sequence number, a hash, or anything unique. Then you have some server-side validation that will check if a request with that unique value has already come in. When the user submits the form, the unique value is checked against a list of "used" values. If it exists in the list, it's a dupe request and can be discarded. If it doesn't exist, then add it to the list and process as normal. As long as you make sure the value is unique, this guarantees the same form cannot be submitted twice.
Of course, if the page the form is on is not dynamically generated, then you'll need to do it the hard way on the server-side to check that the same information has not already been submitted.
Most of the answers so far have been client-side. On the server-side, you can generate a hidden field with a GUID when you first produce the form, and then record that GUID as a submitted form when the post is received. Check it before doing any more processing.
Whenever a page is requested from the server , generate a unique requestToken , save it in server side,mark status as NOT Processed and pass it along with the current requested page. Now whenever a page submit happens , get the requestToken from the "POST"ed data and check the status and save the data or take alternate action.
Most of the banking applications use this technique to prevent double "POST"ing.So this is a time proven & reliable way of preventing double submissions.
A user-side solution is to disable the submission button via Javascript after the first click.
It has drawbacks, but I see it often used on e-commerce websites.
But, it won't never replace a real server-side validation.
Client side techniques are useful, but you may want to couple it with some server side techniques.
One way to do this is to include a unique token in the form (e.g. a GUID or similar), so that when you come to process the form you can check to see whether the token has already been used, preventing a double submission.
In your case, if you have a table with event visitors, you might include this token as a column.
A client-only solution won't be enough, as stated in many of the answers here. You need to go with a server-side fail-safe.
An often overlooked reason that disabling the submit button doesn't work is, the user can simply refresh the submit target (and click OK on the "are you sure you want to resubmit the POST data?" dialog). Or even, some browsers may implicitly reload the submitted page when you try to save the page to disk (for example, you're trying to save a hard-copy of an order confirmation).
Almost no one has js disabled.
Think about coding your e-commerce website for the 70 year old woman who double clicks every link and button.
All you want to do is add a javascript to prevent her clicking "Order Now" twice.
Yes - check this at the server side too "be defensive" - but don't code for that case. But for the sake of a better UI do it on the client side too.
Here are some scripts that I found:
//
// prevent double-click on submit
//
jQuery('input[type=submit]').click(function(){
if(jQuery.data(this, 'clicked')){
return false;
}
else{
jQuery.data(this, 'clicked', true);
return true;
}
});
and
// Find ALL <form> tags on your page
$('form').submit(function(){
// On submit disable its submit button
$('input[type=submit]', this).attr('disabled', 'disabled');
});
None of the solutions address a load-balance server.
If you have some load balancer, send a UUID (or any type of unique number) to the server to store and read again will not work well if the server is not aware of other servers, because each request could be processed by a different server in a stateless environment. These servers need to read/write to the same place.
If you have multiple servers you will need to have some shared cache (like a Redis) among the servers to read/write the unique value in the same place (what could be an over-engineering solution, but works).
Client side alteration is a common technique:
Disable submit button
Change the screen to a "please wait" screen
If the form was modal, changing the screen back to their usual process (this has the benefit of making things look really slick)
But it's not perfect. It all relies on JS being available and if that's not the case, without back-end duplication detection, you'll get duplicates still.
So my advice is to develop some sort of detection behind the scenes and then improve your form to stop people with JS being able to double-submit.
You can track the number of times the form's been submitted and compare it to the number of unique visits to the page with the form on it in the session.
Beside the many good techniques already mentioned, another simple server-side method, that has the drawback of requiring a session, is to have a session variable that is switched off on the first submit.

Resources