2

A common nuisance we have is having to switch this code below depending on whether we are testing locally or committing code for the build server.

    /// <summary>
    /// Main entry point to the application.
    /// </summary>
    public static void Main()
    {
        // Don't forget to uncomment this if committing (!)
        //var servicesToRun = new ServiceBase[] {new myservice()};
        //ServiceBase.Run(servicesToRun);

        // and re-comment this
        RunAsConsoleApp();

    }

It would be really useful if there was a way to test in the code to tell the output type i.e, and avoid all the 'oh-no I committed and broke the build' time wasting.

        if (IsConsoleApp)
        {
            Using(var host= new ServiceHost(typeof(myservice))
            {
               host.Open();
               etc....
            }
        }
        else
        {
            var servicesToRun = new ServiceBase[] {new myservice()};
            ServiceBase.Run(servicesToRun);
        }
SkeetJon
  • 1,491
  • 1
  • 19
  • 40

4 Answers4

4

Have you tried using the Environment.UserInteractive property in place of IsConsoleApp?

Bernard
  • 7,908
  • 2
  • 36
  • 33
2

Environment.UserInteractive does not detect if we have a console running, it only detects if the user can have some kind of interaction possibility to the running process. If you want to check if the application is a console application I found this working:

bool is_console_app = Console.OpenStandardInput(1) != Stream.Null;

All credits to Glen here.

Community
  • 1
  • 1
codingdave
  • 1,207
  • 16
  • 23
1

If you're all definitely not going to commit Debug builds.. then as long as there is a DEBUG constant defined under Project Properties > Build tab, you can try:

#if DEBUG
    RunAsConsoleApp();
#else
    RunNormally();
#endif

But then, this is still just as error prone if someone accidentally commits a Debug build.

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
  • as a side note this approach allows you to define your own statements http://msdn.microsoft.com/en-us/library/4y6tbswk(v=vs.80).aspx. Could also recommend looking into the configuration manager to see if you couldn't use your own configuration, like Debug Local and Debug Remote incase that's what you need. – Thomas Lindvall Oct 16 '12 at 13:00
0

You could setup a separate build configuration (e.g. Release - Service) and have a conditional compilation statement to switch between code blocks.

See here for more:

http://msdn.microsoft.com/en-us/library/aa691095(v=vs.71).aspx

So, in your Release - Service configuration, define a constant e.g. RELEASESERVICE. Then use this like:

#if RELEASESERVICE

    etc
Justin Harvey
  • 14,446
  • 2
  • 27
  • 30