How to see a delegate's source code or encapsulating method when debugging? - c#

So in JavaScript, you can call toString() on a function to return it's source code. However, no such construct exists for C# delegates.
Let's say I have this code sample here:
void DoThing()
{
Console.WriteLine("I did a thing");
}
void Execute(Action act)
{
act();
}
public static int Main(string[] args)
{
Execute(DoThing);
Execute(() => Console.WriteLine("llama lambda"));
}
If I debug this code in Visual Studio 2019, and put a breakpoint on Execute, I can look at the properties of act.
For the first call with DoThing, Visual Studio can at least give me the name of the method and it's return type (Void DoThing()), but not the source code. If I have multiple DoThings in my source code, this will not be very helpful at all.
But for the lambda, I get no useful info in the debugger ({Method = {Void <Process>b__11_0()}}).
Now, of course in this small example code, it is pretty easy to find the functions by just retracing the call stack, but in some cases, this is a very long and arduous endeavour, especially when it needs to be done multiple times.
I searched around on google and I couldn't find a simple answer to this question, or even find anywhere where this question was asked:
Is there any way to find the source code of a delegate in C# when using the Visual Studio debugger (without just retracing the call stack)?
If yes, how?
And if no, why?

Related

Single line debug breakpoint assert and break

I have to use my own 'DebugBreak' and 'DebugAssert' methods in order to have a single line properly-working break or assert:
[System.Diagnostics.Conditional("DEBUG")] //only relevant while coding
[System.Diagnostics.DebuggerHidden] //force VS to stop on the call to this method instead of inside this method
public static void DebugBreak()
{
System.Diagnostics.Debugger.Break();
}
[System.Diagnostics.Conditional("DEBUG")] //only relevant while coding
[System.Diagnostics.DebuggerHidden] //force VS to stop on the call to this method instead of inside this method
public static void DebugAssert(bool conditionExpected)
{
if (!conditionExpected)
System.Diagnostics.Debugger.Break();
}
These methods work perfectly fine, but since this is so common there must be methods that do this in .NET? I want the VS UI to stop exactly where a condition is reached (a call stack is useless for this purpose) and I only want this to happen while debugging - I have no interest in showing obscure messages to the user. I also don't want "#if DEBUG" littered all over the place.
Edit: There seems to be massive confusion about what I want - I suggest trying one of my methods in a test project to see the exact behavior I'm talking about.
Edit: Please don't vote to close if you don't understand the question.
Edit: It appears not to be possible - looking at the answer here where the same kludgy use of a wrapper method is required:
Can .NET source code hard-code a debugging breakpoint?

How to accurately determine whether a method was called by an async method

I am trying to determine whether a particular method was called by an async method.
This answer (which was, granted, describing a somewhat different set of circumstances) suggested using CallerMemberName attribute to find the name of the calling method. Indeed, the signature of my method looks like this:
public void LogCallAsync([CallerMemberName] string caller = "", params object[] parameters)
which works great if you're doing something like
logger.LogCallAsync();
It would also work great if you have a fixed number of parameters. However, given that the next parameter is of type params object[], obviously that isn't the case, so if you try to do something like
logger.LogCallAsync(someObject, someOtherObject)
I'll get a compile exception because someObject isn't a string. I tried the following as a workaround:
logger.LogCallAsync(nameof(CurrentMethod), someObject, someOtherObject);
which is pretty ugly. Actually, I'd prefer it if I didn't have to do that, so if anyone has any suggestions in that regard that would be great, but on to my main question: is there some way of preventing people from calling this improperly? In particular, I'd like to know if "CurrentMethod" is, in fact, an actual async method.
If I look at an instance of StackTrace, for example, is there a reliable way of telling based on that? This article (if I'm reading it correctly) seems to imply that my current solution (see my code sample below) is correct, but it's not really an "authoritative" source and it's about 5 years old at this point.
Let me show a code sample to illustrate how I'm trying to solve this right now:
private static void GetCaller()
{
StackTrace stack = new StackTrace();
MethodBase method = stack.GetFrame(1).GetMethod();
Trace.TraceInformation("Method name: " + method.Name);
}
// Some arbitrary async method
private static async Task UseReflection()
{
// Do some kind of work
await Task.Delay(100);
// Figure out who called this method in the first place
// I want some way of figuring out that the UseReflection method is async
GetCaller();
}
static void Main(string[] args)
{
// AsyncPump is basically to make Async work more like it does on a UI application
// See this link: https://blogs.msdn.microsoft.com/pfxteam/2012/01/20/await-synchronizationcontext-and-console-apps/
AsyncPump.Run(async () =>
{
// In this case, it identifies the calling method as "MoveNext"
// Question: in cases like this, will this always be the case (i.e. will it always be MoveNext)?
await UseReflection();
});
// In this case, it identifies the calling method as "Main"
GetCaller();
}
I'm using Visual Studio 2015 and .NET 4.6 for what it's worth. My question, then, is: can I guarantee that code will always work in a way that's similar to what I have above? For example, if GetCaller was called by an async method, will I always get MoveNext off the stack trace? Also, does anyone know if Microsoft documents that somewhere (in case I'm asked to prove that my solution will work)?
EDIT: The primary purpose here is to log the name and parameters of the method that called the logger. If the caller is not async, then I know that the following code
StackTrace stack = new StackTrace();
MethodBase method = stack.GetFrame(1).GetMethod();
will give me information on who the caller is. However, that obviously won't work at all if the caller is async. In that case I currently do the following:
StackTrace st = new StackTrace();
StackFrame callFrame = st.GetFrames().ToList().FirstOrDefault(x => x.GetMethod().Name == caller);
where caller is the name of the method call that I passed, like in the signature I listed above:
public void LogCallAsync([CallerMemberName] string caller = "", params object[] parameters)
Obviously, this is less efficient. I could, in theory, just do this for every logger call, but it would be a little bit of a performance hit and I'd rather avoid that if possible.
Yes, all async methods end up in MoveNext.

Visual studio detecting unused return

I've just spent the best part of an hour trying to work out why some code appered to not be working. I was getting no compilation errors of any sort, and have tracked the bug down to calling a function and doing nothing with the return value. The code was a little more involved than the sample below as Class1 is immutable, but it still demonstrates the issue:
public class Class1
{
private int MyVal = 0;
public int GetMyVal()
{
return MyVal;
}
}
public void Tester(){
Class1 Instance = new Class1();
Instance.GetMyVal();
}
The function call to GetMyVal() is as technically useless as it is technically correct. As I say the code was more involved, but this is the core issue.
I'm slightly surprised that VS 2013 (For Web) fails to highlight the issue as clearly nothing is gained from calling GetMyVal. Is there some switches I'm missing to detect this sort of thing or is this beyond the scope of what Visual Studio can accomplish?
I doubt there is/are (m)any editors out there can can give you what you want.
VS will tell you if you have a variable you're not referencing (at least for Pro and Ultimate. Haven't used Web for 2012/2013). However within the scope of Class1, private int MyVal is being referenced within your GetMyVal function so it will not be marked as an unreferenced property.
It can often catch useless pieces of code but I don't see how you expect it to say that your previously initialized and referenced variable is not meaningful. It has no way of knowing that the property in Class1 isn't something you want to use/modify later.
Do correct me if I am misunderstanding your question
Side note: If you can figure out a way to make it do what you're after,might I suggest writing a plugin? Bear in mind that existing plugins like Resharper and FXCop add a world of functionality

C# Extension Method Oddity during Unit Test

Using Visual Studio 2008 / C# / VS Unit Testing.
I have a very straightforward extension method, that will tell me if an object is of a specific type:
public static bool IsTypeOf<T, O>(this T item, O other)
{
if (!(item.GetType() is O))
return false;
else
return true;
}
It would be called like:
Hashtable myHash = new Hashtable();
bool out = myHash.IsTypeOf(typeof(Hashtable));
The method works just fine when I run the code in debug mode or if I debug my unit tests. However, the minute I just run all the unit tests in context, I mysteriously get a MissingMethodException for this method. Strangely, another extension method in the same class has no problems.
I am leaning towards the problem being something other than the extension method itself. I have tried deleting temporary files, closing/reopening/clean/rebuilding the solution, etc. So far nothing has worked.
Has anyone encountered this anywhere?
Edit: This is a simplified example of the code. Basically, it is the smallest reproducible example that I was able to create without the baggage of the surrounding code. This individual method also throws the MissingMethodException in isolation when put into a unit test, like above. The code in question does not complete the task at hand, like Jon has mentioned, it is more the source of the exception that I am currently concerned with.
Solution: I tried many different things, agreeing with Marc's line of thinking about it being a reference issue. Removing the references, cleaning/rebuilding, restarting Visual Studio did not work. Ultimately, I ended up searching my hard drive for the compiled DLL and removed it from everywhere that did not make sense. Once removing all instances, except the ones in the TestResults folder, I was able to rebuild and rerun the unit tests successfully.
As to the content of the method, it was in unit testing that I discovered the issue and was never able to get the concept working. Since O is a RunTimeType, I do not seem to have much access to it, and had tried to use IsAssignableFrom() to get the function returning correctly. At this time, this function has been removed from my validation methods to be revisited at another time. However, prior to removing this, I was still getting the original issue that started this post with numerous other methods.
Post-solution: The actual method was not as complex as I was making it out to be. Here is the actual working method:
public static void IsTypeOf<T>(this T item, Type type)
{
if (!(type.IsAssignableFrom(item.GetType())))
throw new ArgumentException("Invalid object type");
}
and the unit test to verify it:
[TestMethod]
public void IsTypeOfTest()
{
Hashtable myTable = new Hashtable();
myTable.IsTypeOf(typeof(Hashtable));
try
{
myTable.IsTypeOf(typeof(System.String));
Assert.Fail("Type comparison should fail.");
}
catch (ArgumentException)
{ }
}
Usually, a MissingMethodException means that you are loading a different version of the dll to the one you referenced during build, and the actual dll you are loading (at run-time) doesn't have the method the compiler found (at compile-time).
Check that you haven't somehow got various versions of the dll referenced by different projects. It could be that when you run it in debug mode, some other code makes the correct dll load first, but when running in-context, this other code doesn't run - so the incorrect version loads instead.
This would apply doubly if the failing method was added recently, so might not be in the older version referenced.
If you are using full assembly versioning, you might be able to watch the debug output to see exactly which assembly loads.
I am speculating here.
Put a constraint on the method to see if that helps
Pseudocode
public static bool IsTypeOf(this T item, O other) Where T: object, O: Type
{
}
Also, which class is this method in?
EDIT: Is this class, part of the assembly which is being tested?

break whenever a file (or class) is entered

In Visual Studio, is there any way to make the debugger break whenever a certain file (or class) is entered? Please don't answer "just set a breakpoint at the beginning of every method" :)
I am using C#.
Macros can be your friend. Here is a macro that will add a breakpoint to every method in the current class (put the cursor somewhere in the class before running it).
Public Module ClassBreak
Public Sub BreakOnAnyMember()
Dim debugger As EnvDTE.Debugger = DTE.Debugger
Dim sel As EnvDTE.TextSelection = DTE.ActiveDocument.Selection
Dim editPoint As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint()
Dim classElem As EnvDTE.CodeElement = editPoint.CodeElement(vsCMElement.vsCMElementClass)
If Not classElem Is Nothing Then
For Each member As EnvDTE.CodeElement In classElem.Children
If member.Kind = vsCMElement.vsCMElementFunction Then
debugger.Breakpoints.Add(member.FullName)
End If
Next
End If
End Sub
End Module
Edit: Updated to add breakpoint by function name, rather than file/line number. It 'feels' better and will be easier to recognise in the breakpoints window.
You could start by introducing some sort of Aspect-Oriented Programming - see for instance
this explanation - and then put a breakpoint in the single OnEnter method.
Depending on which AOP framework you choose, it'd require a little decoration in your code and introduce a little overhead (that you can remove later) but at least you won't need to set breakpoints everywhere. In some frameworks you might even be able to introduce it with no code change at all, just an XML file on the side?
Maybe you could use an AOP framework such as PostSharp to break into the debugger whenever a method is entered. Have a look at the very short tutorial on this page for an example, how you can log/trace whenever a method is entered.
Instead of logging, in your case you could put the Debugger.Break() statement into the OnEntry-handler. Although, the debugger would not stop in your methods, but in the OnEntry-handler (so I'm not sure if this really helps).
Here's a very basic sample:
The aspect class defines an OnEntry handler, which calls Debugger.Break():
[Serializable]
public sealed class DebugBreakAttribute : PostSharp.Laos.OnMethodBoundaryAspect
{
public DebugBreakAttribute() {}
public DebugBreakAttribute(string category) {}
public string Category { get { return "DebugBreak"; } }
public override void OnEntry(PostSharp.Laos.MethodExecutionEventArgs eventArgs)
{
base.OnEntry(eventArgs);
// debugger will break here. Press F10 to continue to the "real" method
System.Diagnostics.Debugger.Break();
}
}
I can then apply this aspect to my class, where I want the debugger to break whenever a method is called:
[DebugBreak("DebugBreak")]
public class MyClass
{
public MyClass()
{
// ...
}
public void Test()
{
// ...
}
}
Now if I build and run the application, the debugger will stop in the OnEntry() handler whenever one of the methods of MyClass is called. All I have to do then, is to press F10, and I'm in the method of MyClass.
Well, as everyone is saying, it involves setting a breakpoint at the beginning of every method. But you're not seeing the bigger picture.
For this to work at all, a breakpoint has to be set at the beginning of every method. Whether you do it manually, or the debugger does it automatically, those breakpoints must be set for this to work.
So, the question really becomes, "If there enough of a need for this functionality, that it is worth building into the debugger an automatic means of setting all those breakpoints?". And the answer is, "Not Really".
This feature is implemented in VS for native C++. crtl-B and specify the 'function' as "Classname::*", this sets a breakpoint at the beginning of every method on the class. The breakpoints set are grouped together in the breakpoints window (ctrl-alt-B) so they can be enabled, disabled, and removed as a group.
Sadly the macro is likely the best bet for managed code.
This works fine in WinDbg:
bm exename!CSomeClass::*
(Just to clarify, the above line sets a breakpoint on all functions in the class, just like the OP is asking for, without resorting to CRT hacking or macro silliness)
You could write a Visual Studio macro that obtained a list of all of the class methods (say, by reading the .map file produced alongside the executable and searching it for the proper symbol names (and then demangling those names)), and then used Breakpoints.add() to programmatically add breakpoints to those functions.
System.Diagnostics.Debugger.Break();
(at the beginning of every method)
No. Or rather, yes, but it involves setting a breakpoint at the beginning of every method.
Use Debugger.Break(); (from the System.Diagnostics namespace)
Put it at the top of each function you wish to have "broken"
void MyFunction()
{
Debugger.Break();
Console.WriteLine("More stuff...");
}
Isn't the simplest method to get closest to this to simply set a break point in the constructor (assuming you have only one - or each of them in the case of multiple constructors) ?
This will break into debugging when the class is first instantiated in the case of a non-static constructor, and in the case of a static constructor/class, you'll break into debugging as soon as Visual Studio decides to initialize your class.
This certainly prevents you from having to set a breakpoint in every method within the class.
Of course, you won't continue to break into debugging on subsequent re-entry to the class's code (assuming you're using the same instantiated object the next time around), however, if you re-instantiate a new object each time from within the calling code, you could simulate this.
However, in conventional terms, there's no simple way to set a single break point in one place (for example) and have it break into debugging every time a class's code (from whichever method) is entered (as far as I know).
Assuming that you're only interested in public methods i.e. when the class methods are called "from outside", I will plug Design by Contract once more.
You can get into the habit of writing your public functions like this:
public int Whatever(int blah, bool duh)
{
// INVARIANT (i)
// PRECONDITION CHECK (ii)
// BODY (iii)
// POSTCONDITION CHECK (iv)
// INVARIANT (v)
}
Then you can use the Invariant() function that you will call in (i) and set a breakpoint in it. Then inspect the call stack to know where you're coming from. Of course you will call it in (v), too; if you're really interested in only entry points, you could use a helper function to call Invariant from (i) and another one from (v).
Of course this is extra code but
It's useful code anyway, and the structure is boilerplate if you use Design by Contract.
Sometimes you want breakpoints to investigate some incorrect behaviour eg invalid object state, in that case invariants might be priceless.
For an object which is always valid, the Invariant() function just has a body that returns true. You can still put a breakpoint there.
It's just an idea, it admittedly has a footstep, so just consider it and use it if you like it.
Joel, the answer seems to be "no". There isn't a way without a breakpoint at every method.
To remove the breakpoints set by the accepted answer add another macro with the following code
Public Sub RemoveBreakOnAnyMember()
Dim debugger As EnvDTE.Debugger = DTE.Debugger
Dim bps As Breakpoints
bps = debugger.Breakpoints
If (bps.Count > 0) Then
Dim bp As Breakpoint
For Each bp In bps
Dim split As String() = bp.File.Split(New [Char]() {"\"c})
If (split.Length > 0) Then
Dim strName = split(split.Length - 1)
If (strName.Equals(DTE.ActiveDocument.Name)) Then
bp.Delete()
End If
End If
Next
End If
End Sub
Not that I'm aware of. The best you can do is to put a breakpoint in every method in the file or class. What are you trying to do? Are you trying to figure out what method is causing something to change? If so, perhaps a data breakpoint will be more appropriate.
You could write a wrapper method through which you make EVERY call in your app. Then you set a breakpoint in that single method. But... you'd be crazy to do such a thing.
You could put a memory break point on this, and set it to on read. I think there should be a read most of the time you call a member function. I'm not sure about static functions.
you can use the following macro:
#ifdef _DEBUG
#define DEBUG_METHOD(x) x DebugBreak();
#else
#define DEBUG_METHOD(x) x
#endif
#include <windows.h>
DEBUG_METHOD(int func(int arg) {)
return 0;
}
on function enter it will break into the debugger
IF this is C++ you are talking about, then you could probably get away with, (a hell of a lot of work) setting a break point in the preamble code in the CRT, or writing code that modifies the preamble code to stick INT 3's in there only for functions generated from the class in question... This, BTW, CAN be done at runtime... You'd have to have the PE file that's generated modify itself, possibly before relocation, to stick all the break's in there...
My only other suggestion would be to write a Macro that uses the predefined macro __FUNCTION__, in which you look for any function that's part of the class in question, and if necessary, stick a
__asm { int 3 }
in your macro to make VS break... This will prevent you from having to set break points at the start of every function, but you'd still have to stick a macro call, which is a lot better, if you ask me. I think I read somewhere on how you can define, or redefine the preamble code that's called per function.. I'll see what I can find.
I would think I similar hack could be used to detect which FILE you enter, but you STILL have to place YOUR function macro's all over your code, or it will never get called, and, well, that's pretty much what you didn't want to do.
If you are willing to use a macro then the accepted answer from this question
Should be trivially convertible to you needs by making the search function searching for methods, properties and constructors (as desired), there is also quite possibly a way to get the same information from the the ide/symbols which will be more stable (though perhaps a little more complex).
You can use Debugger.Launch() and Debugger.Break() in the assembly System.Diagnostics
Files have no existence at runtime (consider that partial classes are no different -- in terms of code -- from putting everything in a single file). Therefore a macro approach (or code in every method) is required.
To do the same with a type (which does exist at runtime) may be able to be done, but likely to be highly intrusive, creating more potential for heisenbugs. The "easiest" route to this is likely to be making use of .NET remoting's proxy infrastructure (see MOQ's implementation for an example of using transparent proxy).
Summary: use a macro, or select all followed by set breakpoint (ctrl-A, F9).
Mad method using reflection. See the documentation for MethodRental.SwapMethodBody for details. In pseudocode:
void SetBreakpointsForAllMethodsAndConstructorsInClass (string classname)
{
find type information for class classname
for each constructor and method
get MSIL bytes
prepend call to System.Diagnostics.Debugger.Break to MSIL bytes
fix up MSIL code (I'm not familiar with the MSIL spec. Generally, absolute jump targets need fixing up)
call SwapMethodBody with new MSIL
}
You can then pass in classname as a runtime argument (via the command line if you want) to set breakpoints on all methods and constructors of the given class.

Categories