Optimize ASP.NET Performance

One of the most important things you can do to improve performance in an ASP.NET application is to reduce the number of round trips to the server. Don’t request the current page if you don’t have any processing to perform on the server before transferring the user to another page. For example, I once had a client whose most frequently used button on the most frequently used page contained a single line of code that did exactly one thing: It redirected the user to the next page. In this circumstance, you can dispense with the button and simply add a Hyperlink control to the page that causes the browser to request the next page directly. Your server will have one less page to process.

Sometimes you use a button and a line of code because the next page needs some data from the current page. In ASP.NET 2.0, however, you can avoid requesting the current page and post the current page’s data to the server by using cross-page posting. All you have to do is set the PostBackUrl property of your button to the URL of the next page. On the new page, use the PreviousPage property to retrieve the data you need from the current page. This code retrieves the value of a control called FirstNameTextBox from the previous page:

Dim Name As String
Name = CType(Me.PreviousPage.FindControl( _
“FirstNameTextBox”), TextBox).TextYou also can reduce the overhead of transferring the user from one page to another. If your user doesn’t need to bookmark a page, use the Transfer method of the Server object to send the user a new page instead of the Redirect method of the Response object. The Redirect method requires two round-trips to the server to get the user to the next page. The Transfer method simply sends the user to the new page, eliminating the overhead of a second request to the server (see Figure 1).

Note that there is a usability cost to employing the Transfer method. You can use the Transfer method only to send the user to a page in the same site. More importantly, the browser doesn’t see the switch in pages, so the address bar of the browser reflects the URL of the original page. This can cause a complication when bookmarking the page because the user is actually bookmarking the page you transferred the user from, rather than the page the user sees. Similarly, a user refreshing the page is requesting a new version of the page specified in the address box, rather than the displayed page.

Reduce the Server’s Load
It’s obvious, but the less work you do on the server, the faster your server will run. Unless you take advantage of some server-side feature of a control, you should consider using the equivalent HTML control for any server-side code. For instance, do the labels on your page need to be ASP.NET server-side labels? If not, use the HTML Label control, which requires considerably less processing on the server. If all you use the DataGrid control for is to display data, you should look at switching to a Table control. You can avoid all the overhead of the DataGrid for the cost of a few lines of code to generate the rows and columns for your data. Faster yet, you can write the Table tags yourself and use a Literal control to display your HTML. It’s more work for you at design time, but less work for your server on every request for the page at run time.

The more processing that you do on the client with client-side code, the less processing you’ll have to do on the server. ASP.NET 1.1 includes several methods for adding client-side code to your page dynamically. In ASP.NET 2.0, the tools are expanded to make it even easier to insert JavaScript into your page. Visual Studio 2005 also provides better support for client-side programming. Setting the GridView’s EnableSortingandPagingCallbacks property (or the DetailView’s EnablePagingCallbacks property) causes all sorting and paging to be performed on the client rather than on the server.

In ASP.NET 2.0, you can use client-side code and callbacks to avoid posting the whole page back to the server for processing (see Additional Resources). A client-side callback lets you send only the data you need back to the server and then retrieve the result of your server-side processing without posting a whole page. It’s not Asynchronous JavaScript And XML (AJAX), but it works, and it reduces the overhead on your server.

You should also consider turning off the ViewState for any control whose properties you won’t be altering from your code. Turning off the ViewState for a control reduces the data traveling between your server and the browser.

Turning off the ViewState does come with a cost, however. It can result in your control’s client-side events firing in unexpected ways. For example, if you turn off the ViewState for a textbox, the TextChanged event fires whenever the Text property’s value is different from its default value, not every time a user changes the Text property. Avoiding code that depends on client-side events solves this problem. In ASP.NET 2.0, controls can store essential data in a section of the ViewState that is never disabled, so clever control authors can minimize unexpected side effects.

Of course, you should consider turning off anything you don’t need. For example, ask yourself if you need authentication. ASP.NET enables authentication by default in your site’s web.config file, but you should turn it off if you’re not using it (set the authentication element’s mode attribute to None). In ASP.NET 2.0, you should also make sure you haven’t enabled personalization inadvertently. Even if you are using the ASP.NET 2.0 personalization feature, ask yourself whether you need to support personalization for anonymous users. If not, turn that off by setting the Enabled property on the anonymousIdentification element to False. The less your server does, the faster everything else will run.

Reduce Trips to the Database
It’s important to reduce any round trips needed by your application, not just round trips to the server. For example, you can keep data on your Web server instead of the database server by storing any data that you retrieve and might need again in the cache. And never, ever store anything bulky in the Application object—put any bulky items in the Cache object.

Note that items in the Cache object are discarded automatically when your server starts to run out of memory. It makes sense to put as much as you can in the ASP.NET Cache object because the memory this object uses will free up automatically when (and if) it’s necessary. For example, consider that table of states and provinces that you keep retrieving from the database to display in listboxes all over your site. Instead, you might retrieve that table into a DataSet stored in the Cache object and bind all your listboxes to that table in the DataSet. Yes, the DataSet takes up memory, but the cache discards the DataSet if memory runs short.

If you use this approach, you must add code to check whether the DataSet is still present in the Cache object before you use the DataSet. But the worst that can happen is that you must go back to the database for your data. You’re no worse off than before, and you’ve probably saved yourself dozens of trips to the server when memory was available. If you need some information to know which item to retrieve from the database when the Cache object dumps your object (a customer number, for instance), store that small amount of data in the Application or Session objects.

Using the Cache object this way gives you an in-memory data store that adapts automatically to changing conditions. The items you haven’t used for the longest period of time are removed from the Cache object first, so you’re guaranteed that your most frequently used objects will stick around the longest. Your code only adds back to the cache the items your program uses, so only the objects that you need creep back into memory. This approach is extremely efficient.

Exploiting the cache is even easier in ASP.NET 2.0 if you use the SqlDataSource object. You can turn on caching for your data by setting the EnableCaching property on the SqlDataSource to True. In this case, you need to ensure that the data you cache doesn’t get out of date relative to the data in the database. Fortunately, there’s an easy fix for this: Simply make sure the SqlDataSource discards cached data after a specified time by setting the DataSource’s CacheDuration property to the number of seconds to hang onto the data.

You should also consider using the OutputCache object for your pages. For example, consider whether you need to regenerate all your pages each time you request them. If not, adding an OutputCache to your page in source view allows you to generate your page once for the first user who requests it and then display that same page for every subsequent user. Assuming you create only a handful of versions of the page, and assuming that you control these versions in the data sent to the page, you can use the VaryByParam attribute to cache those different versions. This directive ensures that you keep copies of the page for 10 minutes for each of the different values of the CustomerText and CountryText controls:

ASP.NET 2.0 includes its own new wrinkles. Assume you have a page that contains a small part that you must regenerate for each request. You can use a Substitution control to define that part of the page. Simply set the control’s MethodName property to the name of the function that provides the content for the control, and ASP.NET caches the rest of your page’s HTML. This means your server has to generate much less HTML, improving server performance.

This might seem like a natural place to discuss ASP.NET 2.0’s ability to discard cached data automatically if the data in the database changes. However, it remains unclear whether this feature will improve your performance if you don’t also use SQL Server 2005. With the current versions of SQL Server, enabling dependencies between SQL Server and ASP.NET requires ASP.NET to check back with SQL Server on some schedule to see if data has changed. This extra work could degrade your performance more than caching helps it.

Caching also demonstrates what I said at the start of the article: Performance is often a trade-off between speed and memory. Faster processing often comes at the cost of using more memory or at the cost of changing your application’s behavior.

The SqlDataSource object’s DataSourceMode in ASP.NET 2.0 provides another demonstration of this rule. Setting the SqlDataSource’s DataSourceMode to DataReader gives you the least memory consumption and fastest processing when retrieving data. However, controls bound to a SqlDataSource can lose some functionality when DataSourceMode is set to DataReader (the DataGrid won’t be able to sort or filter data). Setting DataSourceMode to DataSet gives you that functionality, but at the cost of having the SQLDataSource take up more room in memory and take a little longer to retrieve your data. You might have to experiment to find what gives your site the best results.

Watch for Errors and COM
Things can go wrong, and you should provide error handling to catch those problems. But don’t use error handling to take care of conditions that you can check for (unless those conditions are extremely rare). Exception handling is expensive in ASP.NET. You get better performance by checking for a condition and not raising the error than you do by putting the code in a Try block and hoping the condition doesn’t exist. In other words, check whether your divisor is not equal to zero before dividing—don’t attempt the division in a Try block.

If your application started life as an ASP page with VBScript, then you implemented your error handling using On Error Resume statements. ASP.NET supports using On Error Resume for Visual Basic—but it’s extremely slow. Replace your On Error Resume statements with Try blocks.

If you call a COM object from your ASP.NET page, you need to do more than set your variables to nothing to release your COM objects. Setting a variable to nothing only makes the wrapper that .NET puts around your COM object available for garbage collection. It can be a long time before your wrapper gets garbage collected, and your COM object hangs around in memory until that happens. Use the ReleaseComObject method of the System.Runtime.InteropServices.Marshal object when you finish with an object, passing the reference to your COM object to release it. Your .NET wrapper still must wait for the garbage collector to collect it before you can get back the memory held by your COM object.

Unfortunately, there is a catch when using ReleaseComObject: Under some circumstances, you must call the method more than once. In fact, you must keep calling ReleaseComObject until the method returns 0 to ensure that your COM object is released. This code does the trick:

Dim ComObject As SomeCOMObject
Do Until System.Runtime.InteropServices. _
Marshal.ReleaseComObject(ComObject) = 0
LoopASP.NET 2.0 provides a simpler solution: Call the Marshal object’s FinalReleaseComObject method, passing your object like this:

System.Runtime.InteropServices.Marshal. _
FinalReleaseComObject(ComObject)Another important performance principle is to make sure that you get the fastest (and fewest) compiles. In ASP.NET 1.0, you should change your application’s Configuration setting before you release it. Simply select Build | Configuration Manager and change your application’s Configuration setting to Release. This gives you a more optimized build and skips generating any debug support.

Note that your application’s code is never fully compiled when it leaves Visual Studio—at best, .NET converts your code to IL code, but the code must be compiled to native code after you install the application on the server. In ASP.NET 1.1, this final compilation happens the first time that a page is requested from the site. You shouldn’t make your users wait for your site to compile; instead, you should force compilation by requesting a page from the site yourself.

The situation is compounded in ASP.NET 2.0 where two of the deployment methods (copying the Web site and creating a setup package) don’t even compile your source code to IL. Only Build | Publish Web Site generates IL code. You can force compilation for your Web site by calling the precompile.axd utility after installing your application (the utility ships with .NET 2.0). All you need to do is append the utility’s name to the end of your site’s URL, like this: http://MyServer/MySite/precompile.axd. 

(sursa: http://visualstudiomagazine.com/columns/article.aspx?editorialsid=1987)

Advertisements

Clasa abstracta vs interfata

O clasa abstracta nu poate fi instantiata doar mostenita. O clasa abstracta poate fi complet partial sau deloc implementata (deci poate sa nu contine metode abstracte). Clasa care mosteneste o clasa abstracta trebui sa implementeze toate metodele abstracte ale clasei abstracte. O metoda abstracta este o metoda care nu este implementata si este declarata folosind cuvantule cheie ‘abstract’. Aceste metode sunt implicit virtuale in C#.

abstract class Shape{                 

                  public void PrintMessage(){

                        Console.WriteLine(“o metoda care nu e abstracta”);

                  }

                   public abstract void Area();

            }

class Circle :Shape{

                  public override void Area() {

                        Console.WriteLine(“o metoda abstracta”);

                  }

            }

 

Pentru a evita intr-o clasa implementarea unei metode abstracte din clasa abstracta mostenita clasa respectiva va fi declarata ca abstracta.

abstract class Shape{                 

                  public void PrintMessage(){

                        Console.WriteLine(“o metoda care nu e abstracta”);

                  }

                  public abstract void Area();

                  public abstract void Extent();

            }

      abstract class Circle :Shape{

                  public override void Area(){

                        Console.WriteLine(“o metoda abstracta”);

                  }

            }

 

In C# o clasa abstracta poate mosteni dintr-o clasa care nu e abstracta.

class Lines{

                  public void PrintLine(){

                        Console.WriteLine(“first we have a line”);

                  }

            }

      abstract class Shape :Lines{                 

                  public void PrintMessage(){

                        Console.WriteLine(“o metoda care nu e abstracta”);

                  }

                  public abstract void Area();

                  public abstract void Extent();

            }

 

O clasa abstracta poate implementa o interfata.

 

interface ILines {

                  void PrintMessage();                 

            }

abstract class Shape :ILines {                 

                  public void PrintMessage(){

                        Console.WriteLine(“o metoda care nu e abstracta”);

                  }

                  public abstract void Area();

                  public abstract void Extent();

            }

 

Cand folosesc o clasa abstracta ?

Cand am implementari commune ale unor metode dar si metode care sigur vor fi implementate insa diferit.

O interfata e un set de metode a caror implementare se va face in clasele care implementeaza interfata respectiva (nu contin nici o implementare).Nu se pot crea instante ale unei interfete.Nivelul de access predefinit este public.

interface IShape{

                  void Area();

            }

abstract class Circle :IShape{

                  public void Area(){

                        Console.WriteLine(“Aceasta metoda trebuie implementata!”);

                  }

            }

Diferenta dintre clasele abstracte si interfete in C# este ca in clasele abstracte putem defini metode care sunt  implementate in respectiva clasa.

O clasa poate deriva dintr-o singura clasa dar poate implementa oricate interfete

O interfata nu permite declararea de constante si membrii pe cand o clasa abstracta da.

Alegerea pentru folosirea unei clase abstracte sau a unei interfete poate fi dificila,iata cateva recomandari :

  • Daca se anticipeaza crearea mai multor versiuni ale unei componente se folosesc clase abstracte.Actualizand clasa de baza toate clasele care o mostenesc se vor actualiza conform schimbarilor.Interfetele odata create nu se pot schimba ,daca se va dori o noua versiune a interfetei atunci trebuie creata o noua interfata.
  • Daca functionalitatea oferita va folosita de mai multe obiecte diferite atunci se vor folosi interfetele.Clasele abstracte sunt folosite in primul rand pentru obiecte care sunt inrudite pe cand interfetele prevad functionalitate comuna pentru clase  neinrudite.
  • Pentru proiectarea unor putine functionalitati se folosesc interfetele .
  • Daca se prevede implementarea unor functionalitati  comune mai multor componente atunci se vor folosi clasele abstracte.

(sursa: http://studentclub.ro/lidia/)

ASP.NET Web Site Precompilation Overview

By default, ASP.NET Web pages and code files are compiled dynamically when users first request a resource such as a page from the Web site. After pages and code files have been compiled the first time, the compiled resources are cached, so that subsequent requests to the same page are extremely efficient.
ASP.NET can also precompile an entire site before it is made available to users. This provides a number of advantages, including:

  • Faster response time for users, since pages and code files do not have to be compiled the first time they are requested. This is particularly useful on large sites that are updated frequently.
  • A means to identify compile-time bugs before users see a site.
  • The ability to create a compiled version of the site that can be deployed to a production server without source code.

Precompilation Options

ASP.NET offers two options for precompiling a site:

  • Precompiling a site in place. This option is useful for existing sites where you want to enhance performance and perform error checking.
  • Precompiling a site for deployment. This option creates a special output that you can deploy to a production server.

Additionally, you can precompile a site to make it read-only or updatable. The following sections provide more details about each option.

In-Place Precompilation

You can enhance the performance of your Web site somewhat by precompiling it. This is particularly true in sites where there are frequent changes and additions among ASP.NET Web pages and code files—in a fluid Web site, the extra time required to dynamically compile new and changed pages can affect the users’ perception of the site’s quality.
When you perform in-place precompilation, all ASP.NET file types are compiled. (HTML files, graphics, and other non-ASP.NET static files are left as is.) The precompilation process follows the same logic that ASP.NET uses for dynamic compilation, accounting for dependencies between files. During precompilation, the compiler creates assemblies for all executable output and places them in a special folder under the %SystemRoot%\Microsoft.NET\Framework\version\Temporary ASP.NET Files folder. Thereafter, ASP.NET fulfills requests for pages from the assemblies in this folder.
If you precompile the site again, only new or changed files are compiled (or those with dependencies on new or changed files). Because of this compiler optimization, it is practical to compile the site after even minor updates.

Precompilation for Deployment

Another use for precompiling a site is to produce an executable version of the site that can be deployed to a production server. Precompiling for deployment creates output in the form of a layout that contains assemblies, configuration information, information about the site’s folders, and static files (such as HTML files and graphics).
After compiling the site, you can deploy the layout to a production server using tools such as the Windows XCopy command, FTP, Windows installation, and so on. Once the layout is deployed, it functions as the site, and ASP.NET fulfills requests for pages from the assemblies in the layout.
Precompiling a site for deployment provides a measure of protection for your source code and other intellectual property. For more information about how the compiler works with files during compilation for deployment, see File Handling During Site Compilation for Deployment.
You can precompile for deployment in two ways: precompiling for deployment only, or precompiling for deployment and update.

Precompiling for Deployment Only

When you precompile for deployment only, the compiler produces assemblies from virtually all ASP.NET source files that are normally compiled at run time. This includes program code in pages, .cs and .vb class files, other code files, and resource files. The compiler removes all source and markup from the output. In the resulting layout, compiled files are generated for each of the .aspx files (with the extension .compiled) that contain pointers to the appropriate assembly for that page.
To change the Web site, including the layout of pages, you must change the original files, recompile the site, and redeploy the layout. The only exception is the site configuration; you may make changes to the Web.config file on the production server without having to recompile the site.
This option provides the greatest degree of protection for your pages and the best performance at startup.

Precompiling for Deployment and Update

When you precompile for deployment and update, the compiler produces assemblies from all source code (except page code in single-file pages) and from other files that normally produce assemblies, such as resource files. The compiler converts .aspx files into single files that use the compiled code-behind model and copies them to the layout.
This option enables you to make limited changes to the ASP.NET Web pages in your site after compiling them. For example, you can change the arrangement of controls, colors, fonts, and other appearance aspects of pages. You can also add controls, as long as they do not require event handlers or other code.
When the site runs the first time, ASP.NET performs further compilation in order to create output from the markup.

Precompiling Child Applications

Precompiling a Web site compiles only that site, not any child sites. If a Web site contains a child folder that is marked as an application in IIS, the child application is not compiled when you precompile the parent folder.

Performing Precompilation

You can precompile a Web site using the Aspnet_compiler.exe tool on the command line. For more information, see How to: Precompile ASP.NET Web Sites for Deployment and ASP.NET Compilation Tool (Aspnet_compiler.exe).
Some visual designers such as Visual Studio include commands to precompile a Web site from within the IDE.
One coding restriction applies in sites that you intend to compile with source protection enabled. It is possible for a base page class (a code-behind class) to reference the associated page class (.aspx file) and page class members using a fully qualified class name. However, this type of reference will not work when precompiling your site with source protection enabled. This is because the base page class from the code-behind file is not located in the same assembly as the page class derived from the .aspx page. For more information on precompilation with source protection enabled, see How to: Sign Assemblies for Precompiled Web Sites.

(sursa: http://msdn.microsoft.com/en-us/library/399f057w(VS.85).aspx)

Speed Optimization in ASP.NET 2.0 Web Applications – Part 2

Page and Server Controls
The following topics give you an idea about how to use pages and controls efficiently in your web application:

Use HTML controls whenever possible
HTML controls is lighter than server controls especially if you are using server controls with its default properties. Server controls generally is easier to use than HTML controls, and on the other side they are slower than HTML controls. So, it is recommended to use HTML controls whenever possible and avoid using unnecessary server controls.

Avoid round trips to server whenever possible
Using server controls will extensively increase round trips to the server via their post back events which wastes a lot of time. You typically need to avoid these unnecessary round trips or post back events as possible. For example, validating user inputs can always (or at least in most cases) take place in the client side. There is no need to send these inputs to the server to check their validity. In general you should avoid code that causes a round trip to the server.

The Page.IsPostBack Property
The Page.IspostBack Boolean property indicates whether this page is loaded as a response to a round trip to the server, or it is being loaded for the first time. This property helps you to write the code needed for the first time the page is loaded, and avoiding running this same code each time the page is posted back. You can use this property efficiently in the page_load event. This event is executed each time a page is loaded, so you can use this property conditionally to avoid unnecessary re-running of certain code.

Server Control’s AutoPostBack Property
Always set this property to false except when you really need to turn it on. This property automatically post back to the server after some action takes place depending on the type of the control. For example, in the Text Control this property automatically post back to the server after the text is modified which is a great deal of processing cost and hence much slower performance and most importantly a poor user experience.

Leave Buffering on
It is important to leave page buffering in its on state to improve your page speed, unless you have a serious reason to turn it off.

Server Controls View State
Server control by default saves all the values of its properties between round trips, and this increases both page size and processing time which is of course an undesired behavior. Disable the server control view state whenever possible. For example, if you bind data to a server control each time the page is posted back, then it is useful to disable the control’s view state property. This reduces page size and processing time.

Methods for redirection
There are many ways you can use to redirect a user from the current page to another one in the same application, however the most efficient methods to do this are: the Server.Transfer method or cross-page posting.

Web Applications
The following topics give you some tips about how to make an efficient web application:

Precompilation
When an already deployed ASP.NET web application page is requested for the first time, that page needs to be compiled (by the server) before the user gets a response. The compiled page or code is then cached so that we need not to compile it again for the coming requests. It is clear that the first user gets a slow response than the following users. This scenario is repeated for each web page and code file within your web site.
When using precompilation then the ASP.NET entire web application pages and code files will be compiled ahead. So, when a user requests a page from this web application he will get it in a reasonable response time whatever he is the first user or not.
Precompiling the entire web application before making it available to users provides faster response times. This is very useful on frequently updated large web applications.

Encoding
By default ASP.NET applications use UTF-8 encoding. If your application is using ASCII codes only, it is preferred to set your encoding to ASCII to improve your application performance.

Authentication
It is recommended to turn authentication off when you do not need it. The authentication mode for ASP.NET applications is windows mode. In many cases it is preferred to turn off the authentication in the ‘machin.config’ file located on your server and to enable it only for applications that really need it.

Debug Mode
Before deploying your web application you have to disable the debug mode. This makes your deployed application faster than before. You can disable or enable debug mode form within your application’s ‘web.config’ file under the ‘system.web’ section as a property to the ‘compilation’ item. You can set it to ‘true’ or ‘false’.

Coding Practices
The following topics give you guidelines to write efficient code:

Page Size
Web page with a large size consumes more bandwidth over the network during its transfer. Page size is affected by the numbers and types of controls it contains, and the number of images and data used to render the page. The larger the slower, this is the rule. Try to make your web pages small and as light as possible. This will improve response time.

Exception Handling
It is better for your application in terms of performance to detect in your code conditions that may cause exceptions instead of relying on catching exceptions and handling them. You should avoid common exceptions like null reference, dividing by zero , and so on by checking them manually in your code.

Garbage Collector
ASP.NET provides automatic garbage collection and memory management. The garbage collector’s main task is to allocate and release memory for your application. There are some tips you can take care of when you writing your application’s code to make the garbage collector works for your benefit:

Avoid using objects with a Finalize sub as possible and avoid freeing resources in Finalize functions.
Avoid allocating too much memory per web page because the garbage collector will have to do more work for each request and this increases CPU utilization (not to mention you can go out of memories in larger web applications)
Avoid having unnecessary pointers to objects because this makes these objects alive until you free them yourself within your code not in an automatic way.

Use Try / Finally
If you are to use exceptions anyway, then always use a try / finally block to handle your exceptions. In the finally section you can close your resources if an exception occurred or not. If an exception occurs, then the finally section will clean up your resources and frees them up.

String Concatenation
Many string concatenations are time consuming operations. So, if you want to concatenate many strings such as to dynamically build some HTML or XML strings then use the System.Text.StringBuilder object instead of system.string data type. The append method of the StringBuilder class is more efficient than concatenation.

Threading
If your application contains some operation that consumes time and resources, then instead of blocking the application flow awaiting for this process or operation to be finished it is recommended to create a separate thread for this blocking operation. By threading you will save your application normal flow from delays. Examples of time consuming operations that can be moved to another thread other than the main program thread are: querying on a database and waiting for results, and extensive IO operations.

(sursa: http://www.beansoftware.com/asp.net-tutorials/controls-coding-optimization.aspx)

Speed Optimization in ASP.NET 2.0 Web Applications

To write a well performing web application you must make a balance between four common performance measures. These measures are:
Execution Time: It is the time taken to process a request. This is measured as the time elapsed between the first byte received from the server and the last one.
Response Time: It is the time between issuing a request and the first byte received as a response from the server.
Scalability: It measures the performance of a web application against resources (memory, processors, or computers) allocated for it.
Throughput: It is the number of requests your application can serve in a time unit, usually a second.
What follows is a list of areas that you can invoke to harvest for techniques that you can use to develop a high performance ASP.NET application.
State management
Data access
Page and server controls
Web applications
Coding practices

State Management
The following issues give you some ideas about how to make state management efficient.

SessionState State
Disable session state when you are not using it. Not all web application require a session state for each user. When you disable unneeded session state you are definitely improving your application performance.
To disable session state for a complete page in your application, use the following code:
If your page requires access to session variables only to read them then set the session state for this page to read only.
To disable session state for the entire application, open the ‘web.config’ file, and set the mode attribute to off under the session state section as in the following code:

Session State Provider
There are more than one approach for storing your session state data. You can choose the approach you prefer by setting the mode attribute under the session state section of your application ‘web.config’ file. The supported modes are: in-process mode, state server mode, SQL server mode, and custom mode. Each mode is suitable in some circumstance, and has its own set of advantages. The in-process session state is by far the fastest one. So, it is recommended to use the in-process provider if you want to store small amounts of volatile data in the session state. Other state server and SQL server providers are needed if your application using a web farm or garden, or if you want to retain your session state date if the web server is restarted.

Data Access
The following points give you some ideas about how to render data access efficient:

Use SQL server provider
Among the data providers available to be used, choose SQL data provider to build a high performance, scalable web application.

Use SQL Data Reader
The SQLDataReader class gives you the ability to read only retrieved records from the database for once. So, if this is all what you actually need, then it is extremely recommended to use a data reader class instead of a DataSet or, a Table Class. This will gives your application much higher performance.

Use Stored Procedures
Whenever possible use compiled stored procedure instead of SQL plain text commands, this gives your application an extra speed performance. SQL server builds and stores execution plans for previously stored procedures.

Make use of SQLDataSource useful properties
Instead of writing a query that includes the “Where”, or “Sort By” clauses use the caching, filtering, and sorting properties of the SQLDataSourse provider. You can set the SQLDataSource object’s “EnableCaching” property to true to enable caching of the retrieved data by this data source. When you enable data source caching, SQLDataSource will do the operations like filtering and sorting on the cached data. You can use the “FilterExpression” property, and the “SortParameterName” property to perform filtering and sorting using the SQLDataSource object. This will certainly makes your application faster.

View State Encryption
You must balance between the importance of encrypting your application view state data to make your transferred data more secure, and the cost / the impact of using encryption on your application speed. Encryption has a fixed cost for initialization plus a unfixed cost depends on the size of data to be encrypted. In brief, it is recommended to avoid using unnecessary view state data encryption.

Paging
It is known that to display data from a given data source you have to use data controls like: GridView, and/or DetailsView controls and to bind them to the data source you want to display data from. You may want to adjust the display layout of some data records and columns within your screen by using the GridView, or the DetailsView paging property and set it to true. This paging technique is called UI paging (User Interface paging). To perform this service, the GridView control requests data from the specified data source, it then filters the elements that will be displayed in the current page and simply ignores the rest. It does this process each time a new page is required … which is certainly a great waste of resources.
There is another technique for doing the same task, it is typically referred to as data source paging. In this technique you make use of a data source control that implements the DataSourceView class, and set its CanPage property to true, then you feed the GridView control or the DetailsView control from this data source. In this case the data source object queries only for the elements needed in each page. Thus, data source paging is more efficient than UI paging. The only data source class that allows data source paging is ObjectDataSource class.

Caching
Using the caching technique appropriately can improve the performance of your application more than using any other technique. .Net framework provides some mechanisms for caching pages and data within your ASP.NET application. You can use caching for pages that exhibit heavy traffic and do not change between requests. You can also cache small sized data that is used extensively by your application instead of processing them each time.

To use caching effectively, give attention to the following notes:

– Don’t assign a small duration for your cached items, items that expire quickly take extra cost for cleaning up and garbage collection.
– Don’t cache too many data items, there is a memory cost for each data item. It is not necessary to cache items that can be easily calculated or those which are rarely calculated or used.

Caching is so important and the ASP.NET framework gives a varity of caching mechanisms you can use to improve your application performance more and more. Some of those mechanisms are: Caching application data, Page output casching, Caching web forms, and Caching parts of web forms.

(sursa: http://www.beansoftware.com/asp.net-tutorials/sessionstate-data-optimization.aspx)

SQL Tips – Inner Join Select

SELECT tabela1.*, tabela2.Shares, tabela3.domainID
FROM
(SELECT ID, col2, col3, col4
FROM tabela1) tabela1
INNER JOIN
(SELECT col1,COUNT(col1) AS Shares FROM tabela2
GROUP BY col1) tabela2
ON tabela1.ID = tabela2.col1 INNER JOIN
(SELECT col1, col2 FROM tabela2) AS tabela3
ON tabela3.col1= tabela2.col1

TRUNCATE TABLE WITH FOREIGN KEY
dbcc checkident (numeTabela,reseed,1)