Friday, December 22, 2006

Logging Method Name in C#


logMessage("functionName", "something bad happened");

Yes the above works if IF *if* you remember to update "functionName". However, remembering to update the parameter after copying from another method is often not done. It is also a pain and not necessary. A little reflection easily solves this problem:

// start one up so that we don't get the current
// method but the one that called this one
StackFrame sf = new StackFrame(1, true);
System.Reflection.MethodBase mb = sf.GetMethod();
string methodName = mb != null ? mb.Name : "";
// fileName can be null, if unable to determine
string fileName = sf.GetFileName();
// we only want the filename not the complete path
if (fileName != null) fileName = fileName.Substring(fileName.LastIndexOf('\\') + 1);
int lineNumber = sf.GetFileLineNumber();

However the above does not work if you are using RichException or other proxies. So something a bit more complicated is needed:

private StackFrame GetCallingStackFrame()
{
// Determine the method that called the one that is calling this one.
// This is not just two up the Stack because of RichException support.
StackFrame sf = null;
// Start at 2. 1 for this one and another for the one above that.
StackTrace st = new StackTrace(2, true);
Type thisType = GetType();
foreach (StackFrame sfi in st.GetFrames())
{
// Find a calling method that is not part of this log class but is part
// of the same Namespace.
Type callType = sfi.GetMethod().DeclaringType;
if (callType != thisType &&
callType.Namespace == thisType.Namespace &&
!callType.IsInterface)
{
sf = sfi;
break;
}
}
return sf;
}

This can then be used like so:

StackFrame sf = GetCallingStackFrame();
if (sf != null) // if found add info to log message
{
System.Reflection.MethodBase mb = sf.GetMethod();
string methodName = mb != null ? mb.Name : "";
string fileName = sf.GetFileName();
if (fileName != null) fileName = fileName.Substring(fileName.LastIndexOf('\\') + 1);
int lineNumber = sf.GetFileLineNumber();

if (fileName != null)
{
strMsg = fileName + "(" + lineNumber + ") - " + methodName + " - " + strMsg;
}
else
{
strMsg = "unknown - " + methodName + " - " + strMsg;
}
}

Wednesday, December 20, 2006

WRT54GL with Thibor's HyperWRT QoS setup

I have been using Vonage's VOIP with my WRT54GL setup with Thibor's HyperWRT as outlined in my previous post. It has been working without any problems.

I realized that I never did post my QoS setup. So here it is:

Priority Name Information
Medium POP3 ---
Medium DNS ---
Medium SMTP ---
Medium Http ---
Medium SSH ---
High Skype ---
Medium Yahoo Messenger ---
Medium MSN Messenger ---
Medium AOL Messenger ---
Low Bittorrent ---
Low MSN File Transfers ---
Low FTP ---
Highest Vonage VT2442 MAC xx:xx:xx:xx:xx:xx
Low Port 8080 Port 8080 - 8080