473,325 Members | 2,774 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

Get Function name

Is it possible for a c# function to get it's own name ? We have LOTS of
logging calls for which the programmer has to manually add the name of the
function as part of the output, often people copy code from one area to
another and then forget to update the name. It would be really slick if we
were able to programmatically get the function name without a huge
processing overhead.

Is this possible ? Is it possible to get a calling functions name ? Any
samples anywhere ?
Nov 15 '05 #1
7 21010
Yes, this is!

Here is an snippet of one of the routine I use within my custom exception
(It contains more, but was simplified for clarity).
Playing with the stackFrameLevel, you can determine which routine within the
stack you want to get information from.

Hope this help
José
protected string BuildMsg( string Msg,
Status.Stat MsgStatus,
Severity.Level SeverLevel,
short stackFrameLevel)
{
int nDebLocation = 0;
try
{
// Convert severity to 1 char
string strCurrSeverity = Severity.ToShortString(SeverLevel);

// Get stack information (FileName, Method, Line#)
StackFrame stFrame = new StackFrame(stackFrameLevel, true);

}

string strFileName;
if ( stFrame.GetFileName() != null)
strFileName =
stFrame.GetFileName().Substring(stFrame.GetFileNam e().LastIndexOf(@"\")+1);
else
strFileName = "Unknown???";
// Build information
string strFullInfo = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.ff",
null) +
" [" + processInfo.MainModule.ModuleName + " - " +
strFileName + " - " + stFrame.GetMethod().Name +
"() - Line:" + (stFrame.GetFileLineNumber()).ToString() + "] " +
Environment.NewLine +
" [" + strCurrSeverity + ":" + ((int)MsgStatus).ToString("D5")
+ "] " + Msg + Environment.NewLine;
return strFullInfo;
}
catch (Exception ex)
{
return "Unable to build msg for logger. Err: " + ex.ToString() + ".
Dbg: " +
nDebLocation +
". Make sure the .PDB file has been copied in the Binary directory!";
}
}

You have to play with StackFrame class. It provides a whole lot of
information you can extract for your logging purpose.
"Mike Oliszewski" <mi*************@faxback.com> a écrit dans le message de
news:%2****************@TK2MSFTNGP09.phx.gbl...
Is it possible for a c# function to get it's own name ? We have LOTS of
logging calls for which the programmer has to manually add the name of the
function as part of the output, often people copy code from one area to
another and then forget to update the name. It would be really slick if we were able to programmatically get the function name without a huge
processing overhead.

Is this possible ? Is it possible to get a calling functions name ? Any
samples anywhere ?

Nov 15 '05 #2
Awsome, thank you!

"José Joye" <jose.joye@__No_SPam__bluewin__maPS_oN__.ch> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
Yes, this is!

Here is an snippet of one of the routine I use within my custom exception
(It contains more, but was simplified for clarity).
Playing with the stackFrameLevel, you can determine which routine within the stack you want to get information from.

Hope this help
José
protected string BuildMsg( string Msg,
Status.Stat MsgStatus,
Severity.Level SeverLevel,
short stackFrameLevel)
{
int nDebLocation = 0;
try
{
// Convert severity to 1 char
string strCurrSeverity = Severity.ToShortString(SeverLevel);

// Get stack information (FileName, Method, Line#)
StackFrame stFrame = new StackFrame(stackFrameLevel, true);

}

string strFileName;
if ( stFrame.GetFileName() != null)
strFileName =
stFrame.GetFileName().Substring(stFrame.GetFileNam e().LastIndexOf(@"\")+1); else
strFileName = "Unknown???";
// Build information
string strFullInfo = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.ff",
null) +
" [" + processInfo.MainModule.ModuleName + " - " +
strFileName + " - " + stFrame.GetMethod().Name +
"() - Line:" + (stFrame.GetFileLineNumber()).ToString() + "] " + Environment.NewLine +
" [" + strCurrSeverity + ":" + ((int)MsgStatus).ToString("D5") + "] " + Msg + Environment.NewLine;
return strFullInfo;
}
catch (Exception ex)
{
return "Unable to build msg for logger. Err: " + ex.ToString() + ".
Dbg: " +
nDebLocation +
". Make sure the .PDB file has been copied in the Binary directory!";
}
}

You have to play with StackFrame class. It provides a whole lot of
information you can extract for your logging purpose.
"Mike Oliszewski" <mi*************@faxback.com> a écrit dans le message de
news:%2****************@TK2MSFTNGP09.phx.gbl...
Is it possible for a c# function to get it's own name ? We have LOTS of
logging calls for which the programmer has to manually add the name of the function as part of the output, often people copy code from one area to
another and then forget to update the name. It would be really slick if

we
were able to programmatically get the function name without a huge
processing overhead.

Is this possible ? Is it possible to get a calling functions name ? Any samples anywhere ?


Nov 15 '05 #3
In article <#D**************@TK2MSFTNGP09.phx.gbl>,
mi*************@faxback.com says...

You can use MethodBase.GetCurrentMethod().Name within the function,

Another more flexible approach can be found at

http://msdn.microsoft.com/msdnmag/is...ET/default.asp
x

Nov 15 '05 #4

Hi Mike,

Just as José and Robert suggested, there are 2 ways to get the current
method's name: Use StackFrame class and Use Reflection.
But StackFrame retrieves the file, method name, line number, and column
information from the debug symbols which was stored in .PDB file.
So StackFrame will be most informative with Debug build configurations. By
default, Debug builds include debug symbols, while Release builds do not.
If you still want to use StackFrame in Realse configuration, you need to
change the default build configuration for realse:
Project->Project properties, then chose configuration:Realse, select
"Build" tab page, change "Generate Debugging Information" to true.

I think the most suitable solution is use Reflection. Reflection can be
used to runtime dynamic get the assembly information which was stored in
assembly manifest.
So MethodBase.GetCurrentMethod().Name is an elegant way.

Hope this helps,

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #5

Btw: I think there may be something wrong with Robert's article url, I
think the correct address is:
http://msdn.microsoft.com/msdnmag/is...ContextsinNET/

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #6
When I designed my Custom Exception, I decided to go with the StackFrame
because my goal was to hide all repetiting tasks within the Exception class.
The idea was to be able to throw exception or trace messages giving the
minimal amount of parameters. In fact, I just wanted to pass a string
explaning the problem and an ID of the problem.
Any other information is retrieved from within my custom exception class.
This includes Method name, file name, process name, line # within the file,
VSS file version and other.
In that sense, the easiest way was to use the StackFrame. This allowed me to
walk it and extract information about the correct caller.

José

""Jeffrey Tan[MSFT]"" <v-*****@online.microsoft.com> wrote in message
news:jP**************@cpmsftngxa07.phx.gbl...

Hi Mike,

Just as José and Robert suggested, there are 2 ways to get the current
method's name: Use StackFrame class and Use Reflection.
But StackFrame retrieves the file, method name, line number, and column
information from the debug symbols which was stored in .PDB file.
So StackFrame will be most informative with Debug build configurations. By
default, Debug builds include debug symbols, while Release builds do not.
If you still want to use StackFrame in Realse configuration, you need to
change the default build configuration for realse:
Project->Project properties, then chose configuration:Realse, select
"Build" tab page, change "Generate Debugging Information" to true.

I think the most suitable solution is use Reflection. Reflection can be
used to runtime dynamic get the assembly information which was stored in
assembly manifest.
So MethodBase.GetCurrentMethod().Name is an elegant way.

Hope this helps,

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #7

Hi Jose,

Yes, you are right, StackFrame is more suitable for retriving current
executive statck information.
But Mike only want to get the current function's name, which I think
Reflection is a more elegant way. In any case, thanks for your information
about StackFrame.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Nick Coghlan | last post by:
Time for another random syntax idea. . . So, I was tinkering in the interactive interpreter, and came up with the following one-size-fits-most default argument hack: Py> x = 1 Py> def...
6
by: marcelf3 | last post by:
Hello.. This page opens a window with some information, but everytime the user changes a field in the parent window, the child window needs to be closed. These 2 functions were supposed to do the...
12
by: Susan Cranford | last post by:
Please forgive, I have looked at so much info I can't figure out how to put it together even though I know it must be fairly simple. I have an array of input text boxes (txtDOBn) where n is...
6
by: Bill Rubin | last post by:
The following code snippet shows that VC++ 7.1 correctly compiles a static member function invocation from an Unrelated class, since this static member function is public. I expected to compile the...
4
by: poojak | last post by:
I have write two different js function in a external file. one function write a table (I used innerHTML for this.) and another function is for showing/ hideing some rows depending on radio button...
2
by: ELINTPimp | last post by:
Hello all, Have a really interesting problem (at least to me) with my upload_file() function. I have it working now, with a bit of a work around, but would like to know what everyone thinks in...
6
by: Maguila007 | last post by:
Hi Is there any way to obtain the name of the function, inside the function which was called. Ex: function something() { alert( "The name of the function you invoke is " ......should
2
by: shivendravikramsingh | last post by:
hi friends, i m using a ajax function for retrieving some values from a database table,and display the values in required field,my prob is that the ajax function i m using is working f9 once,but if...
2
by: WGW | last post by:
Hello all, I need another set of eyes cause it just isn't working, no matter how identical I make it. The initRotator function works when called by itself, but when adding another function, only the...
5
by: mad.scientist.jr | last post by:
According to http://www.quirksmode.org/js/forms.html you need to look through a radio button's members to find the value: I tried writing a reusable function to return the value, see code at:...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.