How do you debug a Windows Service? - c#

I read the MSDN article on the topic. To quote:
Because a service must be run from
within the context of the Services
Control Manager rather than from
within Visual Studio, debugging a
service is not as straightforward as
debugging other Visual Studio
application types. To debug a service,
you must start the service and then
attach a debugger to the process in
which it is running. You can then
debug your application using all of
the standard debugging functionality
of Visual Studio.
Now my problem is that my service fails to start in the first place. First it crashes, and says:
An unhandled exception
(System.Runtime.InteropServices.COMException)
occurred in MyServiceName.exe[3596])
and suggests me to debug it (the debugger instance instantly crashes when I choose one). Then it says
Could not start the MyServiceName
service on Local Computer. Error
1053: The service did not respond to
the start or control request in a
timely fashion
So, how can I investigate/debug the reason that my service won't start? The thing is I created a console application that does EXACTLY what the service does and it works fine. (I mean I just copied the OnStart() method's and the main loop's contents to main).
Any help would be appreciated.
The Service is written in C# with heavy use of interop. I am using VS2008

You could use a parameter to let your application decide whether to start as service or regular app (i.e. in this case show a Form or start the service):
static void Main(string[] args)
{
if ((1 == args.Length) && ("-runAsApp" == args[0]))
{
Application.Run(new application_form());
}
else
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyService() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
}
Now if you pass the parameter "-runAsApp" you can debug the application normally - the SCM won't pass this parameter, so you can also use it as service w/o any code change (provided you derive from ServiceBase)
Edit:
The other difference with windows services is identity (this might be especially important with InterOp) - you want to make sure you are testing under the same identity in "app" mode as well as service mode.
To do so you can use impersonation (I can post a C# wrapper if it helps, but this can be easily googled) in app mode to use the same identity your windows service will be running under i.e. usually LocalService or NetworkService.
If another identity is required you can add settings to the app.config that allow you to decide whether to use credentials, and if so which user to impersonate - these settings would be active when running as app, but turned off for the windows service (since the service is already running under the desired identity):
<appSettings>
<add key="useCredentials" value="false"/>
<add key="user" value="Foo"/>
<add key="password" value="Bar"/>
</appSettings>

I usually just manually set a breakpoint, then point it to the currently open project in c#. The code to set a breakpoint is:
System.Diagnostics.Debugger.Break();
That should get you started, then you can just step through your code and see what's really happening.

I stole this from C. Lawrence Wenham, so I can't really take credit, but you can programmatically attach a debugger to a service, WITHOUT breaking execution at that point, with the following code:
System.Diagnostics.Debugger.Launch();
Put this in your service's OnStart() method, as the first line, and it will prompt you to choose an instance of VS to attach its debugger. From there, the system will stop at breakpoints you set, and on exceptions thrown out. I would put an #if DEBUG clause around the code so a Release build won't include it; or you can just strip it out after you find the problem.

You can use WinDbg/NTSD (another debugger from the "Debugging tools for windows" package) to start a debugger together with your service.
To do this open "gflags" (also available in the above mentioned package) to the "Image file" tab and set the path to debugger executable for your image file (service);
If your service is marked as interactive (only possible if it runs under the SYSTEM account) you can directly start WinDbg, just set the debugger to something like "PATH_TO_WINDBG\windbg.exe -g -G" (the -g / -G are needed so that the debugger doesn't break execution on application start or end - the default behaviour). Now when starting your service the windbg window should pop-up and will catch any unhandled exception.
If your service is not interactive you can start the NTSD debugger (a command line debugger) in remote mode and connect to it from WinDbg (that can even be running in another PC). To do this set the debugger in gflags to something like "PATH_TO_NTSD\ntsd -remote tcp:port=6666,server=localhost". Then connect to the remote debugger by starting windbg with something like "windbg -remote tcp:port=6666,server=localhost" and you should have complete control over the other debugging session.
As for finding the source of the exception itself a windbg tutorial is over the topic here but as a start try to execute the "!analyze -v" command after the exception was caught - with some luck this is all information you'll need..
Note: maybe this is overkill for your case but with this approach you can even debug services during system start-up (I had once a timing problem with a service had an issue only when starting the first time with the system)

One thing I do (which may be kind of a hack) is put a Thread.Sleep(10000) right at the beginning of my OnStart() method. This gives me a 10-second window to attach my debugger to the service before it does anything else.
Of course I remove the Thread.Sleep() statement when I'm done debugging.
One other thing you may do is the following:
public override void OnStart()
{
try
{
// all your OnStart() logic here
}
catch(Exception ex)
{
// Log ex.Message
if (!EventLog.SourceExists("MyApplication"))
EventLog.CreateEventSource("MyApplication", "Application");
EventLog.WriteEntry("MyApplication", "Failed to start: " + ex.Message);
throw;
}
}
When you log ex.Message, you may get a more detailed error message. Furthermore, you could just log ex.ToString() to get the whole stack trace, and if your .pdb files are in the same directory as your executable, it will even tell you what line the Exception occurred on.

Add lots of verbose logging in your OnStart. It's painful and old school, but it works.

Seems like the problem is with the user context. Let me confirm whether my assumptions are right.
When you say that the code works perfectly from console application, I assume you are executing the Console application under the same user which you had logged in.
When you say that the same code crashes while called from the windows service, I assume the service is running in "Local System" account in your development machine.
If both my assumptions are right, please try out the following steps.
In the services listing right-click your service, select properties and then "Log On" tab.
Select the option "This account" and provide the existing username and password.
Now try starting the service. It should now start without any errors.
Following could be the root cause of your error
If you are using SQL Server make sure you are not using SSPI authentication.
If you are trying to read any shared folder\resource which you don't have permission when using "local system" account.
If any of the required dependencies required by the application is in a different folder which the "Local System" user doesn't have permission to access.
If you are using VBA automation which wont work in "Local System" account.
Try disabling your firewall or antivirus.

You could add some logging around the interop calls to find out which one fails.
Also services by default aren't associated with a desktop; if you open the services.msc control panel applet, get the properties of your service, go to the "Log On" tab, you could check "Allow service to interact with desktop". This could fix the problem for you in some cases.

I would assume the reason could be causing because of heavy use of interops. So you need to tackle this problem differently. I would suggest create a windows or console app with same logic of you service and make sure that it works first without any issues, and then you may want to go with creation of the Win service.

Debugging services is a pain, particularly since startup seems to be when many of the problems manifest (at least for us).
What we typically do is extract as much of the logic as possible to a single class that has start and stop methods. Those class methods are all that the service calls directly. We then create a WinForm application that has two buttons: one to invoke start, another to invoke stop. We can then run this WinForm applicaiton directly from the debugger and see what is happening.
Not the most elegant solution, but it works for us.

Check out this question, which discusses how to catch unhandled exceptions in a window service.

In order to attach a debugger to the Windows Service, it needs to be started first. The reason why the service failed to start can be checked in Windows Event Log.
After that the process of attaching a debugger is pretty straight forward from Visual Studio Debug->Attach To Process.

What I've done is implemented by OnStart() to look something like this:
_myBusinessObject = new MyBusinessObject();
After the Business Object has been constructed, timers and IPC handlers do all the real (Service) work.
Doing it like this allows you to create a Forms/WPF application that call the same code above in the Form_Loaded handler. This way, debugging the Forms application is the exact same as debugging the Service.
The only issue is that if you are using app.config values, there will be a second app.config file that needs to be kept up-to-date.

Use following Code in Service OnStart Method:
System.Diagnostics.Debugger.Launch();
Choose Visual Studio option from Pop Up message

read the 2 articles mentioned here:
http://geekswithblogs.net/BlackRabbitCoder/archive/2011/03/01/c-toolbox-debug-able-self-installable-windows-service-template-redux.aspx

Step 1 - Add #if region to your Program.cs
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new StockInfoService()
};
ServiceBase.Run(ServicesToRun);
#if (!DEBUG)
ServiceBase[] ServicesToRun = new ServiceBase[] { new SqlBackupService() };
ServiceBase.Run(ServicesToRun);
#else
StockInfoService service = new StockInfoService();
service.OnStart();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#endif
}
Step 2 - In Service.cs change your OnStart(string[] args) method without parameter one. (I commended mine.)
public void OnStart()
//protected override void OnStart(string[] args)
{
**Do your thing.
}
Step 3 - Simply hit Start (F5) and debug your code.

Related

C# Windows service won't start: "Cannot start service from command line or debugger"

Even though there are similar questions, I couldn't find any that solves mine. I have a simple program that runs as a service and I want to start it programatically. It's as simple as this:
private static void StartService()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(ServicesToRun);
}
As expected, I can't just start my service without installing it. Windows gives me the following error message:
Cannot start service from command line or debugger. A windows service must first be installed using installutil.exe and then started with service explorer, Windows services administrative tool or NET start.
So far so good. So I went there and did just as the docs says:
installutil <my_project>.exe
The installation was successful and I can even start my service from Service Manager or net start. The only problem is: when I debug my application (via F5), Windows keeps showing me the exact same message: Cannot start service (...).
I've found a solution here that uses this:
public void onDebug()
{
OnStart(null);
}
Which allows me to run and debug my application normally, but I actually need it to run as a service and Windows refuses to start that way. Is there anything I'm missing?
It is not in your power to just start a Service like a normal programm. The Service must be registered with and started by the Service manager. That is one of the (many) rules of Windows services. And you have to repeat that for every new build.
As this and other Service related rules (no interactive sessions) can make developing them a Pain, a common approach is to develop them using a console application. I could not find my ideal example, but I found something like it:
https://alastaircrabtree.com/how-to-run-a-dotnet-windows-service-as-a-console-app/
Of course a better longterm plan might be to stop using Services alltogether and switch over to the Windows Task Scheduler. It depends heavily on what exactly you need this code to be able to do in practice.

Could not start Windows Service, Error 1064

I wrote a Windows Service to run on Win10, and it worked perfectly fine until I decided to change it a bit. I rewrote some logic, tested it in both Debug and Release configurations, and everything was fine. Then I uninstalled the current version of the service using installutil.exe /u %servicename.exe% and reinstalled it again using installutil.exe %servicename.exe%.
For some reason, this new version cannot start, and it crashes with Error 1064. This is the full error text:
Windows could not start %servicename% service on Local Computer. Error 1064: An exception occurred in the service when handling the control request.
The last time I installed this service, I ran into some difficulties, but quickly fixed them by changing the Log On properties. This time, it is not working. Please help with this issue.
Thanks.
Update 1
Here are my Main() and OnStart() service methods:
Main()
static void Main()
{
#if DEBUG
var service = new SalesforceToJiraService();
service.OnDebug();
Thread.Sleep(Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new SalesforceToJiraService()
};
ServiceBase.Run(ServicesToRun);
#endif
}
OnStart()
protected override void OnStart(string[] args)
{
this.ConfigureServices();
this.timer.Start();
this.logger.Information("SalesforceToJira service started.");
}
Update 2
More code:
ConfigureServices()
protected void ConfigureServices()
{
this.configuration = ConfigurationHelper.LoadConfiguration(ConfigurationPath);
this.logger = ConfigurationHelper.ConfigureLogger(this.configuration.Logs.LogsPath);
this.timer = ConfigurationHelper.ConfigureTimer(this.configuration.ProcessInterval.TotalMilliseconds,
(sender, eventArgs) => this.ProcessCasesAsync(sender, eventArgs).GetAwaiter().GetResult());
this.salesforceClient = new SalesforceCliClient(this.configuration.Salesforce.CliPath);
this.jiraClient = Jira.CreateRestClient(
this.configuration.Jira.Url,
this.configuration.Jira.Username,
this.configuration.Jira.Password);
}
I'm using Newtonsoft.JSON for deserializing a JSON configuration file, Serilog for logging, System.Timers.Timer for periodic events, AtlassianSDK for the Jira API and some wrappers over Salesforce CLI for Salesforce.
Thanks to #Siderite Zackwehdex's comment, I was able to find the full stack trace of the underlying exception in EventViewer, under:
Windows Logs\Application
In my case, my service is named "HttpDispatcher", which appears in the "Source" column in the top pane.
I could see immediately it was due to a dependency issue where my .NET 4.7.2 project was not pulling across my .NET Standard references. (That ol' chestnut).
I faced the same issue. The reason was I forgot to set the Database connection properly in configurations.
I had this exact same error 1064 starting my service. For me the user I had the service registered as was not a valid user in the database. Once added, it worked great.
I also had the same error in my Windows Service.
The reason was it can't read a configuration parameter, so it crash.
Adding some validation (bugfixing), the Windows Services can start it correctly.
In my case the error was due to issues with Event log name
It got fixed after I went to RegEdit and deleted old service name from HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
I have also faced this issue. In my case it is due to connection fail with the data base. I think it is due to code throw the exception.
My error :
Windows could not start the service1 service on local computer.
Error 1064: An exception occured in the service when handling the control request
I corrected my issue by updating the third party DLL.
I faced the same issue, here is how I resolved it after troubleshooting.
If you are running service on the Server with multiple users, make
sure to run the service as admin user. Click on the service
properties and then on Log on tab click on this account and provide
the admin user name and password.
And If your service is accessing some shared drive, then make sure
you have a general user on all servers for accessing the shared
drives and add the user as local admin as well.
For me it happened when I tried to restart a process. Turned out the process was hanging in 'Stopping' so I had to kill it manually via command line and the PID.

Keep C# application running

I'm building a Windows Service that uses FileSystemWatcher, and runs in the background.
I don't want to keep on uninstalling and installing the service every time I want to debug, so would like to do most of my development in a normal program before moving it into a service. But I'm quite new to this, and when I run it, it just runs through the block and exits.
What would be a good way to keep the program running?
http://einaregilsson.com/run-windows-service-as-a-console-program/
I've used this before to debug my service as a Console application based on whether its running in an interactive user environment.
public partial class DemoService : ServiceBase
{
static void Main(string[] args)
{
DemoService service = new DemoService();
if (Environment.UserInteractive)
{
service.OnStart(args);
Console.WriteLine("Press any key to stop program");
Console.Read();
service.OnStop();
}
else
{
ServiceBase.Run(service);
}
}
while (true)
{
// Execute your program's functionality here.
}
I wrote a 7 part series a while ago titled: Building a Windows Service. It covers all the intricacies of building services, making them friendly to debug, and self-installing.
The basic feature set I was looking for was as follows:
Building a service that can also be used from the console
Proper event logging of service startup/shutdown and other activities
Allowing multiple instances by using command-line arguments
Self installation of service and event log
Proper event logging of service exceptions and errors
Controlling of start-up, shutdown and restart options
Handling custom service commands, power, and session events
Customizing service security and access control
The final result was a Visual Studio project template that creates a working service, complete with all of the above, in a single step. It's been a great time saver for me.
see Building a Windows Service – Part 7: Finishing touches for a link to the project template and install instructions.
Here’s documentation from MSDN # http://msdn.microsoft.com/en-us/library/7a50syb3(v=vs.80).aspx?ppud=4 . I have tried it before and it works under .NET Framework 3.x. I could not find my descriptive notes on it, at the moment.
Use the pragma #If DEBUG for debugging purposes like console outputs. Another is using the Debug object.
If you have any trouble with this, say so. I may be able to find my notes or make a Windows Service app myself, just to see if the steps on MSDN still work.

Windows Service Not Starting After Installing

Well, I have created a new windows service and the install from Visual Studio.
When I am done installing, how can I start the service ?
I need something that will allow me to start the process, or an exe.. something?
The Installer is : Visual Studio Installer - Setup Project.
Any help?
My question in order:
Why the service don't start?
How can i control what happen after intall ? Where is the code for it?
Thanks!
even you Set the startup type to Automatic it will not start your service automatically until the machine restart. what you can do is create event handler for AfterInstall event of your service installer class and start the service using ServiceController Start method as below
public serviceInstaller()
{
this.AfterInstall += new InstallEventHandler(serviceInstaller_AfterInstall);
}
void serviceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
ServiceController sc = new ServiceController(serviceInstaller.ServiceName);
sc.Start();
}
you can create event using the visual studio event window as well.
to start your service you can either execute the command:
net start YourServiceName
or go to Control Panel -> Admin tools -> Services and select your service and click start.
full path above depends also on your actual windows version.
even if you did not use any logging, in general service failures are recorded in the Windows Event Log so open Event Viewer and see latest events.
Set the startup type to Automatic in the ServiceInstaller class properties (you can do it in the Designer file).
A windows service needs to be installed ( it should tell you what to do if you try debugging it ), then started in the server manager. Then you can attach to it.
They are a bit of a pain to debug, TBH.
What does the service do? is it opening SQL connections?
looking for a file?
check in your event viewer where the service is installed for errors after you try to start it, it will give us a better understanding.
It is impossible to understand your question unless you take interest in making it understandable.
However from my assumption,
Goto Visual studio Tools => Visual Studio command prompt
use command net start <>
If fails starting the servicce, Check event log (eventvwr.msc in run dialog) to see if there any relevant errors logged.
Your Windows service working in some systems.
If you face some system getting error Windows Service not starting after installing if manually/automatically.
if the service starts and stops like that, it means your code is throwing an unhandled exception. This is pretty difficult to debug, but there are a few options.
Consult the Windows Event Viewer.
Event Viewer - eventvwr.msc
Normally you can get to this by going to the computer/server manager, then clicking Event Viewer -> Windows Logs -> Application. You can see what threw the exception here, which may help, but you don't get the stack trace.
Event Viewer Log Image
Add try/catch block in your service start method.
Let you check whether you are using any hot code(For Ex: "D:\"). That drive is not available in installed system.
This will helps a lot!

Cannot start service

I have 2 other services running on a server and they start and stop without a problem, however one of them will not start. I can't see any difference in their implementation or config files. I'm receiving the following messages when attempting to start the service after installing it with InstallUtil:
The service is not responding to the control function
more help is available by typing NET HELPMSG 2186
NET HELPMSG 2186:
Explanation: The service cannot run your command at this time
Thanks very much in advance!
This is most likely due to service installed, then uninstalled and now you are trying to install again. Reboot the machine and try again.
UPDATE
According to the event log error, you are trying to run the service as the current logged in user (I guess you are connected using remote desktop). This is not the correct approach, you need to run the service as the LocalSystem. In the project properties window, change the identity of the service.
UPDATE 2
In the design view of the service/component class, click on serviceProcessInstaller1 (or similar) and then in tmhe properties you see a drop down: Account with 4 entries: User/LocalNetwork/LocalService/LocalSystem. Make it LocalSystem
On Start event can you put
try
{
//...
}
catch(Exception ex)
{
EventLog.WriteEntry(ex.Message + ex.StackTrace);
}
and watch whats happening?
or
attach (Tools > Attach To Process) your process to Visual Studio for DEBUG. You can see whats happening with debug, but EventLog works good aswell.

Categories