0

I have a scenario where an assembly (i.e. the entry method inside it) can be called both via a GUI application and an IIS hosted application. I want to perform some action depending upon which process is calling it (like if GUI is calling it, some other forms will open while in case of the IIS application, this step will be skipped).

So, is there any way I can detect which process (I know the exact name of the process, in both of the cases) is calling the assembly inside the entry method?

I want to perform something like below

        if (processName == "wpw3.exe")
        {
            LogWindow log = new LogWindow();
            log.Show();
        }
        if (processName == "GUIApplication.exe")
        {
            WriteToLogFile(LogData);
        }
xmojmr
  • 8,073
  • 5
  • 31
  • 54
Atanu Roy
  • 1,384
  • 2
  • 17
  • 29
  • Maybee is this the solution you are search http://stackoverflow.com/questions/394816/how-to-get-parent-process-in-net-in-managed-way – Tom Baires Jun 29 '16 at 05:30
  • 1
    To build logic depending on process name smells to me. Why don't implement your code in the way, that allows some configuration (either programmatically or declarative, using config file), and skips/adds some dependencies? What if host process name will change? – Dennis Jun 29 '16 at 05:31
  • @Dennis : Configuration is not a good idea in this case I think, because both the process can access the assembly together and it is not configurable. – Atanu Roy Jun 29 '16 at 05:34
  • @AtanuRoy: so, make it configurable/extensible. What's the problem? :) Actually, you're building an assembly, which could be executed in web application, and has dependency on some `System.Windows.Forms` or similar. It's not a way to go. – Dennis Jun 29 '16 at 05:36

1 Answers1

1

It is easy. Just use StackTrace.

var stackTrace = new StackTrace();

var assemblies = stackTrace.GetFrames().Select(t =>
{
    var method = t.GetMethod();
    return method.DeclaringType.Assembly;
});

foreach (var assembly in assemblies)
{
    Console.WriteLine(assembly.FullName);
}

Not only assemblies, you can also get the file names, lines etc.

Tommy
  • 3,044
  • 1
  • 14
  • 13
  • This doesn't work when you're trying to get the actual calling assembly in IIS. It just returns mscorlib and System.Web rather than the actual calling app. – Underground Sep 27 '18 at 21:45