Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect .Net application type?

I have a library that needs to respond to exceptions in different ways depending on whether it is running in a Console app, WinForms, AspNet or Windows Service. I have experimented with looking at various properties in the System.Windows.Forms and System.Web namespaces, but I can't find a reliable way of detecting exactly which kind of application is hosting my library. Has anyone been here before? Does anyone have a reliable solution?

like image 741
open-collar Avatar asked Dec 07 '22 07:12

open-collar


2 Answers

If I understand what you are seeking correctly, you have a single library that does error handling, but you want the library to know if the source is web, console, winforms, etc.?

You might be able to utilize a property in the library, say an enumeration, that tracks what the consuming applications type is. For example...

ErrorLogger error = new ErrorLogger(ErrorLoggerAppType.WinForm);
ErrorLogger error = new ErrorLogger(ErrorLoggerAppType.Web);
ErrorLogger error = new ErrorLogger(ErrorLoggerAppType.Console);

EDIT
From Samir in comments...
In addition you could always just have a class for each type of application implement the same interface within your error logger library.

For example in a Web Application you would utilize:

WebErrorLogger error = new WebErrorLogger();
like image 50
RSolberg Avatar answered Dec 23 '22 18:12

RSolberg


I'd question your design before going down this route but I thought this was an interesting challenge and wanted to see if I could find anyways.

ASP.Net : Check HttpContext.Current is not null. You could also look at System.Web.Hosting.ApplicationManager.GetApplicationManager(), but I'm not sure how this will behave outside of Asp.net

Window Forms: You could try and use System.Windows.Forms.Application.OpenForms, this will return any open forms. An assumption is being made that a windows form application would never not have any forms. Also a console application can also start a win form.

Service: Not sure on this but I'm wondering if you can check the name of the process. There must also be a windows API since the task manager shows when a process is a service (At least on Vista it does)

like image 42
JoshBerke Avatar answered Dec 23 '22 19:12

JoshBerke