Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging a Windows Service

I am making a Windows Service and I want to debug it.

This is the error I get when I try to debug it:

Cannot start service from the command line or a debugger. A Windows service must be first installed and then started with the Server Explorer, Windows Services Administrative TOll or the NET start command.

I have already installed my service using InstallUtil, but I am still facing problems.

Also, when I try to attach a process, my service goes into the running mode, it never starts debugging.

EDIT: DO we have to reinstall the Windows Service everytime we make a change or just building it would suffice?

like image 896
Neha Avatar asked Dec 12 '22 11:12

Neha


2 Answers

In your OnStart use something like this:

#if DEBUG
if(!System.Diagnostics.Debugger.IsAttached)
   System.Diagnostics.Debugger.Launch();
#endif
like image 56
Mrchief Avatar answered Dec 27 '22 14:12

Mrchief


For the most use cases it's good enough to run the service as console application. To do this, I usually have the following startup code:

private static void Main(string[] args) {
    if (Environment.UserInteractive) {
        Console.WriteLine("My Service");
        Console.WriteLine();
        switch (args.FirstOrDefault()) {
        case "/install":
            ManagedInstallerClass.InstallHelper(new[] {Assembly.GetExecutingAssembly().Location});
            break;
        case "/uninstall":
            ManagedInstallerClass.InstallHelper(new[] {"/u", Assembly.GetExecutingAssembly().Location});
            break;
        case "/interactive":
            using (MyService service = new MyService(new ConsoleLogger())) {
                service.Start(args.Skip(1));
                Console.ReadLine();
                service.Stop();
            }
            break;
        default:
            Console.WriteLine("Supported arguments:");
            Console.WriteLine(" /install      Install the service");
            Console.WriteLine(" /uninstall    Uninstall the service");
            Console.WriteLine(" /interactive  Run the service interactively (on the console)");
            break;
        }
    } else {
        ServiceBase.Run(new MyService());
    }
}

This makes it easy not only to run and debug the service, but it can then also install and uninstall without needing the InstallUtil program.

like image 22
Lucero Avatar answered Dec 27 '22 12:12

Lucero