Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with testing a Windows service

I want to make a Windows service that will access my database. My database is SQL Server 2005.

Actually I am working on a website and my database is inside our server. I need to access my database every second and update the records. For that purpose I need to make a Windows service that will install into our server and perform the task.

I have been accessing the database from my local machine and then running the service, but problem is I'm not sure how I can test this service.

I tried to install into my local machine. It installed and then I ran the service but it did not perform the task and I think service is not able to connect with the database.

There is no problem in the service nor its installer. The only issue is how to test my Windows service.

like image 934
PrateekSaluja Avatar asked Apr 05 '10 12:04

PrateekSaluja


1 Answers

You can always create a service / console app hybrid, and use the console app for testing purposes.

What you need to do is something like this - in your program.cs, change the Main method to either run the service, or optionally run as a console app:

static class Program
{
    static void Main(params string[] args)
    {
        string firstArgument = string.Empty;

        if (args.Length > 0)
        {
            firstArgument = args[0].ToLowerInvariant();
        }

        if (string.Compare(firstArgument, "-console", true) == 0)
        {
            new YourServiceClass().RunConsole(args);
        }
        else
        {
            ServiceBase[] ServicesToRun = new ServiceBase[] { new YourServiceClass() };
            ServiceBase.Run(ServicesToRun);
        }
    }

and then on your service class, which inherits from ServiceBase and has the OnStart and OnStop, add the RunConsole method like so:

    public void RunConsole(string[] args)
    {
        OnStart(args);

        Console.WriteLine("Service running ... press <ENTER> to stop");

        //Console.ReadLine();
        while (true)
        { }

        OnStop();
    }

Now if you want to run the app to test its functionality, just launch the EXE with a -console command line parameter, and put a breakpoint in the RunConsole method.

like image 195
marc_s Avatar answered Oct 17 '22 09:10

marc_s