Mark's Stuff

My Foray Into Weblogging. Using this to store interesting items for later review.

Wednesday, May 23, 2007

Get Calling MethodName

A question came up in last night VB.Net User Group about how to get the calling method when using a common exception handling method. I remembered I did it somewhere before, but could not even remember any part of it to look up at the time. So I post it here and will send it to Sam for posting to the SIG blog.

Basically, you instantiate a System.Diagnostics.StackTrace object with the StackTrace from the Exception object, then get the MethodName from that. Here is an example using a Console app:

Imports System.Diagnostics
Imports system.reflection
Module Module1
  Sub Main()
      Throw New ApplicationException("HAHA")
    Catch ex As Exception
    End Try
  End Sub

  Sub ProcessException(ByVal ex As Exception)
    Dim stackTrace As StackTrace = New StackTrace(ex)
    Dim stackFrame As StackFrame = stackTrace.GetFrame(0)
    Dim methodBase As MethodBase = stackFrame.GetMethod()
    Console.WriteLine("Error in Method {0} ", methodBase.Name)
  End Sub
End Module

Also, you can instantiate the StackTrace object without any arguments, and it loads the current method. You can then get the calling method (or the entire CallStack of methods) at any point in your code by walking through the StackFrames.

Imports System.Diagnostics
Imports system.reflection
Module Module1
  Sub Main()
  End Sub

  Sub A()
  End Sub

  Sub B()
  End Sub

  Sub C()
    Dim stackTrace As StackTrace = New StackTrace()
    Console.WriteLine("Called By Method {0} ", stackTrace.GetFrame(1).GetMethod().Name)
    Console.WriteLine("Listing the Entire Stack Trace:")
    For Each stackframe As StackFrame In stackTrace.GetFrames()
      Console.WriteLine("Method {0} ", stackframe.GetMethod().Name)
  End Sub
End Module

Labels: , ,

Friday, May 04, 2007

Coming soon: VBx!

Several bloggers and news articles on new version of Visual Basic that was referred to (but not announced) at MIX07 conference this week.

From Panopticon blog: What the heck is "VBx"?
...though, I can now take a bit of the wraps off. "VBx" is our current (subject to change) codename for the next major version of Visual Basic. (The "x" is supposed to signify the Roman numeral X, or 10, since the next major version of Visual Basic is going to be 10.0.

From The Visual Basic Team Blog:
What do the announcements at Mix mean for the Visual Basic developer?
VB on Silverlight – In short, this means that you can now use Visual Basic as the code-behind for whiz-bang rich interactive applications that run on Windows or the Mac and can run in IE, Firefox, and Safari.