views:

46

answers:

2

How do you tell if a .Net application is running as a Desktop application or running as a service?

We are trying to test our application with Fitnesse, which loads the app up as a service then makes calls into it.. but when a modal error box is pushed then it blows up.. I want to put a check to see if it is running in a service and if it is I want to throw an exception instead so our test will fail.

Is there a way to do this, other than passing a parameter to somewhere saying it was started by FitNesse?

A: 

I think this will work (no convenient place to test my air code):

// requires a 'using System.ServiceProcess' statement
type = Assembly.GetExecutingAssembly().EntryPoint.DeclaringType;
bool isRunningAsAService = type.IsSubclassOf(typeof(ServiceBase));
Jeff Sternal
+5  A: 

If you just want to determine whether or not to show a UI control, you can use:

if( Environment.UserInteractive )
{
    // Show UI
}
Todd Benning
+1 for a simpler solution than inspecting the assembly's type.
Jeff Sternal
Not sure what the difference is, but Form.ShowDialog uses SystemInformation.UserInteractive to perform the same check.
Tim Robinson
Judging by the Reflector output, two different people wrote Environment.UserInteractive and SystemInformation.UserInteractive using the same underlying API (GetUserObjectInformation) but without looking at the other's code.
Tim Robinson