Thursday, November 14, 2013

Debugging in Visual Studio, Conditionally

You can use conditional breakpoints to effectively stop your trace based on a predefined condition.  This is extremely useful when you are iterating through large collections of items and you only want to inspect members meeting a specific criteria.  I was going to discuss "Is true" and "Has changed" this week but it appears "Has changed" in Visual Studio 2010 has some unexpected results I want more time to look at before writing about.  So I am doing a shortened post this week.  Sorry. 
 

Simple "Is true" String Comparison Condition

In our first example we'll use a simple string comparison for our breakpoint.  We'll be using a bit of code from Pirate Tips http://www.piratetips.com that I use to display navigation links at the bottom of a page to let you return to the page you previously came from without using your browser's back button.  As you can see I've already added the breakpoint.
Now that I have my breakpoint for some reason I've decided I want to see what's happening in the code when a user is coming back from the page that gives you information about the dreaded Kitten monster from the game Barnacle Wars http://www.barnaclewars.com.  (Don't worry no kittens get killed in the game, they play with balls of yarn)  The title of my page is "Pirate Tips - Beasties: Kitten".
 
  • Right click on your breakpoint.
  • Click Condition on the pop-up menu.
  • Enter your break condition. 
    • Note on more modern versions of Visual Studio Intellisense is available to you as you fill in your condition.
    • When comparing strings I prefer to specify a StringComparison rather than using ToUpper()s, ToLowers()s, etc..
    • In this first example we are using the "Is true" criteria.  There is another criteria called "Has changed".
  • When your condition has been added, click OK.
  • Your breakpoint will now have a + sign in the middle of your red circle.  This means there is a condition on your breakpoint. 
 
  • Now run your debugger as we've discussed in previous posts.
  • Navigate your web page in a manner that will trigger your breakpoint.
  • When you hit your code you will see it highlighted in yellow.
  • In the image below I am indicating with an arrow that in this case I have elected to hover my cursor over PreviousPageTitle to see what the value is.
  • When you're finished simply use your chosen Escape Plan from a previous post to get out of the debugger.
  
 

No comments:

Post a Comment