Jake H.
Jake H.

Reputation: 603

Debugging A Window System Service in C#

I get the error "Cannot start service from the command line or a debugger. A Windows Service must first be installed (using installutil.exe) and then started with the ServerExplorer, Windows Services Administrative tool or the NET START command.

So, is there not a way to run or test the Windows Service without installing it? Should I build my project in a Console Application, then transfer the code to a Windows Server project after it has been tested?

Thanks.

Upvotes: 3

Views: 1406

Answers (3)

VRK
VRK

Reputation: 400

there are two approaches you can use.

  1. Create separate windows form application and call that code from the windows form project.

  2. in the calling method, please use:

     #if Debug
     Debugger.Launch()
     #endif
    

I hope it helps.

Upvotes: 0

gregwhitaker
gregwhitaker

Reputation: 13420

I tend to add a static Main method to my service class so that it can be invoked as a console application for debugging, but installed and ran as a service as well.

Something similar to the following:

    public partial class ControllerService : ServiceBase
    {

        static void Main(string[] args)
        {
            ControllerService service = new ControllerService();

            cmdLine = CommandLineParser.Parse(args);

            if (Environment.UserInteractive)
            {
                switch (cmdLine.StartMode)
                {
                    case StartMode.Install:
                        //Service Install Code Here
                        break;
                    case StartMode.Uninstall:
                        //Service Uninstall Code Here
                        break;
                    case StartMode.Console:
                    default:
                        service.OnStart(args);
                        consoleCloseEvent.WaitOne();
                        break;
                }
            }
            else
            {
                ServiceBase.Run(service);
            }
        }

        protected override void OnStart(string[] args)
        {
             //Do Start Stuff Here
        }

        protected override void OnStop()
        {
            if (Environment.UserInteractive)
            {
                consoleCloseEvent.Set();
            }
        }
   }

Upvotes: 3

chhenni
chhenni

Reputation: 1127

You could try to keep the code that performs the actual work in a separate assembly, and call that code from the service or a console application for testing.

Upvotes: 2

Related Questions