Title: ASP'NET 2'0 Black Belt
1(No Transcript)
2ASP.NET 2.0 Black Belt
3Overview
- Performance improvements with ASP.NET 2.0
- Asynchronous request handling
- SQL caching
- Client callbacks (if time permits)
- Summary
- Questions and answers
4Introducing
- Class-A
- Kennisprovider
- Microsoft development
- Training
- Coaching
- Alex Thissen
- Trainer/coach
- http//www.alexthissen.nl
5Why this session?
- Web Server performance is critical!
- Determined by combination of hardware and
software - Good or bad use of ASP.NET greatly influences
performance - Achieve better performance by
- Good programming practice
- Taking advantage of features in ASP.NET 2.0
6Asynchronous request handling
7The need for asynchronous ASP.NET
- Long running operations performed during handling
of page request can degrade performance - Shorter requests will take much longer than
necessary - On average throughput will be lower
- Asynchronous ASP.NET to the rescue
- Page request can be handled asynchronously
- Do not wait for long running operations to
complete - Spawn long operations on different threads
8Thread pools in .NET and ASP.NET
- .NET uses a pool of threads per process
- Pool has two types of threads
- Worker threads (default 100 in pool)
- IO completion port threads (default 100 in pool)
- Change defaults with calls to ThreadPool.SetMax/Mi
nThreads - Several .NET classes use IO threads
- Sockets, Web Service Proxies, WebRequest,
FileStream
9ASP.NET threads
- ASP.NET uses 20 worker and 20 IO threads by
default - A minimum number of threads is reserved to handle
callbacks from async operations - Performance gain by switching from worker to IO
threads - Avoid draining worker threads in pool
ltprocessModel maxWorkerThreads "20"
minWorkerThreads "1" maxIoThreads "20"
minIoThreads "1" /gt lthttpRuntime
minFreeThreads "threads" minFreeLocalRequestFre
eThreads "threads" ... /gt
10ASP.NET architecture
worker processaspnet_wp.exe (IIS4,5) or w3wp.exe
(IIS6)
ASP.NET runtime in .NET CLR
inetinfo.exe (IIS 4 and 5)
HttpApplication\vdir1
aspnet_isapi.dll(native code)
HTTP pipeline
HttpApplication\vdir2
http.sys kernel mode driver(IIS 6)
aspnet_isapi.dll(native code)
11IHttpAsyncHandler interface
- Asynchronous web pages implement
IHttpAsyncHandler interface - Request threads are returned to pool right after
async operation is started on other thread - Implementing IHttpAsyncHandler is NOT a trivial
or easy task
public interface IHttpAsyncHandler IHttpHandler
IAsyncResult BeginProcessRequest(HttpContext
context, AsyncCallback cb, object extraData)
void EndProcessRequest(IAsyncResult result)
12Asynchronous pages in ASP.NET 2.0
- Add asynctrue to _at_Page directive or ltpagesgt
element in web.config - Pass delegates for start and completion of
asynchronous operation in AddOnPreRenderCompleteAs
ync method - Register event handler for PreRenderComplete
private void Page_Load(object sender, EventArgs
e) this.AddOnPreRenderCompleteAsync( new
BeginEventHandler(BeginAsynchronousOperation),
new EndEventHandler(EndAsynchronousOperation))
this.PreRenderComplete new
EventHandler(LongRunningAsync_PreRenderComplete)
13Effects during page lifecycle
Client
request page
LoadComplete
PreRender
PreRenderComplete
Thread 1
SaveViewState
Render
send response
14Effects during page lifecycle
Client
request page
Thread 1
LoadComplete
PreRender
IAsyncResult
PreRenderComplete
SaveViewState
Render
Thread 2
send response
15Synchronous performance
100 concurrent users
20 concurrent users
50 concurrent users
10 concurrent users
16Asynchronous performance
50 concurrent users
20 concurrent users
10 concurrent users
17Downside of async pages
- Async pages have no timeout
- Not really meant to perform several async
operations - Does not flow impersonation information, current
HttpContext or culture to end handlers - Hard to pass some form of state to async threads
- Requires at least High trust
18Asynchronous tasks
- In ASP.NET 2.0 you can add async tasks to page
request handling - Flow contextual information
- Pass state to async handler
- Have timeout value and timeout handler
- Register tasks before PreRenderComplete
- Registered tasks get executed automatically
- Tasks are executed only once
- ExecuteRegisteredAsyncTasks will only run tasks
that have not executed before
19Async tasks
- Single unit of work encapsulated by PageAsyncTask
class - Constructor takes three delegates
- BeginEventHandler start async operation here
- EndEventHandler complete async operation
- TimeoutHandler called when task times out
- Tasks can execute in parallel for better
concurrency - Page execution halts until all tasks have
completed or timed out
20Configuration of async tasks
- Default timeout of async tasks is 45 seconds
- Change timeout in _at_Page directive or ltpagesgt
element in web.config - Page itself does not have to be asynchronous
- But sync page will block until all async tasks
have completed or timed out
lt_at_Page Asynctrue AsyncTimeout60
gt ltsystem.webgtltpages asyncTimeout60 /gt
21Things to remember
- IIS 5.1 on Windows XP has default setting of 10
concurrent requests - Gives 403.9 errors if exceeded
- Increase by editing metabase key
LM/W3SVC/MaxConnections (40 hardcoded limit) - BUG All requests are handled by IO threads
- On IIS5 and in ASP.NET 1.0 and 1.1 (without SP1)
install hotfix from KB 821156 - ASP.NET 1.1SP1 and 2.0 require registry setting
HKLM\Software\Microsoft\ASP.NET\UseWorkerThreadsO
nIIS5 to 1 (DWORD)
22Fixing IIS5.1ASP.NET bug
After worker threads used
23SQL caching
24Caching in ASP.NET
- ASP.NET has rich caching mechanism
- Automatic cache management
- Scavenging of cache if necessary
- Declarative caching in controls and directives
- Programmatic caching with Cache API
- ASP.NET 2.0 adds new features
- SQL Cache support
- Cache profiles
- More declarative control over cache management
25SQL Caching basics
- Caching data retrieved from database can avoid
lots of trips to database server - Putting data in cache is easy use Cache API
- Determining when to get fresh data is hard part
- Cached items should be invalidated when
underlying data changes - Two mechanisms are available to determine
changes - Polling mechanism periodically checking if data
has changed - Query notifications (new in SQL Server 2005)
26Polling mechanism
- ASP.NET runtime polls for database changes on a
specified interval - Can be used with SQL Server 7, 2000 and 2005
- Triggers on table of interest react to changes by
INSERT, UPDATE and DELETE - Trigger runs sproc to increase Change ID in a
special table AspNet_SqlCacheTablesForChangeNotifi
cation
27Preparing database for polling
- Enable polling on database
- Creates poll table and stored procedures
- Enable polling on specific table
- Creates triggers and adds entry in poll table
aspnet_regsql.exe E d Northwind ed
aspnet_regsql.exe -E -d Northwind -t Categories
-et
28SQL caching configuration
ltconfigurationgt ltconnectionStringsgt ltadd
name"NorthwindConnectionString"connectionString"
" providerName"System.Data.SqlClient" /gt
lt/connectionStringsgt ltsystem.webgt ltcachinggt
ltsqlCacheDependency enabled"true"
pollTime"1000"gt ltdatabasesgt ltadd
name"Northwind" connectionStringName"Nort
hwindConnectionString"/gt lt/databasesgt
lt/sqlCacheDependencygt lt/cachinggt
lt/system.webgt lt/configurationgt
29SQL 2005 Notification architecture
ASP.NET
SQL Server
SqlCommand
Cache
Northwind
TCP Port 1433
Notification Delivery Service
30Preparing for SQL2005 notifications
- Enable Service Broker on database
- Enable caching in web.config
ALTER DATABASEÂ Northwind SET ENABLE_BROKER GO
ltconfigurationgt ltsystem.webgt ltcachinggt
ltsqlCacheDependency enabled"true" /gt
lt/cachinggt lt/system.webgt lt/configurationgt
31Start listening to notifications
- Call SqlDependency.Start with connection string
- Creates a new queue and a new service with GUIDs
in name - Once per connection string in lifetime of an
application, typically global.asax - Remember to call SqlDependency.Stop
void Application_Start(object sender, EventArgs
e) SqlDependency.Start(connectionString) voi
d Application_End(object sender, EventArgs e)
SqlDependency.Stop(connectionString)
32Output Caching with SQL dependencies
- Page output cache can be dependent on query
results retrieved from SQL Server - SqlDependency attribute specifies invalidation
mechanism - CommandNotification for query notification
- Semi-colon separated list for polling
- Automatically adds dependency to SqlCommand
objects used in code
33Page output caching
- Use _at_OutputCache directive to set up output
caching with a dependency to command - SQL Server 2005
- SQL Server 7 and 2000
lt_at_ OutputCache Duration"60" VaryByParam"None"
SqlDependency"CommandNotification" gt
lt_at_ OutputCache Duration"60" VaryByParam"None"
SqlDependency"NorthwindProductsPubsAuthors" gt
34DataSource controls
- SqlDataSource control offers SqlCacheDependency
property - Only for SQL Server databases
- Works same way as page output caching
ltaspSqlDataSource ID"SqlDataSource1"
runat"server" ConnectionString"lt
ConnectionStringsNorthwindConnection
gt" EnableCaching"True" CacheDuration"10"Cache
ExpirationPolicy"Sliding"SelectCommand"SELECT
ProductID, ProductName, QuantityPerUnit FROM
dbo.Products" SqlCacheDependency"CommandNotificat
ion"gt lt/aspSqlDataSourcegt
35DataSource controls
- ObjectDataSource control does not support
notifications - Add caching logic with SqlCacheDependency inside
of Select method - Resort to polling
36SqlCacheDependency class
- Output cache and data source controls create an
instance of SqlCacheDependency - You can use SqlCacheDependency directly
SqlCommand command new SqlCommand(sql,
connection) SqlCacheDependency dependency new
SqlCacheDependency(command) Response.AddCacheDepe
ndency(dependency)-- or -- Cache.Insert("key",
someDataSet, dependency)
37ADO.NET 2.0 and Query Notifications
- SqlClient managed provider has support for Query
Notifications in SQL Server 2005 - Two important classes for Query Notifications
- SqlDependency class for easy wiring
- SqlNotificationRequest
SqlDependency dependency new SqlDependency(comma
nd) dependency.OnChanged new
OnChangedEventHandler(DataChanged) SqlDataReader
reader command.ExecuteReader( ) void
DataChanged(object sender, SqlNotificationEventArg
s args)
38Troubleshooting
- Special rules apply for SELECT statements
- Must use explicit column names
- You cannot use SELECT
- Specify schema name for db objects
- Example SELECT FROM dbo.Customers
- More rules apply, see MSDN
- Database compatibility level must be 90 or higher
sp_dbcmptlevel Northwind, 90 - SQL Server Service cannot run under Local System
account - Add dependency to command before executing it
39Troubleshooting
- ASP.NET identity that is not dbo should have
enough rights - Requires attached instance, not User Instance of
SQL Server Express - SQL CLR must be enabled
40SQL Caching recommendations
- Use wisely infrequently changing data, e.g.
read-mostly lookup tables - For middle tier scenarios you might want to
specify your own service and queue - SqlNotificationRequest for more control and
custom handling of notifications - Check out SqlCacheDependencyAdmin for
administrative tasks related to polling
41Client callbacks
42Client callbacks
- A client callback is a out-of-band call to the
web server - Server round-trip "behind-the-scenes"
- No page refresh or complete page round-trip
- Can perform actions at the server and optionally
retrieve data and update UI - Improves friendliness and responsiveness of the
user interface - Callbacks are made asynchronously by default
- Perceived (not actual) performance is improved
43Client callbacks, AJAX and Atlas
- AJAX Asynchronous JavaScript and XML
- Atlas is Microsoft framework for Web 2.0
applications - Browser compatible client-side libraries for
object-orientation and - Web Server controls for declaratively emitting
markup and script for client callbacks - ASP.NET Client callbacks is like light-weight
AJAX - No XML is transferred between client and server
- No script libraries or server controls
44Callback flow of information
Server-side
Client-side
WebResource script
Web page
WebForm1.aspx
include
onClick
Page state
ltscriptgt lt/scriptgt
DoCallback
ltscriptgtlt/scriptgt
HTTP POST
RaiseCallbackEvent GetCallbackResult
MSXML3.XMLHTTP
Callback
ltscriptgtlt/scriptgt
onReadyStateChange
ltscriptgtlt/scriptgt
ltscriptgtlt/scriptgt
Timeout
45Client-side script
- Client-side JavaScript starts roundtrip to server
- Three functions DoCallback, CallbackComplete,
ExecuteCallback - ASP.NET callback script is included as a Web
Resource - Embedded Resource made available for download
through HTTP handler AssemblyResourceLoader - Special URL WebResource.axd?dt
46Data exchange
- Data is posted back as regular URL-encoded form
data, not necessarily XML - Contains ViewState, Event validation data,
callback ID and param - Response contains response and new Event
validation data
__EVENTTARGET__EVENTARGUMENT__VIEWSTATE2FwEP
Ah4Hb25jbGljawUgR2V0SGVsbG9aXb3JabdcsxMiwgJ2w1__C
ALLBACKID__Page__CALLBACKPARAM12__EVENTVALIDA
TION2FwEWAwL2BraDpAgL72B4SRCAKM54rGBpFe3rPMr2H
7QsP2vv4x4ojYDdL2
14/wEWDgLh94yAQServer Time is 13035
AM LengthEventValidationDataResponse
47Client callback enabled pages
- Pages that can handler client callbacks implement
System.Web.UI.ICallbackEventHandler - RaiseCallbackEvent receives client-side data
- Response is generated in GetCallbackResult
- Split into two methods to allow for asynchronous
pages or tasks
public interface ICallbackEventHandler void
RaiseCallbackEvent(string eventArgument)
string GetCallbackResult( )
48Altered page lifecycle
- Page lifecycle is different for callbacks
- Check withPage.IsCallback property
Client
Init
LoadState
request page
ProcessPostData
Load
2nd ProcessPostData
Change events
Postback events
PreRender/Complete
send response
Render
Unload
49Altered page lifecycle
- Page lifecycle is different for callbacks
- Check withPage.IsCallback property
Client
Init
LoadState
request page
ProcessPostData
Load
2nd ProcessPostData
Change events
RaiseCallbackEvent
send response
GetCallbackResult
Unload
50Putting callbacks together
- Create JavaScript functions for
- Firing callback
- Use server-side code or include from .js file
- Create call with a call to ClientScriptManager
GetCallbackEventReference method - Handling callback
- Error handling (optionally)
- Register client script blocks or includes
- Choose client-side event to call function
- Wire up HTML DOM event handler
51Passing arguments to server
- Retrieve values of controls through HTML DOM
- Choose an appropriate form of marshalling and/or
encoding for complex data
ltselect name"ProvincieLijst" id"ProvincieLijst"
onchange"HaalFlitsers(GetListValue(ProvincieLijst
), null)"gt
ltscript type"text/javascript"gtlt!-- function
HaalFlitsers(args, context) WebForm_DoCallback('
__Page',args,HaalFlitsersCallback,"",HaalFlitsersE
rror,true)// --gt lt/scriptgt
52Context of callback
- Context does not travels back and forth between
client and server - Maintained at client
- Use context to
- Keep track of multiple active async callbacks
- Context can be null, simple datatype (e.g.
string) or object
var context new Object() context.Param1
context.Param2 WebForm_DoCallback('__Page'
,args,OnCallBack,context,OnCallBackError,true)
53Error handling
- Exception thrown during page lifecycle will
result in error scenario on client - Exception is caught and message is propagated to
client (prefixed 'e') - Register a error function
- Requires you to specify async behavior boolean in
call to GetCallbackEventReference
54Client callbacks from controls
- Some controls in ASP.NET 2.0 use Client callbacks
- GridView, TreeView and DetailsView
- Controls that call back need to implement
ICallbackEventHandler - Optionally ICallbackContainer
- Provides a formalized way for controls to
retrieve callback script for buttons
public interface ICallbackContainer string
GetCallbackScript(IButtonControl button,
string argument)
55Event validation
- ASP.NET 2.0 validates events on post/callback
- Not just any control can cause postback and send
arguments - Avoid setting lt_at_Page EnableEventValidation"Fals
e" gt - Register values for event validation inside
GetCallbackResult - Still cannot read directly from control. Use
Request object instead.
ClientScript.RegisterForEventValidation("ListBox1"
, index.ToString( ))
56Browser compatibility
- Works with
- Internet Explorer with MSXML 3.0
- Mozilla and Opera style browsers
- Non-IE browsers do not use XmlHttp object
- Script determines XmlHttp does not exist
- Creates a hidden IFrame for every request
- Data is submitted to server via normal HTTP POST
and form.submit()
57Review
- Performance of ASP.NET web applications can be
drastically improved by using new ASP.NET 2.0
features - Asynchronous pages and task relieve threads
making overall response times better - SQL Caching avoids unnecessary roundtrips to
database server and provides easy cache
invalidation based on data changes - Client callback provides lightweight AJAX
functionality and improves perceived performance
58Questions
59SDC 2006
60Question 1
- What is the name of the property that was
previously called SmartNavigation?
MaintainScrollPositionOnPostback
61Question 2
- How do you take a Web application offline with a
single page?
Place app_offline.htm in root of application
62Question 3
- What is the hardcoded (!) limit of concurrent
requests on IIS 5.1 in Windows XP?
40