Asp.net| Programming | Tips In this paper, we will discuss 10 techniques that programmers need to be aware of when using ASP.net to develop applications that involve changes from the default controls, table Single-name to StringBuilder classes, and help programmers adapt as quickly as possible. NET environment.
1, in the use of visual Studio. NET, do not use the default name except for objects that are directly or not referenced.
. NET, one of the benefits is that all source code and configuration files are plain text files that can be edited using any text editor such as Notepad or WordPad. If not, we are not necessarily using visual Studio. NET as an integrated development environment. But with Visual Studio. NET, we can see files in Windows File Manager, or in Visual Studio. NET to browse the contents of a file from a text editor.
Use Visual Studio. NET as an integrated development environment has many benefits, the most notable of which is that it greatly improves productivity. Use Visual Studio. NET, we are able to develop the software faster with a small cost. IntelliSense, as part of the integrated development environment, provides automatic code completion, provides dynamic help when entering methods or functions, real-time hints of syntax errors, and other features that improve productivity.
Like other complex tools, Visual Studio before learning how to give full play to its role and grasp its "habits". NET also gives us a sense of frustration. Sometimes it's like a black box that's hard to understand, generating a lot of files and lots of useless code.
Visual Studio. NET is the ability to provide a default name for a new object, whether it is a class, a control, or an object in a form. For example, if we create a new ASP.net Web application, the default name will be WebApplication1. We can easily change the name of the application in the "New Project" dialog box, but at the same time change only the name of the application's namespace and its virtual directory, the source code file's default name is still WebForm1.aspx and WebForm1.aspx.cs (C # Engineering) or WebForm1.aspx.vb (vb.net engineering).
We can change the file name used by ASPX and code in the scenario browser, but the name of the Web page class will still be WebForm1. If a button is generated on the Web form, the default name will be Button1. In fact, the names of all controls are made up of the type and number of controls.
We can, and should, change the names of all the forms and controls in the application to meaningful names. The default name is also available for smaller demos, but if the application is composed of multiple forms, with many buttons and labels on each form, tables such as Frmstartup, Frmdataentry, and Frmreports are single-name more than Form1, Names like Form2 and Form3 are easier to understand and maintain.
If a control on a form is to be referenced elsewhere in the code, it is even more important to have a meaningful name. Names such as Btnok, Btncancel, and btnprint make it easier for people looking at the code to understand, and therefore easier to maintain than controls named Button1, Button2, and Button3.
A good way to modify a name that appears in all files in a project is in Visual Studio. NET menu, select Edit-> to find and replace-> the Replace command.
When we look at the code we wrote two weeks ago, it's often like we saw it for the first time, so it's necessary to have a name that helps us understand its meaning.
2, even if you do not use visual Studio. NET programming, using code support files also helps improve application performance
In all asp.net Web projects, such as Web applications, Web services, or Web controls, Visual Studio. NET uses code support files. The code support file makes the project better organized, modular, and more suitable for the development team composed of many people. In addition, it also brings performance improvements.
The contents of the code support file are compiled into a class in a composite file, typically a DLL file, or sometimes an EXE file. The file resides in the application's assembly cache, and can be immediately available when the application starts.
If the code is contained in the <script> tag or in the ASPX file code, it will still be compiled into a Web page class. In this case, each time the page is loaded for the first time in the application dialog, it needs to be compiled again, and the compiled class resides in memory. Each time the computer starts, IIS stops, restarts, or the source code, configuration file changes, the file must be recompiled. Although not large, the resulting loss of performance is considerable.
3. Minimize form Loopback
Whenever you click a button, LinkButton, or ImageButton control on a Web page, the form is sent to the server. If the control's AutoPostBack property is set to True, the form is sent back to the server if the state of the checkbox, CheckBoxList, and so on is changed.
Each time the form is sent back to the server, it is reloaded, the Page_Load event is started, and all the code in the Page_Load event handler is executed. It is most appropriate to put the initialization code of the Web page here. We often want to execute some code every time we load a Web page, but we want to execute some code when the page first loads, and even want some code to execute on every load except for the first load.
You can use the IsPostBack feature to do this. The value of this property is false the first time the page is loaded. If the page is reloaded by loopback, the value of the IsPostBack property is set to true. By testing, you can execute the specified code at any time. The following is the related C # code:
protected void Page_Load (Object sender, EventArgs e)
{
Some of the actions that are performed each time a Web page is loaded
if (! IsPostBack)
{
What to do when a Web page is loaded for the first time
}
Else
{
Actions to perform when loopback
}
What to do when a Web page is loaded each time
}
We would like to try not to cause loopback (each loopback will require the server to do a series of operations), even if caused by loopback. You also want to be able to perform as few operations as possible. Large-scale, waste-time operations, such as database lookups, should be especially avoided because they can prolong the response time of an application.
4, the use of StringBuilder class
String in the. NET Framework, which means that changing the operator and method of a string returns a changed copy of the string, which means there is room for improvement in performance. When doing a lot of string manipulation, using the StringBuilder class is a better choice.
The following C # code tests the time that is required to generate a string from 10,000 substrings in two different ways. A simple string concatenation operation was used for the first time; the StringBuilder class was used for the second time. To see the result string, you can remove the callout symbol for the callout line in the following code:
To perform a string concatenation operation first
StartTime = DateTime.Now;
for (int i=0; I < Intlimit; i++)
{
Strsub = i.ToString ();
Strwhole = Strwhole + "" + strsub;
}
Endtime = DateTime.Now;
ElapsedTime = Endtime-starttime;
Lblconcat.text = Elapsedtime.tostring ();
Lblconcatstring.text = Strwhole;
Doing the same thing with the StringBuilder class
StartTime = DateTime.Now;
StringBuilder sb = new StringBuilder ();
for (int i=0; I < Intlimit; i++)
{
Strsub = i.ToString ();
Sb. Append ("");
Sb. Append (strsub);
}
Endtime = DateTime.Now;
ElapsedTime = Endtime-starttime;
Lblbuild.text = Elapsedtime.tostring ();
Lblbuildstring.text = sb. ToString ();
}
</form>
</body>
The difference in the two ways is quite large: the Append method using the StringBuilder class is nearly 200 times times faster than using string concatenation. The results of the comparison are as follows:
(Figure: PICTURE01)
5. Use server-side controls only when necessary
Asp. NET, a control called Web server controls that runs on the server side is introduced, and in code, they are often illustrated by the following syntax:
<asp:textbox id= "Txtlastname" size= "" runat= "Server"/>
They are also sometimes referred to as ASP controls. The server-side control is indicated by the Runat property, and its value is always "server".
By adding the Runat property, a generic HTML control can be easily converted to a server-side run, and here's a simple example:
<input type= "text" id= "Txtlastname" size= "" runat= "Server"/>
By using the name specified in the id attribute, we can reference the controls in the program and programmatically set the properties and get the values, so the server-side approach has greater flexibility.
There is a certain cost to this flexibility. Each server-side control consumes resources on the server. In addition, unless the control, Web page, or application explicitly prohibits view state, the control's status is contained in the hidden field of view, and is passed in each loopback, causing severe performance degradation.
A good example of this is the application of a control table on a Web page that uses HTML tables that do not require server-side processing if you do not need to refer to elements in the table in your code. We can still place the server control in the HTML table cell and reference the server control in code. If you need to refer to any table element, such as a specified cell, the entire table must be a server control.
6. Differences between hyperlink controls, LinkButton controls
HyperLink, LinkButton controls are the same for web visitors, but they still differ significantly in functionality.
When a user clicks on a control, the hyperlink control immediately "navigates" the user to the destination URL, and the table is not echoed to the server. The LinkButton control first sends the table back to the server and then navigates the user to the target URL. Use the LinkButton control if server-side processing is required before reaching the target URL, or you can use the hyperlink control if you do not need server-side processing.
7. Annotation Code
This technique is not aimed at asp.net, but it is a good programming habit.
Comments should not only explain what the code does, but should also indicate why. For example, instead of just stating in a comment that you are traversing an array, you should explain that the traversal array calculates a value based on an algorithm, unless the algorithm is fairly simple, otherwise the algorithm should be briefly described.
. NET project different programming languages have their own different annotation symbols, the following is a brief description:
HTML <!--annotation-->
JavaScript//Notes
VBScript ' Notes
VB.net ' note
C #//Notes
/* Multiline Content
The annotation
*/
SQL--Comments
There is no annotation symbol in the start and end tag of the server control, but the server can ignore all properties it does not recognize, so we can insert the annotation by using a property that is not defined. Here is an example:
<asp:textbox
Id= "Txtlastname"
Size= "40"
Comment= "This is my note."
runat= "Server"/>
In Visual Studio. NET is very simple to annotate the source code. Highlight the line you want to comment on, and then press Ctrl+k+c to add a comment. To remove a comment, simply display the annotated code with a high brightness and press the Ctrl+k+u key combination.
In C # Engineering, we can also enter XML annotation bars by using///at the beginning of each line. In the annotation section, we can use the following XML markup to organize comments:
<summary></summary>
<remarks></remarks >
<param></param>
<returns></returns>
<newpara></newpara>
To be in visual Studio. NET to view the formatted report of these XML annotations, we can first select the Tools menu item and then select the Create Comment Web page menu item.
8. Use the trace method and trace property to record the execution of pages in the page directory
One of the oldest techniques for debugging is inserting output statements at a key point in the program, where the output information contains the value of the important variable, and the information can be exported to the screen, log file, or database.
In asp.net, this debugging technique is easier to use by using the Trace attribute in the page command. The page command is a line of code at the beginning of the ASPX file, which provides instructions for the compiler. The page command contains one or more properties that provide the compiler with information such as the programming language used, the location of the code support file, or the name of the class to inherit.
One of the properties in the page command is trace, whose value may be true or false, and the following is a typical page command where the value of the Trace property is true:
<%@ Page language= "C #" trace= "true"%>
If the value of the Trace property is set to True, the Web page generated by the ASPX file is displayed, and a large amount of additional information about the page is displayed in addition to the page itself. This information is displayed in a table in the following sections:
· The request details provide the session ID, the requested time, and the status code of the request.
· Trace information contains a list of trace logs, chronological steps in the Web page life cycle. Alternatively, you can add custom information to it.
• The control tree lists all the controls on a Web page in a hierarchical fashion, including the size of each control in bytes.
· The Cookies collection lists all cookies created by the Web page.
• Head collection HTTP headers and their values.
· The server environment variable that the server variable is associated with for this page.
The trace logs contained in the trace Information section are most useful, where we can insert our own tracking commands. There are 2 methods in the Trace class that can insert commands in the trace log: Trace.Write and Trace.Warn, except that the Trace.Warn command is displayed in red font and the Trace.Write command is displayed in black font. Below is a screenshot of the trace log, which contains several Trace.Warn commands.
The most convenient feature in the trace log is that we can insert trace.write and Trace.Warn statements throughout the code during development and testing, and when the application is finally delivered, you can prevent these commands from working by changing the value of the trace property in the page command, without having to remove the output language before deploying the application software Sentence
9. Using Stored Procedures
Microsoft's SQL Server and other modern relational databases use SQL commands to define and process queries. A SQL statement or a series of SQL statements submitted to SQL Server,sql Server resolves the command, then creates a query plan and optimizes it, and then executes the query plan, which takes a lot of time.
A stored procedure is a series of SQL commands that are resolved and optimized by a query processor that is stored and executed quickly. Stored procedures are also called SPROCs, which can receive input parameters so that a single stored procedure can handle a larger range of specific queries.
Because sprocs are resolved in advance and are more important for complex queries, their query plans are optimized, so invoking the query process is much faster than SQL statements that perform the same functions.
10, use. NET command line
. NET command-line tool runs in a command prompt window. In order for the command to execute, it must reside in the current directory at the command prompt, or by setting the PATH environment variable.
The. NET SDK installs a menu item on the Startup menu that opens a command prompt window that correctly sets the PATH environment variable. We can click "Start"-> "program"-> "Microsoft Visual Studio. NET"-> Visual Studio. NET tool "->" Visual Studio. NET command prompt, and start a command prompts window.
By pressing CTRL + C while you drag the menu item from the menus to the desktop, you can copy the menu item's shortcut to the desktop, which is convenient to use.
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.