ASP.NET MVC Repeating Task - asp.net-mvc

I need to run a task repeatedly on an ASP.NET MVC site; it needs to run every time interval (Interval doesn't matter).
I achieved this by setting a background thread from the Global.asax.cs Application_Start which runs the task, sleeps for time interval and then runs again....and again.
While this works it doesn't seem like the right way to do this, seems a bit hacky.
So then I replaced it with a Timer object, this doesn't work reliably - seems others have had problems with it as well - so I'm not going to use this.
This needs to run in the MVC site, it is used for pulling jobs from a queue and rendering them from the Views ready for emailing.
I thought about using the ThreadPool and getting the previous job to leave another job on it's way out but because these can be long running jobs I've read that this can end up not leaving enough threads to deal with web requests through starvation.
Before sticking with the original thread method I thought I'd ask if anyone else knows a better way of doing this.
I hope this makes sense. Effectively what I'm trying to achieve is a heartbeat. Something to act as the consumer part of the producer/consumer pattern in an MVC site.

Stackoverflow itself uses (or at least used to use) a cunning way of doing this. See here: https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/
In brief, you do this:
At startup, add an item to the HttpRuntime.Cache with a fixed
expiration.
When cache item expires, do your work, such as WebRequest or what have
you.
Re-add the item to the cache with a fixed expiration.

I know you've stated that:
This needs to run in the MVC site
However I think this is the wrong place for doing what you're trying to acheive.
Personally I'd set this up as a Windows Service and have the service check the database, compile the email as required, and add the email to a queueing service. The email service would then be seperate from this and would dispatch the emails at some interval.
What's stopping you at present from using another method than embedding this in your MVC site?

Related

ASP MVC 3: run cron jobs without affecting the user

For my site I need to have:
logging of the action & render time
log the visit of a certain product
from time to time agregate votes
from time to time send newsletter
from time to time post on social networks
My approach to this was to create a global filter and OnResultExecuted I do the check and the action that are needed.
I have some questions:
when OnResultExecuted is running did the user received the rendered page and basically is not waiting for anything else? Am I blocking it?
it is a good idea in OnResultExecuted to start a new thread for this
jobs?
is this approach ok in ASP MVC 4
According to MSDN this method is called after the response is written (http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onresultexecuted(v=vs.108).aspx) so you will not be blocking the response.
Apart from the first two points (logging of actions and logging of visits), the others may take considerable resources based on the size of the task.
My advice is to override OnResultExecuted for the first two tasks and use a windows service (can easily be written in C#) to do the others in the background. This way you can use less costly clr threads instead of iis worker threads.
Running the time/resource consuming tasks in the background will add scalability to your web application
Hope this helps

ASP MVC - I need to periodically check my database, how can i do that?

I got an online website written in ASP.MVC. Now, i need to periodically check one table, and if it changes, i need to take further actions related with modifying data in other tables. I could of course write a stand-alone application that would do that for me, but what other options do i have? I am asking, because maybe there is something better which i don't know about.
Assuming that you're using SQL Server, one option would be to add an item to the ASP.NET Cache, and then register a SqlCacheDependency on that item for the table or row that is to be monitored. There is a bit of configuration required to get this up and running, some instructions are here (with the code samples being in VB). When you add the item to the cache that has a SqlCacheDependency, you can specify a callback method that is fired when the data changes, which is how you would update related tables. If you are running SQL Server, want a pre-defined solution provided by Microsoft, and don't mind the setup process and additional database tables and configuration that this includes, this would be a great option.
I got an answer that is satysfying my requirements. There is something called Quartz.net that works just as i wanted it to. :)

About grails In my office tell me about CRUD must be code in service why?

Today I have present about CRUD in grails When I show source code friend tell me it incorrect cause it's not code in service almost coding by use gen controller(this active record correct??)
why me code CRUD in service ?? I dont understand plz suggest me
Doing read only operations in a controller is ok. The reason write operations should be done in a service is because services are transactional by default. If you write to more than 1 table at a time in a controller, and one of them fails, you will have corrupt / incomplete data.
If you do the same in a transactional service, all changes rollback, which is what you want. While there might "centrality not a definite answer", this is common pattern/practice that goes even beyond Grails.

How to implement Observable Design Pattern in Web Application?

I wonder If I could implement Observable design pattern in ASP.Net MVC 3.
I want that every time an information like a value existing on the server, the browser should be notified when there is a change.
Can I do this? If yes, how? Please post examples or link to such examples.
There's a few things you should take a look at before you start building your own.
First, SignalR
http://www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx
Second, read this article that was just recently posted about the Trello web stack. They talk about how they implemented client side updating.
http://blog.fogcreek.com/the-trello-tech-stack/
(The pushing and pulling section)
http://en.wikipedia.org/wiki/Long_polling#Long_polling
http://en.wikipedia.org/wiki/Web_worker
Or as simple method use javascript for pinging server time to time to ask if new data exists, and load it when it occured.

Struts2 and multiple active wizards / workflows

I'm currently working on a Struts2 application that integrates a wizard / workflow in order to produce the desired results. To make it more clear, there is a business object that is changed on three different pages (mostly with AJAX calls). At the moment I'm using a ModelDriven action (that's extended by all the actions working with the same business object) coupled with the Scope interceptor. While this works okay if the user is handling data for only one business object at a time, if the user opens the wizard for different objects in multiple tabs (and we all do this when we want to finish things faster) everything will get messy, mostly due to the fact that I have only one business object stored in the session.
I have read a few articles about using a Conversation Scope Interceptor (main article) and about using the Scope plug-in (here). However, both approaches seem to have problems:
the Conversation Scope Interceptor doesn't auto-expire the conversations, nor does it integrate properly with Struts2;
the Scope plug-in lacks proper documentation and the last build was made in 2007 (and actually includes some of the ideas written by Mark Menard when he defines his Conversation Scope Interceptor, though it doesn't use the same code).
Spring's WebFlow plug-in seems a bit too complex to be used at the moment. I'm currently looking for something that can be implemented in a few hours time, though I don't mind if you can suggest something that works as needed, even if it requires more time than I'd currently want to spend on this now.
So, seasoned Struts2 developers, what do you suggest? How should I implement this?
Okay this isn't a fully baked idea. But seeing as no else has provided anything, here is what I would start with.
1) See if you can move the whole flow into a single page. I'm a big believer in the less pages is better approach. It doesn't reduce complexity for the application at all, but the user generally finds the interface a lot more intuitive. One of the easiest ways to go about this is by using the json plugin and a lot of ajax calls to your json services.
2) If you must transition between pages (or simply think it is too much client side work to implement #1) then I'd look to the s:token tag. The very first page to kick off a flow will use this tag, which will create a unique value each invocation. You will store a map in your session of model objects. An action will need to be provided with a model by looking it up from the session.
There are a couple challenges with #2. One how do you keep the session from getting too many domain objects? a) Well it might not matter, if the session is set to say six hours you can be rather sure that over night they will get cleared up. b) provided a self management interface which can get/set/list objects in the session. It might be what you thought of at first but it would let a worker do a certain amount and then stop and work on another. If the unit of work has some meaningful name (an invoice number or whatever) it could be quite useful.
A little more sophistication would be to move the model objects out of the session and into the service layer. At which point when inserted you would set an insertion time. You would probably need a manager to hold each type of model object and each manager would have a daemon thread that would periodically scan the map of domain objects and clean out expired ones.
You can figure out more complicated system by kicking a flow off with a token and then using another token on each page. "flowId" and "currentPageId" respectively, then you can graph allowable transitions.
Mind you at this point spring web flow is starting to look pretty good.
There is now a conversation plugin for Struts2 that achieves all these goals with very little work required by the developer: http://code.google.com/p/struts2-conversation/
It has:
-nested conversations
-cleanup of dead conversations
-convention over configuration with annotations and naming conventions
-inherited conversations
-fully integrated with Struts2
-the conversation scope can also be used by Spring IoC container-managed beans
Hope it helps somebody.

Resources