C# about Windows service - c#

What would be a short example with a Windows service and how to install and run it?
I've searched on the Internet, but what I've tried didn't have anything written on the On Start method. Plus, when I've tried to install it the error OpenSCManager keeps popping up.

Find install util at C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe
Then run InstallUtil.exe "c:\myservice.exe"
Go to services.msc and then locate and start your service

Here are some examples about how to write and install a Windows service in C#:
A Windows Service Application
Simple Windows Service Sample
ASP.NET Tutorials : Creating Windows Service in C#
Creating a Windows Service in C#
How to Create and Work With Windows Services in C#
Creating a Simple Windows Service in C#

My answer to this question gives you step-by-step instructions for creating a Windows service in C#.
Easiest language for creating a Windows service
My answer to this question shows you have to modify the service so that it can install and uninstall itself from the command line.
How to make a .NET Windows Service start right after the installation?
InstallUtil.exe has been part of .NET since 1.1, so it should be on your system. However, you likely can't use it from a 'normal' command prompt. If you have Visual Studio installed, open the Visual Studio command prompt. That'll define the appropriate environment variables that make InstallUtil accessible without path information.
The OnStart() callback gives you an opportunity to start the business logic of your service. If you don't do anything in the OnStart() callback, your service will immediately shut down. Typically, you'll start a thread that performs the work you're interested in. Here is a small example to show you what it looks like.
private static System.Timers.Timer _timer;
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// Write a message to the event log.
string msg = String.Format("The Elapsed event was raised at {0}", e.SignalTime);
EventLog.WriteEntry(msg, EventLogEntryType.Information);
}
protected override void OnStart(string[] args)
{
// Create a timer with a 10-econd interval.
_timer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Signal the timer to raise Elapsed events every 10 seconds.
_timer.Start();
}
protected override void OnStop()
{
// Stop and dispose of the timer.
_timer.Stop();
_timer.Dispose();
}
Doing something like this will effectively keep your service running until it shuts down. Hope this helps.

Related

Unable to Manually Start C# Windows Service

I have created a Windows Service project in Visual Studio Community 2015 on my Windows 10 laptop (upgraded from Windows 7 and fully updated), but I have been unable to successfully start my service manually, and I am unable to force kill the service once it has begun to start. When I attempt to start my service via the Services Console (services.msc), I get the following behavior:
A "Service Control" dialog pops up with a progress bar.
The progress bar fills slowly over the course of 90 seconds.
When the progress bar is full, I receive Error 1053.
The service's state changes to and remains infinitely at "Starting" (Start Pending).
The service can not be stopped by any means besides a forced reboot.
I've come to understand that Error 1053 is the result of a service that is unable to start after 30 seconds. However, there is no possibility of my service taking longer than 30 seconds to start. My OnStart, OnStop, and OnTimer methods are currently as follows:
protected override void OnStart(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 10000;
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
timer.Start();
}
protected override void OnStop()
{
}
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
{
}
And my Main method looks like this:
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyNewService()
};
ServiceBase.Run(ServicesToRun);
}
Strangely, if my service's startup method is set to "Automatic" then the service will indeed start on its own the next time Windows restarts. When it is started automatically, I am able to manually stop the service (this is the only time it will stop manually). However, after successfully stopping it manually, I still cannot re-start it manually. Attempting to do so produces the exact same behavior as described earlier, resulting again in Error 1053.
My service installs without error (via installutil), and I can uninstall without error. However, if I attempt to uninstall my service (via installutil /u) while the service is stuck in "Starting" (Start Pending) mode, the service does not stop, remains as "Starting", and the startup mode switches to "Disabled". Only upon restarting is the service completely removed.
My question:
Why does my service start automatically on Windows startup, but not by any other manual method? (I need it to start automatically, but also be able to manually start and stop it.)
Thank you for your time and expertise.
The issue was Avast anti-virus stopping the service silently. Annoyingly, Avast does not report the service as a virus or a threat of any kind and makes no log of the blocked service. I was able to successfully start and stop my service manually once I had disabled Avast. As a semi-permanent solution, I have added the path to my service to Avast's exceptions list by going to Settings -> Active Protection -> Customize (File System Shield) -> Exclusions, and clicking "Add."
To answer my original question, my service was able to start automatically on Windows startup because it was able to start before Avast was loaded. This led to the strange behavior I observed where I was able to stop it after it had started automatically, but not restart it manually since Avast was now running by that point.
You shoud cleanup service in method OnStop.
You create a timer and never stop it.
private System.Timers.Timer timer;
protected override void OnStart(string[] args)
{
timer = new System.Timers.Timer();
timer.Interval = 10000;
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
timer.Start();
}
protected override void OnStop()
{
timer.Stop();
timer = null;
}

Error message : Windows service can not start on your local machine windows 7 OS

I am very new to windows service. I want same functionality in my windows service as it is in my asp.net web application.
It haven't any UI.
I am briefing my web application here so according to that you can guide me how to do it in windows service.
Retrieving very Big image from IMAGE folder which resides in my web application according to certain condition.
Resize those image and store it into database.
Retrive resized images stored in database and store it into server folder called Large and again resize that image in 3 more different size and save into their three respective size folders called List, Mini,*Thumb* on server.
Now i want to build windows service with same functionality and it run on server after every 15 mins.
Hope now i am more clear. please help me in this regards.
my web application code is working fin. but i don't know where to put this code in my windows service as I am very new to windows service.
I tried to put that code onstart and also oncontinue method but that time service not allowed to start. It gives error message this service can not start on your local machine.
OnStart must complete within a 30 (??? iirc) second timeout. I'd suggest spinning off a Thread in OnStart to do the work so that OnStart completes immediately.
protected override void OnStart(string[] args)
{
(new Thread(() => DoLongRunningStartupWork()){IsBackground = true})
.Start();
}
void DoLongRunningStartupWork()
{
//actual startup code
}
You will need to create a method that is called from within the OnStart method. The OnStart method is there purely for configuring the service when it starts up. You'll want something like:
void OnStart()
{
DoSomething();
}
void DoSomething()
{
// Your code here
}
I've seen people use Threads in order to start there Windows Service and get then the Thread does the work that is required.

Windows Service output not showing up in Event Log

I am trying to follow this walkthrough.
I'm using Visual Studio 2010 Premium.
The only events I see in Server Explorer or in Event Viewer are "Service started successfully." and "Service stopped successfully."
Here is the service code:
namespace MyNewService
{
public partial class MyNewService : ServiceBase
{
public MyNewService()
{
InitializeComponent();
if (!EventLog.SourceExists("MySource"))
{
EventLog.CreateEventSource("MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
}
protected override void OnStop()
{
eventLog1.WriteEntry("In onStop.");
}
}
}
I had the same issue with Visual Studio 2010 Professional on Win 7 64. My newly compiled service was installed with InstallUtil.exe running as Administrator. It started and stopped correctly. No exceptions but no amount of refreshing the Event Viewer revealed a new event log. Fran71's suggestion worked for me: I closed the Event Viewer and reopened. VoilĂ , the newly created application log file appeared.
FWIW, I ran into this problem in Win8 and found that Refreshing the Event Viewer did not cause my newly created Event Log to show up, but closing and reopening Event Viewer did. Was driving me insane since no exceptions were being thrown when Creating the Event source or writing a log entry.
Probably a permissions problem. Like the commenter said, try running VStudio or your compiled service as an Administrator.
Also, you can still debug a service - put a thread.Sleep(up to 20 seconds) as your first line (to give yourself time to attach the debugger), then put a break point on the line after that. Then go Tools --> Attach To Process and select your .exe. If you get that done before the end of your Thread.Sleep() then you should break.
Keep in mind that the service must complete the OnStart within IIRC 30 seconds or Windows will think it is not responding and kill your process, so move your code out of the service start if you are going to do much debugging. Just throw a timer in there or something.
To make it easier to debug, consider moving your functionality to a DLL and then keep your service to just enough code to call into your DLL - this will ease unit testing and debugging - but don't forget that lots of things change when you're actually running it as a service.

Why doesn't System.Threading.Timer callback fire?

I'm not using a Windows Form Timer--I'm using a System.Threading.Timer. No exceptions are raised when instantiating the timer, and to my understanding, System.Threading.Timer's do not need to be explicitly started.
I've tried using a System.Timers.Timer (See comments in code) and changing the signature of the callback with no luck. Inside the callback method, I stubbed in some EventLog writes, and not even the first writes to the event log. All I see in the Event Log is MyService.OnStart fired followed by MyService started (these are both from the OnStart event). Why aren't the timer callback events firing?
public partial class MyService : ServiceBase
{
private static System.Threading.Timer timer;
public MyService()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("MyService"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MyService", "MyServiceLog");
}
eventLog1.Source = "MyService";
eventLog1.Log = "MyServiceLog";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("MyService.OnStart event fired");
// setup timer to poll and execute an event
//Timer timer = new Timer(new TimerCallback(CheckCalls), null, 0, 10000);
try
{
timer = new System.Threading.Timer(new System.Threading.TimerCallback(CheckCalls), null, 0, 10000);
}
catch (Exception ex)
{
eventLog1.WriteEntry(ex.Message + " Stacktrace: " + ex.StackTrace);
}
eventLog1.WriteEntry("MyServicestarted");
GC.KeepAlive(timer);
}
}
and the callback method, CheckCalls:
private static void CheckCalls(object objectState)
{
EventLog eventLog1 = new EventLog("MyServiceLog", "DAVIDWIN7", "MyService");
eventLog1.WriteEntry("MyService is polling");
}
Arg--For some reason when you Build->Clean Solution, then Build->Build Solution, Visual Studio does not rebuild your setup project. I believe my code above works fine, but I had tried many different fixes without explicitly right-clicking the setup project and selecting Build.
I thought Clean Solution would force all projects to be rebuilt on next build???
it's got to be an error with the timer thread writing to the event log.
I got it working on my computer but I replaced all the eventlog with Console.writeline because I didn't want to mess with my event log permissions.
Did you check if the account under which the service is running has access to the eventlog?
Please can you go and download this test application which mirrors exactly the scenario you are talking about:
https://docs.google.com/leaf?id=0Bw_NnV9fhgmgMThjNDgzOTgtODNiOC00NDE1LWEyMTYtNzVhOTMyNzlmZjZk&hl=en&authkey=CMuupNkC
I've just created this. It's a service that effectively uses the same code as you. The only difference is that I have used the toolbox to drag and drop an eventlog on to the service designer - setting the log to 'Application' and the source to 'Service1'.
Open a VS command prompt at the project folder, go to bin\debug and run installutil windowsservice1.exe - specifying some credentials (so you're installing the dev service directly from your bin output folder).
Start the service and monitor the application log - it will write every ten seconds as you expect to see from your code.
Assuming this works on your machine(tm) like it does on my machine(tm) then I would suggest that the problem is the event logging itself, or, horror of horrors - your service isn't running from your build output folder (most of the devs in my team insist on running their dev services from a different folder and then swear when they forget to actually update the binaries when they start debugging it!).
As I suggested in my comment, you really need to be able to attach the debugger to this and breakpoint the callback to verify that it's not getting fired. I never rely on the eventlog for diagnostics messages simply because the log might be full, or permissions might prevent you etc etc - it might be a windows platform component, but it's not as reliable as I would like.
The debugger, however, rarely lies (unless the deployed binaries are out of date ;) ). Compile a debug build of your project and make sure it's the one that is installed in the services list, start it up and then attach directly to the service exe (there's no point trying to attach to [service].vshost.exe - VS cannot auto-attach or host windows services as the only way they can run is via svchost.exe shelling them).
Hope this helps.

c# Windows Service Console.Writeln

I wrote, installed, and successfully started a Windows Service in c# that does nothing :) Initially I just want echo stuff to the console, db queries the service makes etc. I used the OnStart in my service, but from a cmd prompt when I do a net start "My Service" where do these messages show up?
I'm open to better ways. I'm new to this and feeling my way through it step by step by echoing back to the console my progress. Should I echo to the event log instead? How do I do that?(I know, I know, google it)
protected override void OnStart(string[] args)
{
base.OnStart(args);
Console.WriteLine("Sham-Wow!");
}
You cannot write the console from a Windows Service.
I recommend you using any logging utility, such as log4net.
The second alternative is writing to the Event Log (System.Diagnostics.EventLog)
Try System.Diagnostics.Trace.WriteLine and you will see your messages in Output window of Visual Studio or with dbgview utility.
If you want to run your application as a console application (so you can see your console output) or as a service you can achieve this with the following:
Ensure that your application is compiled as a Console application.
Alter the application's Main method so that you can branch for service or console execution.
Run your application as follows to get a console "myservice.exe /console".
It's been years since I have done this so might need a little tweaking, but something like follows:
static void Main(string[]] args)
{
if (args.Length == 0)
{
//Service entry
System.ServiceProcess.ServiceBase[] services;
services = new System.ServiceProcess.ServiceBase[] { new WinService1() };
System.ServiceProcess.ServiceBase.Run(services);
}
else
{
//Console entry
OnStart(args);
}
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
Console.WriteLine("Sham-Wow!");
}
This is fine for some early experimentation, but I would recommend Log4Net once you have got your head around things.
The most common/accepted way of communicating the status of your service is to write to the Windows Event Log.
For easier debugging, I would recommend that you put all of your business code into a separate class from the service component. You can then use that class from either your service, or from a console application. While you are creating the service, you will use the console application to host your component, so that you can easily step-into the code.
Very old question, but very relevant. This is how I implemented a logging mechanism that I could inspect while the Windows service is running.
Create a log file. My favorite is Log4net as mentioned before.
Open PowerShell and run this command Get-Content "path/to/file.log" -Wait
You will be able to monitor the file as it changes. This is like the tail command in linux.

Categories

Resources