Question

How can I tell if a method I am writing in managed code is being call from an interactive app vs a windows service?

Was it helpful?

Solution 2

I think I may have figured this out (at least this works for my needs--your mileage may vary depending on what you are trying to do). There's a property hanging off of the Environment object called "UserInteractive". It tells you whether or not you are running in a context with access to the desktop.

OTHER TIPS

What part of a Windows Service is it that you want to know about? Or what part of an interactive app do you not want to know about? What actually matters to you?


Any time I hear a request like this, it is almost always a mistake in design. I would suggest a few answers:

  1. Let the caller tell you which formatter to use, or
  2. Place the name of the formatter class into a configuration file. Have all the formatters implement the same interface. At runtime, the first time you need a formatter, create an instance of the one specified in the config file, and call it through the common interface.
  3. Don't reinvent the wheel. Use the classes in System.Diagnostics, which, in fact, configure a lot like my #2.

It is almost always a mistake for code to be sensitive to the context it was called in.

There are at least 2 ways to do this:

  1. "System.Reflection.Assembly.GetCallingAssembly().FullName" will return the name of the assembly that is calling your code.
  2. "Environment.StackTrace" will return the full stack trace for who is calling your code. You should see your calling method name in the string.

You can define two different logger: one for interactive apps and one for windows service. and let client choose which logger he wants to use using a config file. You can also have a default logger if clients chooses a wrong logger or forgets to configure. I think it should be a better idea to have functionality like logging and formatting message to be configurable.

Don't know if there is a builtin possibility, but have a look at the System.Diagnostics.Process class. It has, among other things, a GetService() method, maybe that will help you. If that fails, there is the StartInfo member which may contain helpful information.

If you don't mind using PInvoke, you can get the parent process of the current process. If it is running under the account NT AUTHORITY\SYSTEM and it's name is service.exe, the current process is (most probably) a service.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top