Turn: the website runs smoothly by avoiding the following 10 common ASP. NET Defects

Source: Internet
Author: User
Chinese page: http://blog.163.com/chuan_zheng/blog/static/856478720074155351773/
Http://msdn.microsoft.com/msdnmag/issues/06/07/WebAppFollies/default.aspx.
Sample Source Page: http://msdn.microsoft.com/msdnmag/issues/06/07/WebAppFollies/default.aspx? Fig = true # fig4

What impressed me after reading it:
Loadcontrol and output Cache

There are very few ASP. NET applications that do not use user controls. Before the master page appears, developers use user controls to extract public content, such as headers and footers. Even in ASP. in. NET 2.0, user controls also provide effective methods to encapsulate content and behaviors and divide pages into multiple regions, the cache capabilities of these regions can be controlled independently as a whole page (a special form of output cache called segment cache ).

User Controls can be declared or forcibly loaded. Forced loading depends on page. loadcontrol, which instantiates the user control and returns the control reference. If a user control contains a user-defined member (for example, a public attribute), you can convert the reference and access the User-Defined member from your code. The user control in Figure 1 implements the backcolor attribute. Run the following code to load the user control and assign a value to backcolor:

Protected void page_load (Object sender, eventargs E)
{
// Load the user control and add it to the page
Control control = loadcontrol ("~ /Myusercontrol. ascx ");
Placeholder1.controls. Add (control );

// Set the background color
(Myusercontrol) control). backcolor = color. Yellow;
}

The above code is actually very simple, but it is a trap for careless developers to fall. Can you find out the flaws?

If you guess this problem is related to the output cache, you are correct. As you can see, the above code sample compilation and running are normal, but if you try to add the following statement (completely legal) to myusercontrol. ascx:

<%@ OutputCache Duration="5" VaryByParam="None" %>

When you run this page next time, you will see invalidcastexception (Oh joy !) And the following error messages:

"The object of the type 'System. Web. UI. partialcachingcontrol' cannot be converted to the type 'myusercontrol '."

Therefore, this code runs normally without the outputcache command, but an error occurs if the outputcache command is added. ASP. NET should not run in this way. Pages (and controls) should be unknown for the output cache. So what does this mean?

The problem is that when the output cache is enabled for the user control, loadcontrol no longer returns a reference to the control instance; instead, it returns a reference to the partialcachingcontrol instance, and partialcachingcontrol may or may not wrap the control instance, depends on whether the control output is cached. Therefore, if developers call loadcontrol to dynamically load user controls and convert control references to access control-specific methods and properties, they must pay attention to this operation, so that the code can run regardless of whether it has an outputcache command.

Figure 2 shows the correct method for dynamically loading the user control and converting the reference of the returned control. The following is a summary of its working principles:

If the ascx file lacks the outputcache command, loadcontrol returns a reference to myusercontrol. Page_load converts the reference to myusercontrol and sets the backcolor attribute of the control.

If the ascx file contains an outputcache command and the control output is not cached, loadcontrol returns a reference to partialcachingcontrol. The cachedcontrol attribute of this partialcachingcontrol contains references to the basic myusercontrol. Page_load converts partialcachingcontrol. cachedcontrol to myusercontrol and sets the backcolor attribute of the control.

If the ascx file contains an outputcache command and the control output is cached, loadcontrol returns a reference to partialcachingcontrol (whose cachedcontrol attribute is null. Note that page_load does not continue the operation. The backcolor attribute of the control cannot be set because the output of the control comes from the output cache. In other words, there is no myusercontrol to set the attribute.

No matter whether the. ascx file contains the outputcache command, the code in Figure 2 runs. Although it looks complicated, it can avoid annoying errors. Simplicity does not always mean ease of maintenance.

 

View status: silent performance killer

In a sense, view State is the greatest thing in history. After all, the view status enables the page and control to remain in the status between sending and receiving. Therefore, you do not need to write code like in traditional ASP to prevent text in the text box from disappearing when you click the button, or re-query the database and re-bind the DataGrid after sending the response.

However, the view status also has its disadvantages: when it grows too large, it becomes a silent performance killer. Some controls (such as text boxes) determine the view status accordingly. Other controls (especially the DataGrid and gridview) determine the view status based on the displayed amount of information. If the gridview displays 200 or 300 rows of data, I will be daunting. Even if ASP. NET 2.0 view status is ASP. net 1 x View status is half the size, a bad gridview can also easily reduce the effective bandwidth of the connection between the browser and the Web server by 50% or more.

You can disable the view status of a single control by setting enableviewstate to false, but some controls (especially DataGrid) lose some functionality when they cannot use view status. A better solution to controlling view status is to keep it on the server. In ASP. NET 1.x, You can override the loadpagestatefrompersistencemedium and savepagestatetopersistencemedium methods of the page and process the view status as you like. The code shown in Figure 4 is rewritten to prevent the view status from being retained in the hidden field while retaining it in the session state. When used together with the default session state process model (that is, when the session state is stored in the ASP. NET auxiliary process in the memory), the view State is particularly effective in the session state. On the contrary, if the session status is stored in the database, only the test can be displayed in the session status. Retaining the view status will improve or degrade the performance.

ASP. NET 2.0 uses the same method, but ASP. NET 2.0 provides a simpler way to keep the view State in the session state. First, define a custom page Adapter. The getstatepersister method returns an instance of the. NET Framework sessionpagestatepersister class:

public class SessionPageStateAdapter :
System.Web.UI.Adapters.PageAdapter
{
public override PageStatePersister GetStatePersister ()
{
return new SessionPageStatePersister(this.Page);
}
}

Then, add the app. Browsers file to the app_browsers folder of the application in the following way, and register the custom page adapter as the homepage page adapter:

<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.Page"
adapterType="SessionPageStateAdapter" />
</controlAdapters>
</browser>
</browsers>

(You can name a file as long as its extension is. browsers .) ASP. NET then loads the page adapter and uses the returned sessionpagestatepersister to retain all page states, including view states.

One disadvantage of using a custom page adapter is that it acts globally on every page of the application. If you prefer to retain the view status of some pages in the session state rather than those of other pages, use the method shown in Figure 4. In addition, if you create multiple browser windows in the same session, you may encounter problems using this method.

Uncached role

The following statements are often used in the web. config file of ASP. NET 2.0 applications and an example of ASP. NET 2.0 role Manager:

<roleManager enabled="true" />

But as shown above, this statement does have a significant negative impact on performance. Do you know why?

By default, ASP. NET 2.0 role manager does not cache role data. On the contrary, it will refer to role data storage every time it needs to determine which role (if any) the user belongs. This means that once the user has been authenticated, any page that uses role data (for example, a page that uses a website graph with security cut settings enabled, and a page that uses Web. in config, the restricted page is accessed Based on the role URL Command.) This will cause the role manager to query the role data storage. If the role is stored in the database, you can easily avoid accessing multiple databases when each request needs to access multiple databases. The solution is to configure the role manager to cache role data in cookies:

<roleManager enabled="true" cacheRolesInCookie="true" />

You can use other <rolemanager> attributes to control the features of the role cookie-for example, the cookie should be valid for a long time (and the frequency at which the role manager returns the role database ). By default, role cookies are signed and encrypted. Therefore, although the security risk is not zero, it is mitigated.

Back to Top

Thread Pool saturation

When I perform a database query and wait for 15 seconds or longer to obtain the returned query results, I am often surprised by the actual ASP. NET page number. (I also waited 15 minutes to see the query results !) Sometimes, latency is inevitable because of the large amount of returned data. Sometimes, latency is caused by poor database design. However, for whatever reason, a long database query or any type of long I/O operations may cause a decrease in throughput in ASP. NET applications.

I have described this issue in detail before, so I will not explain it too much here. I can only say one thing, Asp. net depends on a limited thread pool to process requests. If all threads are occupied to wait for database queries, Web service calls, or other I/O operations to complete, before an operation is completed and a thread is released, other requests must wait in queue. When requests are queued, the Performance drops sharply. If the queue is full, ASP. NET will cause subsequent requests to fail with an HTTP 503 error. This is not what we want to see in the production applications of web production servers.

The solution does not belong to asynchronous pages, which is one of the best but little-known functions in ASP. NET 2.0. An asynchronous page request starts from a thread, but when it starts an I/O operation, it returns the thread and the iasyncresult interface of ASP. NET. After the operation is complete, the request uses iasyncresult to notify ASP. NET that ASP. NET extracts another thread from the pool and processes the request. It is worth noting that when I/O operations occur, the thread pool thread is not occupied. In this way, you can significantly increase the throughput by blocking requests from other pages (pages without long I/O operations) waiting in the queue.

You can read all information about asynchronous pages in the October 2005 msdnmagazine journal. I/O binding is likely to become an asynchronous page for any page that requires a long execution time instead of a computer binding.

When I tell developers about asynchronous pages, they often say, "That's great, but I don't need them in my applications ." I replied, "Do You Need to query databases on any page? Do they call Web Services? Have you checked statistics on queuing requests and average waiting time in ASP. NET performance counters? Even if your application runs normally so far, the load of your application may increase as your customer grows ."

In fact, most actual ASP. NET applications require asynchronous pages. Please remember this!

Back to Top
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.