Home > Articles > Programming > Windows Programming

This chapter is from the book

This chapter is from the book

Inline Debugging of ASP.NET Pages

This is so very easy—you're going to be extremely happy about this. If you've ever debugged a program using Visual Studio 6.0 (Visual Basic, Visual C++, and so on) you will feel right at home with what you are about to learn about Visual Studio .NET. Let's discuss these great features using a sample project mentioned earlier in the chapter. As usual, both Visual Basic .NET and C# versions of the code will be provided for you to see.

This sample project will consist of an ASP.NET page and a Visual Basic .NET/C# component so that you can see how easily the two interact and how they can be debugged simultaneously. The project itself will simply ask the user for a valid email address and then send a form letter to that address. Start out by creating the project. We called ours Chap5Visual Basic for the Visual Basic .NET version and Chap5CS for the C# version.

The first thing to do is create the ASP.NET page that the user will see. Listing 7.1 contains the main ASP.NET page that contains the input form on which the user can enter the email address where the mail will be sent. Here the page name is left as WebForm1, the default name provided when the project was created.

Listing 7.1 ASP.NET Page for Debugging Example

<%@ Page Language="vb" AutoEventWireup="false"
Codebehind="WebForm1.aspx.vb"
Inherits="Chap7VB.WebForm1"%>
<html>
  <HEAD>
    <title>Email Test Page</title>
  </HEAD>
  <body MS_POSITIONING="GridLayout">
    <form id="Form1" method="post"
runat="server">
      Please enter the email address to send to:
      <br>
      <input type="text" id="txtEmail"
runat="server" 				NAME="txtEmail">
      <br>
      <input type="submit" id="btnSubmit"
value="Send Email" 				runat="server"
NAME="btnSubmit">
    </form>
  </body>
</html>

This page would work in a Visual Basic .NET project. To have it work in a C# project, change the first line to the following:

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="Chap7CS.WebForm1" %>

This is a very simple page. It consists of two elements: a text box for the email address and a Submit button to send the form to the server. Now you will create the server– side code for this project. It will be contained in two parts: First, you will look at the code-behind file that is associated with this file. Here you will verify that you have a valid email address. Second, you will create a Visual Basic .NET/C# component that will actually send the email. Listing 7.2 contains the code-behind file for the C# project, and Listing 7.3 contains the code-behind file for the Visual Basic .NET project.

Listing 7.2 Listing for Debugging Example (C#)

using System;
namespace Chap7CS
{
  public class WebForm1 : System.Web.UI.Page
  {
    protected System.Web.UI.HtmlControls.HtmlInputText txtEmail;
    protected System.Web.UI.HtmlControls.HtmlInputButton btnSubmit;
  
    public WebForm1()
    {
      Page.Init += new System.EventHandler(Page_Init);
    }
    private void Page_Init(object sender, EventArgs e)
    {
      InitializeComponent();
    }
private void InitializeComponent()
{  
    this.btnSubmit.ServerClick += new 
System.EventHandler(this.btnSubmit_ServerClick); } private void btnSubmit_ServerClick(object sender,
System.EventArgs e) { if(txtEmail.Value.IndexOf("@") == -1 || txtEmail.Value.IndexOf(".") == -1) Response.Write("The supplied email address is not
valid."); } } }

Listing 7.3 Listing for Debugging Example (Visual Basic .NET)

Public Class WebForm1
    Inherits System.Web.UI.Page
    Protected WithEvents txtEmail As
System.Web.UI.HtmlControls.HtmlInputText Protected WithEvents btnSubmit As
System.Web.UI.HtmlControls.HtmlInputButton Private Sub btnSubmit_ServerClick(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnSubmit.ServerClick If txtEmail.Value.IndexOf("@") = -1 Or _ txtEmail.Value.IndexOf(".") = -1 Then Response.Write("The supplied email address is not valid.") End If End Sub End Class

These examples are also extremely simple, but they demonstrate the features of the Visual Studio .NET IDE quite effectively.

In this example, you are listening to the ServerClick event of the Submit button, named btnSubmit. When the user clicks the Submit button, this event is fired. At this point, you can inspect what is in the text box on the form. If it does not contain an @ symbol or a ., it cannot be a valid email address and you then report this back to the user with a Response.Write of an error message.

Next you will look at how the previously mentioned debugging tools can aid you in tracking down a problem in this simple page.

Setting a Breakpoint

Let's start out by setting a breakpoint on the ServerClick event of the Submit button. This is the btnSubmit_ServerClick function in either piece of code. To set a breakpoint, simply move the mouse cursor to the gray left margin in the code editor window, and click. This drops a red dot into the margin, signifying that a breakpoint has been set at that specific line. Figure 7.8 shows exactly where to set this breakpoint and what the margin will look like after clicking.

Figure 7.8 Setting the breakpoint in the example program.

Now go ahead and run the program. When Internet Explorer appears, enter some gibberish into the text box that does not contain either an @ symbol or a .. Now click the Submit button. When this occurs, the Visual Studio .NET IDE should pop up with the breakpoint line highlighted in yellow. The execution of your program has paused, and now you can use some of the other debugging features. You will look at the watch window next.

Watch Window

At the bottom of your screen, you will see a debugging window with some tabs below it. Click the one labeled Watch 1. If this tab is not available, you will find the same entry under the Debug menu as part of the Windows suboption. Figure 7.9 shows the menu entry.

Figure 7.9 The watch window option under the Debug menu.

The watch window enables you to type in a specific variable name, control name, or other object and then see what value it contains and what type it is. For now, type in txtEmail. You will see that you can expand this entry into all the control's properties to see what they each contain. To save space, you might want to see only the Value property—in that case, you could enter txtEmail.Value as your watch name.

With the txtEmail control expanded, you can see that the Value property contains whatever you entered in the control on the client side. This can be extremely useful when debugging all types of controls to see what values they contain. It is always useful to start here when debugging almost any problem to make sure that the data isn't to blame. For example, you might be chasing after a problem only to find that the Value property is empty for some reason or that it does not contain the data that you think it does.

The other thing that you can do with the watch window is change the value of a variable. If you click the property value in the Value column in the watch window, you can enter a new value as you see fit. This might be helpful if you want to test a certain case in your logic that might be difficult to hit. For example, if an error is supposed to occur if a value equals –1, at this point you could change the value to –1 and continue execution to make sure that the code path is operating properly.

That's about it for the watch window. This is a feature that you will use quite a bit in your debugging. Remember that you can enter any variable or any object into the window and view any or all of its specific properties. Also note that you can change the values of any of these properties at any time.

The Command Window

If you have used Visual Basic, this will be a familiar sight. The command window was called the immediate window in Visual Basic, but its features are identical. This window enables you to issue commands to debug or evaluate expressions on the fly.

To display the window, either click the Command Window tab located at the bottom of your screen, or choose Windows, Immediate from the Debug menu at the top of your screen. Figure 7.10 shows where you can find the option under the Debug menu.

Figure 7.10 The immediate window option under the Debug menu.

To view the contents of a variable or object, just type its name into the command window. For example, typing txtEmail.Value while at the breakpoint displays the contents of the text box upon submission to the server.

Similar to the watch window, you can change the value of variables or object properties. To change the value of the form text box, you could enter txtEmail.Value = "newvalue", which would set the string to "newvalue".

What makes the command window a bit more exciting than the watch window is its capability to execute functions. For example, if you want to execute the ValidateEmail function in your code listing at any time, you could do it right from the command window: Just click in the window and call the function with the appropriate parameter. For example, if you type ValidateEmail("test@myhost.com"), you will see that it returns 0. If you type ValidateEmail("asdfasdf"), it returns –1. So, you can test any function that you write right here without having the executing program call it explicitly—a great debugging aid.

Tracing

Tracing is a very simple method of debugging problems. Tracing can be used to print text statements during the execution of your code. This can be used as a log to see exactly what is happening at any point in your code. As you can see in the previous examples, in the ServerClick function of the Submit button, you are calling Debug.WriteLine with the value of the form's text box. This call spits out the value of the text box to the debug stream. The easiest place to see the debug stream is in the output window at the bottom of the Visual Studio .NET IDE.

This window can be displayed by either clicking the Output tab or choosing Output under the View menu and then choosing Other Windows. This window shows you all the debug statements that you have inserted into your code, as well as anything else that gets written to the debug stream by any other components that might be associated with the running project. Keep this in mind if you see a flood of messages that you didn't write into your code.

Execution Control

Before we start talking about the call stack, let's take a brief journey into the execution control features of the debugger. These features enable you to control exactly what is executed in your program—and in what order. They can also be used to trace deeply into certain portions of the code or skip over them, if that level of detail is unnecessary.

All these features can be found under the Debug menu at the top of your screen. All are also associated with keyboard shortcuts that vary depending on how you have configured Visual Studio .NET. The keyboard shortcuts are the easiest method of using these features because they enable you to move through many lines of code in a very quick fashion. We recommend learning the keyboard shortcuts and using them while debugging your own code.

The three options are Step Into, Step Over, and Step Out. Step Into enables you to step one level deeper into the code at the current point of execution or, at the very least, move to the next statement. If you are about to call a function in your code, using Step Into continues execution at the first line of the called function.

Step Over does the opposite of Step Into. If you are about to call a function, using Step Over at this point does just that—it steps over execution of the function to the very next line of the function that you are currently executing. Now keep in mind that this does not mean that it will not execute the function—it just will not allow you to dig into it. It executes the function and moves on to the next line. This is quite useful when you know that a function or block of code is working correctly and you do not want to spend the time hitting every single line.

Step Out enables you to jump out of the current function that you are debugging and go one level up. Again, similar to the Step Over feature, this does not skip the execution of the remaining lines of code; they just execute behind your back, and your debugging cursor moves to the next line in the previous function you were in.

So how do you know which function you were previously in? That leads to the next debugging feature, the call stack.

Call Stack

The call stack shows the current function you are in and all functions that preceded it. When you call a function from a function from a function from a function, you have a call stack that is four levels deep, with the current function on the top. You can view the call stack window by clicking the Call Stack tab at the bottom of your screen or by choosing Call Stack from the Debug menu under Windows.

Continuing the previous example, stop execution again on the btnSubmit_ServerClick function and then trace into the ValidateEmail function. Now you have called a function from a function. Take a look at the call stack window. The top two levels should show you the ValidateEmail function, followed by the btnSubmit_ServerClick function. You will also see quite a few other functions that are called by the ASP.NET system processes.

Now go ahead and double-click the btnSubmit_ServerClick function. A green highlight appears over the point in the function that you currently are in. In this case, the call to ValidateEmail is highlighted because this is the exact position that you are currently at in that function.

This feature can be of use when you are debugging code that might not be all your own. If you are many levels deep into a function stack, you might need to know where you came from. By using this, you can trace back to the calling stack and see exactly who called you and with what information. After you have traced back to the call stack, you can use the watch window or the command window to inspect the local variables from the previous functions. This can be handy when you want to find where certain data values are coming from if they are wrong.

Feature Summary

That about wraps up the baseline features of the Visual Studio .NET IDE. Next you will look at how to add a C# or Visual Basic .NET component to your project and debug that simultaneously with your ASP.NET pages. The process is extremely streamlined and quite seamless, as you will soon see.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020