Best ASP. NET Programming habits

Source: Internet
Author: User
(From the Ms. NET Technology Forum)

New programmers tend to like to collect some "Fantastic" programming skills. However, the accumulation of skills often does not improve the quality of the program. Instead, some programmers are guided to pursue novelty and novelty, having forgotten the cultivation of basic programming habits is not conducive to team cooperation. Maybe, this is why China does not lack smart programmers, but lacks a smart development team. In ASP. NET development, you can learn a lot of skills, but some basic programming habits we must develop, this not only can fundamentally improve the program quality and development efficiency, but also, it is also conducive to program reading and team development. If a program you write can only be understood by yourself, or only a few people can understand it, even if the program skills are superb, the upgrade and maintenance of the program will be fatal.

I. Handling of errors (other)
The most basic requirement for program robustness is the processing and capturing of program errors. in ASP. NET, the error processing mechanism is the same as that in other programming languages. You can use try... Catch... Finally and so on, which is greatly improved compared with ASP. In addition, using these error handling methods can greatly improve the readability and debugging speed of the program. When combining these advantages, we should pay more attention to this.
For error handling, refer to this article (English ):
Http://www.123aspx.com/redir.aspx? Res = 28336

Ii. string processing
In web design, string processing is almost the most common. Use ASP.. net, the string processing speed is faster than ASP. net, specifically added a string processing class stringbulider, using this class can complete some common string operations, and most importantly, using stringbuilder can greatly improve the string processing speed.
In ASP. NET, the most common is to use "&" to connect two strings:
Dim myoutputstring as string = "my name is"
Dim myinputstring as string = "Alex"
Myoutputstring = myoutputstring & myinputstring
Response. Write (myoutputstring)
Now let's take a look at the use of stringbuilder. When using stringbuilder, we can perform some basic operations on strings, such as append, replace, insert, and remove, now let's take a look at the specific example.
(1) Use of append in stringbuilder
Append is the same as append in other languages, that is, adding other characters at the end of the string.
Dim Sb as stringbuilder = new stringbuilder ()
SB. append ("<Table border = '1' width = '000000'> ")
For I = 0 to rowcount-1
SB. append ("<tr> ")
For k = 0 to colcount-1
SB. append ("<TD> ")
SB. append (Dt. Rows (I). Item (K, datarowversion. Current). tostring ())
SB. append ("</TD> ")
Next
SB. append ("<tr> ")
Next
SB. append ("</table> ")
Dim stroutput as string = sb. tostring ()
Lblcompany. Text = stroutput
In the above program, the append method is used to output a table. Note that the stringbulider must first use tostring () the method can be converted to the string type for direct output. In the above example, all we see is a direct string of append. In fact, this method has a very convenient function, that is, it can directly append other types of variables, for example, you can appemd a value of the integer type directly. Of course, the output will be automatically converted into a string:
Sub page_load (source as object, e as eventargs)
Dim Sb as system. Text. stringbuilder
Dim varother as integer
Varothers = 9999
SB = new system. Text. stringbuilder ()
SB. append ("<font color = 'blue'> Other append types are supported: </font> ")
SB. append (varother)
Response. Write (sb. tostring ())
End sub
(2) Use of other methods in strings
We can also use other methods to look at the common ones:
Insert method. you can insert other characters at the specified position. Use the insert method: insert (insert position, insert character );
The remove method can be used to delete a specified number of characters at a specified position. Usage: Remove (actual position, number of characters );
Replace method, which can replace specified characters. Usage: Replace (Replaced string, replaced string)
For the detailed introduction and usage of strings, refer to the following article (English ):
Http://aspfree.com/aspnet/stringbuilder.aspx
Http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemTextStringBuilderClassTopic.asp

Iii. database connection and datareader Shutdown
When programming with ASP, we know that after connecting to a database, we must close the connection and set it to nothing. In ASP. net, we still need to use it like this, however, in ASP. net, due to the use of ADO. net. Therefore, there are some subtle differences in some related processing. These differences are often the most important during our design. Now, let's take an example to see what issues need to be paid attention to in common ADO. Net operations.
(1) Example 1
Dim myconnection as sqlconnection = new sqlconnection (configurationsettings. receivettings ("dsn_pubs "))
Dim mycommand as sqlcommand = new sqlcommand ("select pub_id, pub_name from publishers", myconnection)
Dim mydatareader as sqldatareader
Try
Myconnection. open ()
Mydatareader = mycommand. executereader (commandbehavior. closeconnection)
Dropdownlist1.datasource = mydatareader
Dropdownlist1.databind ()
Catch myexception as exception
Response. Write ("an error has occurred:" & myexception. tostring ())
Finally
If not mydatareader is nothing then
'Close datareader
Mydatareader. Close ()
End if
End try
In the preceding example, we noticed that only datareader is disabled and connection is not disabled. Why? Observe the preceding executereader method carefully. Originally, the executereader parameter is set. After the executereader is executed, the connection is automatically closed. Therefore, after this setting, there is no need to manually close the connection.
(2) Example 2
Dim myconnection as sqlconnection = new sqlconnection (configurationsettings. receivettings ("dsn_pubs "))
Dim mycommand as sqlcommand = new sqlcommand ("select pub_id, pub_name from publishers", myconnection)
Try
Myconnection. open ()
Dropdownlist1.datasource = mycommand. executereader ()
Dropdownlist1.databind ()
Catch myexception as exception
Response. Write ("an error has occurred:" & myexception. tostring ())
Finally
If not myconnection is nothing andalso (myconnection. State and connectionstate. Open) = connectionstate. Open) then
Myconnection. Close ()
End if
End try
In the above example, we found that datareader was not closed. Why? In fact, the above Code does not directly generate the datareader object, and of course it cannot be closed. Note that before closing the connection, the program first checks whether the connection is enabled. If the connection is not enabled, it is unnecessary to close the connection.

4. Use web. config/maching. config to save common data
Some data needs to be used frequently. For example, when using ADO. net, the most common is the database connection statement. In ASP, we often save this information in the application. Of course, in ASP. net. However, Asp. net has provided a configuration file web. config, so we 'd better save the information on the web. config, of course, we can also save it in machine. config. However, in this case, the entire website must be used. Therefore, we generally use web. config. Now, let's take a look at the usage of this file.
(1) settings of the web. config file
First, let's take a look at the settings of Web. config. We Add the following two items in this file:
<Configuration>
<Deleetask>
<Add key = "DSN" value = "myserver"/>
<Add key = "someotherkey" value = "somevalue"/>
</Appsettings>
</Configuration>
(2) Use of Variables
The above XML file sets the DSN and someotherkey variables. Now let's see how to use them in the program:
<HTML>
<Script language = "VB" runat = Server>
Sub page_load (sender as object, e as eventargs)
Dim deleetaskas hashtable = context. getconfig ("deleetask ")
DSN. Text = deleettings ("DSN ")
Someother. Text = maid ("someotherkey ")
End sub
</SCRIPT>
<Body>
DSN setting: <asp: Label id = "DSN" runat = server/> <br>
Some other setting: <asp: Label id = "someother" runat = server/>
</Body>
</Html>
The above program shows that using the variables defined in this way is very simple and convenient.

V. Use. Net to debug the program
Debugging ASP programs has always been the most difficult part to compile ASP programs. asp programmers may have a deep understanding of this point, because everyone uses response. Write for debugging. The biggest drawback of such debugging is that when debugging is completed, we must delete or comment out the information one by one. Think about it. If the program code Reaches hundreds of lines or many pages, this kind of work is so boring and boring. If you forget to delete the write for debugging, some indecent debugging information may appear when you use it.
After ASP. NET is used, we can directly define trace to debug the program. The above mentioned troubles can be easily solved. Familiar with trace, trace can be implemented through specific pages and on the web. in the config configuration file, define the implementation. In this way, after the program debugging is completed, set trace to off. In this way, the program will not have the debugging function.
(1) Implementation of page debugging
When debugging is required for a specific page, we can set it as follows:
<% @ Page Language = "VB" trace = "true" %>
(2) define web. config implementation
In web. config, we can also enable program debugging:
<Configuration>
<System. Web>
<Trace enabled = "true" requestlimit = "10" localonly = "false"/>
</System. Web>
</Configuration>
After you use the preceding settings to open Trace, you can use trace in a specific program to debug the program. For example:
Trace. Write ("this is some custom debugging information ")
Or debug program variables:
Trace. Write ("this is my variable and it's value is:" & myvariable. tostring ())
The above settings show that in ASP. net, the program debugging function is very convenient and simple. If we ignore these features in the program design and continue to use ASP thinking to design the program, then our program will not only improve the efficiency, it also makes it more difficult for other developers to cooperate.

Vi. Summary
The above programming Habits can be developed slowly. During program design, Do not worry too much about whether the program is the most concise and flexible. For general developers, program standardization and readability may be more important than pursuing program flexibility. In the case of increasingly rich Internet resources, we can refer to some very standard program source code to learn, of course, the best is Microsoft's own thing, we can refer to the following url: http://www.asp.net, for more programming problems,

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.