Let me start by saying that I know about the DebuggerStepThroughAttribute and I'm using it in a number of places with much success.
However, I'm searching for a complementary solution that would work for my specific scenario, which I'll now illustrate...
Say I have a homegrown data-access framework. This framework comes with lots of unit tests which ensure that all my high-level data-access APIs are working as expected. In these tests, there is often a requirement to first seed some test-specific data to a one-off database, then execute the actual test on that data.
The thing is, I might rely on unit tests not just to give me a passive green/red indication about my code, but also to help me zero in on the source of occasional regression. Given the way I've written the tests, it's easy to imagine that a small subset of them could sometimes give me grief, because the code that performs the test data seeding and actual test code both use the same framework APIs at lower levels.
So for example, if my debugging of a failed test happened to require that I place a breakpoint inside one such common method, debugger would stop there a number of times (maybe an annoyingly large number of times!) before I'd get to the point I'm interested in (the actual test, not the seeding).
Leaving aside the fact that I could theoretically refactor everything and improve decoupling, I'm asking this:
Is there a general way to quickly and easily disable debugger breaking for a specific code block, including any sub-calls that might be made from that block, when any of the executed lines could have a breakpoint associated?
The only solution that I'm aware of is to use conditional breakpoints. I would need to set a certain globally accessible flag when entering the method that I wanted to exclude and clear it when exiting. Any conditional breakpoints would then have to require that flag must not be set.
But this seems tedious, because breakpoints are often added, removed, then added again, etc. Given the rudimentary breakpoint management support in Visual Studio this quickly becomes really annoying.
Is there another way? Preferably by manipulating the debugger directly or indirectly, similarly to how the DebuggerStepThroughAttribute does it for single method scope?
EDIT:
Here's a contrived example of what I might have:
public class MyFramework
{
public bool TryDoCommonWork(string s)
{
// Picture an actual breakpoint here instead of this line.
// As it is, debugger would stop here 3 times during the seeding
// phase and then one final time during the test phase.
Debugger.Break();
if (s != null)
{
// Do the work.
return true;
}
return false;
}
}
[TestClass]
public class MyTests
{
[TestMethod]
public void Test()
{
var fw = new MyFramework();
// Seeding stage of test.
fw.TryDoCommonWork("1");
fw.TryDoCommonWork("2");
fw.TryDoCommonWork("3");
// Test.
Assert.IsTrue(fw.TryDoCommonWork("X"));
}
}
What I'm really looking for is something roughly similar to this:
[TestClass]
public class MyTests
{
[TestMethod]
public void Test()
{
var fw = new MyFramework();
// Seeding stage of test with no debugger breaking.
using (Debugger.NoBreakingWhatsoever())
{
fw.TryDoCommonWork("1");
fw.TryDoCommonWork("2");
fw.TryDoCommonWork("3");
}
// Test with normal debugger breaking.
Assert.IsTrue(fw.TryDoCommonWork("X"));
}
}
I'm looking for ways to quickly debug the code I've just written to see if it behaves correctly and all my assumptions are correct. I don't want to run the full system yet because parts of infrastructure to get to this code are missing. I use unit testing for it but I find it cumbersome. Is there anything better?
Objectives are:
Debug any code quickly without creating additional projects, applications etc.
Easily repeat debugging.
The test is for this specific purpose, might use fixed file paths, database connections, anything. Typically thrown away after getting things right.
Need to access internal members of my objects.
Accessing private member would be great benefit.
I'm fine with writing test functions directly in my object. Actually this would be preferred.
The dream way of doing it would be:
namespace Aaa
{
class SomeClass
{
public string Name { get; private set; }
public SomeClass(string name, int value)
{
this.Name = name;
InitializeSth();
}
public DoSomethingPublic()
{
// ...
}
private DoSomethingPrivate()
{
// ...
}
public static void TestThis() // <-- debug this
{
var obj = new SomeClass("a", 1); // <-- put breakpoint here
obj.DoSomethingPublic();
obj.DoSomethingPrivate();
}
}
}
This is possible in Java and is such a great thing. This allows for accessing private things too.
But I'm open to other options as well. Is there anything like this in VS2015?
What I have tried so far:
Immediate Window - I don't think it can be configured for such purpose
C# Interactive - this doesn't seem to support debugging. Or does it?
Unit testing - this is what I use now (with MSTest). But I find it very cumbersome, because:
I need to create new projects, or include references to MS testing assemblies
I need to make extra steps to access internal types and members, or change things to public (I don't like this).
Even more steps to access private members.
I mess with other tests if Unit Testing is used in the project.
Starting debugging again needs many clicks instead of sth+sth+F5.
There are some workarounds for some of these items, but in general the testing infrastructure seems to be made for different purposes and I always have a feeling I'm fighting against it.
I also found some information about Resharper having ability to debug any static function. But I don't want to use Resharper, mainly because of performance.
To debug one method without running the whole app, I often use the unit test in VS IDE, since it would not really impact our app's development.
I also got the method using the Resharper tool before: https://blog.jetbrains.com/dotnet/2015/08/28/run-configurations-debug-any-static-method-in-visual-studio-and-more/
In VS IDE, to debug the method directly without debugging/running the app, it really has no better suggestions than unit test project.
Of course, it also has other third party tool if you want to debug code without running the app:
http://www.linqpad.net/
Take a look at this answer: #if DEBUG vs. Conditional(“DEBUG”)
Basically you could use something like the following:
#if DEBUG
public void DoSomething() { }
#endif
public void Foo()
{
#if DEBUG
DoSomething();
#endif
}
Answering my own question - it seems I didn't evaluate Immediate Window enough.
It is possible to invoke any static method either using
Immediate Window (just type TestThis())
Command Window (type ?TestThis() or Debug.EvaluateStatement TestThis())
This even allows to invoke private static methods. The projects will be built before starting the method if they need to be and the method is executed in debugger, so it will stop at any breakpoint.
So summarizing: press Alt+Ctrl+I to get to the Immediate Window, type-in method name with parentheses and press Enter.
There are two disadvantages:
If the method is not in main class (one with Main method), you have to use full namespace and class name, for example MyCompany.MyApp.Logic.SomeClass.TestMethod() to run it
to start debugging again, you have to go to immediate window and recall last command with Up-Arrow, Enter. This is better than right-clicking on a test and selecting "Debug this test", but not optimal.
Please add an answer if you know anything better or some ways to make these two issues better. I looked for quite some time to find a keyboard shortcut to repeat last Immediate Window command, but cannot find one. I don't mark this answer as accepted for now, in case something better is posted.
With the move to EF6.1, our goal is to use exclusivity the Async/Await options speaking with our data sets. While porting from our previous Linq2Sql, there are many .ToList(), .FirstOrDefault(), and .Count()'s. I know we can search and fix those all, but it would be nice if we could, at compile time, prevent those functions from even being permitted into a build. Does anyone have have a creative idea on how to accomplish this? Even if they were compiler warnings that could be thrown (such as use of the Obsolete attribute).
You can use the .NET Compiler Platform to write a Diagnostic and Code Fix that will look for these patterns and provide warnings/errors.
You could even implement a Syntax Transformation to automatically change these constructs - though the effort might be more expensive than just doing it by hand.
Following up to this... i never found a solution that can detect this at compile time, but I was able to do this in code in the DataContext:
public EfMyCustomContext(string connctionString)
: base(string.Format(CONNECTION_STRING, connctionString))
{
#if DEBUG
this.Database.Log = LogDataBaseCall;
#endif
}
#if DEBUG
private void LogDataBaseCall(string s)
{
if (s.Contains("Executing "))
{
if (!s.Contains("asynchronously"))
{
// This code was not executed asynchronously
// Please look at the stack trace, and identify what needs
// to be loaded. Note, an entity.SomeOtherEntityOrCollection can be loaded
// with the eConnect API call entity.SomeOtherEntityOrCollectionLoadAsync() before using the
// object that is going to hit the sub object. This is the most common mistake
// and this breakpoint will help you identify all synchronous code.
// eConnect does not want any synchronous code in the code base.
System.Diagnostics.Debugger.Break();
}
}
}
#endif
Hope this helps someone else, and still would love if there was some option during compile.
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.