views:

205

answers:

4

What i'd like to generate into method bodies:

private void SomeMethod()
{
Logger.Log("Entering SomeMethod.");

// do stuff here

Logger.Log("Exiting SomeMethod.")
}

Is there a tool which can generate that for me? If there isn't, and I'd like to implement one myself, then where do I start, which library should I look into for recognizing methods in c# source code? Simple regexes should be enough?

+1  A: 

Use AOP framework for that.

Take a look at Spring.NET or Castle Dynamic Proxy.

Code generation is generally not a good idea in most cases.

Krzysztof Koźmic
+4  A: 

You're definitely looking for PostSharp here - Aspect Oriented Programming (AOP) for .NET. It will allow you to add handlers that get executed before the start and after the end of arbitrary methods, so that you effectively only need define your logging code in one place.

Noldorin
+3  A: 

check out postsharp

http://www.postsharp.org/

this is an Aspect-orientated-programming framework. It will allow you to paint your methods with attributes that will run loggers, security checks etc.

Bluephlame
+1  A: 

If you're intent on code generation, then you should really do a full (and proper) parse of each code file.

Some googling of "C Sharp Parser" gives a couple of possible results: Here And Here

Then all you need to do is to traverse the parse tree, and add your method calls at the start and end of each method.

Nick