0% found this document useful (0 votes)
12 views110 pages

PerfByDesign Aspnet

The document discusses web application performance, focusing on ASP.NET architecture and strategies for building scalable and responsive web applications. Key topics include session state management, caching, page load time measurement, and the impact of network latency on performance. It also covers the ASP.NET programming model, IIS architecture, and state management techniques for optimizing web applications.

Uploaded by

yahsuD
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views110 pages

PerfByDesign Aspnet

The document discusses web application performance, focusing on ASP.NET architecture and strategies for building scalable and responsive web applications. Key topics include session state management, caching, page load time measurement, and the impact of network latency on performance. It also covers the ASP.NET programming model, IIS architecture, and state management techniques for optimizing web applications.

Uploaded by

yahsuD
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 110

Web application

Performance

 Mark Friedman
Architect
Developer Division
Microsoft Corporation
Web Application Performance

 Agenda:
 ASP.NET architecture for building dynamic
web applications
 Building scalable web applications
 Persisting Session state
 Caching application data
 n-Tiered application scaling
 Building responsive web applications
 Page Load Time and Round trips
 AJAX
 Tips for Silverlight and WPF-based applications

3
ASP.NET Application Performance

 Framework for developing web sites that


generate Dynamic HTML Responses
 Get Request ↔ Response message
 Additional files are frequently embedded
in the Response HTML
 e.g.,
<A HREF="resumepage.html">my resume</A>
 Web Browser (e.g., IE) performs
HTML layout
 Frames
 Tables
 Images
 Cascading Style Sheets
<LINK REL=STYLESHEET HREF="mystyles.css"
TYPE="text/css"> 4
ASP.NET Application Performance
 From Web Pages to Web Applications
 aka, Rich Internet Applications (RIA)
 Dynamic HTML (Server-side processing)
 SOAP (Web services)
 AJAX (Client-side scripting)
 Silverlight (Client-side runtime)
 XAML elements (WPF)
 etc.,

 Dynamic HTML is layered on top of the HTTP


protocol, which was originally designed to be both
connectionless and sessionless.
 Individual requests are independent of each other
 No “state” is preserved between one request and
another 5
ASP.NET Application Performance
 Server-side Request processing
 Event-oriented programming model (Postback)
 HttpContext wrapper around the HTTP Request
 Persistent State
 ViewState
 Session State
 Application and Page Cache objects
 etc.

6
ASP.NET Application Performance

 Client-side scripting
 Rich Internet Applications (RIA)
 AJAX
 Browser Document Object Model (DOM)
 Javascript
 Asynchronous server Postbacks (to web services)

7
ASP.NET Application Performance

 Measurement considerations
 On the client
 Performance counters
 Network Monitor traces
 ETW traces (IE, etc.)
 Direct measurements inside Javascript code
 On the server
 IIS logs (especially Time-Taken fields)
 Performance counters
 web app response time data is not available
 ETW traces (IIS, ASP.NET, CLR, etc.)
 volume considerations
 Direct measurement inside .NET code
 e.g., Stopwatch
8
ASP.NET Application Performance

 Measurement considerations
 End-to-End
 Multiple tiers

9
Web Application Performance

 HTTP application performance is constrained


by network latency!
Client-side
script

Client-side
script Network
Client-side Latency
script Network
Network Latency
Latency
Server-side Server-side Server-side
.aspx .aspx .aspx

Unit Test Load Test Production

e.g., VS TeamTest 10
Web Application Performance

 Measuring Page Load Time


 Time to First Byte
 Network Monitor capture data
 DNS Lookup
 TCP Session handshaking
 SYN, SYN-ACK, ACK sequence
 Calculates 1st Round Trip Time used by Fast
Retransmit logic
 Dynamic HTML Response message generated by the
ASP.NET application
 Which can then reference additional files
embedded in the HTML
 e.g., css, js, jpg, gif, xml, xaml, wmv, etc.
 When is the application Ready to use? 11
ASP.NET Application Performance

12
Web Application Performance

13
demo
Visual Roundtrip
Analyzer
Web Application Performance

 VRTA (Visual Round Trip Analyzer)

15
Web Application Performance
 Elements of Page Load Time
 Html
 CSS
 Javascript (serializes)
 XAML
 Images
 Audio
 Video
 Banner ads (often from 3rd parties)
 etc.
 Page Load parallelism
 IE7 limited to two parallel sessions
 IE8 and Chrome support six parallel sessions
16
Web Application Performance

 Pages are assembled from a variety of


elements, some of which may reside on
different web servers
 Static content can be cached:
 on the client
 on the server
 somewhere in-between
 Proxy servers
 Cache engines
 etc.
 Semi-dynamic content may also be
cacheable
17
Web Application Performance

 Semi-dynamic content generated by


ASP.NET server-side code may be cacheable
 Multiple facilities in IIS/ASP.NET available for
caching
IIS kernel mode Cache
ASP.NET Application cache
ASP.NET Page cache
 Virtual memory constraints relieved in x64 OS!

 Note: these are complex facilities that may


require considerable monitoring & analysis to
achieve optimal results.
18
Web Application Performance

 Cache performance and efficiency


 Caching is ubiquitous across the web
 In the Browser
 in the content delivery network infrastructure,
 on the proxy server
 on the web server (in multiple forms)
 on the database server

 For the sake of latency, cache data as close to the


client as possible
 Multiple layers of cache hold largely redundant data
 One effective layer is usually sufficient

 See “
Caching Architecture Guide for .NET Framework Applications”
19
ASP.NET Application Architecture

w3wp.exe
w3wp.exe

Common Language Runtime (CLR)


JIT compiler
Garbage Collection threads

mscoree.dll
MyApp.dll mscorsvr.dll

20
ASP.NET programming model

 Event-driven programming (runat=“server”)

Form:
<asp:DropDownList id="FileDropDownList" style="Z-INDEX: 111;
LEFT: 192px; POSITION: absolute; TOP: 240px“ runat="server"
Width="552px" Height="40px“
AutoPostBack="True"></asp:DropDownList>

Code behind:
Private Sub FileDropDownList_SelectedIndexChanged _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles FileDropDownList.SelectedIndexChanged

Session("FileSelected") = FileDropDownList.SelectedValue
End Sub

21
IIS Architecture
Application Pool Application Pool
IIS
Administration

net.tcp net.tcp

Metabase
http http

Cache
Windows
Authentication WAS Default.aspx Default.aspx
FTP
<code-behind>.dll <code-behind>.dll

SSL SMTP
W3SVC Mscoree.dll Mscoree.dll
NNTP
W3wp W3wp
LSSAS Inetinfo SVCHOST W3wp W3wp
User
Kernel

HTTP

TCP HTTP Response Cache


IP
(Physical Memory)
Network HTTP Kernel Mode
Interface Driver
(http.sys) 22
HTTP Request
IIS Architecture

 Kernel mode driver


(http.sys)
 Dedicated kernel mode
Response object cache
 Static (jpgs, gifs, etc.) and
semi-dynamic (ASP.NET)
content
 Accessed using Physical
addresses only!
 Monitor Web Service
Cache\Kernel: Current
URIs Cached, etc.

See “IIS 7.0 Output Caching”


at http://learn.iis.net/page.aspx/154/iis-7-output-caching/ 23
IIS Architecture
 ASP and ASP.NET
requests processed by
w3wp.exe worker
processes
 Worker processes are
configured into
Application Pools
managed by the
Windows Process
Activation Service
(WAS)
 Pool Health options
(including automatic
recycling)
 Pool Performance
options
24
IIS Architecture
 ASP.NET w3wp.exe
worker processes
Health monitoring
 Performance counters
per worker process in
IIS 7.0

From a command line:


\windows\system32\inetsrv\appcmd list WP
25
demo
Monitoring IIS
worker
processes
Monitoring IIS worker processes

27
Monitoring IIS worker processes

28
IIS 7.0 Integrated Pipeline

 ASP.NET services can be made Request Life-cycle Events


available to non-ASP.NET Begin Request
applications!
Authentication
Authorization
 ApplicationManager Resolve Cache
 HostingEnvironment Map Handler
Acquire State
 Per Request Execute Handler
 HttpContext Release State
 HttpRequest Update Cache
 HttpResponse Log Request
Send Request

29
IIS 7.0 Integrated Mode

 HttpApplication Event Handlers (IHttpModule)


Event Event
BeginRequest PreRequestHandlerExecute
AuthenticateRequest PostRequestHandlerExecute
PostAuthenticateRequest ReleaseRequestState
AuthorizeRequest PostReleaseRequestState
PostAuthorizeRequest PostMapRequestHandler
ResolveRequestCache PostMapRequestHandler
PostResolveRequestCache PostMapRequestHandler
MapRequestHandler UpdateRequestCache
PostMapRequestHandler PostUpdateRequestCache
AcquireRequestState LogRequest
PostAcquireRequestState EndRequest

30
IIS 7.0 Integrated Mode

 Leverage ASP.NET Modules (services)


 FormsAuthenticationModule
 ProfileModule
 RoleManagerModule
 SessionStateModule
 See ApplicationHost.config <modules> section

 See Mike Volodarsky,


 “Explore The Web Server For Windows Vista And Beyond,” MSDN
Magazine, March 2007
 “Enhance Your Apps with the Integrated ASP.NET Pipeline,” MSDN
Magazine, January 2008.
 “Build Web Server Solutions with End-to-End Extensibility,” MSDN 31
Magazine, March 2008.
demo
Configure IIS ETW tracing to
gather RequestNotification
events
 Mark Friedman
Architect
Developer Division
Configure IIS Tracing using Logman

 IIS: WWW Server Event Trace Provider

33
Configure IIS Tracing using Logman

 IIS: WWW Server Event Trace Provider


Keywords

34
Configure IIS Tracing using Logman

 IIS: WWW Server Event Trace Provider –


Level = 5 (Diagnostic level)

35
ETW Trace reporting tools

 Post-process etl Trace using


 tracerpt

tracerpt filename.etl –of CSV –o mytrace.csv

 logparser

logparser "select * from filename.etl" -e 20


-o:DATAGRID -rtp 30 -compactModeSep "|"

 xperf
36
ETW Trace reporting tools

37
ETW Trace reporting tools

38
Configure IIS Tracing using Logman

 IIS: WWW Server Event Trace Provider


Keywords
 e.g., UseUrlFilter to control the volume of data
 Configure the TraceUriPrefix Metabase Property

See “How to Trace Requests for a


Specific URL or Set of URLs” at
http://www.microsoft.com/technet/pro
dtechnol/WindowsServer2003/Library/II
S/c56d19af-b3d1-4be9-8a6f-4aa86bacac
3f.mspx?mfr=true

39
ASP.NET programming model

 The HTTP protocol is


 connectionless
 sessionless
 .NET wrappers for HTTP protocol services
 HttpContext
 Provides programmatic access to all properties
associated with an HTTP Request
 Request
 Response
 Session
 Cache

40
ASP.NET programming model

 .NET wrappers for HTTP protocol services


 HttpContext.Request
 HttpMethod (GET, POST, etc.)
 URL
 Cookies collection
 Headers
 InputStream
 UserHostAddress (IP address of the Requestor)
 etc.

 The ASP.NET programming model provides several


facilities to persist User/Application state
41
ASP.NET Page Events

Event Usage
PreInit Create dynamic controls, set the Theme; master page, etc.
Init Read or initialize control properties
InitComplete Raised by the Page object.
PreLoad Perform any processing on your page or control before the Load event.
Load The Page calls the OnLoad event method on the Page, then recursively for each
child control and its children
Control events Button Clicks and other Control events are processed after Page_Load
LoadComplete Fires after all controls on the page are loaded.
PreRender Data binding for controls occurs now.
SaveStateComplete Fires when the ViewState for all controls is complete and saved.
Render Method that writes out the html markup associated with the control.
Unload Do final cleanup, such as closing files or database connections

42
ASP.NET scalability strategies
 Session State management
 ASP.NET Cache
 n-Tiered applications
 e.g.,
 Presentation Layer
 Business Logic Layer
 Data Layer

43
ASP.NET State Management

 What is State?
 Any information about the user,
his/her history and association with
the application that informs the
application’s processing.
 e.g.,
 how to associate a (potential)
customer with his/her shopping cart?

44
ASP.NET State Management

 Session State management


 Client-side options
 Hidden fields
 Cookies
 Query strings (including Web Beacons or Clear GIFs )
 View state
 Control state
 Server-side options
 Application state (HttpApplicationState)
 Session state
 Profile Properties

45
ASP.NET State Management

 State by Scope:
 Application state (HttpApplicationState)
 Page
 Static variables
 potentially use Page.Cache for dynamic data
 Session
 Client-side options
 Query strings
 Cookies
 Hidden fields
 View state
 Control state
 Server-side options
 Session state 46

ASP.NET Application Performance

 Persisting state
 on the client
 on the server
State Management
ViewState Stored in _VIEWSTATE hidden field

ControlState Override if ViewState is turned off on the Page

HiddenField control
Cookies Add cookie data to the Cookies collection in the HttpResponse object

Query strings
Application State HttpApplicationState

Session State
Profiles SqlProfileProvider
47
ASP.NET Application Performance

 Persisting state on the server (ViewState)

 Control ViewState (e.g., a DataGrid control)


 View state is enabled for all server controls by
default.
 Additional round trips to the server may be
required to re-send the Control’s ViewState
 remember, the HTTP protocol is sessionless
 Set the control's EnableViewState property to false
to disable…
 Or, use AJAX functions to eliminate server
postbacks so you can maintain ViewState on the
48
client (browser)
demo
Inspecting
controls
ViewState
ASP.NET ViewState

 ViewState
 Passed to the client in _ViewState hidden field in the
Response message
 Returned to the Server on a postback Request

 Inspect using
 %@ Page Trace="true“
 View html Source on the client
 3rd party tools like Fiddler

 Be careful of
 Data bound controls (GridView, etc.)
 50
Large TreeViews, DropDownLists, etc.
ASP.NET Application Performance

 Understanding what is in your ViewState?


 e.g., ASP.NET ViewState Helper tool from
Binary Fortress Software

51
ASP.NET Application State

 Page.Application Gets the


HttpApplicationState object for the current
Web request.
 Remember: application state must be locked to
update the data stored there correctly:
Application.Lock();
Application["PageRequestCount"] =
((int)Application["PageRequestCount"])+1;
Application.UnLock();

52
ASP.NET Session state

 HttpContext.Session
 Data associated with a logical sequence of Requests
that need to be persisted across interactions
 Unique session IDs are passed along automatically
with each Request as either cookies or embedded in
the URL
 Session data is stored in a Dictionary collection,
allowing individual session state variables to be
accessed directly by Key name
 Three external storage options
 InProc
 StateServer
 SQL Server
 Timeout management 53
ASP.NET Session

 HttpContext.Session
 InProc option provides fastest service, but does
not permit access to Session data from a
different process in a Web garden application
or a different Web server in a cluster
 Using alternatives to InProc session storage has
significant performance implications
 StateServer
 SQL Server
 Custom provider

 Measure impact using the IIS


RequestNotification events
 e.g., AcquireRequestState, PostAcquireRequestState
54
Session State options
 InProc
 StateServer
 Does not require using a separate computer
 ASP.NET State service must be active
 Provides persistent state for multiprocess IIS Web gardens with
automatic restart
 SQLServer
 Uses a separate computer where the DB is stored
 Multicomputer front-end clustering. e.g., Round-Robin DNS
 Failover on an HA cluster to a secondary copy of SQL Server

55
Session State configuration
options

56
Session State options
For example,

 Run either InstallSqlState.sql or InstallPersistSqlState.sql to create


the Session State stored procedures
 Code the sessionState attribute in web.config:

<configuration>
<system.web>
<sessionState mode="SQLServer"
sqlConnectionString=" Integrated
Security=SSPI;datasource=dataserver;"
cookieless="false"
timeout="20"/>
</sessionState>
</system.web> 57
</configuration>
Caching strategies

 Cache objects based on


 Frequency of re-use
 Cost to re-generate
 Size

 Optimize:
Max(Cache Hit %)

Min(Space x Time)

58
ASP.NET Cache

 Optimize to:
 maximize Cache Hit %
 minimize Cache
memory size

Cache Size
 Analyze web logs for
patterns of re-use
 Usually, there are
diminishing returns
from increasing cache
size to be large enough 0 25 50 75 100
to hold infrequently
referenced objects Cache Hit %
59
Caching strategies

 Multiple facilities:
 e.g.,
 IIS kernel mode Cache
 ASP.NET Application cache
 ASP.NET Page cache
 etc.

 Which cache facility?


 e.g., results from a complex database Query

 Depends on the scope of the data


 Application, User, Page (or some combination)
 Static vs. Dynamic data 60
Caching strategies

 Access to large process vm in x64 OS!


 To be effective, cached data should reside in
physical memory!
 Caching the same data in multiple places tends
to be wasteful
 Multiple layers of cache hold largely redundant data
 For the sake of latency, cache data as close to the client
as possible
 One effective layer is usually sufficient

 Note: effective caching is difficult & complex


 To achieve optimal results, be prepared to monitor
performance & analyze results.
61
ASP.NET Cache

 Application cache
 HttpContext.Cache
 Page.Cache
 Page output caching
 Full page
 @ OutputCache Directive
 Use VaryByParam with Query Strings to cache multiple versions of a Page
 Partial page
 Control Caching
 <PartialCaching> Attribute
 Post-cache substitution: dynamically updating portions of a cached page
 Substitution.MethodName
 HttpResponse.WriteSubstitution Method

 You can also cache data in the Session object, where 62


appropriate
ASP.NET Application & Page Cache

 What to cache:
 Frequently used data that is relatively static and expensive to
re-create
 Additional considerations based on object size

 space-time product: frequency of use x object size

 The Cache is instrumented using performance Counters


 But to use Cache effectively, you might need additional
performance data:
 e.g.,
 Enumerate the contents of the Cache
 Identify and log Underused entries
 63
Calculate cache residency times per entry
ASP.NET Application & Page Cache

 Steven Smith’s ASPAlliance Cache Manager Plug-in

64
ASP.NET Application & Page Cache

 Cache object is a hybrid of the Dictionary class


with additional methods and properties
 implements IEnumerable
 to manage cache effectiveness
 to help deal with cache synchronization issues
 Note: no built-in Lock object !
 Locking is not normally required, but may be necessary
to avoid race conditions in special situations

65
ASP.NET Application & Page Cache

 Cache Methods
 Add (key, value, dependencies, expiration, sliding
expiration, priority, onRemoveCallback);
 e.g., Cache.Add("Key1", "Value 1", null,
DateTime.Now.AddSeconds(60),
Cache.NoSlidingExpiration, CacheItemPriority.High,
onRemove);
 Dependencies (permits bulk removal)
 Notification upon removal

 Insert (also overwrites an existing entry)


 Get
 Remove 66
ASP.NET Application & Page Cache

 Cache Object Removal Policy


 Scavenging (based on Priority)
 Low, BelowNormal, Normal, AboveNormal,High
 NotRemovable
 Expiration
 Dependencies
 whenever the underlying data has changed
 set up an AggregateCacheDependency
 set up a SqlCacheDependency:
 uses SQL Query Notification mechanism when the
underlying data Table or View changes
 See
http://msdn.microsoft.com/en-us/library/system.web.ca
ching.sqlcachedependency.aspx 67
ASP.NET Application & Page Cache

 Calculate Application Cache effectiveness from


the ASP.NET Cache instrumentation
 Cache API Entries
 Cache API Hits
 Cache API Misses
 Cache API Hit Ratio
 Cache API Turnover Rate: The number of calls to
the Add, Insert, and Remove Methods per second

68
ASP.NET Application & Page Cache

 Cache Object Notifications upon removal

public void RemovedCallback


(String k, Object v,
CacheItemRemovedReason r){
}
 Examine the CacheItemRemovedReason
 DependencyChanged
 Expired
 Removed
 by a Remove method call, or
 by an Insert method call that specified the same key.
 Underused 69
ASP.NET Application & Page Cache

 InstrumentedCacheValue (to be processed by


CacheItemRemovedCallback delegate)
public class InstrumentedCacheValue {
private object _value;
private DateTime _timestamp_added;
// unfortunately, it is a sealed class; otherwise…
// private Int64 _refcount;
// private DateTime _lastreftimestamp;
public object Value { get { return _value; } }
public DateTime timestamp_added {
get { return _timestamp_added; } }
public InstrumentedCacheValue(object value){
_value = value;
_timestamp_added = DateTime.Now; }
}

70
ASP.NET Application & Page Cache

 Cache Object ReadOnly Properties


 Count
 EffectivePrivateBytesLimit
 can be set with the privateBytesLimit attribute
 EffectivePercentagePhysicalMemoryLimit
 can be set with the
percentagePhysicalMemoryUsedLimit attribute
 Cache Configuration Attributes in web.config
disableMemoryCollection
disableExpiration
privateBytesLimit
percentagePhysicalMemoryUsedLimit privateBytesPollTime="HH:MM:SS"
71
ASP.NET Page Output Cache

 Page output caching


 Full page
 @ OutputCache Directive
 Duration parameter (in seconds)
 Use VaryByParam to cache multiple versions of a Page
 Location
 Any (equivalent to HttpCacheability.Public )
 Client, Proxy Server, Edge Server, etc.
 Client: (equivalent to HttpCacheability.Private)
 Server: (equivalent to HttpCacheability.Server)
 None: (equivalent to HttpCacheability.NoCache)
 ServerAndClient: (equivalent to
HttpCacheability.Private & to HttpCacheability.Server)72
ASP.NET Page Output Cache

 Programmatically, set the HttpCachePolicy of


the Response.Cache object

Response.Cache.SetCacheability(HttpCacheability.Pu
blic);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(
300));
Response.Cache.SetMaxAge(TimeSpan.FromSeconds(300)
);
Response.Cache.SetValidUntilExpires(true);
Response.Cache.SetLastModified(DateTime.Now);
Response.Cache.SetOmitVaryStar(true);

73
ASP.NET Page Output Cache

 Programmatically set the Cache-Control header


 Call Response.Cache.SetCacheability Method and
set the HttpCacheability property
 NoCache
 Public
 Private (default)

 Server
 ServerAndNoCache
 PublicAndPrivate

74
ASP.NET Page Output Cache

 Calculate Cache effectiveness from the ASP.NET


Cache instrumentation
 Cache Entries
 Cache Hits
 Cache Misses
 Cache Hit Ratio
 Cache Turnover Rate: The number of calls to the
Add, Insert, and Remove Methods per second

75
ASP.NET Partial Page Output Cache

 When page caching will not work due to


dynamic content
 Two partial page caching options:
 Control caching for user controls
[PartialCaching(120)] public partial
class CachedControl :
System.Web.UI.UserControl
{ // Class Code }
 Post-Cache substitution
 Banner ads, etc.

76
ASP.NET & AJAX
 Web pages built with ASP.NET Web server
controls perform postbacks initiated by clicking
a button, etc.
 In Response, the server renders a new page.
 Frequently this re-renders controls and text that did
not change between postbacks.
 AJAX refers to set of patterns and practices that
perform partial rendering of the page at the
client using Javascript and asynchronous HTTP
requests
 Microsoft pioneered the use of AJAX prior to
ASP.NET
 AJAX support for ASP.NET was not provided 77
until.NET Framework 3.0
ASP.NET & AJAX

 Reduce server Round Tripping using client-side


scripting (Responsiveness)
 Support popular UI elements such as progress bars,
tooltips, pop-up windows
 Client call-backs (ICallbackHandler)
 AJAX (Asynchronous JavaScript and XML)
 XMLHttpRequest
 Microsoft AJAX Library on the client (browser)
 Server controls:
 ScriptManager
<asp:ScriptManager EnablePartialRendering="True“ />
 UpdatePanel
 UpdateProgress
 Timer
 Web services sending & receiving JSON or XML 78
 Web services located in the Cloud
ASP.NET and AJAX

 Asynchronous XMLHttpRequest
 Note: implementation of XMLHttpRequest is
browser-dependent
xmlhttp.open('GET', url, true);
xmlhttp.onreadystatechange = AsyncUpdateEvent;
xmlhttp.send(null);

79
ASP.NET and AJAX
 UpdatePanel Control
 Define regions of the page that can be updated independently using an
XMLHttpRequest
 converts PostBacks into Asynchronous XML and HTTP Requests
 Somewhat larger Request messages vs. significantly smaller server Response
messages
 Flicker-free update
 Re-sends all Viewstate data, however, for controls within the UpdatePanel

 Triggers Property
 ChildrenAsTriggers Property for controls inside the UpdatePanel

 See “Cutting Edge, “AJAX Application Architecture, Part 1” by Dino


Esposito for more details 80
AJAX Page Processing Events

Client Server
 HTTP Get Request
 Response message
 Sys.Application.Init
 All scripts loaded
 ScriptManager control
 UpdatePanel
 Sys.Application.Load

 A Button inside the


UpdatePanel is clicked…

81
AJAX Page Processing Events

Client Server
 PageRequestManager
 initializeRequest
 beginRequest
 Asynchronous postback
request to the server
 Response message
 pageLoading event
 pageLoaded event
 Application load event
 endRequest event

82
ASP.NET + AJAX

 Persisting state on the client using callbacks (e.g., a


TreeView control)
 on the server:
 Implement the ICallbackEventHandler interface.
 Implement the RaiseCallbackEvent method.
 Implement the GetCallbackResult method.
 on the client, provide three scripts:
 a helper method that performs the actual request to the
server,
 the client callback function to receive results from the server.
 A helper function that performs the actual request to the
server
 generated automatically by ASP.NET when you reference the
GetCallbackEventReference method in server code
 See : “Implementing Client Callbacks Programmatically Without Postbacks 83
in ASP.NET Web Pages” for details.
ASP.NET and AJAX and WCF

 Representational State Transfer service (REST)


 AJAX library wraps asynchronous WCF service endpoints
 WCF non-SOAP endpoints (i.e., JavaScript Object
Notation or JSON)
 Try the new Asynchronous WCF HTTP Module/Handler
for long running Requests
 New in VS 2008 SP1
 Releases the IIS worker thread immediately after processing
 Supports much higher levels of concurrency
 See Wenlong Dong’s blog for details
 ADO.NET Data Services Framework
 See http://msdn.microsoft.com/en-us/library/cc907912.aspx

84
ASP.NET + AJAX + WCF
 WCF code is protocol-independent
 WCF endpoints:
 Addresses
 Bindings (e.g., WebHttpBinding)
 Contracts

 configure declaratively

85
WCF Performance Caution: your
mileage will vary.
 Service Binding alternatives:
Binding Response Time (msecs) Throughput

wsHttpBinding 1300 1200


basicHttpBinding 1150 1800
netTcpBinding 400 5100
netNamedPipeBinding 280 7000

Throughput
8000
Source: Resnik, Crane, & Bowen,
6000
Essential Windows
4000
Communication Foundation,
Addison Wesley, 2008. Chapter 4. 2000

See also, “ i ng i ng i ng i ng
nd nd nd nd
A Performance Comparison of Windows Co p Bi p Bi pB
i
e Bi
tt tt Tc ip
mmunication Foundation (WCF) with Existing sH icH et P
w s n ed
Distributed Communication Technologies ba m
” e tNa 86
n
WCF Scalability

 Instancing
 per-Call servicing is the default mode
 per-Session servicing (the default)
[ServiceContract(Session = true)]
interface IMyContract {...}
[ServiceBehavior(InstanceContextMode =
InstanceContextMode.PerSession)]
class MyService : IMyContract {...}
<netTcpBinding>
<binding name="TCPSession">
<reliableSession enabled="true"
inactivityTimeout="00:25:00"/>
</binding>
</netTcpBinding>

 shareable service instances


WCF Scalability

 WCF Sessions
 Explicitly initiated and terminated by the calling
application.
 Messages are processed in the order in which
they are received.
 Sessions explicitly group messages into a
conversation.
 Note: WCF does not create a specific session-
oriented data store

 WCF Session-oriented behavior can be


handy with Transactions.
WCF Scalability

 Singleton service
 one instance of the service is configured
 the instance lasts until the Host shuts down
 the instance can have multiple concurrent threads…
[ServiceBehavior(
InstanceContextMode=InstanceContextMode.Single,
ConcurrencyMode = ConcurrencyMode.Multiple )]
class MySingleton : IMyContract, IDisposable
WCF Scalability

 Threading
 ConcurrencyMode.Multiple
 requires locking and synchronization of shared state
data
 ConcurrencyMode.Reentrant
 can be used with per-Session callers to limit the
number of concurrent instances

 Use serviceThrottling to control


concurrency levels
<behavior name="Throttled">
<serviceThrottling
maxConcurrentCalls="100"
maxConcurrentSessions=“30"
maxConcurrentInstances=“20" />
demo
Configure WCF
performanceCounters
 Mark Friedman
Architect
Developer Division
WCF Diagnostics
 In App.config:

<system.serviceModel>

<!--Enables the WCF ServiceModel performance counters for


this application.-->
<diagnostics performanceCounters="All"></diagnostics>

But
<diagnostics
performanceCounters=“ServiceOnly"></diagnostics>

is recommended (less overhead)


92
WCF Diagnostics

93
WCF Diagnostics

 WCF supports diagnostic tracing & end-to-


end tracing scenarios
 See
“Using Service Trace Viewer for Viewing Cor
related Traces and Troubleshooting”
 See also, Essential Windows
Communication Foundation, Ch. 9.

94
WCF Diagnostics

95
WCF Diagnostics

96
ASP.NET + AJAX + WCF
 WCF makes it easy to develop web services
Uri baseAddress = new Uri("http://localhost:8000/HelloService");
string address = "http://localhost:8000/HelloService/MyService";
using (ServiceHost serviceHost = new ServiceHost(typeof(HelloService),
baseAddress))
{
serviceHost.AddServiceEndpoint(typeof(IHello), new WebHttpBinding(),
address);
serviceHost.Open();
Console.WriteLine("Press <enter> to terminate service");
Console.ReadLine();
serviceHost.Close();
}

 AJAX support makes it easy to integrate asynchronous


web services into ASP.NET pages
97
ASP.NET + AJAX + WCF

 Use ASP.NET + AJAX + WCF for building Rich


Internet Applications
 Browser Document Object Model (DOM)
 Tree of all HTML page elements
 Need to decompose your web pages into
 Synchronous HTML requests for Server-side rendering
 Asynchronous HTML requests and Javascript
rendering
 Silverlight controls and WPF XAML elements
 Measure:
 Server-side rendering
 Download time for all server-side elements
 Client-side rendering 98
 Javascript execution time
ASP.NET programming tools

 Use tools like Fiddler

99
ASP.NET Application Performance
 HTTP performance is constrained by the TCP Protocol
 TCP ensures in order delivery of all packets
 All packets must be Acknowledged
 Note: full duplex protocol
 TCP Session handshaking
 SYN, SYN-ACK, ACK sequence
 Negotiates the TCP Window Size
 Calculates 1st Round Trip Time used by Fast Retransmit logic
 TCP Window
 Upper limit on the amount of data that can be sent to a
Receiver without receiving an Acknowledgement
 Congestion control (pacing) mechanism
 Slow Start
 Full Window used as a congestion signal
 Round Trip Time, or RTT, determines Timeout interval for
retransmitting unacknowledged, i.e., dropped packets
100
demo
Visual Roundtrip
Analyzer

Best Practices for Improving Page Load Time


ASP.NET Application Performance

102
Web Application Performance

103
Web Application Performance

 TCP measures Round Trip Time (RTT)


 RTT calculated for the initial SYN-ACK sequence
is used a baseline
 RTT is sampled thereafter and used to drive
reTransmits
 See also Timestamps Option
 It is the Latency, not the Bandwidth that
matters.

104
Web Application Performance

 VRTA (Visual Round Trip Analyzer)

105
Web Application Performance

 Elements of Page Load Time


 Html
 CSS
 Javascript (serialized)
 XAML
 Images
 Audio
 Video
 Banner ads (often from 3rd parties)
 etc.
 Page Load parallelism
 IE7 limited to two parallel sessions
 IE8 and Chrome support 5 or 6 parallel sessions 106
VRTA (Visual Round Trip Analyzer) File
details

107
VRTA (Visual Round Trip Analyzer) File
details

108
ASP.NET Application Performance

 Best Practices for improving Page Load Time


 Avoid needless Round Trips to the Server
 Use compression!!!
 Consolidate small image files (image clustering)
 Set Expiration dates for static content (strong
suggests versioning your web site)
 Be careful with ETAGs when IIS front-end machines
are clustered
 Beware of Javascript blocking
 Trade off download time against AJAX client
functionality
 Increase Parallel TCP Ports
 HTML 1.1 default is two simultaneous TCP Ports
 Make sure Keep_Alives are turned on 109
ASP.NET Application Performance

 Best Practices for improving Page Load Time


 Measure! Measure! Measure!
 Client-side interaction time measurements
 Timestamp Javascript execution time behavior
 Return response time data to the Server using a Get
Request for a clear gif, passing the response time
data in the Query string
 Using a c.gif for this client-server communication
(aka web beacon) is a common practice in Web
analytics
 Use an Asynchronous Get Request that doesn’t
block!!!

110

You might also like