I have a requirement that a Windows Forms C# .NET 2.0 program running in user-space (not a service) must always be running. As I'm not infallible and make coding mistakes, I wanted to know of any extra safeguards I could use to ensure this requirement is met. The things I've been thinking of are TaskScheduler to check it every 5 minutes, A stub watcher or a secondary process. Are these good / bad ideas?
Thanks,
Richard
EDIT: The reason I didn't use a service (the obvious and sensible answer!) was the program runs in a kiosk type environment and has has a heavy GUI component. The service option didn't work well across Windows 2000 - W7.
EDIT: The second reason not to use a service was the app needs internet access and on some of our customer sites, proxies are set up to only allow specific users (not the local system account) so it would be tricky to ensure access if multiple users log onto the machine.
Task scheduler is a cheap solution for this which does work. I use this to keep our Perforce Proxy server running (had some issues with the service), and so far there's been no problems - though now I've said that the server's probably exploded!
However, the most complete solution is a Windows service which invokes your app. You can make that service catch error return codes from the app, restart it on failure and notify you by email, which may help you diagnose and fix those issues. I think the Task Scheduler does something similar but it won't be able to provide as much insight into your application as a custom service.
If you're unsure of how to do that, then something like this should work:
http://www.codeproject.com/KB/install/csharpsvclesson1.aspx
There are three approaches that you can take:
Heartbeat Message.
A heartbeat is useful in a distributed application and is simply message that is sent (from let say a client to server) to confirm that it is still healthy/running.
Manager Process
A stub program, implemented as either a user process or a service. It launches the main application, monitors any unhandled exceptions, reports errors, and restarts on failure.
An exception guard on the entry point.
A try-catch-all in the application entry point.
I would recommend either of the first two options; the third option, the try-catch-all, is a particular nasty hack for the lazy and inexperienced programmer (IMHO).
I have successfully used both heartbeat and manager process in a large distributed application.
UPDATE
As for ready-to-go™ restart managers, take a look at the Windows API Codepack as discussed in Emmanuel Istace blog post (http://istacee.wordpress.com/2013/09/21/automatic-recovery-restart-in-net-application/).
You can install the package from https://www.nuget.org/packages/WindowsAPICodePack-Core/
Related
I have a requirement where I want to implement a WCF Service which checks a status from a Database column after a certain time interval lets say 20 minuets, if this status is true I want to execute some operation else some other operation.
So is it possible to implement the desired functionality using WCF Service, If yes please guide me how should I implement, As I have no idea how to do it.
If its is not possible, then please suggest me some good options like (Web Services, windows service etc.).
Please provide me sample code or some good links where I can find the way to approach this problem.
I want this service to run on my PC always and check status after 10-20 minuets.
I am more comfortable with C#, So If it could be done in C# its well and good.
Otherwise also not an issue.
I have windows PC
What you describe is a Windows Service. A Task running in the background, even without an active user login, that executes code periodically. Look up a tutorial on Windows Services, maybe start with the Visual Studio template for building one.
I think you miss the idea of WCF and only see word "service". WCF service is used to call some code on the server from remote machine. It is not supposed to do any work on its own. Only when called.
By your description, you should create a Windows Service, which should have a loop. It will look how much time has passed and execute your action.
There are two common options:
1) windows service
2) long running service in AppFabric
Depending on production environment, second one might be not acceptable. But it have real benefits:
1) you don't need admin access to server
2) you can use FTP/Web Deploy publishing
3) you run service in IIS with all it cons and pros
So I created a Windows Service using C# and created an installer in Visual Studio for it. It's set up to run manually as I don't want it running all the time. I then have another application (C# WPF) that should have an option to turn the service on and off (the service itself creates a web service that in turn communicates back to my WPF application). This works fine in Windows XP, but testing it on a Windows 7 machine, it won't start. Surprisingly it does throw an exception and crash, it just does nothing. I believe this is a permissions problem. If I go to the services control panel using the same Windows 7 account, I'm not able to start or stop the service either.
So my question is, is there a way to set my service so that regular user accounts can start and stop it? And is there a way to set my installer to do this automatically.
I don't want my WPF application to have run as administrator!
Whilst I believe that it is possible to secure a service so that regular users can start and stop it, I do not recommend doing so. This will create a lot of complication and is a potential cause for confusion. I always prefer to keep things simple, especially when it comes to installation and security.
So, if we can't let the user start and stop the service we probably need to let the service run all the time. Since you don't want the service to be active all the time I suggest you give the service its own internal Running flag. When this is set true, the service is active and does busy things, otherwise the service remains idle. You can use your preferred IPC mechanism (sockets, named pipes, WCF etc.) to allow the user to toggle this switch.
Windows 8 has a feature to allow services to start on demand, basically in response to some kind of trigger. But for Windows 7, your only real option is to set it to start automatically on startup. You could set it to start delayed, so that its not adding to the time it takes windows to start.
Regular users cannot start and stop services.
EDIT: Reading the link in the comment above it sounds to me as that is a blanket ability for users to start and stop services. I think the question here is about how to do this for a particular service.
Also, while it may be possible to set the service to run as that particular user, it really means it only works for that particular user and other users on the work station would not be able to use the application as they'd not be able to start or stop the service, assuming that the service running as a user implies that the user may control it, which may not be the case.
Also in reading the comments and other answer, I'm left to wonder if the service can be used by any user which can run the application. That is, if user A logs on to the work station and starts this app (and thus the service), locks it and walks away, what happens when use B logs on and tries to run the same service? Can the service support multiple users at the same time, or will funny things begin to happen if the service is utlized by the application running multiple times.
This really sounds like what is desired is for a background to be started when the application starts. This thread (or threads) would do the work of the service, and by their nature would end when the application ends. Of course more detail in the question would help give a better answer.
Of course if it is appropriate as a service, I see no reason not to have a service with a worker thread that sleeps, and another timer thread that acts as a producer that checks if there's work to do.
I have built one windows service that sends out email after every 30 minutes in C#. The Service start mode is set to Automatic. But still windows doesn't start automatic. I need to manually start by going to Services.msc and right clicking the service and select start
When the StartMode is set to automatic, that just means that it will start up when Windows boots up.
You can start the service yourself in a custom action in your installer. I assume you have an Installer class already and that it is already a custom action for your setup project since the service is installing, but not starting.
Override the OnAfterInstall method in the Installer class you have and you can start the service like this:
protected override void OnAfterInstall(IDictionary savedState) {
base.OnAfterInstall(savedState);
ServiceController sc = new ServiceController(“MyServiceName”);
sc.Start();
}
However, a scheduled task is not a bad way to go.
Why put yourself through all the overhead and suffering of troubleshooting and maintaining a windows service for a time based/polling application? The windows OS has built in support for this. Just create a simple console application. Run it as a scheduled task.
You should already have unit tests and decoupling to make the code unit-testable. If you don't your troubleshooting is overly difficult. Once you have your code in this unit-testable format flipping to a console app is a no brainer.
I knew a guy who made everything a windows service and labeled it SOA. Piling up windows services for polling/time based mechanisms isn't SOA. Its so sloppy compared to console applications and so much more difficult to maintain I can't even begin to express how bad an idea it is. I had to deal with about ~20-30 of these win services and once they were converted to n-tier and a console app suddenly the stability of the application went through the roof and my life got 10x easier. So please, do yourself a favor and listen to somebody who has been through months and many iterations of these types of app. Run it as a scheduled task in a console app.
Auto-starting services are subject to problems with service initialization order. You have plenty of dependencies, the TCP/IP stack better be in working order before you try to send an email, for example. Look in the Windows event log for an exception message that prevented OnStart() from getting the service started.
This can be configured for a service, check out the Dependencies tab for the Print Spooler service for example. This is however difficult to deal with, hard to figure out exactly which services need to be running and hard to write the registry entries that configure the dependencies.
Punt the problem: don't send an email message right away. Wait a while, 30 minutes for example.
You install it with installutil? You're right, it doesn't start the service, even if it's set to automatic. If I were you, I'd provide a batch file which calls installutil and then also runs 'net start whatever'. Or if you're using other kinds of installation, those should provide this ability too.
I have been quite comfortable with windows-services, I have been practicing since from last two weeks. Would you please explain me some of the basic applications of Windows service, so that I can take it as homework and practice. (it need not be too basic)
I have already designed and implemented a project/service which is meant for closing all the browsers, when I open a program(or process) saying "Gtalk".
I am interested and very eager to learn more things about Windows services.
Regards.
The word 'service' (Windows or othwerwise) implies that it is something that runs without a User Interface and possibly without any user interaction; it is constantly 'running' waiting to service commands sent to it.
a Windows service is a long-running
executable that performs specific
functions and which is designed not to
require user intervention. Windows
services can be configured to start
when the operating system is booted
and run in the background as long as
Windows is running, or they can be
started manually when required.
Ref.
You could try implementing your own scheduler? I think the most basic use of services is to have automatic process run according to a particular schedule.
Few points
The OnStart method should return within 30 seconds or the SCM will time out. OnStart should handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory.
ServiceAccount: Some of the bugs in windows service are caused by inability to access privileged resources. Choose account type carefully or have a custom account.
Asynchronous Programming: In case you are going to connect to web services, then asynchronous programming approach is far better approach.
System.Timers.Timer: In case your service does "something" periodically, consider using System.Timers.Timer.
What can Services do under Windows?
Testing windows service
I need to implement a background process that runs on a remote windows server 24/7. My development environment is C#/ASP.NET 3.5. The purpose of the process is to:
Send reminder e-mails to employees and customers at appropriate times (say 5:00PM on the day before a job is scheduled)
Query and save GPS coordinates of employees when they are supposed to be out on jobs so that I can later verify that their positions were where they were supposed to be.
If the process fails (which it probably will, especially when updates are added), I need for it to be restarted immediately (or within just a few minutes) as I would have very serious problems if this process failed to send a notification, log a GPS coordinate, or any of the other tasks its meant to perform.
Implement your process as a Windows service.
For a straightforward example of how
to code a Windows service this in
.Net see http://www.developer.com/net/csharp/article.php/2173801 .
To control what happens should the
service fail configure this through
the "Recovery" tab on your service
in services.msc. (see image below)
For higly critical operation you
might look into setting up a server cluster for mitigating single
server failure (see http://msdn.microsoft.com/en-us/library/ms952401.aspx ).
(source: microsoft.com)
You need a Windows Service. You can do non-visual iterative operations in windows services.
Another alternative is to create a normal application and run it on a schedule. Your application is run at certain times a day to perform its actions, depending on how often you need to log GPS coordinates and send reports. If your service doesn't need to run constantly this is usually the recommended approach, as services are supposed to be limited to always-on applications.
As well as being a service, you might want to run on a cluster, and make your service known to the cluster management software.
You can create Windows Service (server programming on Windows) or use scheduler to periodically execute a task.
Depending on the requirements for the high availability, program can be installed on a fail-over cluster where there will be other server (passive node) started and quietly waiting as a hot-backup if the first (active node) dies. This is wide topic. Start with High availablity on Wikipedia.
In my experience if you need to run something 24x7 you need to have (one or more) watchdog process to verify that your service(s) are running correctly. Just relying on the normal service framework cannot guarantee that the program is working correctly - even if it looks like it is running. The watchdog program (which also is a service) can query the service automatically e.g. posting messages checking response times, querying for statistics and so on - when it detects problems it can restart the service (or do some other fail-recovery)
The reason for having a watchdog program as opposed to just rely on user queries to detect errors is that it can be done automatically. This is the preferred method because it allows for a proactive detection.