ASP.NET Ajax - Asynch request has separate session? - asp.net

We are writing a search application that saves the search criteria to session state and executes the search inside of an asp.net updatepanel. Sometimes when we execute multiple searches successively the 2nd or 3rd search will sometimes return results from the first set of search criteria.
Example: our first search we do a look up on "John Smith" -> John Smith results are displayed. The second search we do a look up on "Bob Jones" -> John Smith results are displayed.
We save all of the search criteria in session state as I said, and read it from session state inside of the ajax request to format the DB query. When we put break points in VS everything behaves as normal, but without them we get the original search criteria and results.
My guess is because they are saved in session, that the ajax request somehow gets its own session and saves the criteria to that, and then retrieves the criteria from that session every time, but the non-async stuff is able to see when the criteria is modified and saves the changes to state accordingly, but because they are from two different sessions there is a disparity in what is saved and read.
EDIT:::
To elaborate more, there was a suggestion of appending the search criteria to the query string which normally is good practice and I agree thats how it should be but following our requirements I don't see it as being viable. They want it so the user fills out the input controls hits search and there is no page reload, the only thing they see is a progress indicator on the page, and they still have the ability to navigate and use other features on the current page. If I were to add criteria to the query string I would have to do another request causing the whole page to load, which depending on the search criteria can take a really long time. This is why we are using an ajax call to perform the search and why we aren't causing another full page request..... I hope this clarifies the situation.

Just another thought, I've always run into problems with updatepanel and prefer to write my atlas ajax requests through the library directly, using PageMethods. You have more control over what you send and receive. UpdatePanel sends the entire page, and receives the entire page control heirarchy, then it parses out what is 'fresh' and displays that.
Edit: What is the code you're using to save the criteria to the session? And do you have code in the method that actually checks to see if the session has some saved criteria, and passes that back instead? Maybe that's why the 2nd/3rd updatepanel postbacks are returning the first set of criteria instead of the expected results? As an aside, I know from doing some heavy atlas ajax things that there is definitely not two sessions (one for normal postback, one for async) Is there any chance you're using a webfarm?
Edit #2: I wouldn't have been able to write what I've written above (first para) if I hadn't been a fan of someone who replied as well: https://stackoverflow.com/users/60/dave-ward

There are not multiple sessions between normal ASP.NET page loads, postbacks, and ASP.NET AJAX partial postbacks. I can tell you that with certainty.
Rather than storing the search string in the session, how about just using the search TextBox's contents directly? I can't think of any reason why you'd need to shuffle it around, since it will be available throughout the entire page lifecycle anyway.
Finally, concerning your requirements... Using an UpdatePanel does not fulfill the requirement that your users should be able to use other functionality on the page if that functionality also raises partial postbacks. Only one partial postback can be in progress at a time. If another event is raised while your search is in progress, the search request will be canceled without any notification.
Using a page method or web service for the search would be a much faster, easier, and more robust way of doing it. I don't usually plug my own site, but I think a couple of my posts are exactly relevant to what you're doing:
You could use a user control to render the search results through a web service (very much faster than an UpdatePanel): http://encosia.com/2008/02/05/boost-aspnet-performance-with-deferred-content-loading/
Or, you could return the search results as JSON and render that on the client side (even faster): http://encosia.com/2008/06/26/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/
Either of those methods could take your search functionality out of the partial postback paradigm, so that it runs faster, uses less bandwidth and server resource, and doesn't preclude other UpdatePanel activity from occurring concurrently.

You need to set the EnableSession property of the WebMethod attribute for the function you are calling.
[WebMethod( EnableSession=true )]
public static void DoSomething(){
/// ....
}

If you use generic handlers .ashx, just derive from IRequiresSessionState interface
public class ActionRequest : IHttpHandler, IRequiresSessionState
{
}

Related

Fetch data via ajax+webmethod or via traditional codebehind?

I'm going to display a product detail from a database. But I can't decide whether to use an $.ajax post to a WebMethod that returns a JSON string, or a traditional Page.Load with sqldatareader in codebehind.
I know how to do both, coding is not the issue. I'm wondering what would be faster and more secure?
It depends on what kind of data you are showing on the page. (more of howmuch data)
Lets say if you are showing a fixed amount of data like, summary, product detail then its better to fetch data from server side and bind in label in Page Load event.
But if you are about to display the list of item (which may vary depending on the user input) for example product list, order list, employee list. in that case it is good to fetch the rows using ajax. reason is to display the fixed number of rows on the page (lets say 10) and there should be a pagination to jump to the next/pre page. now when user click next or previous it should not post back the page and should get the rows using ajax.
Each method has its advantages and disadvantages.
AJAX advantages and disadvantages
Advantages:
Forces you to separate the concerns in the code a bit more, you will have the data gathering and the data display in different places
The code will be more testable due to this additional modularity
Disadvantages:
Slower due to the additional HTTP request
Harder to deal with the back button and with bookmarking
Search engine optimization will be harder due to data not being right in the html

Async Compute on User interaction

I have a standard web page with Ajax update panel. WorkFlow of the page is : The user can add some entity, delete some entity(on click of their respective buttons) to create some definition. And then user can save these definition, edit it and delete it.
Upon adding/deleting the entities, a complex calculation needs to take place which would be time intensive. What I want is, when the user adds or deletes some entity, a separate thread should do the computation and update the UI. The point to be kept in mind here is, when the entity are added or deleted , the corresponding server side code need to be run first, which adds/deletes the entities from a collection stored in session(that means I can not launch a ajax call on the button, because the server side code for the button needs to run first), and then the logic for computation.
What I have thought of doing is
1. Make the server call for button click
2. When response returns, use AJAX client life cycle to catch the response before page is rendered. This is the place where I would make ajax call, if request was for add/delete entity.
This how ever seems over complicated. I am sure, there must be a easy way to do this.
Found out answer to my problem. What I needed was PageAsyncTask which is in built in asp.net for these kind of jobs.
Google

gridview sorting: need to re-read every time?

I'm populating a GridView with code, setting datasource to the dataset returned by a query. So apparently sorting and paging don't just work magically like if I use a datasourceid= some sqldatasource.
I've found a number of examples of how to do this on the web, but they all appear to re-execute the query every time. Shouldn't the contents of the query be saved in the view state? Is there some way to just get the previous query results and re-sort without having to go back to the database? (Is it saving all the data in the view state? If so, why can't I get to it? It seems pretty dumb to send it all to the user's browser and send it all back, wasting all the bandwidth, if there's no way to get to it.)
Also, if I try to allow paging, it appears I again have to re-execute the query every time the user goes to another page. And if the user sorts and then pages, then I have to remember what the sort order was in a hidden field or some such, so I can re-read the data, re-sort, and then go to the right page.
Given that when you use a data source control all this behavior is built in, I think I'm missing something here. But given all the examples out there that do it this slow, hard way, if I'm missing something, a lot of other programmers are missing it, too.
If you're using an ASP.NET GridView control every time you sort a column or page through the data set then you're making a server postback. Sorting and paging with this particular control has never worked 'magically' and has long been a bugbear of mine.
You can speed things up by storing the data source that you're building the grid from in memory, either as a session or through the ViewState. Both have pros and cons and I suggest you read up.
If at all possible I suggest forgetting the ASP.NET GridView and looking at a client side solution such as the jQuery jqGrid. It uses AJAX calls to sort and page and is much, much faster and less of a headache. The only drawback is the learning curve but believe me it's worth it in the long run.
Yes the gridview re-execute the query every time.
If the query takes too long, you can manually store data in the session, or ViewState. And in the Algorithm that populates the grid just read them directly for it, instead of running the query.
you can, in the page load event, run the query one time when there is no postback (you can check for postback with
if (!Page.IsPostBack){
//Run the query and save it to the session
}
and the the method that populate the grid, should read from the session directly. no need to run the query again

session object design pattern

I'm looking to build an ajax page; it's a reporting page. By default, load today's report. On the page there's a calendar control and when the user clicks on a date, reload the gridview with the corresponding data. Is it considered good practice to do the following:
1) on the first page load, query the data for the page
2) put the query result in the session object and display it in a gridview
3) if the user requests new data, get new data from the query with different parameters
4) put the result of the second query in the session object and display it
5) if the user then requests the data from the first query, get it from the session object
6) do the sorting and paging with the data held in the session.
Note: the data of each query will contain about 300-500 rows and about 15 columns. I'd like to do all this with ajax calls. What are some suggestions and pitfalls to avoid.
Thanks.
I would use Backbone.js:
Server produces report in JSON format.
Client has a Backbone.js Model for this report, which binds to the JSON endpoint.
Client renders the Report Model as a Backbone view.
Client reloads the report from server only when appropriate.
Reports from previously viewed days will still be around in the client as Backbone Model instances, so you don't need to reload from server unless the user forces. I believe this is your main concern?
You're probably still in the realm of can-do-without-a-client-side-framework, but if you plan on doing more of these pages or getting any more complex, you can go to spaghetti pretty quickly without something like Backbone.js.
PS. I just noticed this is .NET related. I know nothing about .NET so maybe there's a built-in client-side framework that can do something similar.
EDIT (updated after reading comment):
For server-side caching, I think a either a denormalized report table in the DB or a separate dedicated cache store (e.g. memcache) is a better practice than session object.
It depends though. If there was say, 1 possible report per-user per-day, and you didn't have memcache set up, and you don't want to use the DB for whatever reason, then it could make sense to store it in their session object. However, if each day's report is the same for all users, you're now caching it N times instead of 1. It could also be hard to invalidate from an external hook and the user loses their cache when they logout.
So I would probably just have a typical get-or-set pattern to try and load report from cache first, and fallback to DB. Then invalidate/update the cached report only when the user forces, or if data used to create the report has changed. AJAX call requests the report by date or however a report is identified.
Since you are hoping to use the data in Javascript Ajax scenerios it would make the most sense to create a HTTP Handler to query and return the needed data result sets on demand.
Using the session object is not a solution because it cannot be accessed asynchronously. As a result, your page would not be able to query this data to feed back to your Javascript objects (unless you created an HTTP Handler to send it back, but that would be pointless when you could just query the data in the HTTP Handler directly).
You are forgetting about windows. A client isn't a window, a client is a browser it can contain many windows/tabs. You need to make sure you are rendering/feeding the correct window. Usually i handle this by submit hidden values.
Problem is separating resuming a session / Starting a new window.
I wouldn't bother holding more than one copy of the query in the Session. The primary reason you'd want to hold it in Session is to improve the sorting/paging speed, presumably. Users expect those to be relatively fast, but choosing new dates can be slower. Plus, what's the likelihood that they'll really reload the first query?
The other answers raise good pitfalls with storing in Session in general.

very large viewstate breaking web app

I have a web app, that consumes a web service. The main page runs a search - by passing parameters to a particular web service method, and I bind the results to a gridview.
I have implemented sorting and paging on the grid. By putting the datatable that the grid is bound to in the viewstate and then reading / sorting / filtering it as necessary - and rebinding to the grid.
As the amount of data coming back from the web service has increased dramatically, when I try to page/sort etc I receive the following errors.
The connection was reset
The connection to the server was reset while the page was loading.
I have searched around a bit, and it seems that a very large viewstate is to blame for this.
But surely the only other option is to
Limit the results
Stick the datatable in the session rather than the viewstate
Something else I am unaware of
Previously I did have the datatable in the session, as some of this data needed to persist from page to page - (not being posted however so viewstate was not an option). As the amount of data rose and the necessity to persist it was removed, I used the viewstate instead. Thinking this was a better option than the session because of the amount of data the session would have to hold and the number of users using the app.
It appears maybe not.
I thought that when the viewstate got very big, that .net split it over more than one hidden viewstate field, but it seems all I'm getting is one mammoth viewstate that I have trouble viewing in the source.
Can anyone enlighten me as to how to avoid the error I'm getting? If it is indeed to do with the amount of data in the viewstate?
It sounds like your caching the whole dataset for all pages even though you are only presenting one page of that data. I would change your pagination to only require the data for the current page the user is on.
If the query is heavy and you don't want to have to be constantly calling it over and over because there is a lot of paging back and forth (you should test typical useage pattern) then I would implement some type of caching on the web service end to cache page by page (by specific user if the data is specific to a user) and have it expire rather quick (eg a few minuites).
I think you need to limit the total amount of data your dealing with. Change your code to not pass back extra data that might never be needed is a good place to start.
EDIT: Based on your comments:
You can't change the web service
The user can manipulate the query by filtering or sorting
There is a large amount of data returned by the web service
The data is user specific
Well I think you have a perfect case for using the Session then. This can be taxing the the server with large amounts of users and data so you might want to implement some logic to clear the data from the Session and not wait for it to expire (like on certain landing pages you know the user will go when they are done, clear the session data).
You really want to get it out of the ViewState beacuse it is a huge bandwidth hog. Just look at your physical page size and that data is being passed back and forth with every action. Moving it to the Session would eliminate that bandwidth useage and allow for you to do everything you need.
You could also look at the data the web service is bringing back and store it in a custom object that you make as 'thin' as possible. If your storing a DataSet or a DataTable in your Session, those objects have some extra overhead you probably don't need so store the data as an array of some custom thin object and just bind to that. You would need to map the result from the WS to your custom object but this is a good option you cut down on memory useage.
Let me know if there is something else I am missing.
I wouldn't put the data in either the view state or the session. Instead store the bare minimum information to re-request the dataset from the web service and store that (in either view state or session, or even on the URL). Then call the web service using that data and reaction the data on each request. If necessary, look to use some form of caching (memCache) to improve performance.

Resources