Data prefetching using scheduled tasks in an ASP.NET environment - asp.net

We're developing an ASP.Net application that retrieve data from WCF services.
The user interface (develped with JQM and ASP.NET) shows a loading panel while the request is processed and data are server-side paged so our db returns only first n records per request.
In this scenario, user performs a search and until he navigates through pages, we want to prefetch results of the next n pages to store in a RAM cache object to avoid delay.
To do this we've created a scheduled process with quartz.net, triggered every 3 seconds, that checks a FIFO queue to request data for subsequent pages.
Scheduled JOB is configured to allow quartz.net to execute concurrent execution and quartz.net is set to use a maximum of 10 threads.
In your opinion, is this a good approach?
Which may be the issues?
Can the intensive use of a job (fired every 3 second) and eventually threads cause the application to be unstable?
A solution based on a FileSystemWatcher trigger would be better?

I assume that you cannot avoid the delay when the user searches for the first time. In such a case you can make an ajax request to cache data for subsequent requests.
If you are using classic asp.net then this link discusses making ajax calls in asp.net http://weblogs.asp.net/craigshoemaker/archive/2008/11/07/using-jquery-to-call-asp-net-ajax-page-methods-by-example.aspx
If you are decide to use quartz, then you need to embed it in asp.net application, which is an overhead.

Related

Background task in ASP.NET

I am writing a web application using ASP.NET (not MVC), with .NET v4 (not v4.5).
I fetch some of the data which I must display from a 3rd-party web service, one of whose methods takes a long time (several seconds) to complete. The information to be fetched/prefetched varies depending on the users' initial requests (because different users ask for details about different objects).
In a single-user desktop application, I might:
Display my UI as quickly as possible
Have a non-UI background task to fetch the information in advance
Therefore hope have an already-fetched/cached version of the data, by the time the user drills down into the UI to request it
To do something similar using ASP.NET, I guessed I can:
Use a BackgroundWorker, passing the Session instance as a parameter to the worker
On completion of the worker's task, write fetched data to the Session
If the user's request for data arrives before the task is complete, then block until it it has completed
Do you foresee problems, can you suggest improvements?
[There are other questions on StackOverflow about ASP.NET and background tasks, but these all seem to be about fetching and updating global application data, not session-specific data.]
Why not use same discipline as in a desktop application:
Load the page without the data from the service ( = Display my UI as quickly as possible)
Fetch the service data using an ajax call (= Have a non-UI background task to fetch the information in advance)
this is actually the same, although you can show an animated gif indicating you are still in progress... (Therefore hope have an already-fetched/cached version of the data, by the time the user drills down into the UI to request it)
In order to post an example code it will be helpful to know if you are using jquery? plain javascript? something else? no javascript?
Edit
I am not sure if this was your plan but Another idea is to fetch the data on server side as well, and cache the data for future requests.
In this case the stages will be:
Get a request.
is the service data cached?
2.a. yes? post page with full data.
2.b. no? post page without service data.
2.b.i. On server side fetch service data and cache it for future requests.
2.b.ii. On client side fetch service data and cache it for current session.
Edit 2:
Bare in mind that the down side of this discipline is that in case the method you fetch the data changes, you will have to remember to modify it both on server and client side.

How to do asynchronous/independent handling of webpage request?

I'm looking to generate a set of images as a result of a user submitting a form on an ASP.net web page. There's a risk that the server will be overloaded with requests so I'm looking for some way of handing off the image generation to a separate process which does the generation and emails the user when they're ready for download. Ideally the separate process would be continuously running so that it can respond to requests promptly.
Any ideas what to use here? Needs to be .net.
Cheers, Ian.
I would create a Java Servlet and some class with a quartz scheduler that will handle the background jobs.
If a user submits the form you can create the background jobs, quartz will then handle the queuing and processing of those jobs.
You could then have the JavaScript client ask from time to time (every 10 seconds or so) if the jobs are finished and if so, return the urls to the pictures.

ASP.NET: How parallel requests are processed

Let's imaging there are 2 pages on the web site: quick and slow. Requests to slow page are executed for a 1 minute, request to quick 5 seconds.
Whole my development career I thought that if 1st started request is slow: he will do a (synchronous) call to DB... wait answer... If during this time request to quick page will be done, this request will be processed while system is waiting for response from DB.
But today I've found:
http://msdn.microsoft.com/en-us/library/system.web.httpapplication.aspx
One instance of the HttpApplication class is used to process many requests in its lifetime. However, it can process only one request at a time. Thus, member variables can be used to store per-request data.
Does it mean that my original thoughts are wrong?
Could you please clarify what they mean? I am pretty sure that thing are as I expect...
The requests have to be be processed in the sequential order on the server side if the both request use the same session state with read/write access, because of asp.net session locking.
You can find more information here:
http://msdn.microsoft.com/en-us/library/ie/ms178581.aspx
Concurrent Requests and Session State
Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished. (The second session can also get access if the exclusive lock on the information is freed because the first request exceeds the lock time-out.) If the EnableSessionState value in the # Page directive is set to ReadOnly, a request for the read-only session information does not result in an exclusive lock on the session data. However, read-only requests for session data might still have to wait for a lock set by a read-write request for session data to clear.
Your original thoughts are right, and so is the documentation. The IIS worker process can spawn many threads, each with their own instance of the HttpApplication class.
ASP .NET will host multiple AppDomains for your web application under a single worker process (w3wp.exe). It may even share AppDomains for different web applications under the same worker process (if they are assigned to the same app pool).
Each AppDomain that ASP .NET creates can host multiple HttpApplication instances which serve requests and walk through the ASP .NET lifecycle. Each HttpApplication can (as you've said) respond to one request at a time.

Close if no active threads, or if any active, then wait till it's complete and close

My application overview is
alt text http://img823.imageshack.us/img823/8975/modelq.jpg
ASP.Net webservice entertains requests from various applications for digital signing and verification via a client. The webservice will then route these requests to a smart card
When the system date changes, I want the following to happen.
New request from the clients are made to wait
Current work between webservice and smart card should get completed
If there is any prior pending requests then they should get completed.
The reason why I need the above things to happen is, I need to close the existing sessions between the smartcard and webservice. This should happen only when there is no signing/verification of files. I cannot just close all the sessions as it might affect a file being processed by any one of the threads. So I need to make sure that there are no current active threads between webservice and smart card.
I wrote a piece of code which gives the total number of active threads between webservice and smartcard.
int vWorkerThreads,vWorkerThreadsMax;
int vPortThreads,vPortThreadsMax;
System::Threading::ThreadPool ^ vThreadPool;
vThreadPool->GetAvailableThreads(vWorkerThreads, vPortThreads);
vThreadPool->GetMaxThreads(vWorkerThreadsMax, vPortThreadsMax);
ActiveThreadCount = vWorkerThreadsMax - vWorkerThreads;
This means, I also need to make the client requests wait?
CLEANUP MECHANISM: Close the PKCS#11 API using C_CloseAllSessions and C_Finalize call which will free up the library so that it cleans all the session objects. This should be done once everyday.
Any ideas on how I can perform such a task?
UPDATE:
I could have been much more clearer in my query. I want to make it clear that my aim is not to shutdown the ASP.NET webservice. My aim is to reset the smartcard. As I am accessing the smartcard via ASP.NET webservice, I need a mechanism to perform this task of resetting the smart card.
I am giving the current process below
Client detects Date change, At midnight
Client calls the function WebService_Close_SmartCard
Web Service receives the request WebService_Close_SmartCard and in turn
calls PKCS11_Close_SmartCard. This
Call will be served via one of the
available threads from the Thread
Pool. PKCS11_Close_SmartCard will
close all the existing current
sessions with the smartcard.
At this point, I want to make sure that there are no threads with
function calls such as
PKCS11_DigitalSign_SmartCard/
PKCS11_DigitalVerify_SmartCard talking
to smartcard, as
PKCS11_Close_SmartCard will abruptly
end the other ongoing sessions.
PS: I am new to ASP.NET and Multithreading.
The question was updated in a big way, so bear with me...
Given that no threads are being created directly\indirectly by your web method code:
Quesiton So you are not explicitly creating any new threads or using ThreadPool threads directly\indirectly, you are simply receiving calls to your web method and executing your code synchronously?
Answer Yes, you are correct. There is a client API which calls the webservice. Then the webservice manages the threads automatically(creats/allocates etc) inresponse to the client's demands.The webservice talks to a smart card by opening multiple sessions for encryption/decryption.
It is more helpful to rephrase the original question along the lines of "requests" rather than threads, e.g.
When the system date changes I want to re-start my ASP.NET application and ensure that all requests that are currently executing are completed, and that any outstanding\queued requests are completed as well.
This is handled automatically as there is a concept of a request queue and active requests. When your ASP.NET application is restarted, all current and queued requests are completed (unless they do not complete in a timely fashion), and new requests are queued and then serviced when a new worker process comes back up. This process is followed when you recycle the Application Pool that your ASP.NET application belongs to.
You can configure your application pool to recycle at a set time in IIS Manager via the "Recycle" settings for the associated Application Pool. Presumably you want to do this at "00:00".
Update
I think I can glean from your comments that you need to run some cleanup code when all requests have been serviced and then the application is about to shut down. You should place this code in the global "Application_End" event handler.
Update 2
In answer to your updated question. Your requirements are:
When the application is restarted:
New request from the clients are made to wait
Current work between webservice and smart card should get completed
If there is any prior pending requests then they should get completed.
This is supported by the standard recycling pattern that I have described. You do not need to deal with request threads yourself - this is one of the pillars of the ASP.NET framework, it deals with this for you. It is request orientated and abstracts how requests are handled i.e. serviced on multiple threads. It manages putting requests onto threads and manages the lifeclyle of those requests when the application is recycled.
Update 3
OK, I think we have the final piece of the scenario here. You are trying to shut down ASP.NET from your client by issuing a "CLOSED" web service call. Basically
you want to implement your own ASP.NET shut down behaviour by making sure that all current and queued request are dealt with before you then execute your clean-up code.
You are trying to re-invent the wheel.
ASP.NET already has this behaviour and it is supported by:
a. Application Recycling It will service outstanding requests cleanly and start-up a new process to serve new requests. It will even queue any new requests that are received whilst this process is going on.
b. Application_End A global application event handler where you can put your clean-up code. It will execute after recycling has cleanly dealt with your outstanding requests.
You do not need your "CLOSED" command.
You should consider letting IIS recycle your application as it has support for recycling at a specified daily time(s). If you cannot configure IIS due to deployment reasons then you can you use web.config "touching" to force a recycle out-of-bounds of IIS:
a. Have a timer running in the server which can check for the date change condtion and then touch the web.config file.
b. Still have the client call a "CLOSED" web method, but have the "CLOSED" method just touch the web.config file.
IIS, then "a" are the most desirable.
Honestly Microsoft have already thought about it. :)
Update 4
#Raj OK, let me try and rephrase this again.
Your conditions are:
You have a requirement to reset your smartcard once a day.
Before resetting your smartcard, all current and queued web service requests must be completed i.e. the outstanding requests.
After outstanding requests are completed, you reset your smartcard.
Any new requests that come in whilst this process is happening should be queued and then serviced after the smartcard has been reset.
These conditions allow you to complete existing requests, queue any new requests, reset your smartcard, and then start processing new requests after the card has been reset.
What I am suggesting is:
Place your smartcard reset code in "Application_End".
Configure IIS to recycle your application at "00:00". Ensure that in advanced settings for the associated Application Pool that you configure "Disable Overlapped Recycle = True".
At "00:00" application recycling ensures that all current and queued requests will be completed.
After "00:00" application recycling ensures that all new requests will be queued whilst requests in "3" are completed and the application performs shutdown steps.
After requests in "3" are completed, "Applicaton_End" will be called automatically. This ensures that your smartcard is reset after all current requests are completed.
Application recycling ensures that your application is re-started in a new process, and that new requests queued in step "4" start to be processed. The important thing here is that your reset code has been called in "5".
Unless there is some detail missing from your question, the above appears to meet your conditions. You wish to do "x,y,z" and ASP.NET has built-in support which can be used to achieve "x,y,z" and gives you mature, guaranteed and well-documented implementations.
I am still struggling to understand why you are talking about threads. I do multi-threaded development, but talking about threads instead of requests when thinking about ASP.NET adds unnecessary complexity to this discussion. Unless your question is still unclear.
Perhaps you are missing the point I'm making here. I am drawing a parallel between the behaviour you require when you call "CLOSED" from your client application, and what happens when you recycle an application. You can use recycling and "Application_End" to achieve the required results.
I am trying to help you out here, as trying to implement this behaviour yourself is unnecessary and non-trivial.

A Way to Run a Long Process From ASP.NET page

What are your most successful ways of running a long process, like 2 hours, in asp.net and return information to the client on the progress.
I've heard creating a windows service, httphandler and remoting can be successful.
Just a suggestion...
If you have logic that you are tyring to utilize already in asp.net... You could make an external app (windows service, console app, etc.) that calls a web service on your asp.net page.
For example, I had a similiar problem where the code I needed was asp.net and I needed to update about 3000 clients using this code. It started timing out, so I exposed the code through a web service. Then, instead of trying to run the whole 3000 clients at through asp.net all at once, I used a console app that is run by a nightly sql server job that ran the web service once for each client. This way all the time consuming processing was handled by the console app that doesn't have the time out issue, but the code we had already wrote in asp.net did not have to be recreated. In the end slighty modifying the design of my existing architecture allowed me easily get around this problem.
It really depends on the environment and constraints you have to deal with...Hope this helps.
There are two ways that I have handled this. First, you can simply run the process and let the client time out. This has two drawbacks: the UI isn't in synch and you are tying up an IIS thread for non-html purposes (I did this for a process that used to return quickly enough but that grew beyond time-out limits).
The better way to handle this is to write a "Service" application that handles the request as passed through a database table (put the details of the request there). Then you can create a window that gives the user a "window" into ongoing progress on the task (e.g. how many records have been processed or emails sent). This status window can either have a link to permit the user to refresh or you can automate the refresh using Ajax callbacks on a timer.
This isn't directly applicable but I wrote code that will let you run processes similar to "scheduled tasks" inside of ASP.NET without needing to use windows services or any type of cron jobs.
Scheduled Tasks in ASP.NET!
I very much prefer WCF service to scheduled tasks. You might (off the top of my head) pass an addr to the WCF service as a sort of 'callback' that the service can call with progress reports as it works.
I'd shy away from scheduled tasks... too course grained.

Resources