 Mark Friedman Architect Developer Division Microsoft Corporation            Dynamic    my resume      TYPE="text/css">          connectionless sessionless       Postback HttpContext     ViewState Session State.

Download Report

Transcript  Mark Friedman Architect Developer Division Microsoft Corporation            Dynamic    my resume      TYPE="text/css">          connectionless sessionless       Postback HttpContext     ViewState Session State.

 Mark Friedman
Architect
Developer Division
Microsoft Corporation










3

Dynamic



<A HREF="resumepage.html">my resume</A>





<LINK REL=STYLESHEET HREF="mystyles.css"
TYPE="text/css">
4









connectionless
sessionless


5




Postback
HttpContext




ViewState
Session State
6






7

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



End-to-End
Multiple tiers
9

network latency
Client-side
script
Client-side
script
Client-side
script
Network
Latency
Server-side
.aspx
Unit Test
Network
Latency
Network
Latency
Server-side
.aspx
Load Test
e.g., VS TeamTest
Server-side
.aspx
Production
10
Page Load Time











Ready
11
12
13

VRTA
15













16









Semi-dynamic
17

may be






18











effective
Caching Architecture Guide for .NET Framework
Applications
19
w3wp.exe
Common Language Runtime (CLR)
JIT compiler
Garbage Collection threads
MyApp.dll
mscoree.dll
mscorsvr.dll
20
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
http
http
Metabase
Cache
Windows
Authentication
WAS
FTP
SSL
SMTP
W3SVC
NNTP
LSSAS
Inetinfo
SVCHOST
Default.aspx
Default.aspx
<code-behind>.dll
<code-behind>.dll
Mscoree.dll
Mscoree.dll
W3wp
W3wp
W3wp
W3wp
User
Kernel
HTTP
HTTP Response Cache
TCP
IP
Network
Interface
HTTP Request
HTTP Kernel Mode
Driver
(http.sys)
(Physical Memory)
22

http.sys

Response object cache



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

w3wp.exe



24

w3wp.exe

From a command line:
\windows\system32\inetsrv\appcmd list WP
25
27
28

Request Life-cycle Events
Begin Request
Authentication


Authorization
Resolve Cache
Map Handler

Acquire State



Execute Handler
Release State
Update Cache
Log Request
Send Request
29

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






<modules>




31
RequestNotification
 Mark Friedman
Architect
Developer Division

33

34

Level = 5 (Diagnostic level)
35


tracerpt
tracerpt filename.etl –of CSV –o mytrace.csv

logparser
logparser "select * from filename.etl" -e 20
-o:DATAGRID -rtp 30 -compactModeSep "|"

xperf
36
37
38



UseUrlFilter to control the volume of data
Configure the TraceUriPrefix
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-8a6f4aa86bacac3f.mspx?mfr=true
39





HttpContext





Request
Response
Session
Cache
40


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
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

Session State

Cache


e.g.,



Presentation Layer
Business Logic Layer
Data Layer
43




44











HttpApplicationState
45



Application
Page



HttpApplicationState
Page.Cache
Session









46



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
ViewState







48

ViewState

Passed to the client in _ViewState hidden field in the
Response message
Returned to the Server on a postback Request

Inspect using





View html Source on the client
3rd party tools like Fiddler
Be careful of


Data bound controls (GridView, etc.)
Large TreeViews, DropDownLists, etc.
50


51

Page.Application

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

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





SQLServer



55
56
Session State options


InstallSqlState.sql
InstallPersistSqlState.sql
sessionState
57




Frequency of re-use
Cost to re-generate
Size

Max(Cache Hit %)
Min(Space x Time)
58

Cache Size




diminishing returns
0
25
50
75
100
Cache Hit %
59






IIS kernel mode Cache
ASP.NET Application cache
ASP.NET Page cache





60







Note:
effective
difficult
complex

61




HttpContext.Cache
Page.Cache



@ OutputCache
VaryByParam



<PartialCaching>


Substitution.MethodName
HttpResponse.WriteSubstitution


62



frequency of use x object size







Underused
63

64

Cache
Dictionary
IEnumerable





65


Add






Insert
Get
Remove
66









AggregateCacheDependency
SqlCacheDependency


http://msdn.microsoft.com/enus/library/system.web.caching.sqlcachedependency.a
spx
67
effectiveness






Cache API Entries
Cache API Hits
Cache API Misses
Cache API Hit Ratio
Cache API Turnover Rate
68

public void RemovedCallback
(String k, Object v,
CacheItemRemovedReason r){
}

Examine the CacheItemRemovedReason






69

InstrumentedCacheValue
// unfortunately, it is a sealed class; otherwise…
// private Int64 _refcount;
// private DateTime _lastreftimestamp;
70



Count
EffectivePrivateBytesLimit


EffectivePercentagePhysicalMemoryLimit


disableMemoryCollection
disableExpiration
privateBytesLimit
percentagePhysicalMemoryUsedLimit privateBytesPollTime="HH:MM:SS"
71






@ OutputCache
Duration
VaryByParam
Location






72

HttpCachePolicy
73

Response.Cache.SetCacheability
HttpCacheability







74
effectiveness






Cache Entries
Cache Hits
Cache Misses
Cache Hit Ratio
Cache Turnover Rate
75

When page caching will not work due to
dynamic content


[PartialCaching(120)] public partial class
CachedControl :
System.Web.UI.UserControl
// Class Code


Banner ads, etc.
76




not change
that did
AJAX
requests
Javascript
asynchronous HTTP


77


ICallbackHandler






<asp:ScriptManager EnablePartialRendering="True“ />





78


XMLHttpRequest
xmlhttp.open('GET', url, true);
xmlhttp.onreadystatechange = AsyncUpdateEvent;
xmlhttp.send(null);
79

UpdatePanel








“
Triggers
ChildrenAsTriggers
AJAX Application Architecture, Part 1
80



Sys.Application.Init




Sys.Application.Load

UpdatePanel
81

PageRequestManager






pageLoading
pageLoaded

endReques

82


ICallbackEventHandler
RaiseCallbackEvent
GetCallbackResul









Implementing Client Callbacks Programmatically Without Postbacks
in ASP.NET Web Pages
83
REST



AJAX library wraps asynchronous WCF service endpoints

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

http://msdn.microsoft.com/en-us/library/cc907912.aspx
See Wenlong Dong’s blog for details

84





WebHttpBinding

85
Caution: your
mileage will vary.

Binding
Binding
Response Time (msecs)
Throughput
wsHttpBinding
1300
1200
basicHttpBinding
1150
1800
netTcpBinding
400
5100
netNamedPipeBinding
280
7000
Throughput
8000
Source: Resnik, Crane, & Bowen,
Essential Windows
Communication Foundation,
Addison Wesley, 2008. Chapter 4.
6000
4000
2000
0
See also, “A Performance Comparison of
Windows Communication Foundation (WCF)
with Existing Distributed Communication
Technologies”
86



[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>




they are received

conversation


in the order in which




[ServiceBehavior(
InstanceContextMode=InstanceContextMode.Single,
ConcurrencyMode = ConcurrencyMode.Multiple )]
class MySingleton : IMyContract, IDisposable


ConcurrencyMode.Multiple


requires locking and synchronization of shared state
data
ConcurrencyMode.Reentrant


serviceThrottling
<behavior name="Throttled">
<serviceThrottling
maxConcurrentCalls="100"
maxConcurrentSessions=“30"
maxConcurrentInstances=“20" />
performanceCounters
 Mark Friedman
Architect
Developer Division

<system.serviceModel>
<diagnostics performanceCounters="All"></diagnostics>
But
<diagnostics
performanceCounters=“ServiceOnly"></diagnostics>
is recommended (less overhead)
92
93



“Using Service Trace Viewer for Viewing
Correlated Traces and Troubleshooting”
Essential Windows
Communication Foundation
94
95
96

string
using
new
"http://localhost:8000/HelloService"
"http://localhost:8000/HelloService/MyService"
new
new
"Press <enter> to terminate service"

97








Measure:




98

Fiddler
99








TCP Window Size






without
100
Best Practices for Improving Page Load Time
102
103





104

105










(serialized)



106
107
108











109





Request
Get


110