Agenda
. Error Type and Handling Method
. Improve data access performance
. Use of server controls
. Cache Usage
Practical skills to improve performance
Error types and Handling Methods
1. Error Type
. Analysis program error
-Syntax error: syntax error
-Logical error: except 0 error, Type mismatch, incorrect output,
Use incorrect objects and process invalid data
. Compilation error: it cannot be recognized by the Language compiler,
But ASP. NET can recognize other keywords or statements.
Error
. Runtime error
. Configuration error: the Web. config file has an error.
2. handle errors
. Use verification controls
. Programming
-Verification statement
Checked and unchecked statements
-Try... catch... finally
Try {block}
Catch (formatexception) {response. Write ("format error ");}
Catch (overflowexception) {response. Write ("overflow ");}
Catch (exception ex) {ex. Message. tostring ();}
Some common exceptions:
Formatexception thrown when the parameter format does not comply with the parameter specifications of the called method.
Arithmeticexception. Exceptions caused by errors in arithmetic operations, type conversion, or conversion operations.
Overflowexception (inheriting arithmeticexception) is an exception that occurs when arithmetic operations, type conversion, or conversion operations are performed in the selected context.
Dividebyzeroexception (inherited from arithmeticexception) is an exception that is thrown when an integer or decimal value is division by zero.
-Page_error
Error Event of the Page Object
. Use Template
Void page_error (Object sender, eventargse)
{
Response. Write ("error occurred:" + server. getlasterror (). tostring ());
Server. clearerror ();
}
-Application_error: declarative error handling performed for the application in the application configuration file
Appliation object error event
. Any page in the application throws an exception and calls
. In Global. asax
. Format:
Void application_error (Object sender, eventargse)
{...}
Demo2
Write Windows error logs
Send the error email to the Administrator.
Handle errors using configuration files
. ASP. NET is the same as ASP in the past.
When the row time or Compilation Time is incorrect, an HTML error page is generated.
However, unlike ASP, ASP. NET pays special attention to the following:
The "security" information will not be disclosed because of this error.
. <System. Web>
<Customerrorsdefaultredirect = "url" mode = "remoteon
Ly ">
<Errorstatuscode = "code" Redirect = "url"> </error>
</Customerrors>
</System. Web>
Agenda
. Error Type and Handling Method
. Improve data access performance
. Use of server controls
. Cache Usage
Practical skills to improve performance
Performance Overview
. Yes
-Xmldocumentloadxml (stringstrfileid) // Add
Load XML
-Boolcheckidexisit (stringstrfileid, stringstrid)
// Determine whether a node exists
. Or
-Boolcheckidexisitbyxml (string strxml, stringstrid) // you can check whether a node exists.
-Or boolcheckidexisitbyxml (xmlbeanentobjxml, stringstrid) // you can check whether a node exists.
Logic Design
Suggestion: Use a three-layer Logical Model
-Pages (. aspx) and user controls (. ascx) UI
-Business and data access classes in \ bin dir
-Data within a SQL database via sprocs
Use the best data provider
. Ado. Net supports multiple providers:
-System. Data. sqlclient
-System. Data. oracleclient
-System. Data. oledb
-System. Data. ODBC
. All providers have the same programming model.
-However, there are significant performance differences
. Suggestion: Use the best provider
-Always use sqlclient when accessing MSDE/SQL
-Always use oracleclient when accessing Oracle
Data Provider Test
. Solution:
-Extract 50 rows from the SQL northwinds Database
-<% = %> HTML table formatting Technology
. Three techniques to measure (different data providers ):
-Traditional ASP/ADO
-ASP. NET w/system. Data. oledb provider
-ASP. NET w/system. Data. sqlclient provider
0
100
200
300
400
500
600
700
800
900
Traditional ASP/ADO with oledb
ASP. NET
ASP. NET with SQL
Request/second (4 P Service)
Data performance test
Datareaders and datasets
. Datareader
-Provides one-way read operations on the query results.
-Lightweight and fast-but always connected before reader is closed
. Dataset
-Non-Linked Data Access Method
-Datareader is used internally to obtain data.
-Datareader is automatically disabled after dataset is obtained.
. How to choose?
-Depends on your application
-In general, the system reads a large amount of data and does not process the returned data in large quantities.
Sqldatareader. Use datset to compare the large amount of returned data
Datareader? Dataset
Generally, the datareader Ratio
Dataset is faster than 16% !!
Executenonquery and executescalar
. Executenonquery
-No result set is required for data update.
-Because no result set is returned, network data transmission can be saved. It only returns the affected
The number of rows. If you only need to update the data with executenonquery performance overhead
Relatively small.
. Executescalar
-Only the first column in the first row of the result set is returned. Use executescalar
To retrieve a single value (for example, ID number) from the database ).
-Execute the returned data using the executereader method to generate a single value
The required operation requires less code than the operation.
. How to choose?
-Executenonquery only needs to update data.
Executescalar
Data Binding databinder
. General Binding method <% #
Databinder. eval (container. dataitem, "field name ")
%> You do not need to care about the data source when binding with databinder. eval.
(Dataread or dataset ). Don't worry about the data type eval
Converts the data object to a string. BIND at the underlying layer
I made a lot of work and used reflection performance. This is because
Convenience, but it affects data performance.
. Directly converted to datarowview will bring performance
Great improvements:
. <@ % (Datarowview) container. dataitem) ["
Segment name "] %>
Connection Pool
. Ado. Net has a built-in connection pool
-Automatic Cache/re-use connection
-You do not have to write any code for this purpose.
. Code Recommendations:
-"Open the connection in the code later, and then
Close"
-Do not keep the connection for a long time
-Immediately close the database connection to return it
Back to pool
Connection Pool
. Optimization tips:
-Different connection strings can generate multiple different connection pools
-Store a single connection string in Web. config.
-Use configurationsettings. deleettings
Use programming to access a row.
. Close the data connection explicitly to avoid connection leakage.
-Otherwise, the connection will remain open before the next garbage collection.
-Leakage of connections significantly reduces performance
Use stored procedures
We recommend that you use sproc for data access.
-Easier performance debugging with DBA
-Avoid distributed transaction costs by using Database Transaction Processing
-Helps prevent SQL injection attacks
-Helps eliminate the cost of repeated application and database calls
. Interesting tips:
-You can use the Enterprise Manager to disable dynamic SQL support and use it forcibly.
Sproc
Demo3
Use the connection pool Optimizer
Agenda
. Error Type and Handling Method
. Improve data access performance
. Use of server controls
. Cache Usage
Practical skills to improve performance
Server Control
. Provides a clear programming model (reuse, concise, applicable)
-Create the mode advocated by ASP. NET page
There are two considerations for performance optimization:
-Viewstate
-Number of controls
Viewstate Management
. ASP. NET controls can maintain the status of the page Control Element
-The status is transmitted as "viewstate" hidden field.
. Negative impact:
-Increase the network load (both on render and PostBack)
-Additional server performance consumption (serialize values to/from viewstate)
. Viewstate flexibility:
-Page Level (can disable viewstateentirely for a page)
-Control level (can disable viewstateusage on a per control basis)
. Suggestion:
-Carefully review the use of this function
-If the PostBack function is not used, disable viewstate at the page level.
-The control is re-generated every time during PostBack. Please block the control-level viewstate.
-Use <% @ page trace = "true" %> to trace the viewstate size
Viewstate management prompt
. If you want to more clearly limit the use of viewstate, you can
ASP. NET is disabled by default.
. Machine. config:
<Configuration>
<System. Web>
<Pages enableviewstate = "false"/>
</System. Web>
</Configuration>
The page that requires viewstate will be manually entered in the page command.
Row settings:
-<% @ Page enableviewstate = "true" %>
Number of controls generated
. Each Server Control on the page has a fixed
Cost
-The cost of each control is usually negligible.
. Composite controls can sometimes block the number of controls used, although
The following situations may occur:
-Clustering costs can be accumulated sometimes.
-Open ASP. NET trace to view the actual count.
Agenda
. Error Type and Handling Method
. Improve data access performance
. Use of server controls
. Use cache for program optimization
Practical skills to improve performance
Cache Technology
1. What is cache technology?
Cache is a way for computers to quickly obtain data again.
2. cache Principle
Storing frequently accessed data on a computer can be faster,
It is easier to read the location.
3. cache location in ASP. NET
Client Cache
Customer
Server
① Read data from the server
② Cache to Hard Disk
③ Access and read later
Hard Disk Data
Server Cache
Server ASP. NET Engine
ASP. NET Engine
Customer
③ Subsequent requests directly
Retrieve data from Cache
① Send data from ASP. NET
② Cache data
4. When to use cache?
Do not cache users
Modified object, such as shopping cart
Do not cache pages containing time
Surface
Cache the entire application
The setting or object used (
These settings and objects must be in
The lifetime does not change)
Do not cache personal information
Prevent theft by others
Cache those frequently accessed,
And little changed data
Cache should not be used
5. How to Use cache?
. ASP. NET has two caching technologies for Web applications:
Out buffer and data buffer.
-Output buffer: stores the dynamic output produced by a request.
.
-Data Buffer refers to the protection of uncertain objects according to certain policies.
Stored in memory.
. Use of output Cache
-Use the @ outputcache command
-For example (add to the page header)
<% @ Outputcacheduration = "10" varybyparam = "NONE" %>
Demo4
Output cache exercise
Data Cache
. ASP. NET provides an excellent cache engine.
Allows you to store pages and index HTTP requests.
Various objects required. ASP. NET Cache
Each application is private and stores various
Image Storage. The cache lifecycle depends on the application.
Life cycle, that is, when the application restarts
The cache has actually been rebuilt.
. Data Buffer
-Usage (similar to the use of session variables)
Cache ["username"] = "meme ";
Response. Write (cache ("username "));
-Note that you cannot access the variables in the cache by subscript, as shown in figure
Response. Write (Cache [0]); is incorrect.
-Cache Deletion
Cache. Remove ("username ");
. Use cache dependency
-Add cache Variables
. Cache. Add ()
. Cache. insert ()
They have the same functions, but insert is more flexible.
-Insert
(Key, value, dependencies, absoluteexpiration,
Slidingexpiration, priority, prioritydecay, onrem
Ovecallback)
Cache replacement policy
1. scavenging)
. When the memory becomes less nervous, the cache mechanism will find the most
Removes the least frequently used and least important objects from the memory.
To reduce system pressure.
2. "Expiration control" (expiration)
The programmer can specify the lifecycle of the cached object.
The specified time can be absolute or relative.
3. "file and key-value dependency"
Whether the foreign file or other cache key values have changed,
To determine whether the key value is valid.
Demo5
Data Cache
Agenda
. Error Type and Handling Method
. Improve data access performance
. Use of server controls
. Use cache for program optimization
Practical skills to improve performance
Practical Skills for improving performance
. Do not use unnecessary sessions, as in ASP,
Do not use session when necessary
Unnecessary Server Control
. Unnecessary viewstate is not used.
. Do not use exception to control program processes.
. Disable VB and JScript Dynamic Data Types
. Use the stored procedure to complete data access
Do not use dataset for read-only data access.
Disable ASP. NET debug mode
. Use ASP. netoutput cache to buffer data
Practical Skills for improving performance
. Use SQL to return the dataset to be bound to the DataGrid.
Perform secondary processing on dataset, especially for dataset.
A large number of rows are deleted, which proves to be slow. It is better to copy part of the data.
. Try to minimize the number of database operations to query data.
1-2 database operations can be completed;
. Optimize database query operations
. Do not select all data by default during page loading, although it is convenient
Follow-up operations, but the user will think that "no operation is so slow"
. We recommend that you replace complicated dataset with more efficient SQL statements as much as possible.
Secondary Processing
Practical Skills for improving performance
. Open the database connection only when necessary
. Once the database operation is complete, close the connection.
When closing the connection, remember to delete the temporary object.
Before closing the connection, make sure to close any user-defined transactions.
. Displays non-interactive data, which can be obtained using sqldatareader.
Optimal Performance
. Share the data that is obtained after complex processing or long query.
When you jump to the page, remember to terminate the processing of the current page.
. Do not use + for string operations with a large number of connections. Use it instead.
Stringbuilder