0

I want to know what is the best way to detect from where a request has been sent (function calls)

The meaning: my project goes like this:

  • Engine
  • Web project (uses the engine)
  • Test Project-console project (uses the engine)

Now I want that some code will not be executed in the function when I am running the Test project.

I know that I can send a boolean parameter to detect this but I want to know if there is any why to detect if the request comes from web project or not...

Thanks!!

Orel.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Orel Gabay
  • 35
  • 6

4 Answers4

3

If the code being called should behave differently based on whether the call comes from the web project or the console project, the code shouldn't be in a shared library. It really belongs in the respective project.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
2

You can check that HttpContext.Current is not null. @JustinNiessner's advice is still applicable, however.

Matthew
  • 24,703
  • 9
  • 76
  • 110
  • This will work in most cases, but it will return incorrect result, if called from Application_Start method in global.asax or from new thread (and probably in few other cases too). – Ňuf Apr 18 '12 at 19:22
2

Compile your test project with TESTPROJECT symbol set and web project without this symbol. Then because of ConditionalAttribute, SetIsFromTest() method will be executed only if your code was called from test project (and therefore field IsFromTest will be set to true).

static class Class1
{
    static bool IsFromTest = false;

    static Class1()
    {
        SetIsFromTest();
    }

    [Conditional("TESTPROJECT")]
    public static void SetIsFromTest()
    {
        IsFromTest = true;
    }

}

Another option is to test name of calling assembly from your shared library.

if(System.Reflection.Assembly.GetCallingAssembly().FullName == "...")
Ňuf
  • 6,027
  • 2
  • 23
  • 26
0

You could use the StackFrame object to access stack trace and see what was the previous method calling yours. By using the method you could easily find the corresponding project. From older so post:

StackTrace trace = new StackTrace();
int caller = 1;
StackFrame frame = trace.GetFrame(caller);
MethodBase callerMethod = frame.GetMethod();

Though I should warn you that's the thing you should use only for fun/when debugging.

Community
  • 1
  • 1
Dmitry Reznik
  • 6,812
  • 2
  • 32
  • 27