Lesson 18 - Setting a Break Point and Debugging

Tutorial Series: Free C# Fundamentals via ASP.NET Web Apps

Previous Article  |  Next Article


Get GitHub Code

In this lesson, we're going to briefly cover the debugging features of Visual Studio. Debugging is probably the most crucial skill that you'll develop as a beginner because it's going to help you figure out where you went wrong in the code you've written. When you first encounter vexing problems in your code, you can stare at it and hope the solution dawns on you, or you can set a breakpoint and debug. Setting a breakpoint is the first step in debugging, and it determines where the execution of your code should halt in order that you, the developer, can take control. When execution is in your control, you effectively slow down the code allowing you to inspect the values of variables and Server Controls while they change.

Step 1: Create a New Project

For this lesson, create a new ASP.NET project and call it “CS-ASP_018.” Set the Default.aspx with the following Server Controls, and programmatic IDs:

  1. myTextBox

  2. firstCalendar

  3. secondCalendar

  4. okButton

  5. resultLabel

cs-asp-018---setting-a-break-point-and-debugging.001

cs-asp-018---setting-a-break-point-and-debugging.002

Step 2: Write Code for Debugging Purposes

In the Default.asxp.cs file write out the following code, purely for the purpose of demonstrating problem-solving via debugging:

cs-asp-018---setting-a-break-point-and-debugging.003

Step 3: Set Break Points to Take Control of Execution

The imaginary rules, for this imagined application, are:

  1. A user must select a date in secondCalendar that is at least 14 days from the selected date in firstCalendar. Otherwise, an error is displayed in the resultLabel.

  2. The resultLabel should be the sum of the TextBox and the TimeSpan.TotalDays, obtained from the dates between both Calendars, multiplied by 100.

The application intentionally has some errors when attempting to perform the calculation. Let’s now add a breakpoint to help track down the problem. You can either place your cursor on the line you want execution to halt and press the F9 key on your keyboard, or you can simply left-click on the margin beside that line of code, in this case the line that the if() statement is on:

cs-asp-018---setting-a-break-point-and-debugging.004

You can also set multiple breakpoints. To demonstrate this add another breakpoint to this line of code. Do this in the Page_Load where the myTextBox.Text value is set:

cs-asp-018---setting-a-break-point-and-debugging.005

Now run the application and you will notice that focus will shift from the browser back to the first breakpoint in the code execution order:

cs-asp-018---setting-a-break-point-and-debugging.006

Tip: Think of the red dot, which represents the breakpoint, as being the “stop” sign in your application. Your code will execute as normal, up until the point it reaches this stop sign, at which point further execution is handed off to you.

At this point, the application is in your control. You can move to the next line of code by hitting F10 on the keyboard or by clicking on the “Step Over” icon in the toolbar. You will then see an arrow indicating the next line of code to be executed:

cs-asp-018---setting-a-break-point-and-debugging.009

cs-asp-018---setting-a-break-point-and-debugging.010

If you no longer want to debug this part of code you can deselect the red dot once you've stepped to another line of code, while still in debug mode, and click on the “continue” button in the toolbar. When clicking on the button, execution will then halt on the next breakpoint:

cs-asp-018---setting-a-break-point-and-debugging.011

Step 4: Inspecting Values in Variables as the Application Runs

When at a breakpoint, you can then hover your mouse over different variables to inspect what values they are holding at that given moment. Here we see something that would produce an error, and that is the date held in SelectedDate:

cs-asp-018---setting-a-break-point-and-debugging.012

If you hover over the SelectedDate for secondCalendar, you will also find the same problem. Note that you can inspect the values of all variables, currently in scope, by referring to the “Locals” window.

Debug > Windows > Locals

cs-asp-018---setting-a-break-point-and-debugging.013

As you step into this code block (F11), notice how variables are added to the Locals and Watch Windows. The Watch Window shows you variables that you can keep track of even if they are not within the scope of the current code block. To open the Watch Window go to:

Debug > Windows > Watch

As you continue to step forward, notice how you can see variables taking on values in real-time:

cs-asp-018---setting-a-break-point-and-debugging.014

The red font indicates that a value has just changed in response to something that occurred on the previous line of code (here, it is being assigned with the myTextBox.Text value):

cs-asp-018---setting-a-break-point-and-debugging.015

Step 5: Pinning Down Particular Variables

You can also zero-in on particular variables by hovering over them. In this case, this particular variable, SelectedDate is a DateTime which means you can access constituent variables (properties) contained within it:

cs-asp-018---setting-a-break-point-and-debugging.016

You can even pin certain variables down so you can see their values update with the editor itself (this stays pinned, even when done with debugging, so you can see the last value it held):

cs-asp-018---setting-a-break-point-and-debugging.017

cs-asp-018---setting-a-break-point-and-debugging.018

Continue to step into the code until you’re at this line:

cs-asp-018---setting-a-break-point-and-debugging.019

Step 6: Real-Time Variable Assignment via Locals Window

You can even test out what would happen if variables held certain values. Go to the Locals Window and manually change days to 34:

cs-asp-018---setting-a-break-point-and-debugging.020

Step 7: Stepping Backwards

It may seem that we changed the value for days a bit too late, as you may have noticed days was referenced on the previous line of code (in the calculation that ends up being assigned to sum). However, we can step backward to re-read the previous line, this time with the new value for days as set in the Locals Window. You can do this by right-clicking on the line you want to step to and select “Set Next Statement” (or, Ctrl+Shift+F10):

cs-asp-018---setting-a-break-point-and-debugging.021

Now, when you manually step forward it will include this update to days and sum, which is then reflected in the resultLabel:

cs-asp-018---setting-a-break-point-and-debugging.022

Step 8: Using the Watch Window for Handling Properties

Unfortunately, not every variable is going to be so easily adjusted in real-time as we have seen here. Take, for instance, the firstCalendar property which isn’t even referenced in the current Locals Window. However, we can add it to the Watch Window by highlighting it, and then clicking/dragging it there:

cs-asp-018---setting-a-break-point-and-debugging.023

cs-asp-018---setting-a-break-point-and-debugging.024

After you drag firstCalendar to the Watch Window, it, along with all its properties, will be accessible there:

cs-asp-018---setting-a-break-point-and-debugging.025

Step 9: Using the Immediate Window to Write Code In Real-Time

However, when you click on the arrow to inspect the constituent properties, you will notice that some are resistant to editing such as with SelectedDate. There is a way around this and that is by going to the Immediate Window which allows you to write code while debugging. You can display the Immediate Window by pressing Ctrl+Alt+I on your keyboard or via the menu:

Debug > Windows > Immediate

Type in the following code and hit enter to execute it:

cs-asp-018---setting-a-break-point-and-debugging.026

Notice when you hover over SelectedDate you will see it storing the value you wrote in the Immediate Window:

cs-asp-018---setting-a-break-point-and-debugging.027

Back in the Immediate Window, you can also query any variable to see its current values, by inserting a question mark before the variable name:

cs-asp-018---setting-a-break-point-and-debugging.028

When you stop debugging, all of these temporary changes you made will be reset. However, pinned values are kept for reference purposes, and are found by clicking on the pin in the left margin:

cs-asp-018---setting-a-break-point-and-debugging.029

Sometimes it’s useful to temporarily disable a breakpoint while keeping the reminder that a breakpoint was used. You can do this by right-clicking on the breakpoint and selecting “disable breakpoint” (or Ctrl+F9):

cs-asp-018---setting-a-break-point-and-debugging.030

Tip: Armed with all of the information you learned from a debugging session, you should have a better understanding of how to go back and fix the problematic code. Debugging is therefore not an automatic solution to problems in your code, but more like a “magnifying glass” that clarifies the fuzzy areas.

Debugging is incredibly useful when writing code, as there will always be unexpected bugs and errors that you will write. Being able to slowly track down these errors is a very useful skill. Use these tools throughout this course to help write better code and quickly fix problems you're having. Great job so far!


Related Articles in this Tutorial:

Lesson 1 - Series Introduction

Lesson 2 - Installing Visual Studio 2015

Lesson 3 - Building Your First Web App

Lesson 4 - Understanding What You Just Did

Lesson 5 - Working with Projects in Visual Studio

Lesson 6 - Simple Web Page Formatting in Visual Studio

Challenge 1

Solution 1

Lesson 7 - Variables and Data Types

Lesson 8 - Data Type Conversion

Lesson 9 - Arithmetic Operators

Lesson 10 - C# Syntax Basics

Challenge 2 - ChallengeSimpleCalculator

Solution - ChallengeSimpleCalculator

Lesson 11 - Conditional If Statements

Lesson 12 - The Conditional Ternary Operator

Challenge 3 - ChallengeConditionalRadioButton

Solution - Challenge Conditional RadioButton

Lesson 13 - Comparison and Logical Operators

Lesson 13 Challenge - First Papa Bob's Website

Solution - Challenge First Papa Bob's Website

Lesson 14 - Working with Dates and Times

Lesson 15 - Working With Spans of Time

Lesson 16 - Working with the Calendar Server Control

Challenge 4 - Challenge Days Between Dates

Solution - Challenge Days Between Dates

Lesson 17 - Page_Load and Page.IsPostBack

Lesson 18 - Setting a Break Point and Debugging

Lesson 19 - Formatting Strings

Challenge 5 - Challenge Epic Spies Assignment

Solution - Challenge Epic Spies Assignment

Lesson 20 - Maintaining State with ViewState

Lesson 21 - Storing Values in Arrays

Lesson 22 - Understanding Multidimensional Arrays

Lesson 23 - Changing the Length of an Array

Challenge 6 - Challenge Epic Spies Asset Tracker

Solution - Challenge Epic Spies Asset Tracker

Lesson 24 - Understanding Variable Scope

Lesson 25 - Code Blocks and Nested If Statements

Lesson 26 - Looping with the For Iteration Statement

Challenge 7 - Challenge For Xmen Battle Count

Solution - Challenge For Xmen Battle Count

Lesson 27 - Looping with the while() & do...while() Iteration Statements

Lesson 28 - Creating and Calling Simple Helper Methods

Lesson 29 - Creating Methods with Input Parameters

Lesson 30 - Returning Values from Methods

Lesson 31 - Creating Overloaded Methods

Lesson 32 - Creating Optional Parameters

Lesson 33 - Creating Names Parameters

Lesson 34 - Creating Methods with Output Parameters

Challenge 8 - Challenge Postal Calculator Helper Methods

Solution - Challenge Postal Calculator Helper Methods

Mega Challenge Casino

Solution - Mega Challenge Casino

Lesson 35 - Manipulating Strings

Challenge 9 - Phun With Strings

Solution - Challenge Phun With Strings

Lesson 36 - Introduction to Classes and Objects

Challenge - Hero Monster Classes Part 1

Solution - Hero Monster Classes Part 1

Challenge - Hero Monster Classes Part 2

Solution - Challenge Hero Monster Classes Part 2

Lesson 37 - Creating Class Files Creating Cohesive Classes and Code Navigation

Lesson 38 - Understanding Object References and Object Lifetime

Lesson 39 - Understanding the .NET Framework and Compilation

Lesson 40 - Namespaces and Using Directives

Lesson 41 - Creating Class Libraries and Adding References to Assemblies

Lesson 42 - Accessibility Modifiers, Fields and Properties

Lesson 43 - Creating Constructor Methods

Lesson 44 - Naming Conventions for Identifiers

Lesson 45 - Static vs Instance Members

Challenge 10 - Challenge Simple Darts

Solution - Challenge Simple Darts

Lesson 46 - Working with the List Collection

Lesson 47 - Object Initializers

Lesson 48 - Collection Initializers

Lesson 49 - Working with the Dictionary Collection

Lesson 50 - Looping with the foreach Iteration Statement

Lesson 51 - Implicitly-Typed Variables with the var Keyword

Challenge 11 - Challenge Student Courses

Solution - Challenge Student Courses

Mega Challenge War

Solution - Mega Challenge War

Lesson 52 - Creating GUIDs

Lesson 53 - Working with Enumerations

Lesson 54 - Understanding the switch() Statement

Lesson 55 - First Pass at the Separation of Concerns Principle

Lesson 56 - Understanding Exception Handling

Lesson 57 - Understanding Global Exception Handling

Lesson 58 - Understanding Custom Exceptions

Lesson 59 - Creating a Database in Visual Studio

Lesson 60 - Creating an Entity Data Model

Lesson 61 - Displaying the DbSet Result in an ASP.NET GridView

Lesson 62 - Implementing a Button Command in a GridView

Lesson 63 - Using a Tools-Centric Approach to Building a Database Application

Lesson 64 - Using a Maintenance-Driven Approach to Building a Database Application

Lesson 65 - Creating a New Instance of an Entity and Persisting it to the Database

Lesson 66 - Package Management with NuGet

Lesson 67 - NuGet No-Commit Workflow

Lesson 68 - Introduction the Twitter Bootstrap CSS Framework

Lesson 69 - Mapping Enum Types to Entity Properties in the Framework Designer

Lesson 70 - Deploying the App to Microsoft Azure Web Services Web Apps

Papa Bob's Mega Challenge

Papa Bob's Mega Solution Part 1 - Setting up the Solution

Papa Bob's Mega Solution Part 2 - Adding an Order to the Database

Papa Bob's Mega Solution Part 3 - Passing an Order from the Presentation Layer

Papa Bob's Mega Solution Part 4 - Creating the Order Form

Papa Bob's Mega Solution Part 5 - Adding Enums

Papa Bob's Mega Solution Part 6 - Creating an Order with Validation

Papa Bob's Mega Solution Part 7 - Calculating the Order Price

Papa Bob's Mega Solution Part 8 - Displaying the Price to the User

Papa Bob's Mega Solution Part 9 - Creating the Order Management Page


Comments

Please login or register to add a comment