views:

59

answers:

4

I would like to write a helper function which build the exception message to write to a log. The code look like:

if(IsWebApp)
{

      use HttpContext to get the Request Path and RawUrl }
else
{
      //else it a winform/console
      Use Assembly to get executing path.

}

+4  A: 

Use the HttpRuntime class:

if (!String.IsNullOrEmpty(HttpRuntime.AppDomainAppVirtualPath))
    //ASP.Net
else 
    //Non-ASP.Net
SLaks
+1 for pointing out to the rest of us that not everything in asp.net is a request thread - learn something new every day :)
Ray
A: 

You can check to see if HttpContext.Current != null.

Ryan Rinaldi
Wrong. This will be null in a non-request thread inside an ASP.Net AppDomain.
SLaks
A: 

How about

If (Not System.Web.HttpContext.Current Is Nothing) Then

End If

or

if(System.Web.HttpContext.Current != null){

}
Jeremy
Wrong. This will be null in a non-request thread inside an ASP.Net AppDomain. Also, VB.Net has an `IsNot` keyword. Finally, he's using C#.
SLaks
Never have so many been so wrong in so short a period of time! Thanks for setting us straight.I've been been programming in VB since VB5 so sometimes old habits die hard.That's why I included both.
Jeremy
+1  A: 

Just check for some object that only exists in a web application, like HttpRuntime.AppVirtualPath that SLaks suggested.

If it's a web application, you would still want to check if HttpContext.Current is null. If the exception occurs in code that is not run beacuse of a request, it doesn't have any context. The Session_OnEnd event for example runs when a server session is removed, so it doesn't have the context.

Guffa