ASP.NET Best Practices

Post on 16-Nov-2014

3,777 views 0 download

Tags:

description

Presention on ASP.NET Security and Performance Tips and Tricks

transcript

Best practices in developing web based

applications

Harish RanganathanWeb Developer Evangelist

Microsoft Corporation India

Agenda• Web Application Security – Quick Tips

• Performance Overview

• Performance Improvements in .NET 2.

• Performance when developing

• Performance when deploying

• Results of a Few Performance Tests

Security – Quick Tips• ValidateRequest• Custom Errors• Query String• Authentication Mechanism – Choose the Right One• Validations – Client Side, Server Side

Performance Overview

Performance Is A Feature• Design up front with performance in mind

– Have performance plan in the very beginning

• Don’t “add performance” as a post step!– Much harder to-do once a project written

• Measure & iterate throughout project– Performance isn’t a one-time step– Iterative investigation is the approach to take– Always know the status of your performance

Web Performance Best Practice Recommendations

Some Code Best Practices• Write clean/organized code

– Don’t ‘hack’ solutions (keep code simple) – Easier to optimize – Easier to maintain

• Follow good design practices:– Data Access– Server Controls– Output Caching

Data Recommendations

Connection Pooling• ADO.NET has built-in connection pooling

– Automatic caching/re-use of connections– No need to write any code for this to happen

• Code Recommendation:– “Open connections in your code late, and then close

them early”– Don’t hold on to connections for long periods of time –

do not try to build your own “smart” connection pool logic

– Close the connection as soon as you are finished with it (this returns it to the pool)

Watch for Connection Leaks• Always explicitly close data connections

– Otherwise connection will remain open until the next Garbage Collection

– Leaking connections slows perf dramatically

• Specifically watch for leaks during stress:– Monitor user connection count on database– Watch the .NET CLR Data Perf Counters– Look for steady state behavior (growing = bad)

Connection Pooling• Optimization Tip:

– Different connection strings can generate multiple different connection pools

– Store single connection string in Web.Config

– Using ConfigurationManager.ConnectionStrings to access it programmatically at runtime

DataReaders vs. DataSets• DataReader provides forward only data cursor

over a query resultset– Lightweight and fast – but connection stays in use

until Reader closed or finished

• DataSet provides disconnected data access collection for data manipulation– Internally uses a DataReader to populate

• Which is better?– Depends on size of data returned, and confidence

that devs will close DataReader

ADO.NET Optimizations

• Only return data you need from the database– Memory allocations increase the more you return

• SqlCommand.ExecuteScalar method– Tuned for scenarios where only a single value is returned for

database

• SqlCommand.ExecuteNonQuery– Tuned for scenarios where resultsets are not returned (except

as params)

Server Control Performance Recommendations

Server Controls• Provides a clean programming abstraction

– Recommended way to build ASP.NET pages– Makes profiling your code a lot easier

• Controls do more work than old-style <%= %>– Should understand and optimize this

• Two areas to review for optimization:– ViewState– Number of controls generated (especially for lists)

ViewState Management• ASP.NET controls can maintain state across round trips

– State stored within “viewstate” hidden field

• Some downsides:– Increases network payload (both on render and postback)– Performance overhead to serialize values to/from viewstate– Additional Per-Request Memory Allocation

• Viewstate Flexibility:– Can disable viewstate entirely for a page– Can disable viewstate usage on a per control basis– Can use <%@ Page Trace=“true” %> to track usage size

• Recommendations:– Always disable at page if you are not doing postback on a page– Disable on a control if you are always re-generating it on postback

View State Management Tip• If you want to be more explicit about usage of

viewstate, you can configure ASP.NET to turn it off by default

• Machine.config:<configuration>

<system.web><pages enableViewState=“false”/>

</system.web></configuration>

• Pages that need viewstate will then need to manually set it in page directive:– <%@ Page EnableViewState=“true” %>

Caching Performance Best Practices

Design For Caching• Leverage the built-in ASP.NET caching features

– Output Caching– Partial Page Caching– Cache API

• Recommendation:– Specifically design pages around these features – can

lead to massive perf wins

StaticD

ynamic

Dynam

ic Static

Output Caching

demo

Testing Tools

• Trace Tools• Profiler Tools• Load Tools

Trace Tools• ASP.NET Page or Application Tracing

Display trace information on page

• System.Diagnostics TracingWrite trace information tocustom listener

The Test

• Request page 1050 times• Discard first 50 requests• Log time of each request• Average results

Database SetupFour Database Tables• Products10 – 10 Rows• Products50 – 50 Rows• Products100 – 100 Rows• Products500 – 500 Rows

What’s Faster?

• DataReader• DataSet

DisplayDataReader.aspx DisplayDataSet.aspx

DataReader

0.9612

1.1982

1.4234

3.5585

0.0000

0.5000

1.0000

1.5000

2.0000

2.5000

3.0000

3.5000

4.0000

10 Row s 50 Row s 100 Row s 500 Row s

Mill

isec

onds

DisplayDataReader.aspx

DataSet

1.0979

1.3436

1.6516

4.2160

0.0000

0.5000

1.0000

1.5000

2.0000

2.5000

3.0000

3.5000

4.0000

4.5000

10 Row s 50 Row s 100 Row s 500 Row s

Mill

isec

onds

DisplayDataSet.aspx

DataReader Versus DataSet

0.9612

1.1982

1.4234

3.5585

1.0979

1.3436

1.6516

4.2160

0.0000

0.5000

1.0000

1.5000

2.0000

2.5000

3.0000

3.5000

4.0000

4.5000

10 Row s 50 Row s 100 Row s 500 Row s

Mill

isec

onds

DisplayDataReader.aspx DisplayDataSet.aspx

DataReader Versus DataSetFinal Results

On average, a DataReader is 16% faster than DataSet

3rd Option – ArrayListUsing an ArrayList instead of a DataReader results in similar performance with the advantages of a static representation of data

DisplayArrayList.aspx

ArrayList

0.9612

1.1982

1.4234

3.5585

1.0979

1.3436

1.6516

4.2160

0.9717

1.1925

1.4450

3.6802

0.0000

0.5000

1.0000

1.5000

2.0000

2.5000

3.0000

3.5000

4.0000

4.5000

1 2 3 4

Mill

isec

onds

DisplayDataReader.aspx DisplayDataSet.aspx DisplayArrayList.aspx

What’s Faster?

• SqlDataReader• OleDbDataReader

OleDbDataReader

0.96121.1982

1.4234

3.5585

1.6592

2.2088

2.8741

8.6055

0.0000

1.0000

2.0000

3.0000

4.0000

5.0000

6.0000

7.0000

8.0000

9.0000

10.0000

1 2 3 4

Mill

isec

onds

DisplayDataReader.aspx DisplayDataReaderOleDb.aspx

OleDbDataReaderFinal Results

On average, a SqlDataReader is 115% faster than an OleDbDataReader

What’s Faster?

• Inline SQL• Stored Procedure

Stored Procedure

0.9612

1.1982

1.4234

3.5585

0.9458

1.1648

1.4217

3.5966

0.0000

0.5000

1.0000

1.5000

2.0000

2.5000

3.0000

3.5000

4.0000

10 Row s 50 Row s 100 Row s 500 Row s

Mill

isec

onds

DisplayDataReader.aspx DisplayDataReaderStoredProc.aspx

What’s Faster?DataReader Column Reference

• By Name:Response.Write(dr[“ProductName”]);

• By Ordinal:Response.Write(dr[0]);

• By GetString():Response.Write(dr.GetString(0));

Column Reference

0.9612

1.1982

1.4234

3.5585

0.9485

1.1209

1.3194

3.0171

0.9732

1.2306

1.5029

4.0562

0.0000

0.5000

1.0000

1.5000

2.0000

2.5000

3.0000

3.5000

4.0000

4.5000

10 Row s 50 Row s 100 Row s 500 Row s

Mill

isec

onds

DisplayDataReader.aspx DisplayColumnOrdinal.aspx DisplayColumnNative.aspx

Column ReferenceFinal Results

On average, ordinal reference is 11% faster than by name

What’s Faster?• Proper Casedr[“ProductName”]

• Improper Casedr[“PRODUCTNAME”]

Proper Case

0.9612

1.1982

1.4234

3.5585

0.9753

1.2007

1.4428

3.6232

0.0000

0.5000

1.0000

1.5000

2.0000

2.5000

3.0000

3.5000

4.0000

10 Row s 50 Row s 100 Row s 500 Row s

Mill

isec

onds

DisplayDataReader.aspx DisplayDataReaderBadCase.aspx

Proper CaseFinal Results

Using proper column case is 1% faster than improper column case

What’s Faster?

• Inline• ASP.NET Controls

DataGrid

0.9612 1.1982 1.4234

3.5585

0.9652 1.23371.5173

4.0302

1.4247

2.5259

3.8963

15.9660

0.0000

2.0000

4.0000

6.0000

8.0000

10.0000

12.0000

14.0000

16.0000

18.0000

10 Row s 50 Row s 100 Row s 500 Row s

Mill

isec

onds

DisplayDataReader.aspx DisplayDataReaderHTML.aspx DisplayDataGrid.aspx

DataGridFinal Results

• Inline script is 233% faster than a DataGrid

What’s Faster?

• DataGrid with ViewState Disabled• DataGrid with ViewState Enabled

ViewState

1.42472.5259

3.8963

15.9660

1.7315

3.4100

5.5437

28.8384

0.0000

5.0000

10.0000

15.0000

20.0000

25.0000

30.0000

35.0000

1 2 3 4

Mill

isec

onds

DisplayDataGrid.aspx DisplayDataGridViewState.aspx

ViewStateFinal Results

DataGrid with ViewState disabled is 66% faster than DataGrid with ViewState enabled

What’s Faster?

• AutoGenerateColumns• Template Columns

Template Columns

1.4247

2.5259

3.8963

15.9660

1.5350

3.1174

5.1431

23.3265

0.0000

5.0000

10.0000

15.0000

20.0000

25.0000

1 2 3 4

Mill

isec

onds

DisplayDataGrid.aspx DisplayDataGridTemplate.aspx

Template ColumnsFinal Results

A DataGrid without templates is 39% faster than a DataGrid with templates

What’s Faster?How to improve template performance?

• DataBinder.Eval<%# DataBinder.Eval(Container.DataItem, “ProductName”) %>

• Explicit Cast<%# ((DbDataRecord)Container.DataItem)["ProductName"]%>

• ItemDataBoundvoid ItemDataBound(Object s, DataGridItemEventArgs e)

DisplayItemDataBound.aspx

Template Performance

1.5350

3.1174

5.1431

23.3265

1.6122

3.5255

5.9879

27.7291

1.4977

2.8716

4.6660

20.7450

0.0000

5.0000

10.0000

15.0000

20.0000

25.0000

30.0000

1 2 3 4

Mill

isec

onds

DisplayDataGridTemplate.aspx DisplayItemDataBound.aspx DisplayDataGridTemplateCast.aspx

Template PerformanceFinal Results

Explicit cast is 11% faster than using a databinding expression

Creating A Custom ControlWould a custom DataGrid (with severely reduced functionality) be faster than the standard DataGrid?

FastGrid.cs

Custom Control

1.5350

3.1174

5.1431

23.3265

1.4329

2.4726

3.8371

16.4522

0.0000

5.0000

10.0000

15.0000

20.0000

25.0000

1 2 3 4

Mill

isec

onds

DisplayDataGridTemplate.aspx DisplayFastGrid.aspx

Custom ControlFinal Results

FastGrid is 37% faster than astandard DataGrid

What’s Faster?

• DataGrid with no caching• DataGrid with data caching• DataGrid with output caching

Data Caching

1.4247

2.5259

3.8963

15.9660

0.8336 0.7974 0.7985 0.8009

0.0000

2.0000

4.0000

6.0000

8.0000

10.0000

12.0000

14.0000

16.0000

18.0000

1 2 3 4

Mill

isec

onds

DisplayDataGrid.aspx DisplayDataGridCache.aspx

Data CacheFinal Results

Using the data cache is 637% faster than a standard DataGrid

Output Cache

1.4247

2.5259

3.8963

15.9660

0.8336 0.7974 0.7985 0.8009

0.0000 0.0000 0.0000 0.00000.0000

2.0000

4.0000

6.0000

8.0000

10.0000

12.0000

14.0000

16.0000

18.0000

1 2 3 4

Mill

isec

onds

DisplayDataGrid.aspx DisplayDataGridCache.aspx DisplayDataGridOutputCache.aspx

Output CacheFinal Results

Using the output cache is infinitely faster than using a standard DataGrid

Conclusions• A DataReader is faster than a DataSet• An inline DataReader is faster

than a DataGrid• You pay a high price for ViewState• AutoGenerateColumns is faster than template

columns• Caching is always a good idea!

ASP.NET 2.0 Deployment Unveiled• Default Deployment Model copies both ASPX and Source

files

• Both Compiled Dynamically on first request

• Precompiled Applications can be better in performance

• Web Site Publishing Wizard pre-compiles the Source Files

• ASPNET Compiler Tool Pre-compile both ASPX & Source

Deployment Tips

demo

QUESTIONS

BLOG

http://geekswithblogs.net/ranganh

© 2007 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.