Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use "HostingEnvironment" to determine if it is Web or Win

In my library I use HostingEnvironment.MapPath for my web application. But I need to call the same function from a windows forms and a windows service.

In Windows application HostingEnvironment.ApplicationID is null, in Web application HostingEnvironment.ApplicationID is something like "99xxx999".

Can I use "HostingEnvironment" to determine if it is Web or Win?

Is it safe to use this?

if (HostingEnvironment.ApplicationID == null)
{
    //called from windows application
}
else
{
    //called from web application
}
like image 462
adyusuf Avatar asked Mar 26 '12 12:03

adyusuf


2 Answers

A more standard way to do this it to use the HttpContext.Current method:

if (HttpContext.Current == null)
{
    // called from windows application
}
else
{
    // called from web application
}

Of course using HttpContext related stuff in non-HTTP related layers of your application is a design smell. It not only smells => it stinks.

A more standard way is to have your code be passed as argument directly the filename as argument. When called from within a web application you would pass Server.MapPath("~/foo.txt") and when you call it from within a Windows Application you would directly pass the file name relative to the current executable.

This way your code doesn't need to depend on any HTTP specific stuff and can be happily reused in any platform. It is the responsibility of the caller to pass it the filename that your code needs to process. The way this filename is determined is platform specific. Not your code responsibility. Don't mix responsibilities.

like image 131
Darin Dimitrov Avatar answered Nov 07 '22 23:11

Darin Dimitrov


Read the msdn documentation here: http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.applicationid(v=vs.100).aspx

It states:

"The application must be running with AspNetHostingPermissionLevel set to high trust to access the ApplicationId property"

I hope you've got your answer.

like image 3
Mian Zeshan Farooqi Avatar answered Nov 07 '22 22:11

Mian Zeshan Farooqi