Sunday, June 1, 2008

ASP.Net Quick Tips

Select the Release mode before making the final Build for your application.

This option is available in the Top Frame just under the Window Menu option. By default, the Mode is Debug

Use Foreach loop instead of For loop for String Iteration


Use strString=string.Empty instead of strString=""  And perhaps instead of strString=null also (?)


GIF and PNG are similar,
but PNG typically produces a lower file size. (True, but some browsers not supporting PNG format)



Deploy application with debug="false"

When we develop asp.net application using Visual Studio, the default value for debug attribute is true. This setting will help developers to debug the application in development environment. For example, executing the application in this mode will not cache the resource files rendered by WebResources.axd handler. This prevents the need to clear the temporary cache every time when the developer needs to check the changes done. There will be other useful things done for developers for debugging like debug symbols, settings that will enable breakpoints etc. These setting will give a poor performance in production if released in the default debug mode (false).

So, never release your website with debug mode set to true. It should be set to false in web.config when moving to production. <compilation debug="true">

Alternate will be in machine.config. If you are a server administrator, make this change in machine.config <deployment retail=”true”/> so that it will enforce the debug attribute in the application’s web.config to false. It also disables the page output tracing and the ability to show the detailed exception report to the remote users when there is an exception.

<configuration>
    <system.web>
          <deployment retail=”true”/>
    </system.web>
</configuration>



Turn off Tracing

Turn off Tracing unless until required. (by default it's off, use on the pages where it's required)
<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"/>

Using Server.Transfer instead of Response.Redirect 


Response.Redirect sends a metatag to the client that makes the client send a new request to the server by using the new URL. Server.Transfer avoids this indirection by making a server-side call.

View State Optimization
Avoid using ViewState for storing huge objects or disable it when you don’t need it. ViewState is also used by server controls so that they can retain their state after postback. You can also save your objects that are marked Serializable in the ViewState. ASP.NET serializes all objects and controls in the ViewState and transmits them in a hidden field to the browser. If not managed properly ViewState can increase page size and therefore increase network traffic. Also precious CPU cycles are used for Serialization and De-Serialization of ViewState objects. Disable ViewState if:

  • Your pages don’t do postback.

  • You controls are not bound to a data source or they don’t handle server events like OnClick, OnSelectedIndexChanged etc or their properties are set on each postback

  • You recreate controls on every postback.
You can disable ViewState in both web.config or @Page directive
      <pages enableViewState="false">      or
      <%@ Page EnableViewState="false"%>


 

Page.IsPostBack is your friend


Use the Page.IsPostBack property to ensure that you only perform page initialization logic when a page is first loaded and not in response to client postbacks. The following code fragment shows how to use the Page.IsPostBack property.



if (!Page.IsPostBack) //IsPostBack property will be false for the first time
{
  //load the dataset for the first time
}
else               
{
  //use the loaded dateset for other post back requests
}




Remove unnecessary Http Modules for faster pipeline


Make sure you don’t execute code needlessly. I don’t know how many web developers forget about checking IsPostBack! It seems like such a basic thing to me! Needless processing!

There are several ASP.NET default HttpModules which sit in the request pipeline and intercept each and every request. For example, SessionStateModule intercepts each request, parses the session cookie and then loads the proper session in the HttpContext. Not all of these modules are always necessary. For example, if you aren't using Membership and Profile provider, you don't need FormsAuthentication module. If you aren't using Windows Authentication for your users, you don't need WindowsAuthentication. These modules are just sitting in the pipeline, executing some unnecessary code for each and every request.

The default modules are defined in machine.config file (located in the $WINDOWS$\Microsoft.NET\Framework\$VERSION$\CONFIG directory).

&lt;httpModules&gt;
&lt;add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/&gt;
&lt;add name="Session" type="System.Web.SessionState.SessionStateModule"/&gt;
&lt;add name="WindowsAuthentication" ="System.Web.Security.WindowsAuthenticationModule"/&gt;
&lt;add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/&gt;
&lt;add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule"/&gt;
&lt;add name="RoleManager" type="System.Web.Security.RoleManagerModule"/&gt;
&lt;add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule"/&gt;
&lt;add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule"/&gt;
&lt;add name="AnonymousIdentification" type="System.Web.Security.AnonymousIdentificationModule"/&gt;
&lt;add name="Profile" type="System.Web.Profile.ProfileModule"/&gt;
&lt;add name="ErrorHandlerModule" type="System.Web.Mobile.ErrorHandlerModule, System.Web.Mobile, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/&gt;
&lt;add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/&gt;httpModules&gt;

You can remove these default modules from your Web application by adding nodes in your site's web.config. For example:

&lt;httpModules&gt;        
&lt;remove name="Session" /&gt;     
&lt;remove name="WindowsAuthentication" /&gt;    
&lt;remove name="PassportAuthentication" /&gt;    
&lt;remove name="AnonymousIdentification" /&gt;     
&lt;remove name="UrlAuthorization" /&gt;     
&lt;remove name="FileAuthorization" /&gt;    
&lt;remove name="OutputCache" /&gt;    
&lt;remove name="RoleManager" /&gt;    
&lt;remove name="Profile" /&gt;    
&lt;remove name="ErrorHandlerModule" /&gt;    
&lt;remove name="ServiceModel" /&gt;  httpModules&gt;


Connection Pooling

Creating a connection to a database is a resource intensive process and takes time. Connection pooling allows you to reuse these connections saving time and resources. When a new connection is requested the connection pool managers first searches in the connection pool and if doesn’t finds one, it creates a new one. There are various things that need to be done to use connection pooling effectively:

  • Avoid Connection Leakage. This means that you opened a connection but didn’t close it. If you don’t close the connection the connection pool manager will never put it in the pool for later reuse until the GC is called.

  • Use the same connection string. Connection pool manager searches for similar connection in the pool by the connection string.

  • Use SQL Servers and .NET CLR Data performance counters to monitor pooling.

  • Open connections as late as possible and close them as early as possible

  • Don’t share same connection between multiple function calls. Instead open a new connection and close it in each function.

  • Close transactions prior to closing the connection.

  • Keep at least one connection open to maintain the connection pool.
Avoid DataBinder.Eval

Avoid calling DataBinder.Eval multiple times for example in case of grids, repeaters etc. Instead use Continer.DataBind. DataBinder.Eval uses reflection to evaluate the arguments and therefore can decrease performance if called numerous times.

No comments:

Post a Comment