473,425 Members | 1,791 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,425 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 21012
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:...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.