What are the basic applications of Windows services? - c#

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

Related

Synchronization with external services ASP.NET MVC

We want to synchronize the data in our application with the data of an external service. (Such as accountancy software. This synchronization should be executed every night and when the customer wants to.
I am aware that long running threads don't belong in web applications and this synchronization should be executed within an external windows service. But the downside of this method is, that is becomes harder to deploy / maintain, since the application can be installed on the customer's webserver too.
Is it possible to completely integrate this synchronization with just the use of a class library project withing my solution, which will start up at the Application_Start event?
Since your application is hosted on IIS, it's maintained by the application pool process. If you create additional module for your task, it will be running within context of the same process. You have to be sure this process is still working in the middle of the night, when application is not used, in order to perform the synchronization you want. You can use Quartz.NET to schedule your sync task.
But still, I think much better idea is to perform the synchronization from windows service. Service should communicate with the application for example by using database, where it logs its current activity. It gives you the possibility to monitor of the service state from the web by connecting to such database. I know service forces some additional administration effort, but it will be much more reliable and secure. You can also add service starting possibility from your web application (if pool process user has access rights to windows service) to overcome (or at least minimize) administration effort connecting with restarting your service after some failure.
I've written such functionality, so just to give you an overall look of what I mean by web monitoring of such external service, check the screen below. It can be written with the ajax support to achieve more responsiveness (pooling mechanism), which will be convenient for the end user.

How to set permissions on a Windows Service

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.

Windows program that always runs

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/

Windows Service doesn't start after installation

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.

When to use a webservice over a windows service?

I have a data loading application that has to be executed multiple times per day at irregular intervals. I am planning to write a service to kick off the downloads and import the data to a database server. Are there advantages to using a standard service over a webservice or vice versa?
I think you're missing the point here.
Web Services typically are used for a form of communication or remote execution. You call a remote function on a web-service to either adjust the behavior of the machine it's running on or to retrieve data from it.
Windows Services are background processes that run on a machine without any "logged on user" being required. They can perform tasks and do things while the user is at the login screen, or do elevated operations. You can talk to services to adjust their behavior or retrieve information, but it's general purpose is different than a webservice.
The biggest notable difference here is that web-services must be called, they don't run on their own.
For your application I would suggest using a Windows (Standard) Service, as you can have it execute code once per day. I would only use a web-service if you've got something else to automate the calls to the web-service and you require a response from the server detailing it's execution result (success/fail/warning/etc...)
You could also consider writing a normal (windows or console) application that is triggered by a Windows Scheduled Task. What you've described doesn't necessarily sound like something that would require a service.
Sounds like a good use of a windows service to me. Off the top of my head, I'd use a windows service if:
1. Work is performed on a scheduled basis (regular or irregular intervals) in the background;
2. No interaction is needed - work is just done in the background and kicks off based on polling or some other type of trigger (message dropped in queue, database value trigger, scheduled timespan, etc.);
3. Needs to be monitored (either starts/stops along with logging) and you can take advantage of WMI, perfmon and event log with little effort.
A web service is better for tasks that are interactive (like if you wanted to initiate the download based upon a request received).
Sounds like a windows service is the approach you should take.
Hope this helps. Good luck!
If "irregular interval" does mean, the application is invoked by another application, I would use a web service.
If the action is scheduled, I would use a windows service.
If you are working with SQL Server (scheduled or not), I would also consider SQL Server Integration Services.

Categories

Resources