Tuesday, April 10, 2007

Finding calling method using reflection

Add namespaces:

using System.Diagnostics;
using System.Reflection;

There's probably a more elegant way to do this, but I wanted to find out which method had called the current method for logging. For example, I am calling a method in my DAO and i want to know which method from my Service layer called it...the Stack trace caught during an exception cuts me off and I could only find snippets of getting the current method name for logging purposes.

So, here's a method I drummed up to get the name of the calling-calling method:



private string GetPreviousMethodName(MethodBase currentMethod)

{

string methodName = string.Empty;

try

{

StackTrace sTrace = new System.Diagnostics.StackTrace(true);

//loop through all the stack frames

for (Int32 frameCount = 0; frameCount <>

{

StackFrame sFrame = sTrace.GetFrame(frameCount);

System.Reflection.MethodBase thisMethod = sFrame.GetMethod();

//If the Type in the frame is the type that is being searched

if (thisMethod == currentMethod)

{

if (frameCount + 1 <= sTrace.FrameCount)

{

StackFrame prevFrame = sTrace.GetFrame(frameCount + 1);

System.Reflection.MethodBase prevMethod = prevFrame.GetMethod();

methodName = prevMethod.ReflectedType + "." + prevMethod.Name;

//get the method and its parameter info

//then exit out of the for loop

}

break;

}

}

}

catch (Exception)

{

//swallow all exceptions this may encounter...this is informational and mroe for convenience anyways

return string.Empty;

}

return methodName;

}

1 comment:

Anonymous said...

am not getting anything from this article. so please do some more description........