Re-use receive activity - c#

I'm a total noob at workflow!
I want to host several workflows (not as a service, bog standard workflows); however i also want them to share a common activity (ActivityX). Now ActivityX should block / idle the current workflow, until it gets a receive call.
Can I re-use this activity? I'm guessing I need to make it a service, asmx? But then how to make it block the workflows that it's used in - if I drag it on to those workflows that tries to invoke the service, rather than just wait until that call happens.
Can anybody make some suggestions? It doesn't necessarily have to be a receive activity, but I need a convenient way of idling the workflow until a particular object (or if needs be, a set of parameters) arrives.
I'm quite stuck and clearly missing something in my very poor understanding of WF 4.0.
Thanks,
Pete.

If you use a Receive activity you have to use a WorkflowServicehost as the host and can't use a WorkflowApplication or WorkflowInvoker as it depends on the WCF infrastructure from the BaseServiceHost.
Creating blocking activities is done using a bookmark. You create a bookmark and the workflow stops until you resume that bookmark, at least with the default options. In fact the receive activity does exactly this as part of making the workflow wait for the WCF message.

Related

Can I store a System.Timers.Timer in ObjectCache for later access?

I need to implement the following requirement for my job.
When a user starts a new application, a 5-minute timer begins.
If the user makes any edits to the application before the 5 minutes is up, the timer is canceled.
If the timer runs to completion, an email is sent to our company ("an application was created but abandoned").
The web server for this project is a .NET MVC project, though other than the Home Controller, all controllers inherit from System.Web.Http.ApiController rather than System.Web.Mvc.Controller. The front end is Angular 6.
It seems easy enough to start a 5-minute timer that will execute the "email send" method after 5 minutes. I'm stuck on how to implement the ability to cancel the timer if the user edits the application before the timer has run out. The command to start the application and any subsequent edits will come as separate queries to the API, so I don't have any state maintained from call to call.
My current idea is to create the timer via System.Timers.Timer when the application is started and store the timer in an ObjectCache under a unique ID representing that particular application. Then when the edit action is called, I can check the cache to see if a timer is stored that matches the application being edited, and if so, cancel the timer. If such a call doesn't come within 5 minutes, the timer will fire and the email be sent.
Will this work? (Both being able to access the timer to cancel it, and the timer firing as expected if not canceled?) Is there a better or more .NET-appropriate way to implement this requirement? Apologies for the vague scope of this question; I've had no luck with Google or searching SO, though my unfamiliarity with working with timers might be hindering my searches.
Thank you!
The root of your problem is architectural. You should probably give more thought to how your server-side is designed and how the client-side design and the server-side designs compliment one another. For starters, persistent state, the ability to run some background tasks, and the utilization of locking functionality (such as C#'s lock keyword) when accessing that persistent state would help in producing a more extensible and flexible design. How you design those features and how your client-side interacts with is up to you. One approach would be to have the API controller write to the persistent state, using locking to prevent concurrent writing, and then using a background task to monitor that persistent state and fire certain actions when necessary. Play around with designs and figure out what works for your needs. Good luck with your application.

BackgroundWorker vs. Android Service in Xamarin

I'm investigating about mobile apps using Mono on Visual Studio.Net.
Currently we have an application we want to translate to Android from Windows CE. The original program used small BackgroundWorkers to keep the UI responsive and to keep it updated with the ProgressChanged event. However I have been reading that in Android there are Services that can replace that functionality.
Reading pros and cons about services I know that they are usually used because they have a better priority than threads and, mainly, if the functionality will be used in more than one app.
More info I have found comparing threads and Services say that Services are better used for multiple tasks (like downloading multiple files) and threads for individual tasks (like uploading a single file). I consider this info because BackgroundWorker uses threads.
Is there something I am missing? Basically a service should be for longer tasks because the O.S. gives it better priority (there are less risk it will be killed) and Threads/BackgroundWorkers are better for short tasks. Are there any more pros/cons to use one or the other?
Thank you in advance!
[Edit]
If you need a very specific question... how about telling me when and why would you use a Service instead of a BackgroundWorker? That would be useful.
Some of the functionality I have to recreate on Android:
- GPS positioning and compass information - this has to be working most of the time to get the location of the device when certain events are working and trace in a map its movements.
- A very long process that might even be active for an hour.
The last one is the one I am concerned about. It must be very reliable and responsible, keeping the user informed of what it is doing but also being able to keep working even if the user moves to other activity or functionality (doing a call, hitting the home button, etc.)
Other than that I believe the other functionality that used BackgroundWorker on WinCE will not have problems with Android.
[Edit 2: 20140225]
However I would like to know if the AsyncTask can help me in the next scenario:
- The app reads and writes information from/to another device. The commands are short in nature and the answer is fast so for individual commands there is no problem. However there is a process that can take even an hour or so and during that time it will be asking the status from the device. How would you do it?
I think you're misunderstanding what a Service in Android is. See the documentation on Services:
A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application.
Also note:
A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise).
Using a worker thread and using a Service are not mutually exclusive.
If you are looking to move work off the main thread, then clearly you need to use another thread. Through a BackgroundWorker or perhaps the TPL will do just fine in many cases but if you want to interact with UI (e.g. on completion of the task or to update progress in the UI), the Android way is to use an AsyncTask (mono docs).
If this work needs to continue outside of the user interaction with your application, then you may want to host this work (including the BackgroundWorker/Thread/AsyncTask/etc.) in a Service. If the work you want to do is only ever relevant while the user is interacting with your application directly, then a Service is not necessary.
Basically, a service is used when something needs run at the same time as the main app - for example keeping a position updated on a map. A thread is used when consuming a webservice or a long running database call.
The rule-of-thumb, as far as I can see, is rather use threads and close them, unless there is something that needs to happen in the background (like navigation updates). This will keep the footprint of the app smaller, which is a large consideration.
I hope this helps at least a little.
Now that you know you don't need a Service, I want to point out how is the Xamarin guideline doing/recommending this: create a separate thread using ThreadPool and when you want to make changes to GUI from that thread, you call the main thread to do them using the RunOnUiThread method.
I'm not sure that by using AsyncTask you can write your code inline in c#, but with Xamarin recommendation you certainly can, like so:
//do stuff in background thread
ThreadPool.QueueUserWorkItem ((object state) => {
//do some slow operation
//call main thread to update gui
RunOnUiThread(()=>{
//code to update gui here
});
//do some more slow stuff if you want then update gui again
});
http://developer.xamarin.com/guides/android/advanced_topics/writing_responsive_applications/

Detect Idle in Windows Service

I have a windows service that will be started(remotly) when it is called. I dont want to keep service running so I want the service be self-stopped when enter in idle time, means few minutes after the last call.
I dont want to stop the service from my remote client because I dont know if I finish to work with, that's why I want to use some Idle event in service side.
There is some way ?
thanks,
Add a timer in the Windows Service which is reset on each call. When the timer elapses (some number of minutes later) have it call the service's Stop method, effectively stopping the server once it becomes idle.
Additional Info
In order to reduce your coding overhead you're looking for an intercept point to handle this timer. If you're using WCF for your service calls the simplest way to do that is with a custom IParameterInspector added as a service extension. You can add the timer logic into the AfterCall() method so that every service call runs through this same block of code & resets the timer. See this MSDN article for details on implemnting custom behaviors.
If you aren't using WCF it's a little trickier. You could use an AOP framework like Castle Windsor or PostSharp, or design your service in a message passing style. AOP allows you to decorate your methods with a property that will call your reset code. Message passing involves desigining your service's contract such that there is a single generic entry point into the service which inspects the incomping message & routes it to the correct method based on it's contents. As you can imagine, one entry point = one place to add the timer reset code. But neither of these are as clean or easy to implement as the WCF-based solution IMO.

Windows service to do job every 6 hours

I've got a windows service with only two methods - one private method DoWork(), and an exposed method which calls DoWork method. I want to achieve the following:
Windows service runs DoWork() method every 6 hours
An external program can also invoke the exposed method which calls DoWork() method. If the service is already running that method called from the service, DoWork() will again be invoked after the current method ends.
What's the best approach to this problem? Thanks!
An alternative approach would be to make use of a console application which can be scheduled by Windows task scheduler to run every 6 hours. In that case you don't waste resources to keep the Windows service running the entire time but only consume resources when needed.
For your second question: when you take the console app approach you can have it called by making use of Process.Start for example.
If the purpose of your application is only to run a specific task every six hours, you might be better off creating a command line application and creating a scheduled task that Windows runs automatically. Obviously, you could then manually start this application.
If you're still convinced you need a service (and honestly, from what I've seen so far, it sounds like you don't), you should look into using a Timer, but choose your timer carefully and read this article to get a better understanding of the timers built into .NET (Hint: Pay close attention to System.Timers.Timer).
To prevent reentry if another method tries to call DoWork() while the process is in the middle of performing its operation, look into using either a Mutex or a Semaphore.
there are benefits and drawbacks either way. my inclination with those options is to choose the windows service because it makes your deployment easier. scheduling things with the windows task scheduler is scriptable and can be automated for deployment to a new machine/environment, but it's still a little more nonstandard than just deploying and installing a windows service. you also need to make sure with task scheduler it is running under an account that can make the webservice call and that you aren't going to have problems with passwords expiring and your scheduled tasks suddenly not running. with a windows service, though, you need to have some sort of checking in place to make sure it is always running and that if it restarts that you don't lose hte state that lets it know when it should run next.
another option you could consider is using nservicebus sagas. sagas are really intended for more than just scheduling tasks (they persist state for workflow type processes that last for more than the duration of a single request/message), but they have a nice way of handling periodic or time-based processes (which is a big part of long running workflows). in that a saga can request that it get back a message from a timeout manager at a time it requests. using nservicebus is a bigger architectural question and probably well beyond the scope of what you are asking here, but sagas have become how i think about periodic processes and it comes with the added benefit of being able to manage some persistent state for your process (which may or may not be a concern) and gives you a reason to think about some architectural questions that perhaps you haven't considered before.
you can create a console application for your purpose. You can schedule the application to run every 6 hours. The console will have a default method called on application start. you can call your routine from this method. Hope this helps!!

Developing a polling mechanism

In C#, what is the best way to create a polling mechanism? So I have some code which can periodically do some action.
This is for web services so any UI-related solutions won't apply.
Thanks
If you are saying that you have a web service which is supposed to periodically take some action on it's own, then I think you haven't quite got the web services model. Web services are supposed to sit there (just like a web page) until something kicks it off.
Otherwise you are dealing with a very brittle situation where anything could cause it to just stop.
If you have a bit of code that needs to run on a timer, then you should investigate placing that code in a windows service (not to be confused with Web Service). That's what they are for.
"code which can periodically do some action" is called a "Timer". Search MSDN, you'll find three or four classes for the purpose, several of which are non-gui (System.Threading.Timer comes to mind).
EDIT: To whom do the changes need to be visible? If they are only visible to other consumers of the web service, then one approach is for each incoming request can check whether a periodic action is overdue and perform it. However, you shouldn't do things this way if (1) the changes need to be visible to e.g. other clients of the same database, or (2) the periodic changes need greater permissions than arbitrary incoming requests. Also, the periodic actions might be interrupted if the client cancels their request, and doing the actions might significantly delay the response to the client. For these reasons I don't recommend adding periodic processing to normal request/response processing.
Take a look at the System.Threading.Timer class. This makes periodic calls to a method you supply. These calls are made on a separate thread (a thread in the thread pool).
You'll want to use a timer.
There are a few timers in the .NET framework, including:
System.Timers.Timer
System.Threading.Timer
System.Windows.Forms.Timer
See this article for help choosing the right one: Comparing the Timer Classes in the .NET Framework Class Library
It sounds like you want a Timer, but that does not make sense to use in a Web service. It would make more sense if the timer was in a client. What clients use your web service?

Categories

Resources