C # debugging trilogy: from entry to mastery _ reprint

Source: Internet
Author: User

C # debugging, the novice should be helpful, the original address: http://tech.it168.com/a2010/1116/1126/000001126474_all.shtml

We are doingProgramErrors and exceptions are inevitable during development. How to quickly find the cause of the error, analyze the cause of the error, and find a solution to the problem is a problem that many junior programmers are troubled by. This is also a valuable experience. Below I will briefly introduce debugging in Visual Studio and some advanced debugging and common errors.

PS: Unless otherwise specified, Visual Studio refers to dev10, namely Visual Studio 2010.

Entry

Suppose you are a programmer with A. NET platform and use Visual Studio as a development tool.

Breakpoint: the simplest method is to set a breakpoint. When the program is executed, it is automatically interrupted and enters the debugging state. Set the breakpoint.CodeLine, click on the left side, a red dot is displayed, that is, the breakpoint.

Enable: Press F5, or choose "enable" from the menu bar to start debugging, or click the toolbar icon.

Quick monitoring: You can quickly view the values of variables or expressions, or customize expressions for calculation.

One-step execution

There are three types: one is to execute one row (F10) each time; the other is to execute one row each time, but will jump to the called function (F11) when a function call occurs ); one is to directly execute the remaining commands in the current function and return the upper-level function (SHIFT + F11 ).

Another kind of regret is to set it to the next sentence (set next statement), that is, the statement that will be executed in the next sentence (right-click the setting or shortcut key: Ctrl + Shift + F10 ), however, when debugging data-related statements, setting the next sentence may report exceptions. For example, when you add rows to a able, existing rows cannot be added to the able repeatedly.

Monitoring

The debugger may automatically list the values of some related variables, but you may also be concerned about the values of other variables. You can add monitoring for these variables. You can also monitor the value of an expression, such as A + B. However, it is recommended that you do not modify the value of a variable in this expression. For example, if you monitor a ++, the value of a is modified during monitoring, which affects the running result of the program.

Debugging skills

Using shortcut keys can greatly improve our debugging efficiency. common debugging shortcut keys:

F5 start debugging

F10 executes the next line of code, but does not execute any function call.

After the F11 execution enters the function call, the code is executed one by one.

Shift + F11 the remaining row of the function where the current execution point is located.

Shift + F5 stop the current application in the running program. It can be used in interrupt and run modes.

Drag the breakpoint (thanks to the reminder from the Paladin)

During debugging, we can drag the breakpoint so that the program runs to the desired place. It is usually used to verify whether this code has any impact on the running results of the program. Because we drag the code, the filtered code will not be executed. Compared with the original code, we can see the impact of removing this code.

Conditional interruption

If you write a for loop with a large number of cycles, the following code shows that there will be exceptions when I = 50, then we cannot press F5 50 times to debug the code, otherwise this efficiency ....

Private void conditiondebug ()
{
For (INT I = 0; I <100; I ++ ){
If (I = 50)
{
// Some error code here
Console. writeline ("I = 50 here ");
}}}

We can directly use the function provided by Vs to modify the value of variable I. Once I = 0 is opened, it is just entering the for loop. We set the I to 49 and press enter to debug it again, I = 50, as shown in figure

Of course, we can also directly write code in the code to achieve this purpose. The Code is as follows:

Private void conditiondebug ()
{
For (INT I = 0; I <100; I ++)
{
System. Diagnostics. Debug. Assert (I! = 50 );
If (I = 50)
{
// Some error code here
Console. writeline ("I = 50 here ");
}}}

When the assert (assert) in debugging is used, the following prompt box is displayed after the program is executed. Click ingore (ignore,

Immediate window

During debugging, the immediate window calculates the expression value, executes the statement, and prints the variable value. We enter the command (note that it must start with ">"), there will be smart prompts, And the names are all self-explanatory.

For example, if you want to know the value of I, you can enter the name> Debug. Print I (or simply use it>? I), such

Immediate window has more powerful usage. The return value of the calculation method (if any)

If this function is available

Int methodvalue (int)
{
If (A = 1)
{
Return 1;
}
Else
{
Return 0;
}}

We can use the immediate command>? Class. Method (ARGs) to call this method, as shown in figure

Where p is the instance of the current class (because methodvalue is the class method, note? And expression)

Use debug for some real-time programs (such as socket. write () writes errors to log files ,. net can write the debug information to the file you specified, remember that the write in and out information is not necessarily error information, it can also be some important information about the running of your program, when you find that a module has a problem but cannot determine the location during debugging, you can use this method. If an error occurs only one day, then you must use this method.

Instance

Debugging of WS (WebServices)

In the actual development based on winform, we often use WS for data transmission. We get the collected data at the front end and pass the data to the backend through ws, after the backend completes the corresponding business logic processing, it will last in the database. We often write related code in WS, such as identity authentication, log records, and prompt information. How can we debug the code.

Debugging involving Javascript

Many programmers are confused about debugging JavaScript, because there is no good debugging tool. Some people like to use firebug to debug JavaScript, which is indeed a good choice. firebug provides a lot of JavaScript Information and is a good tool for debugging JavaScript. Next, I will introduce how to use Visual Studio to debug Javascript. in Visual Studio, debugging JS is similar to debugging C #, and breakpoint is set, the difference is that we need to pay attention when viewing element values.

Debugging involving Ajax

Nowadays, Ajax is very popular, but it comes with debugging difficulties. Most Junior programmers do not know how to effectively debug the background code from the front-end to a lot of imperfect Ajax applications.

The following uses a simple example to describe how to use Visual Studio to debug JavaScript. The instance uses ajax to verify user logon. If the verification succeeds, the system prompts "Logon successful". Otherwise, the system prompts "Logon Failed ".

The following is the main code. We use jquery to implement Ajax and make a deliberate error in the background file.

The correct username and password are admin and 1.

The debugging method is as follows: Set a breakpoint at the entrance of the background, set a breakpoint at the method of calling the background in the foreground JS, and then press F5 to start debugging. After we enter the user name and password, click log on and you will find that the front-end breakpoint is triggered.

Press F5 to continue debugging. Sometimes it will jump to the jquery source code. If you continue with F5, you will find that the breakpoint is executed in the background, as shown in

The background code debugging is very simple. (PS: Sometimes you can directly go to the background for debugging without setting breakpoints on the foreground. If not, you can set breakpoints in HTML or aspx files on the foreground where errors may occur, step-by-Step debugging)

Some common errors during debugging (will be updated one after another ):

1. When we debug a code sentence, we suddenly jumped out unexpectedly. In fact, this sentence was just executed with an exception. We can use try... Catch to catch exceptions, check the causes of exceptions, and then handle the exceptions accordingly.

2. In ADO. net, we will use the DS. Merge () method to merge memory tables. If there is an exception, there are generally three situations:

A. One of the tables has two rows of identical data, including the primary key.

B. The two tables have different structures.

C. The type of a field in the two tables does not match. For example, if the field age is a Chinese string in Table A, it is indeed a decimal in table B.

Breakpoint

Hit count (hit counts)

Right-click the breakpoint and you can set hit counts (number of hits). The following dialog box is displayed.

When the condition is met, the breakpoint will be hit (that is, it will be executed). The number of hits is the number of times the breakpoint is hit. The default value is always break. The options are as follows: always break; when the number of hits reaches, the break; when the number of hits is a multiple; break when the number of hits is greater than or equal.

Therefore, the conditions in the previous article can also be implemented in this way. When the number of hits is set to 50, the break is set. After pressing F5, the breakpoint is triggered. At this time, I = 50.

Breakpoint Filter

We can restrict breakpoints in specific processors and threads. You can set certain conditions in the machine name, process ID, process name, thread ID, and thread name to filter some breakpoints.

Note: threadid must be particularly noted that threadid is not in a hosting program, and system. Threading. thread. managedthreadid In the. NET Framework cannot be the same. In short, managedthreadid is the identifier of the thread in the CLR, while threadid is the identifier of the thread in the operating system. Therefore, threadid needs to be obtained from the "Threads" window in the debugger.

Breakpoint Conditions

We can set the conditions for the breakpoint to be reached. For example, we set the expression to I = 5 (note that it is equivalent, not equal to the value assigned), press F5, And the breakpoint is triggered again, at this time, I = 50.

Another option is that the variable has been changed, and the condition is the specific variable. For example, our code is as follows:

Private void conditiondebug ()
{
Int hitcount = 0;
For (INT I = 0; I <100; I ++)
{
If (I = 49)
{
Hitcount = 1;
}
}
Console. Write ("hit count = {0}", hitcount );
}

In the code, if I = 49, change the value of hitcount and set the breakpoint condition

When the breakpoint is triggered again, I = 50. When is this change usually used to find a variable.

Breakpoint location

You can set the position of the breakpoint, for example, to trigger the breakpoint when the program reaches the nth line of the file.

When a breakpoint is triggered...

We can set other things when the breakpoint arrives, such as printing messages and running a macro.

Custom call stack

When stack tracing is performed, vs executes your program step by step to intuitively display the inheritance relationships of the current method call. When debugging a program, we will go through one method after another, including nested call of the method. Stack tracing records each layer of the method. Select debug> WINDOW> call stack, or press CTRL + ALT + C to view the current stack trace status. Each method is displayed as a single row with a row number and parameter value. Each new method call is called a stack frame.

Stack tracing is a widely known debugging tool. It has the advantage that you can double-click any row to jump to the code that calls the method at this layer in the program. So you can see how the program runs to this position, and the parameter values accepted by the method. In addition, you can use Ctrl + C to copy one or all stack frames to the clipboard and send the call information of this method to the partner.

Start external program: Start the internal program during debugging

Start browser with URL: Open the URL address during debugging

Debug ASP. NET with trace. axd

In the past, in ASP, we usually used the response. Write method to view the value of a variable. Many ASP. NET programmers may also use the response. Write method in the background to write the variable value. In fact, Microsoft provides a good debugging tool, namely trace. axd. Its function is mainly to configure ASP. NET code tracking service to control how to collect, store, and display tracing results.

Key options:

1. The default value of localonly is false. This is easy to understand. If it is true, only trace information is output locally.

2. Enabled: whether to enable tracking.

3. pageoutput specifies whether the Trace Output is displayed at the end of each page. If it is false, the trace output can only be accessed through the trace utility.

4. requestlimit specifies the number of Trace Requests stored on the server. The maximum is 10000. The default value is 10.

5. tracemode specifies the sequence in which trace information is displayed. Sortbycategory or sortbytime (default)

For more information, see

Http://msdn.microsoft.com/zh-cn/library/6915t83k%28VS.80%29.aspx

The following uses a demo to describe how to use trace. axd to debug ASP. NET.

1. Create a web project named webtracetest

2. Edit the Web. config file and add a trace node (on)

The content is as follows:

<Trace enabled = "true" localonly = "true"
Pageoutput = "true"
Requestlimit = "15"
Mostrecent = "true"/>

3. Create a page named test. aspx, and add a text box and a button (both server-side controls) to it)

Press F5 to start debugging. The following page is displayed:

5. Enter text in the text box, such as alexis. click the button and you will find detailed information in Form collection, as shown below:

NOTE: With Trace. axd, we can obtain the following information:

Request details: request details

Trace information: trace information

Control tree: Control tree

Session state: session state

Application State: application state

Request cookies collection: a collection of request cookies.

Response cookies collection: Response Cookie set

Headers collection: Header set

Response Headers collection: Response Header set

Form collection: a collection of forms.

Querystring collection: the querystring collection (in the URL? String Information)

Server variables: Server Variables

Connect Visual Studio to a running process

When you press F5 to start debugging the program, vs. NET will generate the project (if necessary) and start the program in debug mode. That is to say, as long as the project is located in the debug assembly, vs. Net establishes a connection with the running program to respond to methods related to debugging, such as breakpoints.

However, sometimes we need or want to debug a process that is running outside of Visual Studio. This can be done when the process is located in the debug version assembly.

1. Select tool> debugging process to list all running programs, as shown in figure

2. Select the process you are interested in and click Connect. Visual Studio automatically switches to the debugging mode.

3. Open the SS window and find that the process we just selected is in the list, as shown in figure

This technique allows you to debug Windows service processes. When writing Windows service processes, you cannot start debugging by pressing F5, because they must be installed by administrative tools before they can run. If you generate and install a service program in debug mode, you can use this technique for debugging.

You can also debug SQL stored procedures in the same way. If you have installed the SQL Server debugging component and have sufficient permissions, you can connect to the SQL server process and set breakpoints for the stored procedure on the server for step-by-step execution.

Debug multiple projects in Visual Studio

In actual development, we often divide many layers, and there are many projects under a solution. Right-click the project to be debugged and select "Debug --> run new instance" to debug the project. You can also right-click the solution and select multi-project debugging, as shown in figure

We can also set the expected sequence of projects. In the Client/Server (CS structure) program, we can use this method to ensure that the server program runs before the client program.

It is interrupted only when a specific type of exception occurs.

A robust program will handle all possible exceptions at runtime. However, developers may find this troublesome when debugging complex programs. All exceptions are handled. In case of any exceptions, Visual Studio does not process them, or interrupts the code to prompt users.

Fortunately, Visual Studio has an option for developers to specify the exception type they are concerned about. Select the menu bar à debug à exception, or use the shortcut key CTRL + ALT + E. For example

We can see a tree structure listing all exceptions that vs can monitor.

The following two check boxes indicate whether to be thrown or not.

Test code download: http://down.51cto.com/data/138874

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.