Welcome to mirror list, hosted at ThFree Co, Russian Federation.

HttpApplication.cs « System.Web « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9bc91f54b46bb3805d6da8f025ce5d85c2d45347 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
//------------------------------------------------------------------------------
// <copyright file="HttpApplication.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Web {
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.Design;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Runtime.ExceptionServices;
    using System.Runtime.InteropServices;
    using System.Runtime.Remoting.Messaging;
    using System.Runtime.Serialization.Formatters;
    using System.Security;
    using System.Security.Permissions;
    using System.Security.Principal;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Compilation;
    using System.Web.Configuration;
    using System.Web.Configuration.Common;
    using System.Web.Hosting;
    using System.Web.Management;
    using System.Web.Security;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.Util;
    using IIS = System.Web.Hosting.UnsafeIISMethods;


    //
    // Async EventHandler support
    //


    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    public delegate IAsyncResult BeginEventHandler(object sender, EventArgs e, AsyncCallback cb, object extraData);

    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    public delegate void EndEventHandler(IAsyncResult ar);

    // Represents an event handler using TAP (Task Asynchronous Pattern).
    public delegate Task TaskEventHandler(object sender, EventArgs e);


    /// <devdoc>
    ///    <para>
    ///       The  HttpApplication class defines the methods, properties and events common to all
    ///       HttpApplication objects within the ASP.NET Framework.
    ///    </para>
    /// </devdoc>
    [
    ToolboxItem(false)
    ]
    public class HttpApplication : IComponent, IHttpAsyncHandler, IRequestCompletedNotifier, ISyncContext {
        // application state dictionary
        private HttpApplicationState _state;

        // context during init for config lookups
        private HttpContext _initContext;

        // async support
        private HttpAsyncResult _ar; // currently pending async result for call into application

        // list of modules
        private static readonly DynamicModuleRegistry _dynamicModuleRegistry = new DynamicModuleRegistry();
        private HttpModuleCollection  _moduleCollection;

        // event handlers
        private static readonly object EventDisposed = new object();
        private static readonly object EventErrorRecorded = new object();
        private static readonly object EventRequestCompleted = new object();
        private static readonly object EventPreSendRequestHeaders = new object();
        private static readonly object EventPreSendRequestContent = new object();

        private static readonly object EventBeginRequest = new object();
        private static readonly object EventAuthenticateRequest = new object();
        private static readonly object EventDefaultAuthentication = new object();
        private static readonly object EventPostAuthenticateRequest = new object();
        private static readonly object EventAuthorizeRequest = new object();
        private static readonly object EventPostAuthorizeRequest = new object();
        private static readonly object EventResolveRequestCache = new object();
        private static readonly object EventPostResolveRequestCache = new object();
        private static readonly object EventMapRequestHandler = new object();
        private static readonly object EventPostMapRequestHandler = new object();
        private static readonly object EventAcquireRequestState = new object();
        private static readonly object EventPostAcquireRequestState = new object();
        private static readonly object EventPreRequestHandlerExecute = new object();
        private static readonly object EventPostRequestHandlerExecute = new object();
        private static readonly object EventReleaseRequestState = new object();
        private static readonly object EventPostReleaseRequestState = new object();
        private static readonly object EventUpdateRequestCache = new object();
        private static readonly object EventPostUpdateRequestCache = new object();
        private static readonly object EventLogRequest = new object();
        private static readonly object EventPostLogRequest = new object();
        private static readonly object EventEndRequest = new object();
        internal static readonly string AutoCulture = "auto";

        private EventHandlerList _events;
        private AsyncAppEventHandlersTable _asyncEvents;

        // execution steps
        private StepManager _stepManager;

        // callback for Application ResumeSteps
        #pragma warning disable 0649
        private WaitCallback _resumeStepsWaitCallback;
        #pragma warning restore 0649

        // event passed to modules
        private EventArgs _appEvent;

        // list of handler mappings
        private Hashtable _handlerFactories = new Hashtable();

        // list of handler/factory pairs to be recycled
        private ArrayList _handlerRecycleList;

        // flag to hide request and response intrinsics
        private bool _hideRequestResponse;

        // application execution variables
        private HttpContext _context;
        private Exception _lastError;  // placeholder for the error when context not avail
        private bool _timeoutManagerInitialized;

        // session (supplied by session-on-end outside of context)
        private HttpSessionState _session;

        // culture (needs to be set per thread)
        private CultureInfo _appLevelCulture;
        private CultureInfo _appLevelUICulture;
        private CultureInfo _savedAppLevelCulture;
        private CultureInfo _savedAppLevelUICulture;
        private bool _appLevelAutoCulture;
        private bool _appLevelAutoUICulture;

        // pipeline event mappings
        private Dictionary<string, RequestNotification> _pipelineEventMasks;


        // IComponent support
        private ISite _site;

        // IIS7 specific fields
        internal const string MANAGED_PRECONDITION = "managedHandler";
        internal const string IMPLICIT_FILTER_MODULE = "AspNetFilterModule";
        internal const string IMPLICIT_HANDLER = "ManagedPipelineHandler";

        // map modules to their index
        private static Hashtable _moduleIndexMap = new Hashtable();
        private static bool _initSpecialCompleted;

        private bool _initInternalCompleted;
        private RequestNotification _appRequestNotifications;
        private RequestNotification _appPostNotifications;

        // Set the current module init key to the global.asax module to enable
        // the custom global.asax derivation constructor to register event handlers
        private string _currentModuleCollectionKey = HttpApplicationFactory.applicationFileName;

        // module config is read once per app domain and used to initialize the per-instance _moduleContainers array
        private static List<ModuleConfigurationInfo> _moduleConfigInfo;

        // this is the per instance list that contains the events for each module
        private PipelineModuleStepContainer[] _moduleContainers;

        // Byte array to be used by HttpRequest.GetEntireRawContent. Windows OS 
        private byte[] _entityBuffer;

        // Counts the number of code paths consuming this HttpApplication instance. When the counter hits zero,
        // it is safe to release this HttpApplication instance back into the HttpApplication pool.
        // This counter can be null if we're not using the new Task-friendly code paths.
        internal CountdownTask ApplicationInstanceConsumersCounter;

        private IAllocatorProvider _allocator;

        //
        // Public Application properties
        //


        /// <devdoc>
        ///    <para>
        ///          HTTPRuntime provided context object that provides access to additional
        ///          pipeline-module exposed objects.
        ///       </para>
        ///    </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public HttpContext Context {
            get {
                return(_context != null) ? _context : _initContext;
            }
        }

        private bool IsContainerInitalizationAllowed {
            get {
                if (HttpRuntime.UseIntegratedPipeline && _initSpecialCompleted && !_initInternalCompleted) {
                    // return true if
                    //      i) this is integrated pipeline mode,
                    //     ii) InitSpecial has been called at least once in this AppDomain to register events with IIS,
                    //    iii) InitInternal has not been invoked yet or is currently executing
                    return true;
                }
                return false;
            }
        }

        private void ThrowIfEventBindingDisallowed() {
            if (HttpRuntime.UseIntegratedPipeline && _initSpecialCompleted && _initInternalCompleted) {
                // throw if we're using the integrated pipeline and both InitSpecial and InitInternal have completed.
                throw new InvalidOperationException(SR.GetString(SR.Event_Binding_Disallowed));
            }
        }

        private PipelineModuleStepContainer[] ModuleContainers {
            get {
                if (_moduleContainers == null) {

                    Debug.Assert(_moduleIndexMap != null && _moduleIndexMap.Count > 0, "_moduleIndexMap != null && _moduleIndexMap.Count > 0");

                    // At this point, all modules have been registered with IIS via RegisterIntegratedEvent.
                    // Now we need to create a container for each module and add execution steps.
                    // The number of containers is the same as the number of modules that have been
                    // registered (_moduleIndexMap.Count).

                    _moduleContainers = new PipelineModuleStepContainer[_moduleIndexMap.Count];

                    for (int i = 0; i < _moduleContainers.Length; i++) {
                        _moduleContainers[i] = new PipelineModuleStepContainer();
                    }

                }

                return _moduleContainers;
            }
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public event EventHandler Disposed {
            add {
                Events.AddHandler(EventDisposed, value);
            }

            remove {
                Events.RemoveHandler(EventDisposed, value);
            }
        }


        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected EventHandlerList Events {
            get {
                if (_events == null) {
                    _events = new EventHandlerList();
                }
                return _events;
            }
        }

        internal IExecutionStep CreateImplicitAsyncPreloadExecutionStep() {
            ImplicitAsyncPreloadModule implicitAsyncPreloadModule = new ImplicitAsyncPreloadModule();
            BeginEventHandler beginHandler = null;
            EndEventHandler endHandler = null;
            implicitAsyncPreloadModule.GetEventHandlers(out beginHandler, out endHandler);
            return new AsyncEventExecutionStep(this, beginHandler, endHandler, null);            
        }

        private AsyncAppEventHandlersTable AsyncEvents {
            get {
                if (_asyncEvents == null)
                    _asyncEvents = new AsyncAppEventHandlersTable();
                return _asyncEvents;
            }
        }

        // Last error during the processing of the current request.
        internal Exception LastError {
            get {
                // only temporaraly public (will be internal and not related context)
                return (_context != null) ? _context.Error : _lastError;
            }

        }

        // Used by HttpRequest.GetEntireRawContent. Windows OS 
        internal byte[] EntityBuffer
        {
            get
            {
                if (_entityBuffer == null)
                {
                    _entityBuffer = new byte[8 * 1024];
                }
                return _entityBuffer;
            }
        }

        // Provides fixed size reusable buffers per request
        // Benefit:
        //   1) Eliminates global locks - access to HttpApplication instance is lock free and no concurrent access is expected (by design).
        //      36+ cores show really bad spin lock characteristics for short locks.
        //   2) Better lifetime dynamics - Buffers increase/decrease as HttpApplication instances grow/shrink on demand.
        internal IAllocatorProvider AllocatorProvider {
            get {
                if (_allocator == null) {
                    AllocatorProvider alloc = new AllocatorProvider();

                    alloc.CharBufferAllocator = new SimpleBufferAllocator<char>(BufferingParams.CHAR_BUFFER_SIZE);
                    alloc.IntBufferAllocator = new SimpleBufferAllocator<int>(BufferingParams.INT_BUFFER_SIZE);
                    alloc.IntPtrBufferAllocator = new SimpleBufferAllocator<IntPtr>(BufferingParams.INTPTR_BUFFER_SIZE);

                    Interlocked.CompareExchange(ref _allocator, alloc, null);
                }

                return _allocator;
            }
        }

        internal void ClearError() {
            _lastError = null;
        }

        /// <devdoc>
        ///    <para>HTTPRuntime provided request intrinsic object that provides access to incoming HTTP
        ///       request data.</para>
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public HttpRequest Request {
            get {
                HttpRequest request = null;

                if (_context != null && !_hideRequestResponse)
                    request = _context.Request;

                if (request == null)
                    throw new HttpException(SR.GetString(SR.Request_not_available));

                return request;
            }
        }


        /// <devdoc>
        ///    <para>HTTPRuntime provided
        ///       response intrinsic object that allows transmission of HTTP response data to a
        ///       client.</para>
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public HttpResponse Response {
            get {
                HttpResponse response = null;

                if (_context != null && !_hideRequestResponse)
                    response = _context.Response;

                if (response == null)
                    throw new HttpException(SR.GetString(SR.Response_not_available));

                return response;
            }
        }


        /// <devdoc>
        ///    <para>
        ///    HTTPRuntime provided session intrinsic.
        ///    </para>
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public HttpSessionState Session {
            get {
                HttpSessionState session = null;

                if (_session != null)
                    session = _session;
                else if (_context != null)
                    session = _context.Session;

                if (session == null)
                    throw new HttpException(SR.GetString(SR.Session_not_available));

                return session;
            }
        }


        /// <devdoc>
        ///    <para>
        ///       Returns
        ///          a reference to an HTTPApplication state bag instance.
        ///       </para>
        ///    </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public HttpApplicationState Application {
            get {
                Debug.Assert(_state != null);  // app state always available
                return _state;
            }
        }


        /// <devdoc>
        ///    <para>Provides the web server Intrinsic object.</para>
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public HttpServerUtility Server {
            get {
                if (_context != null)
                    return _context.Server;
                else
                    return new HttpServerUtility(this); // special Server for application only
            }
        }


        /// <devdoc>
        ///    <para>Provides the User Intrinsic object.</para>
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public IPrincipal User {
            get {
                if (_context == null)
                    throw new HttpException(SR.GetString(SR.User_not_available));

                return _context.User;
            }
        }


        /// <devdoc>
        ///    <para>
        ///       Collection
        ///          of all IHTTPModules configured for the current application.
        ///       </para>
        ///    </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public HttpModuleCollection Modules {
            [AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.High)]
            get {
                if (_moduleCollection == null)
                    _moduleCollection = new HttpModuleCollection();
                return _moduleCollection;
            }
        }

        // event passed to all modules
        internal EventArgs AppEvent {
            get {
                if (_appEvent == null)
                    _appEvent = EventArgs.Empty;

                return _appEvent;
            }

            set {
                _appEvent = null;
            }
        }

        // DevDiv Bugs 151914: Release session state before executing child request
        internal void EnsureReleaseState() {
            if (_moduleCollection != null) {
                for (int i = 0; i < _moduleCollection.Count; i++) {
                    IHttpModule module = _moduleCollection.Get(i);
                    if (module is SessionStateModule) {
                        ((SessionStateModule) module).EnsureReleaseState(this);
                        break;
                    }
                }
            }
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public void CompleteRequest() {
            //
            // Request completion (force skipping all steps until RequestEnd
            //
            _stepManager.CompleteRequest();
        }

        internal bool IsRequestCompleted {
            get {
                if (null == _stepManager) {
                    return false;
                }

                return _stepManager.IsCompleted;
            }
        }

        bool IRequestCompletedNotifier.IsRequestCompleted {
            get {
                return IsRequestCompleted;
            }
        }

        // Dev10 745301: Asynchronous pipeline steps can start a new thread that triggers
        // a SendResponse notification.  E.g., it might call Flush when a module is registered
        // for PreSendRequestHeaders/Content.  If the async pipeline step returns from ExecuteStep
        // while the SendResponse notification is executing, the NotificationContext can 
        // be corrupted.  To fix this, a lock is now taken to prevent multi-threaded access when
        // the async pipeline step sets the NotificationContext.PendingAsyncCompletion field.  
        // The SendResponse notification also acquires the lock when it enters managed code and 
        // releases the lock when it leaves.
        internal void AcquireNotifcationContextLock(ref bool locked) {
            Debug.Assert(HttpRuntime.UseIntegratedPipeline, "HttpRuntime.UseIntegratedPipeline");
            Monitor.Enter(_stepManager, ref locked);
        }

        internal void ReleaseNotifcationContextLock() {
            Debug.Assert(HttpRuntime.UseIntegratedPipeline, "HttpRuntime.UseIntegratedPipeline");
            Monitor.Exit(_stepManager);
        }

        // Some frameworks built on top of the integrated pipeline call Flush() on background thread which will trigger nested 
        // RQ_SEND_RESPONSE notification and replace the old context.NotificationContext with the new context.NotificationContext.
        // In order to maintain proper synchronization logic at the time when the completion callback is called we need to make sure 
        // we access the original context.NotificationContext (and don't touch the nested one).
        // It will make sure that we read the correct NotificationContext
        [MethodImpl(MethodImplOptions.NoInlining)]
        private void GetNotifcationContextPropertiesUnderLock(ref bool isReentry, ref int eventCount) {
            bool locked = false;
            try {
                AcquireNotifcationContextLock(ref locked);
                isReentry = Context.NotificationContext.IsReEntry;
                eventCount = CurrentModuleContainer.GetEventCount(Context.CurrentNotification, Context.IsPostNotification) - 1;
            }
            finally {
                if (locked) {
                    ReleaseNotifcationContextLock();
                }
            }
        }
        
        [MethodImpl(MethodImplOptions.NoInlining)] // Iniling this causes throughtput regression in ResumeStep
        private void GetNotifcationContextProperties(ref bool isReentry, ref int eventCount) {
            // Read optimistically (without lock)
            var nc = Context.NotificationContext;
            isReentry = nc.IsReEntry;
            // We can continue optimistic read only if this is not reentry
            if (!isReentry) {
                eventCount = ModuleContainers[nc.CurrentModuleIndex].GetEventCount(nc.CurrentNotification, nc.IsPostNotification) - 1;
                // Check if the optimistic read was consistent
                if (object.ReferenceEquals(nc, Context.NotificationContext)) {
                    return;
                }
            }
            GetNotifcationContextPropertiesUnderLock(ref isReentry, ref eventCount);
        }

        private void RaiseOnError() {
            EventHandler handler = (EventHandler)Events[EventErrorRecorded];
            if (handler != null) {
                try {
                    handler(this, AppEvent);
                }
                catch (Exception e) {
                    if (_context != null) {
                        _context.AddError(e);
                    }
                }
            }
        }

        private void RaiseOnRequestCompleted() {
            EventHandler handler = (EventHandler)Events[EventRequestCompleted];
            if (handler != null) {
                try {
                    handler(this, AppEvent);
                }
                catch (Exception e) {
                    WebBaseEvent.RaiseRuntimeError(e, this);
                }
            }
        }

        internal void RaiseOnPreSendRequestHeaders() {
            EventHandler handler = (EventHandler)Events[EventPreSendRequestHeaders];
            if (handler != null) {
                try {
                    handler(this, AppEvent);
                }
                catch (Exception e) {
                    RecordError(e);
                }
            }
        }

        internal void RaiseOnPreSendRequestContent() {
            EventHandler handler = (EventHandler)Events[EventPreSendRequestContent];
            if (handler != null) {
                try {
                    handler(this, AppEvent);
                }
                catch (Exception e) {
                    RecordError(e);
                }
            }
        }

        internal HttpAsyncResult AsyncResult {
            get {
                if (HttpRuntime.UseIntegratedPipeline) {
                    return (_context.NotificationContext != null) ? _context.NotificationContext.AsyncResult : null;
                }
                else {
                    return _ar;
                }
            }
            set {
                if (HttpRuntime.UseIntegratedPipeline) {
                    _context.NotificationContext.AsyncResult = value;
                }
                else {
                    _ar = value;
                }
            }
        }

        internal void AddSyncEventHookup(object key, Delegate handler, RequestNotification notification) {
            AddSyncEventHookup(key, handler, notification, false);
        }

        private PipelineModuleStepContainer CurrentModuleContainer { get { return ModuleContainers[_context.CurrentModuleIndex]; } }

        private PipelineModuleStepContainer GetModuleContainer(string moduleName) {
            object value = _moduleIndexMap[moduleName];

            if (value == null) {
                return null;
            }

            int moduleIndex = (int)value;

#if DBG
            Debug.Trace("PipelineRuntime", "GetModuleContainer: moduleName=" + moduleName + ", index=" + moduleIndex.ToString(CultureInfo.InvariantCulture) + "\r\n");
            Debug.Assert(moduleIndex >= 0 && moduleIndex < ModuleContainers.Length, "moduleIndex >= 0 && moduleIndex < ModuleContainers.Length");
#endif

            PipelineModuleStepContainer container = ModuleContainers[moduleIndex];

            Debug.Assert(container != null, "container != null");

            return container;
        }

        private void AddSyncEventHookup(object key, Delegate handler, RequestNotification notification, bool isPostNotification) {
            ThrowIfEventBindingDisallowed();

            // add the event to the delegate invocation list
            // this keeps non-pipeline ASP.NET hosts working
            Events.AddHandler(key, handler);

            // For integrated pipeline mode, add events to the IExecutionStep containers only if
            // InitSpecial has completed and InitInternal has not completed.
            if (IsContainerInitalizationAllowed) {
                // lookup the module index and add this notification
                PipelineModuleStepContainer container = GetModuleContainer(CurrentModuleCollectionKey);
                //WOS 1985878: HttpModule unsubscribing an event handler causes AV in Integrated Mode
                if (container != null) {
#if DBG
                    container.DebugModuleName = CurrentModuleCollectionKey;
#endif
                    SyncEventExecutionStep step = new SyncEventExecutionStep(this, (EventHandler)handler);
                    container.AddEvent(notification, isPostNotification, step);
                }
            }
        }

        internal void RemoveSyncEventHookup(object key, Delegate handler, RequestNotification notification) {
            RemoveSyncEventHookup(key, handler, notification, false);
        }

        internal void RemoveSyncEventHookup(object key, Delegate handler, RequestNotification notification, bool isPostNotification) {
            ThrowIfEventBindingDisallowed();

            Events.RemoveHandler(key, handler);

            if (IsContainerInitalizationAllowed) {
                PipelineModuleStepContainer container = GetModuleContainer(CurrentModuleCollectionKey);
                //WOS 1985878: HttpModule unsubscribing an event handler causes AV in Integrated Mode
                if (container != null) {
                    container.RemoveEvent(notification, isPostNotification, handler);
                }
            }
        }

        private void AddSendResponseEventHookup(object key, Delegate handler) {
            ThrowIfEventBindingDisallowed();

            // add the event to the delegate invocation list
            // this keeps non-pipeline ASP.NET hosts working
            Events.AddHandler(key, handler);

            // For integrated pipeline mode, add events to the IExecutionStep containers only if
            // InitSpecial has completed and InitInternal has not completed.
            if (IsContainerInitalizationAllowed) {
                // lookup the module index and add this notification
                PipelineModuleStepContainer container = GetModuleContainer(CurrentModuleCollectionKey);
                //WOS 1985878: HttpModule unsubscribing an event handler causes AV in Integrated Mode
                if (container != null) {
#if DBG
                    container.DebugModuleName = CurrentModuleCollectionKey;
#endif
                    bool isHeaders = (key == EventPreSendRequestHeaders);
                    SendResponseExecutionStep step = new SendResponseExecutionStep(this, (EventHandler)handler, isHeaders);
                    container.AddEvent(RequestNotification.SendResponse, false /*isPostNotification*/, step);
                }
            }
        }

        private void RemoveSendResponseEventHookup(object key, Delegate handler) {
            ThrowIfEventBindingDisallowed();

            Events.RemoveHandler(key, handler);

            if (IsContainerInitalizationAllowed) {
                PipelineModuleStepContainer container = GetModuleContainer(CurrentModuleCollectionKey);
                //WOS 1985878: HttpModule unsubscribing an event handler causes AV in Integrated Mode
                if (container != null) {
                    container.RemoveEvent(RequestNotification.SendResponse, false /*isPostNotification*/, handler);
                }
            }
        }

        //
        // Sync event hookup
        //


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler BeginRequest {
            add { AddSyncEventHookup(EventBeginRequest, value, RequestNotification.BeginRequest); }
            remove { RemoveSyncEventHookup(EventBeginRequest, value, RequestNotification.BeginRequest); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler AuthenticateRequest {
            add { AddSyncEventHookup(EventAuthenticateRequest, value, RequestNotification.AuthenticateRequest); }
            remove { RemoveSyncEventHookup(EventAuthenticateRequest, value, RequestNotification.AuthenticateRequest); }
        }

        // internal - for back-stop module only
        internal event EventHandler DefaultAuthentication {
            add { AddSyncEventHookup(EventDefaultAuthentication, value, RequestNotification.AuthenticateRequest); }
            remove { RemoveSyncEventHookup(EventDefaultAuthentication, value, RequestNotification.AuthenticateRequest); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler PostAuthenticateRequest {
            add { AddSyncEventHookup(EventPostAuthenticateRequest, value, RequestNotification.AuthenticateRequest, true); }
            remove { RemoveSyncEventHookup(EventPostAuthenticateRequest, value, RequestNotification.AuthenticateRequest, true); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler AuthorizeRequest {
            add { AddSyncEventHookup(EventAuthorizeRequest, value, RequestNotification.AuthorizeRequest); }
            remove { RemoveSyncEventHookup(EventAuthorizeRequest, value, RequestNotification.AuthorizeRequest); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler PostAuthorizeRequest {
            add { AddSyncEventHookup(EventPostAuthorizeRequest, value, RequestNotification.AuthorizeRequest, true); }
            remove { RemoveSyncEventHookup(EventPostAuthorizeRequest, value, RequestNotification.AuthorizeRequest, true); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler ResolveRequestCache {
            add { AddSyncEventHookup(EventResolveRequestCache, value, RequestNotification.ResolveRequestCache); }
            remove { RemoveSyncEventHookup(EventResolveRequestCache, value, RequestNotification.ResolveRequestCache); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler PostResolveRequestCache {
            add { AddSyncEventHookup(EventPostResolveRequestCache, value, RequestNotification.ResolveRequestCache, true); }
            remove { RemoveSyncEventHookup(EventPostResolveRequestCache, value, RequestNotification.ResolveRequestCache, true); }
        }

        public event EventHandler MapRequestHandler {
            add {
                if (!HttpRuntime.UseIntegratedPipeline) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }
                AddSyncEventHookup(EventMapRequestHandler, value, RequestNotification.MapRequestHandler);
            }
            remove {
                if (!HttpRuntime.UseIntegratedPipeline) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }
                RemoveSyncEventHookup(EventMapRequestHandler, value, RequestNotification.MapRequestHandler);
            }
        }

        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler PostMapRequestHandler {
            add { AddSyncEventHookup(EventPostMapRequestHandler, value, RequestNotification.MapRequestHandler, true); }
            remove { RemoveSyncEventHookup(EventPostMapRequestHandler, value, RequestNotification.MapRequestHandler); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler AcquireRequestState {
            add { AddSyncEventHookup(EventAcquireRequestState, value, RequestNotification.AcquireRequestState); }
            remove { RemoveSyncEventHookup(EventAcquireRequestState, value, RequestNotification.AcquireRequestState); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler PostAcquireRequestState {
            add { AddSyncEventHookup(EventPostAcquireRequestState, value, RequestNotification.AcquireRequestState, true); }
            remove { RemoveSyncEventHookup(EventPostAcquireRequestState, value, RequestNotification.AcquireRequestState, true); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler PreRequestHandlerExecute {
            add { AddSyncEventHookup(EventPreRequestHandlerExecute, value, RequestNotification.PreExecuteRequestHandler); }
            remove { RemoveSyncEventHookup(EventPreRequestHandlerExecute, value, RequestNotification.PreExecuteRequestHandler); }
        }

        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler PostRequestHandlerExecute {
            add { AddSyncEventHookup(EventPostRequestHandlerExecute, value, RequestNotification.ExecuteRequestHandler, true); }
            remove { RemoveSyncEventHookup(EventPostRequestHandlerExecute, value, RequestNotification.ExecuteRequestHandler, true); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler ReleaseRequestState {
            add { AddSyncEventHookup(EventReleaseRequestState, value, RequestNotification.ReleaseRequestState ); }
            remove { RemoveSyncEventHookup(EventReleaseRequestState, value, RequestNotification.ReleaseRequestState); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler PostReleaseRequestState {
            add { AddSyncEventHookup(EventPostReleaseRequestState, value, RequestNotification.ReleaseRequestState, true); }
            remove { RemoveSyncEventHookup(EventPostReleaseRequestState, value, RequestNotification.ReleaseRequestState, true); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler UpdateRequestCache {
            add { AddSyncEventHookup(EventUpdateRequestCache, value, RequestNotification.UpdateRequestCache); }
            remove { RemoveSyncEventHookup(EventUpdateRequestCache, value, RequestNotification.UpdateRequestCache); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler PostUpdateRequestCache {
            add { AddSyncEventHookup(EventPostUpdateRequestCache, value, RequestNotification.UpdateRequestCache, true); }
            remove { RemoveSyncEventHookup(EventPostUpdateRequestCache, value, RequestNotification.UpdateRequestCache, true); }
        }

        public event EventHandler LogRequest {
            add {
                if (!HttpRuntime.UseIntegratedPipeline) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }
                AddSyncEventHookup(EventLogRequest, value, RequestNotification.LogRequest);
            }
            remove {
                if (!HttpRuntime.UseIntegratedPipeline) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }
                RemoveSyncEventHookup(EventLogRequest, value, RequestNotification.LogRequest);
            }
        }

        public event EventHandler PostLogRequest {
            add {
                if (!HttpRuntime.UseIntegratedPipeline) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }
                AddSyncEventHookup(EventPostLogRequest, value, RequestNotification.LogRequest, true);
            }
            remove {
                if (!HttpRuntime.UseIntegratedPipeline) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }
                RemoveSyncEventHookup(EventPostLogRequest, value, RequestNotification.LogRequest, true);
            }
        }

        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler EndRequest {
            add { AddSyncEventHookup(EventEndRequest, value, RequestNotification.EndRequest); }
            remove { RemoveSyncEventHookup(EventEndRequest, value, RequestNotification.EndRequest); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler Error {
            add { Events.AddHandler(EventErrorRecorded, value); }
            remove { Events.RemoveHandler(EventErrorRecorded, value); }
        }


        // Dev10 902404: a new HttpApplication.RequestCompleted event raised when the managed objects associated with 
        // the request are being released.  It allows modules to cleanup resources after all managed modules and handlers
        // have executed.  This may occur before the native processing of the request has completed; for example, before 
        // the final response bytes have been sent to the client.  The HttpContext is not available during this event 
        // because it has already been released.
        public event EventHandler RequestCompleted {
            add { Events.AddHandler(EventRequestCompleted, value); }
            remove { Events.RemoveHandler(EventRequestCompleted, value); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler PreSendRequestHeaders {
            add { AddSendResponseEventHookup(EventPreSendRequestHeaders, value); }
            remove { RemoveSendResponseEventHookup(EventPreSendRequestHeaders, value); }
        }


        /// <devdoc><para>[To be supplied.]</para></devdoc>
        public event EventHandler PreSendRequestContent {
            add { AddSendResponseEventHookup(EventPreSendRequestContent, value); }
            remove { RemoveSendResponseEventHookup(EventPreSendRequestContent, value); }
        }

        //
        // Async event hookup
        //

        public void AddOnBeginRequestAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnBeginRequestAsync(bh, eh, null);
        }

        public void AddOnBeginRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventBeginRequest, beginHandler, endHandler, state, RequestNotification.BeginRequest, false, this);
        }

        public void AddOnAuthenticateRequestAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnAuthenticateRequestAsync(bh, eh, null);
        }

        public void AddOnAuthenticateRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventAuthenticateRequest, beginHandler, endHandler, state,
                                   RequestNotification.AuthenticateRequest, false, this);
        }

        public void AddOnPostAuthenticateRequestAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnPostAuthenticateRequestAsync(bh, eh, null);
        }

        public void AddOnPostAuthenticateRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventPostAuthenticateRequest, beginHandler, endHandler, state,
                                   RequestNotification.AuthenticateRequest, true, this);
        }

        public void AddOnAuthorizeRequestAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnAuthorizeRequestAsync(bh, eh, null);
        }

        public void AddOnAuthorizeRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventAuthorizeRequest, beginHandler, endHandler, state,
                                   RequestNotification.AuthorizeRequest, false, this);
        }

        public void AddOnPostAuthorizeRequestAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnPostAuthorizeRequestAsync(bh, eh, null);
        }

        public void AddOnPostAuthorizeRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventPostAuthorizeRequest, beginHandler, endHandler, state,
                                   RequestNotification.AuthorizeRequest, true, this);
        }

        public void AddOnResolveRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnResolveRequestCacheAsync(bh, eh, null);
        }

        public void AddOnResolveRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventResolveRequestCache, beginHandler, endHandler, state,
                                   RequestNotification.ResolveRequestCache, false, this);
        }

        public void AddOnPostResolveRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnPostResolveRequestCacheAsync(bh, eh, null);
        }

        public void AddOnPostResolveRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventPostResolveRequestCache, beginHandler, endHandler, state,
                                   RequestNotification.ResolveRequestCache, true, this);
        }

        public void AddOnMapRequestHandlerAsync(BeginEventHandler bh, EndEventHandler eh) {
            if (!HttpRuntime.UseIntegratedPipeline) {
                throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
            }
            AddOnMapRequestHandlerAsync(bh, eh, null);
        }

        public void AddOnMapRequestHandlerAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            if (!HttpRuntime.UseIntegratedPipeline) {
                throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
            }
            AsyncEvents.AddHandler(EventMapRequestHandler, beginHandler, endHandler, state,
                                   RequestNotification.MapRequestHandler, false, this);
        }

        public void AddOnPostMapRequestHandlerAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnPostMapRequestHandlerAsync(bh, eh, null);
        }

        public void AddOnPostMapRequestHandlerAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventPostMapRequestHandler, beginHandler, endHandler, state,
                                   RequestNotification.MapRequestHandler, true, this);
        }

        public void AddOnAcquireRequestStateAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnAcquireRequestStateAsync(bh, eh, null);
        }

        public void AddOnAcquireRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventAcquireRequestState, beginHandler, endHandler, state,
                                   RequestNotification.AcquireRequestState, false, this);
        }

        public void AddOnPostAcquireRequestStateAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnPostAcquireRequestStateAsync(bh, eh, null);
        }

        public void AddOnPostAcquireRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventPostAcquireRequestState, beginHandler, endHandler, state,
                                   RequestNotification.AcquireRequestState, true, this);
        }

        public void AddOnPreRequestHandlerExecuteAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnPreRequestHandlerExecuteAsync(bh, eh, null);
        }

        public void AddOnPreRequestHandlerExecuteAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventPreRequestHandlerExecute, beginHandler, endHandler, state,
                                   RequestNotification.PreExecuteRequestHandler, false, this);
        }

        public void AddOnPostRequestHandlerExecuteAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnPostRequestHandlerExecuteAsync(bh, eh, null);
        }

        public void AddOnPostRequestHandlerExecuteAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventPostRequestHandlerExecute, beginHandler, endHandler, state,
                                   RequestNotification.ExecuteRequestHandler, true, this);
        }

        public void AddOnReleaseRequestStateAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnReleaseRequestStateAsync(bh, eh, null);
        }

        public void AddOnReleaseRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventReleaseRequestState, beginHandler, endHandler, state,
                                   RequestNotification.ReleaseRequestState, false, this);
        }

        public void AddOnPostReleaseRequestStateAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnPostReleaseRequestStateAsync(bh, eh, null);
        }

        public void AddOnPostReleaseRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventPostReleaseRequestState, beginHandler, endHandler, state,
                                   RequestNotification.ReleaseRequestState, true, this);
        }

        public void AddOnUpdateRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnUpdateRequestCacheAsync(bh, eh, null);
        }

        public void AddOnUpdateRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventUpdateRequestCache, beginHandler, endHandler, state,
                                   RequestNotification.UpdateRequestCache , false, this);
        }

        public void AddOnPostUpdateRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnPostUpdateRequestCacheAsync(bh, eh, null);
        }

        public void AddOnPostUpdateRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventPostUpdateRequestCache, beginHandler, endHandler, state,
                                   RequestNotification.UpdateRequestCache , true, this);
        }

        public void AddOnLogRequestAsync(BeginEventHandler bh, EndEventHandler eh) {
            if (!HttpRuntime.UseIntegratedPipeline) {
                throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
            }
            AddOnLogRequestAsync(bh, eh, null);
        }

        public void AddOnLogRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            if (!HttpRuntime.UseIntegratedPipeline) {
                throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
            }
            AsyncEvents.AddHandler(EventLogRequest, beginHandler, endHandler, state,
                                   RequestNotification.LogRequest, false, this);
        }

        public void AddOnPostLogRequestAsync(BeginEventHandler bh, EndEventHandler eh) {
            if (!HttpRuntime.UseIntegratedPipeline) {
                throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
            }
            AddOnPostLogRequestAsync(bh, eh, null);
        }

        public void AddOnPostLogRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            if (!HttpRuntime.UseIntegratedPipeline) {
                throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
            }
            AsyncEvents.AddHandler(EventPostLogRequest, beginHandler, endHandler, state,
                                   RequestNotification.LogRequest, true, this);
        }

        public void AddOnEndRequestAsync(BeginEventHandler bh, EndEventHandler eh) {
            AddOnEndRequestAsync(bh, eh, null);
        }

        public void AddOnEndRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
            AsyncEvents.AddHandler(EventEndRequest, beginHandler, endHandler, state,
                                   RequestNotification.EndRequest, false, this);
        }

        //
        // Public Application virtual methods
        //


        /// <devdoc>
        ///    <para>
        ///       Used
        ///          to initialize a HttpModule?s instance variables, and to wireup event handlers to
        ///          the hosting HttpApplication.
        ///       </para>
        ///    </devdoc>
        public virtual void Init() {
            // derived class implements this
        }


        /// <devdoc>
        ///    <para>
        ///       Used
        ///          to clean up an HttpModule?s instance variables
        ///       </para>
        ///    </devdoc>
        public virtual void Dispose() {
            // also part of IComponent
            // derived class implements this
            _site = null;
            if (_events != null) {
                try {
                    EventHandler handler = (EventHandler)_events[EventDisposed];
                    if (handler != null)
                        handler(this, EventArgs.Empty);
                }
                finally {
                    _events.Dispose();
                }
            }
        }

        [SecurityPermission(SecurityAction.Assert, ControlPrincipal = true)]
        internal static void SetCurrentPrincipalWithAssert(IPrincipal user) {
            Thread.CurrentPrincipal = user;
        }

        [SecurityPermission(SecurityAction.Assert, ControlPrincipal = true)]
        internal static WindowsIdentity GetCurrentWindowsIdentityWithAssert() {
            return WindowsIdentity.GetCurrent();
        }

        private HttpHandlerAction GetHandlerMapping(HttpContext context, String requestType, VirtualPath path, bool useAppConfig) {
            CachedPathData pathData = null;
            HandlerMappingMemo memo = null;
            HttpHandlerAction mapping = null;

            // Check if cached handler could be used
            if (!useAppConfig) {
                // Grab mapping from cache - verify that the verb matches exactly
                pathData = context.GetPathData(path);
                memo = pathData.CachedHandler;

                // Invalidate cache on missmatch
                if (memo != null && !memo.IsMatch(requestType, path)) {
                    memo = null;
                }
            }

            // Get new mapping
            if (memo == null) {
                // Load from config
                HttpHandlersSection map = useAppConfig ? RuntimeConfig.GetAppConfig().HttpHandlers
                                                       : RuntimeConfig.GetConfig(context).HttpHandlers;
                mapping = map.FindMapping(requestType, path);

                // Add cache entry
                if (!useAppConfig) {
                    memo = new HandlerMappingMemo(mapping, requestType, path);
                    pathData.CachedHandler = memo;
                }
            }
            else {
                // Get mapping from the cache
                mapping = memo.Mapping;
            }

            return mapping;
        }

        internal IHttpHandler MapIntegratedHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, bool useAppConfig, bool convertNativeStaticFileModule) {
            IHttpHandler handler = null;

            using (new ApplicationImpersonationContext()) {
                string type;

                // vpath is a non-relative virtual path
                string vpath = path.VirtualPathString;

                // If we're using app config, modify vpath by appending the path after the last slash
                // to the app's virtual path.  This will force IIS IHttpContext::MapHandler to use app configuration.
                if (useAppConfig) {
                    int index = vpath.LastIndexOf('/');
                    index++;
                    if (index != 0 && index < vpath.Length) {
                        vpath = UrlPath.SimpleCombine(HttpRuntime.AppDomainAppVirtualPathString, vpath.Substring(index));
                    }
                    else {
                        vpath = HttpRuntime.AppDomainAppVirtualPathString;
                    }
                }


                IIS7WorkerRequest wr = context.WorkerRequest as IIS7WorkerRequest;
                type = wr.MapHandlerAndGetHandlerTypeString(method: requestType, path: vpath, convertNativeStaticFileModule: convertNativeStaticFileModule, ignoreWildcardMappings: false);

                // If a page developer has removed the default mappings with <handlers><clear>
                // without replacing them then we need to give a more descriptive error than
                // a null parameter exception.
                if (type == null) {
                    PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_NOT_FOUND);
                    PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_FAILED);
                    throw new HttpException(SR.GetString(SR.Http_handler_not_found_for_request_type, requestType));
                }

                // if it's a native type, don't go any further
                if(String.IsNullOrEmpty(type)) {
                    return handler;
                }

                // Get factory from the mapping
                IHttpHandlerFactory factory = GetFactory(type);

                try {
                    handler = factory.GetHandler(context, requestType, path.VirtualPathString, pathTranslated);
                }
                catch (FileNotFoundException e) {
                    if (HttpRuntime.HasPathDiscoveryPermission(pathTranslated))
                        throw new HttpException(404, null, e);
                    else
                        throw new HttpException(404, null);
                }
                catch (DirectoryNotFoundException e) {
                    if (HttpRuntime.HasPathDiscoveryPermission(pathTranslated))
                        throw new HttpException(404, null, e);
                    else
                        throw new HttpException(404, null);
                }
                catch (PathTooLongException e) {
                    if (HttpRuntime.HasPathDiscoveryPermission(pathTranslated))
                        throw new HttpException(414, null, e);
                    else
                        throw new HttpException(414, null);
                }

                // Remember for recycling
                if (_handlerRecycleList == null)
                    _handlerRecycleList = new ArrayList();
                _handlerRecycleList.Add(new HandlerWithFactory(handler, factory));
            }

            return handler;
        }

        internal IHttpHandler MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, bool useAppConfig) {
            // Don't use remap handler when HttpServerUtility.Execute called
            IHttpHandler handler = (context.ServerExecuteDepth == 0) ? context.RemapHandlerInstance : null;

            using (new ApplicationImpersonationContext()) {
                // Use remap handler if possible
                if (handler != null){
                    return handler;
                }

                // Map new handler
                HttpHandlerAction mapping = GetHandlerMapping(context, requestType, path, useAppConfig);

                // If a page developer has removed the default mappings with <httpHandlers><clear>
                // without replacing them then we need to give a more descriptive error than
                // a null parameter exception.
                if (mapping == null) {
                    PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_NOT_FOUND);
                    PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_FAILED);
                    throw new HttpException(SR.GetString(SR.Http_handler_not_found_for_request_type, requestType));
                }

                // Get factory from the mapping
                IHttpHandlerFactory factory = GetFactory(mapping);


                // Get factory from the mapping
                try {
                    // Check if it supports the more efficient GetHandler call that can avoid
                    // a VirtualPath object creation.
                    IHttpHandlerFactory2 factory2 = factory as IHttpHandlerFactory2;

                    if (factory2 != null) {
                        handler = factory2.GetHandler(context, requestType, path, pathTranslated);
                    }
                    else {
                        handler = factory.GetHandler(context, requestType, path.VirtualPathString, pathTranslated);
                    }
                }
                catch (FileNotFoundException e) {
                    if (HttpRuntime.HasPathDiscoveryPermission(pathTranslated))
                        throw new HttpException(404, null, e);
                    else
                        throw new HttpException(404, null);
                }
                catch (DirectoryNotFoundException e) {
                    if (HttpRuntime.HasPathDiscoveryPermission(pathTranslated))
                        throw new HttpException(404, null, e);
                    else
                        throw new HttpException(404, null);
                }
                catch (PathTooLongException e) {
                    if (HttpRuntime.HasPathDiscoveryPermission(pathTranslated))
                        throw new HttpException(414, null, e);
                    else
                        throw new HttpException(414, null);
                }

                // Remember for recycling
                if (_handlerRecycleList == null)
                    _handlerRecycleList = new ArrayList();
                _handlerRecycleList.Add(new HandlerWithFactory(handler, factory));
            }

            return handler;
        }


        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public virtual string GetVaryByCustomString(HttpContext context, string custom) {

            if (StringUtil.EqualsIgnoreCase(custom, "browser")) {
                return context.Request.Browser.Type;
            }

            return null;
        }

        public virtual string GetOutputCacheProviderName(HttpContext context) {
            // default implementation
            return System.Web.Caching.OutputCache.DefaultProviderName;
        }

        //
        // IComponent implementation
        //


        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public ISite Site {
            get { return _site;}
            set { _site = value;}
        }

        //
        // IHttpAsyncHandler implementation
        //


        /// <internalonly/>
        IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) {
            HttpAsyncResult result;

            // Setup the asynchronous stuff and application variables
            _context = context;
            _context.ApplicationInstance = this;

            _stepManager.InitRequest();

            // Make sure the context stays rooted (including all async operations)
            _context.Root();

            // Create the async result
            result = new HttpAsyncResult(cb, extraData);

            // Remember the async result for use in async completions
            AsyncResult = result;

            if (_context.TraceIsEnabled)
                HttpRuntime.Profile.StartRequest(_context);

            // Start the application
            ResumeSteps(null);

            // Return the async result
            return result;
        }


        /// <internalonly/>
        void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) {
            // throw error caught during execution
            HttpAsyncResult ar = (HttpAsyncResult)result;
            if (ar.Error != null)
                throw ar.Error;
        }

        //
        // IHttpHandler implementation
        //


        /// <internalonly/>
        void IHttpHandler.ProcessRequest(HttpContext context) {
            throw new HttpException(SR.GetString(SR.Sync_not_supported));
        }


        /// <internalonly/>
        bool IHttpHandler.IsReusable {
            get { return true; }
        }

        //
        // Support for external calls into the application like app_onStart
        //

        [ReflectionPermission(SecurityAction.Assert, Flags=ReflectionPermissionFlag.RestrictedMemberAccess)]
        private void InvokeMethodWithAssert(MethodInfo method, int paramCount, object eventSource, EventArgs eventArgs) {
            if (paramCount == 0) {
                method.Invoke(this, new Object[0]);
            }
            else {
                Debug.Assert(paramCount == 2);

                method.Invoke(this, new Object[2] { eventSource, eventArgs });
            }
        }

        internal void ProcessSpecialRequest(HttpContext context,
                                            MethodInfo method,
                                            int paramCount,
                                            Object eventSource,
                                            EventArgs eventArgs,
                                            HttpSessionState session) {
            _context = context;
            if (HttpRuntime.UseIntegratedPipeline && _context != null) {
                _context.HideRequestResponse = true;
            }
            _hideRequestResponse = true;
            _session = session;
            _lastError = null;

            using (new DisposableHttpContextWrapper(context)) {
                using (new ApplicationImpersonationContext()) {
                    try {
                        // set culture on the current thread
                        SetAppLevelCulture();
                        InvokeMethodWithAssert(method, paramCount, eventSource, eventArgs);
                    }
                    catch (Exception e) {
                        // dereference reflection invocation exceptions
                        Exception eActual;
                        if (e is TargetInvocationException)
                            eActual = e.InnerException;
                        else
                            eActual = e;

                        RecordError(eActual);

                        if (context == null) {
                            try {
                                WebBaseEvent.RaiseRuntimeError(eActual, this);
                            }
                            catch {
                            }
                        }

                    }
                    finally {

                        // this thread should not be locking app state
                        if (_state != null)
                            _state.EnsureUnLock();

                        // restore culture
                        RestoreAppLevelCulture();

                        if (HttpRuntime.UseIntegratedPipeline && _context != null) {
                            _context.HideRequestResponse = false;
                        }
                        _hideRequestResponse = false;
                        _context = null;
                        _session = null;
                        _lastError = null;
                        _appEvent = null;
                    }
                }
            }
        }

        //
        // Report context-less error
        //

        internal void RaiseErrorWithoutContext(Exception error) {
            try {
                try {
                    SetAppLevelCulture();
                    _lastError = error;

                    RaiseOnError();
                }
                finally {
                    // this thread should not be locking app state
                    if (_state != null)
                        _state.EnsureUnLock();

                    RestoreAppLevelCulture();
                    _lastError = null;
                    _appEvent = null;
                }
            }
            catch { // Protect against exception filters
                throw;
            }
        }

        //
        //
        //

        internal void InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers) {
            Debug.Assert(context != null, "context != null");

            // Remember state
            _state = state;

            PerfCounters.IncrementCounter(AppPerfCounter.PIPELINES);

            try {
                try {
                    // Remember context for config lookups
                    _initContext = context;
                    _initContext.ApplicationInstance = this;

                    // Set config path to be application path for the application initialization
                    context.ConfigurationPath = context.Request.ApplicationPathObject;

                    // keep HttpContext.Current working while running user code
                    using (new DisposableHttpContextWrapper(context)) {

                        // Build module list from config
                        if (HttpRuntime.UseIntegratedPipeline) {

                            Debug.Assert(_moduleConfigInfo != null, "_moduleConfigInfo != null");
                            Debug.Assert(_moduleConfigInfo.Count >= 0, "_moduleConfigInfo.Count >= 0");

                            try {
                                context.HideRequestResponse = true;
                                _hideRequestResponse = true;
                                InitIntegratedModules();
                            }
                            finally {
                                context.HideRequestResponse = false;
                                _hideRequestResponse = false;
                            }
                        }
                        else {
                            InitModules();

                            // this is used exclusively for integrated mode
                            Debug.Assert(null == _moduleContainers, "null == _moduleContainers");
                        }

                        // Hookup event handlers via reflection
                        if (handlers != null)
                            HookupEventHandlersForApplicationAndModules(handlers);

                        // Initialization of the derived class
                        _context = context;
                        if (HttpRuntime.UseIntegratedPipeline && _context != null) {
                            _context.HideRequestResponse = true;
                        }
                        _hideRequestResponse = true;

                        try {
                            Init();
                        }
                        catch (Exception e) {
                            RecordError(e);
                        }
                    }

                    if (HttpRuntime.UseIntegratedPipeline && _context != null) {
                        _context.HideRequestResponse = false;
                    }
                    _hideRequestResponse = false;
                    _context = null;
                    _resumeStepsWaitCallback= new WaitCallback(this.ResumeStepsWaitCallback);

                    // Construct the execution steps array
                    if (HttpRuntime.UseIntegratedPipeline) {
                        _stepManager = new PipelineStepManager(this);
                    }
                    else {
                        _stepManager = new ApplicationStepManager(this);
                    }

                    _stepManager.BuildSteps(_resumeStepsWaitCallback);
                }
                finally {
                    _initInternalCompleted = true;

                    // Reset config path
                    context.ConfigurationPath = null;

                    // don't hold on to the context
                    _initContext.ApplicationInstance = null;
                    _initContext = null;
                }
            }
            catch { // Protect against exception filters
                throw;
            }
        }

        // helper to expand an event handler into application steps
        private void CreateEventExecutionSteps(Object eventIndex, ArrayList steps) {
            // async
            AsyncAppEventHandler asyncHandler = AsyncEvents[eventIndex];

            if (asyncHandler != null) {
                asyncHandler.CreateExecutionSteps(this, steps);
            }

            // sync
            EventHandler handler = (EventHandler)Events[eventIndex];

            if (handler != null) {
                Delegate[] handlers = handler.GetInvocationList();

                for (int i = 0; i < handlers.Length; i++)  {
                    steps.Add(new SyncEventExecutionStep(this, (EventHandler)handlers[i]));
                }
            }
        }

        internal void InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) {
            // Remember state
            _state = state;

            try {
                //  Remember the context for the initialization
                if (context != null) {
                    _initContext = context;
                    _initContext.ApplicationInstance = this;
                }

                // if we're doing integrated pipeline wireup, then appContext is non-null and we need to init modules and register event subscriptions with IIS
                if (appContext != IntPtr.Zero) {
                    // 1694356: app_offline.htm and <httpRuntime enabled=/> require that we make this check here for integrated mode
                    using (new ApplicationImpersonationContext()) {
                        HttpRuntime.CheckApplicationEnabled();
                    }

                    // retrieve app level culture
                    InitAppLevelCulture();

                    Debug.Trace("PipelineRuntime", "InitSpecial for " + appContext.ToString() + "\n");
                    RegisterEventSubscriptionsWithIIS(appContext, context, handlers);
                }
                else {
                    // retrieve app level culture
                    InitAppLevelCulture();

                    // Hookup event handlers via reflection
                    if (handlers != null) {
                        HookupEventHandlersForApplicationAndModules(handlers);
                    }
                }

                // if we're doing integrated pipeline wireup, then appContext is non-null and we need to register the application (global.asax) event handlers
                if (appContext != IntPtr.Zero) {
                    if (_appPostNotifications != 0 || _appRequestNotifications != 0) {
                        RegisterIntegratedEvent(appContext,
                                                HttpApplicationFactory.applicationFileName,
                                                _appRequestNotifications,
                                                _appPostNotifications,
                                                this.GetType().FullName,
                                                MANAGED_PRECONDITION,
                                                false);
                    }
                }
            }
            finally  {
                _initSpecialCompleted = true;

                //  Do not hold on to the context
                if (_initContext != null) {
                    _initContext.ApplicationInstance = null;
                    _initContext = null;
                }
            }
        }

        internal void DisposeInternal() {
            PerfCounters.DecrementCounter(AppPerfCounter.PIPELINES);

            // call derived class

            try {
                Dispose();
            }
            catch (Exception e) {
                RecordError(e);
            }

            // dispose modules

            if (_moduleCollection != null) {
                int numModules = _moduleCollection.Count;

                for (int i = 0; i < numModules; i++) {
                    try {
                        // set the init key during Dispose for modules
                        // that try to unregister events
                        if (HttpRuntime.UseIntegratedPipeline) {
                            _currentModuleCollectionKey = _moduleCollection.GetKey(i);
                        }
                        _moduleCollection[i].Dispose();
                    }
                    catch {
                    }
                }

                _moduleCollection = null;
            }

            // Release buffers
            if (_allocator != null) {
                _allocator.TrimMemory();
            }
        }

        private void BuildEventMaskDictionary(Dictionary<string, RequestNotification> eventMask) {
            eventMask["BeginRequest"]              = RequestNotification.BeginRequest;
            eventMask["AuthenticateRequest"]       = RequestNotification.AuthenticateRequest;
            eventMask["PostAuthenticateRequest"]   = RequestNotification.AuthenticateRequest;
            eventMask["AuthorizeRequest"]          = RequestNotification.AuthorizeRequest;
            eventMask["PostAuthorizeRequest"]      = RequestNotification.AuthorizeRequest;
            eventMask["ResolveRequestCache"]       = RequestNotification.ResolveRequestCache;
            eventMask["PostResolveRequestCache"]   = RequestNotification.ResolveRequestCache;
            eventMask["MapRequestHandler"]         = RequestNotification.MapRequestHandler;
            eventMask["PostMapRequestHandler"]     = RequestNotification.MapRequestHandler;
            eventMask["AcquireRequestState"]       = RequestNotification.AcquireRequestState;
            eventMask["PostAcquireRequestState"]   = RequestNotification.AcquireRequestState;
            eventMask["PreRequestHandlerExecute"]  = RequestNotification.PreExecuteRequestHandler;
            eventMask["PostRequestHandlerExecute"] = RequestNotification.ExecuteRequestHandler;
            eventMask["ReleaseRequestState"]       = RequestNotification.ReleaseRequestState;
            eventMask["PostReleaseRequestState"]   = RequestNotification.ReleaseRequestState;
            eventMask["UpdateRequestCache"]        = RequestNotification.UpdateRequestCache;
            eventMask["PostUpdateRequestCache"]    = RequestNotification.UpdateRequestCache;
            eventMask["LogRequest"]                = RequestNotification.LogRequest;
            eventMask["PostLogRequest"]            = RequestNotification.LogRequest;
            eventMask["EndRequest"]                = RequestNotification.EndRequest;
            eventMask["PreSendRequestHeaders"]     = RequestNotification.SendResponse;
            eventMask["PreSendRequestContent"]     = RequestNotification.SendResponse;
        }

        private void HookupEventHandlersForApplicationAndModules(MethodInfo[] handlers) {
            _currentModuleCollectionKey = HttpApplicationFactory.applicationFileName;

            if(null == _pipelineEventMasks) {
                Dictionary<string, RequestNotification> dict = new Dictionary<string, RequestNotification>();
                BuildEventMaskDictionary(dict);
                if(null == _pipelineEventMasks) {
                    _pipelineEventMasks = dict;
                }
            }


            for (int i = 0; i < handlers.Length; i++) {
                MethodInfo appMethod = handlers[i];
                String appMethodName = appMethod.Name;
                int namePosIndex = appMethodName.IndexOf('_');
                String targetName = appMethodName.Substring(0, namePosIndex);

                // Find target for method
                Object target = null;

                if (StringUtil.EqualsIgnoreCase(targetName, "Application"))
                    target = this;
                else if (_moduleCollection != null)
                    target = _moduleCollection[targetName];

                if (target == null)
                    continue;

                // Find event on the module type
                Type targetType = target.GetType();
                EventDescriptorCollection events = TypeDescriptor.GetEvents(targetType);
                string eventName = appMethodName.Substring(namePosIndex+1);

                EventDescriptor foundEvent = events.Find(eventName, true);
                if (foundEvent == null
                    && StringUtil.EqualsIgnoreCase(eventName.Substring(0, 2), "on")) {

                    eventName = eventName.Substring(2);
                    foundEvent = events.Find(eventName, true);
                }

                MethodInfo addMethod = null;
                if (foundEvent != null) {
                    EventInfo reflectionEvent = targetType.GetEvent(foundEvent.Name);
                    Debug.Assert(reflectionEvent != null);
                    if (reflectionEvent != null) {
                        addMethod = reflectionEvent.GetAddMethod();
                    }
                }

                if (addMethod == null)
                    continue;

                ParameterInfo[] addMethodParams = addMethod.GetParameters();

                if (addMethodParams.Length != 1)
                    continue;

                // Create the delegate from app method to pass to AddXXX(handler) method

                Delegate handlerDelegate = null;

                ParameterInfo[] appMethodParams = appMethod.GetParameters();

                if (appMethodParams.Length == 0) {
                    // If the app method doesn't have arguments --
                    // -- hookup via intermidiate handler

                    // only can do it for EventHandler, not strongly typed
                    if (addMethodParams[0].ParameterType != typeof(System.EventHandler))
                        continue;

                    ArglessEventHandlerProxy proxy = new ArglessEventHandlerProxy(this, appMethod);
                    handlerDelegate = proxy.Handler;
                }
                else {
                    // Hookup directly to the app methods hoping all types match

                    try {
                        handlerDelegate = Delegate.CreateDelegate(addMethodParams[0].ParameterType, this, appMethodName);
                    }
                    catch {
                        // some type mismatch
                        continue;
                    }
                }

                // Call the AddXXX() to hook up the delegate

                try {
                    addMethod.Invoke(target, new Object[1]{handlerDelegate});
                }
                catch {
                    if (HttpRuntime.UseIntegratedPipeline) {
                        throw;
                    }
                }

                if (eventName != null) {
                    if (_pipelineEventMasks.ContainsKey(eventName)) {
                        if (!StringUtil.StringStartsWith(eventName, "Post")) {
                            _appRequestNotifications |= _pipelineEventMasks[eventName];
                        }
                        else {
                            _appPostNotifications |= _pipelineEventMasks[eventName];
                        }
                    }
                }
            }
        }

        private void RegisterIntegratedEvent(IntPtr appContext,
                                             string moduleName,
                                             RequestNotification requestNotifications,
                                             RequestNotification postRequestNotifications,
                                             string moduleType,
                                             string modulePrecondition,
                                             bool useHighPriority) {

            // lookup the modules event index, if it already exists
            // use it, otherwise, bump the global count
            // the module is used for event dispatch

            int moduleIndex;
            if (_moduleIndexMap.ContainsKey(moduleName)) {
                moduleIndex = (int) _moduleIndexMap[moduleName];
            }
            else {
                moduleIndex = _moduleIndexMap.Count;
                _moduleIndexMap[moduleName] = moduleIndex;
            }

#if DBG
            Debug.Assert(moduleIndex >= 0, "moduleIndex >= 0");
            Debug.Trace("PipelineRuntime", "RegisterIntegratedEvent:"
                        + " module=" + moduleName
                        + ", index=" + moduleIndex.ToString(CultureInfo.InvariantCulture)
                        + ", rq_notify=" + requestNotifications
                        + ", post_rq_notify=" + postRequestNotifications
                        + ", preconditon=" + modulePrecondition + "\r\n");
#endif

            int result = UnsafeIISMethods.MgdRegisterEventSubscription(appContext,
                                                                       moduleName,
                                                                       requestNotifications,
                                                                       postRequestNotifications,
                                                                       moduleType,
                                                                       modulePrecondition,
                                                                       new IntPtr(moduleIndex),
                                                                       useHighPriority);

            if(result < 0) {
                throw new HttpException(SR.GetString(SR.Failed_Pipeline_Subscription, moduleName));
            }
        }


        private void SetAppLevelCulture() {
            CultureInfo culture = null;
            CultureInfo uiculture = null;
            CultureInfo browserCulture = null;
            //get the language from the browser
            //DevDivBugs 2001091: Request object is not available in integrated mode during Application_Start,
            //so don't try to access it if it is hidden
            if((_appLevelAutoCulture || _appLevelAutoUICulture) && _context != null && _context.HideRequestResponse == false) {
                string[] userLanguages = _context.UserLanguagesFromContext();
                if (userLanguages != null) {
                    try { browserCulture = CultureUtil.CreateReadOnlyCulture(userLanguages, requireSpecific: true); }
                    catch { }
                }
            }

            culture = _appLevelCulture;
            uiculture = _appLevelUICulture;
            if(browserCulture != null) {
                if(_appLevelAutoCulture) {
                    culture = browserCulture;
                }
                if(_appLevelAutoUICulture) {
                    uiculture = browserCulture;
                }
            }

            _savedAppLevelCulture = Thread.CurrentThread.CurrentCulture;
            _savedAppLevelUICulture = Thread.CurrentThread.CurrentUICulture;

            if (culture != null && culture != Thread.CurrentThread.CurrentCulture) {
                HttpRuntime.SetCurrentThreadCultureWithAssert(culture);
            }

            if (uiculture != null && uiculture != Thread.CurrentThread.CurrentUICulture) {
                Thread.CurrentThread.CurrentUICulture = uiculture;
            }
        }

        private void RestoreAppLevelCulture() {
            CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
            CultureInfo currentUICulture = Thread.CurrentThread.CurrentUICulture;

            if (_savedAppLevelCulture != null) {
                // Avoid the cost of the Demand when setting the culture by comparing the cultures first
                if (currentCulture != _savedAppLevelCulture) {
                    HttpRuntime.SetCurrentThreadCultureWithAssert(_savedAppLevelCulture);
                }

                _savedAppLevelCulture = null;
            }

            if (_savedAppLevelUICulture != null) {
                // Avoid the cost of the Demand when setting the culture by comparing the cultures first
                if (currentUICulture  != _savedAppLevelUICulture) {
                    Thread.CurrentThread.CurrentUICulture = _savedAppLevelUICulture;
                }

                _savedAppLevelUICulture = null;
            }
        }

        // Initializes the thread on entry to the managed pipeline. A ThreadContext is returned, on
        // which the caller must call Leave.  The IIS7 integrated pipeline uses setImpersonationContext
        // to prevent it from being set until after the authentication notification.

        // OnThreadEnterPrivate returns ThreadContext.
        // ThreadContext.Enter sets variables that are stored on the thread,
        // and saves anything currently on the thread so it can be restored
        // during the call to ThreadContext.Leave.  All variables that are
        // modified on the thread should be stored in ThreadContext so they
        // can be restored later.  ThreadContext.Enter should only be called
        // when holding a lock on the HttpApplication instance.
        // ThreadContext.Leave is also normally called under the lock, but
        // the Integrated Pipeline may delay this call until after the call to
        // IndicateCompletion returns.  When IndicateCompletion is called,
        // IIS7 will execute the remaining notifications for the request on
        // the current thread.  As a performance improvement, we do not call
        // Leave before calling IndicateCompletion, and we do not call Enter/Leave
        // for the notifications executed while we are in the call to
        // IndicateCompletion.  But when IndicateCompletion returns, we do not
        // have a lock on the HttpApplication instance and therefore cannot
        // modify request state, such as the HttpContext or HttpApplication.
        // The only thing we can do is restore the state of the thread.
        // There's one problem, the Culture/UICulture may be changed by
        // user code that directly updates the values on the current thread, so
        // before leaving the pipeline we call ThreadContext.Synchronize to
        // synchronize the values that are stored on the HttpContext with what
        // is on the thread.  Because of this, the next notification will end up using
        // the Culture/UICulture set by user-code, just as it did on IIS6.
        private ThreadContext OnThreadEnterPrivate(bool setImpersonationContext) {
            ThreadContext threadContext = new ThreadContext(_context);
            threadContext.AssociateWithCurrentThread(setImpersonationContext);

            // An entry is added to the request timeout manager once per request
            // and removed in ReleaseAppInstance.
            if (!_timeoutManagerInitialized) {
                // ensure Timeout is set (see ASURT 148698)
                // to avoid ---- getting config later (ASURT 127388)
                _context.EnsureTimeout();

                HttpRuntime.RequestTimeoutManager.Add(_context);
                _timeoutManagerInitialized = true;
            }

            return threadContext;
        }

        // consumed by AppVerifier when it is enabled
        HttpContext ISyncContext.HttpContext {
            get {
                return _context;
            }
        }

        // consumed by AspNetSynchronizationContext
        ISyncContextLock ISyncContext.Enter() {
            return OnThreadEnter();
        }

        internal ThreadContext OnThreadEnter() {
            return OnThreadEnterPrivate(true /* setImpersonationContext */);
        }

        internal ThreadContext OnThreadEnter(bool setImpersonationContext) {
            return OnThreadEnterPrivate(setImpersonationContext);
        }

        /*
         * Execute single step catching exceptions in a fancy way (see below)
         */
        internal Exception ExecuteStep(IExecutionStep step, ref bool completedSynchronously) {
            Exception error = null;

            try {
                try {
                    if (step.IsCancellable) {
                        _context.BeginCancellablePeriod();  // request can be cancelled from this point

                        try {
                            step.Execute();
                        }
                        finally {
                            _context.EndCancellablePeriod();  // request can be cancelled until this point
                        }

                        _context.WaitForExceptionIfCancelled();  // wait outside of finally
                    }
                    else {
                        step.Execute();
                    }

                    if (!step.CompletedSynchronously) {
                        completedSynchronously = false;
                        return null;
                    }
                }
                catch (Exception e) {
                    error = e;

                    // Since we will leave the context later, we need to remember if we are impersonating
                    // before we lose that info - VSWhidbey 494476
                    if (ImpersonationContext.CurrentThreadTokenExists) {
                        e.Data[System.Web.Management.WebThreadInformation.IsImpersonatingKey] = String.Empty;
                    }
                    // This might force ThreadAbortException to be thrown
                    // automatically, because we consumed an exception that was
                    // hiding ThreadAbortException behind it

                    if (e is ThreadAbortException &&
                        ((Thread.CurrentThread.ThreadState & ThreadState.AbortRequested) == 0))  {
                        // Response.End from a COM+ component that re-throws ThreadAbortException
                        // It is not a real ThreadAbort
                        // VSWhidbey 178556
                        error = null;
                        _stepManager.CompleteRequest();
                    }
                }
#pragma warning disable 1058
                catch {
                    // ignore non-Exception objects that could be thrown
                }
#pragma warning restore 1058
            }
            catch (ThreadAbortException e) {
                // ThreadAbortException could be masked as another one
                // the try-catch above consumes all exceptions, only
                // ThreadAbortException can filter up here because it gets
                // auto rethrown if no other exception is thrown on catch

                if (e.ExceptionState != null && e.ExceptionState is CancelModuleException) {
                    // one of ours (Response.End or timeout) -- cancel abort

                    CancelModuleException cancelException = (CancelModuleException)e.ExceptionState;

                    if (cancelException.Timeout) {
                        // Timed out
                        error = new HttpException(SR.GetString(SR.Request_timed_out),
                                            null, WebEventCodes.RuntimeErrorRequestAbort);
                        PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_TIMED_OUT);
                    }
                    else {
                        // Response.End
                        error = null;
                        _stepManager.CompleteRequest();
                    }

                    Thread.ResetAbort();
                }
            }

            completedSynchronously = true;
            return error;
        }

        /*
         * Resume execution of the app steps
         */

        private void ResumeStepsFromThreadPoolThread(Exception error) {
            if (Thread.CurrentThread.IsThreadPoolThread) {
                // if on thread pool thread, use the current thread
                ResumeSteps(error);
            }
            else {
                // if on a non-threadpool thread, requeue
                ThreadPool.QueueUserWorkItem(_resumeStepsWaitCallback, error);
            }
        }

        private void ResumeStepsWaitCallback(Object error) {
            ResumeSteps(error as Exception);
        }

        private void ResumeSteps(Exception error) {
            _stepManager.ResumeSteps(error);
        }


        /*
         * Add error to the context fire OnError on first error
         */
        private void RecordError(Exception error) {
            bool firstError = true;

            if (_context != null) {
                if (_context.Error != null)
                    firstError = false;

                _context.AddError(error);
            }
            else {
                if (_lastError != null)
                    firstError = false;

                _lastError = error;
            }

            if (firstError)
                RaiseOnError();
        }


        //
        // Init module list
        //

        private void InitModulesCommon() {
            int n = _moduleCollection.Count;

            for (int i = 0; i < n; i++) {
                // remember the module being inited for event subscriptions
                // we'll later use this for routing
                _currentModuleCollectionKey = _moduleCollection.GetKey(i);
                _moduleCollection[i].Init(this);
            }

            _currentModuleCollectionKey = null;
            InitAppLevelCulture();
        }

        private void InitIntegratedModules() {
            Debug.Assert(null != _moduleConfigInfo, "null != _moduleConfigInfo");
            _moduleCollection = BuildIntegratedModuleCollection(_moduleConfigInfo);
            InitModulesCommon();
        }

        private void InitModules() {
            HttpModulesSection pconfig = RuntimeConfig.GetAppConfig().HttpModules;

            // get the static list, then add the dynamic members
            HttpModuleCollection moduleCollection = pconfig.CreateModules();
            HttpModuleCollection dynamicModules = CreateDynamicModules();

            moduleCollection.AppendCollection(dynamicModules);
            _moduleCollection = moduleCollection; // don't assign until all ops have succeeded

            InitModulesCommon();
        }

        // instantiates modules that have been added to the dynamic registry (classic pipeline)
        private HttpModuleCollection CreateDynamicModules() {
            HttpModuleCollection moduleCollection = new HttpModuleCollection();

            foreach (DynamicModuleRegistryEntry entry in _dynamicModuleRegistry.LockAndFetchList()) {
                HttpModuleAction modAction = new HttpModuleAction(entry.Name, entry.Type);
                moduleCollection.AddModule(modAction.Entry.ModuleName, modAction.Entry.Create());
            }

            return moduleCollection;
        }

        internal string CurrentModuleCollectionKey {
            get {
                return (null == _currentModuleCollectionKey) ? "UnknownModule" : _currentModuleCollectionKey;
            }
        }

        internal static void RegisterModuleInternal(Type moduleType) {
            _dynamicModuleRegistry.Add(moduleType);
        }

        public static void RegisterModule(Type moduleType) {
            RuntimeConfig config = RuntimeConfig.GetAppConfig();
            HttpRuntimeSection runtimeSection = config.HttpRuntime;
            if (runtimeSection.AllowDynamicModuleRegistration) {
                RegisterModuleInternal(moduleType);
            }
            else {
                throw new InvalidOperationException(SR.GetString(SR.DynamicModuleRegistrationOff));
            }
        }

        private void RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) {
            RequestNotification requestNotifications;
            RequestNotification postRequestNotifications;

            // register an implicit filter module
            RegisterIntegratedEvent(appContext,
                                    IMPLICIT_FILTER_MODULE,
                                    RequestNotification.UpdateRequestCache| RequestNotification.LogRequest  /*requestNotifications*/,
                                    0 /*postRequestNotifications*/,
                                    String.Empty /*type*/,
                                    String.Empty /*precondition*/,
                                    true /*useHighPriority*/);

            // integrated pipeline will always use serverModules instead of <httpModules>
            _moduleCollection = GetModuleCollection(appContext);

            if (handlers != null) {
                HookupEventHandlersForApplicationAndModules(handlers);
            }

            // 1643363: Breaking Change: ASP.Net v2.0: Application_OnStart is called after Module.Init (Integarted mode)
            HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(context, this);

            // Call Init on HttpApplication derived class ("global.asax")
            // and process event subscriptions before processing other modules.
            // Doing this now prevents clearing any events that may
            // have been added to event handlers during instantiation of this instance.
            // NOTE:  If "global.asax" has a constructor which hooks up event handlers,
            // then they were added to the event handler lists but have not been registered with IIS yet,
            // so we MUST call ProcessEventSubscriptions on it first, before the other modules.
            _currentModuleCollectionKey = HttpApplicationFactory.applicationFileName;

            try {
                _hideRequestResponse = true;
                context.HideRequestResponse = true;
                _context = context;
                Init();
            }
            catch (Exception e) {
                RecordError(e);
                Exception error = context.Error;
                if (error != null) {
                    throw error;
                }
            }
            finally {
                _context = null;
                context.HideRequestResponse = false;
                _hideRequestResponse = false;
            }

            ProcessEventSubscriptions(out requestNotifications, out postRequestNotifications);

            // Save the notification subscriptions so we can register them with IIS later, after
            // we call HookupEventHandlersForApplicationAndModules and process global.asax event handlers.
            _appRequestNotifications |= requestNotifications;
            _appPostNotifications    |= postRequestNotifications;

            for (int i = 0; i < _moduleCollection.Count; i++) {
                _currentModuleCollectionKey = _moduleCollection.GetKey(i);
                IHttpModule httpModule = _moduleCollection.Get(i);
                ModuleConfigurationInfo moduleInfo = _moduleConfigInfo[i];

#if DBG
                Debug.Trace("PipelineRuntime", "RegisterEventSubscriptionsWithIIS: name=" + CurrentModuleCollectionKey
                            + ", type=" + httpModule.GetType().FullName + "\n");

                // make sure collections are in sync
                Debug.Assert(moduleInfo.Name == _currentModuleCollectionKey, "moduleInfo.Name == _currentModuleCollectionKey");
#endif

                httpModule.Init(this);

                ProcessEventSubscriptions(out requestNotifications, out postRequestNotifications);

                // are any events wired up?
                if (requestNotifications != 0 || postRequestNotifications != 0) {

                    RegisterIntegratedEvent(appContext,
                                            moduleInfo.Name,
                                            requestNotifications,
                                            postRequestNotifications,
                                            moduleInfo.Type,
                                            moduleInfo.Precondition,
                                            false /*useHighPriority*/);
                }
            }

            // WOS 1728067: RewritePath does not remap the handler when rewriting from a non-ASP.NET request
            // register a default implicit handler
            RegisterIntegratedEvent(appContext,
                                    IMPLICIT_HANDLER,
                                    RequestNotification.ExecuteRequestHandler | RequestNotification.MapRequestHandler /*requestNotifications*/,
                                    RequestNotification.EndRequest /*postRequestNotifications*/,
                                    String.Empty /*type*/,
                                    String.Empty /*precondition*/,
                                    false /*useHighPriority*/);
        }

        private void ProcessEventSubscriptions(out RequestNotification requestNotifications,
                                               out RequestNotification postRequestNotifications) {
            requestNotifications = 0;
            postRequestNotifications = 0;

            // Begin
            if(HasEventSubscription(EventBeginRequest)) {
                requestNotifications |= RequestNotification.BeginRequest;
            }

            // Authenticate
            if(HasEventSubscription(EventAuthenticateRequest)) {
                requestNotifications |= RequestNotification.AuthenticateRequest;
            }

            if(HasEventSubscription(EventPostAuthenticateRequest)) {
                postRequestNotifications |= RequestNotification.AuthenticateRequest;
            }

            // Authorize
            if(HasEventSubscription(EventAuthorizeRequest)) {
                requestNotifications |= RequestNotification.AuthorizeRequest;
            }
            if(HasEventSubscription(EventPostAuthorizeRequest)) {
                postRequestNotifications |= RequestNotification.AuthorizeRequest;
            }

            // ResolveRequestCache
            if(HasEventSubscription(EventResolveRequestCache)) {
                requestNotifications |= RequestNotification.ResolveRequestCache;
            }
            if(HasEventSubscription(EventPostResolveRequestCache)) {
                postRequestNotifications |= RequestNotification.ResolveRequestCache;
            }

            // MapRequestHandler
            if(HasEventSubscription(EventMapRequestHandler)) {
                requestNotifications |= RequestNotification.MapRequestHandler;
            }
            if(HasEventSubscription(EventPostMapRequestHandler)) {
                postRequestNotifications |= RequestNotification.MapRequestHandler;
            }

            // AcquireRequestState
            if(HasEventSubscription(EventAcquireRequestState)) {
                requestNotifications |= RequestNotification.AcquireRequestState;
            }
            if(HasEventSubscription(EventPostAcquireRequestState)) {
                postRequestNotifications |= RequestNotification.AcquireRequestState;
            }

            // PreExecuteRequestHandler
            if(HasEventSubscription(EventPreRequestHandlerExecute)) {
                requestNotifications |= RequestNotification.PreExecuteRequestHandler;
            }

            // PostRequestHandlerExecute
            if (HasEventSubscription(EventPostRequestHandlerExecute)) {
                postRequestNotifications |= RequestNotification.ExecuteRequestHandler;
            }

            // ReleaseRequestState
            if(HasEventSubscription(EventReleaseRequestState)) {
                requestNotifications |= RequestNotification.ReleaseRequestState;
            }
            if(HasEventSubscription(EventPostReleaseRequestState)) {
                postRequestNotifications |= RequestNotification.ReleaseRequestState;
            }

            // UpdateRequestCache
            if(HasEventSubscription(EventUpdateRequestCache)) {
                requestNotifications |= RequestNotification.UpdateRequestCache;
            }
            if(HasEventSubscription(EventPostUpdateRequestCache)) {
                postRequestNotifications |= RequestNotification.UpdateRequestCache;
            }

            // LogRequest
            if(HasEventSubscription(EventLogRequest)) {
                requestNotifications |= RequestNotification.LogRequest;
            }
            if(HasEventSubscription(EventPostLogRequest)) {
                postRequestNotifications |= RequestNotification.LogRequest;
            }

            // EndRequest
            if(HasEventSubscription(EventEndRequest)) {
                requestNotifications |= RequestNotification.EndRequest;
            }

            // PreSendRequestHeaders
            if(HasEventSubscription(EventPreSendRequestHeaders)) {
                requestNotifications |= RequestNotification.SendResponse;
            }

            // PreSendRequestContent
            if(HasEventSubscription(EventPreSendRequestContent)) {
                requestNotifications |= RequestNotification.SendResponse;
            }
        }

        // check if an event has subscribers
        // and *reset* them if so
        // this is used only for special app instances
        // and not for processing requests
        private bool HasEventSubscription(Object eventIndex) {
            bool hasEvents = false;

            // async
            AsyncAppEventHandler asyncHandler = AsyncEvents[eventIndex];

            if (asyncHandler != null && asyncHandler.Count > 0) {
                asyncHandler.Reset();
                hasEvents = true;
            }

            // sync
            EventHandler handler = (EventHandler)Events[eventIndex];

            if (handler != null) {
                Delegate[] handlers = handler.GetInvocationList();
                if( handlers.Length > 0 ) {
                    hasEvents = true;
                }

                foreach(Delegate d in handlers) {
                    Events.RemoveHandler(eventIndex, d);
                }
            }

            return hasEvents;
        }


        //
        // Get app-level culture info (needed to context-less 'global' methods)
        //

        private void InitAppLevelCulture() {
            GlobalizationSection globConfig = RuntimeConfig.GetAppConfig().Globalization;
            string culture = globConfig.Culture;
            string uiCulture = globConfig.UICulture;
            if (!String.IsNullOrEmpty(culture)) {
                if (StringUtil.StringStartsWithIgnoreCase(culture, AutoCulture)) {
                    _appLevelAutoCulture = true;
                    string appLevelCulture = GetFallbackCulture(culture);
                    if(appLevelCulture != null) {
                        _appLevelCulture = HttpServerUtility.CreateReadOnlyCultureInfo(culture.Substring(5));
                    }
                }
                else {
                    _appLevelAutoCulture = false;
                    _appLevelCulture = HttpServerUtility.CreateReadOnlyCultureInfo(globConfig.Culture);
                }
            }
            if (!String.IsNullOrEmpty(uiCulture)) {
                if (StringUtil.StringStartsWithIgnoreCase(uiCulture, AutoCulture))
                {
                    _appLevelAutoUICulture = true;
                    string appLevelUICulture = GetFallbackCulture(uiCulture);
                    if(appLevelUICulture != null) {
                        _appLevelUICulture = HttpServerUtility.CreateReadOnlyCultureInfo(uiCulture.Substring(5));
                    }
                }
                else {
                    _appLevelAutoUICulture = false;
                    _appLevelUICulture = HttpServerUtility.CreateReadOnlyCultureInfo(globConfig.UICulture);
                }
            }
        }

        internal static string GetFallbackCulture(string culture) {
            if((culture.Length > 5) && (culture.IndexOf(':') == 4)) {
                return culture.Substring(5);
            }
            return null;
        }

        //
        // Request mappings management functions
        //

        private IHttpHandlerFactory GetFactory(HttpHandlerAction mapping) {
            HandlerFactoryCache entry = (HandlerFactoryCache)_handlerFactories[mapping.Type];
            if (entry == null) {
                entry = new HandlerFactoryCache(mapping);
                _handlerFactories[mapping.Type] = entry;
            }

            return entry.Factory;
        }

        private IHttpHandlerFactory GetFactory(string type) {
            HandlerFactoryCache entry = (HandlerFactoryCache)_handlerFactories[type];
            if (entry == null) {
                entry = new HandlerFactoryCache(type);
                _handlerFactories[type] = entry;
            }

            return entry.Factory;
        }


        /*
         * Recycle all handlers mapped during the request processing
         */
        private void RecycleHandlers() {
            if (_handlerRecycleList != null) {
                int numHandlers = _handlerRecycleList.Count;

                for (int i = 0; i < numHandlers; i++)
                    ((HandlerWithFactory)_handlerRecycleList[i]).Recycle();

                _handlerRecycleList = null;
            }
        }

        /*
         * Special exception to cancel module execution (not really an exception)
         * used in Response.End and when cancelling requests
         */
        internal class CancelModuleException {
            private bool _timeout;

            internal CancelModuleException(bool timeout) {
                _timeout = timeout;
            }

            internal bool Timeout { get { return _timeout;}}
        }

        // Setup the asynchronous stuff and application variables
        // context for the entire deal is already rooted for native handler
        internal void AssignContext(HttpContext context) {
            Debug.Assert(HttpRuntime.UseIntegratedPipeline, "HttpRuntime.UseIntegratedPipeline");

            if (null == _context) {
                _stepManager.InitRequest();

                _context = context;
                _context.ApplicationInstance = this;

                if (_context.TraceIsEnabled)
                    HttpRuntime.Profile.StartRequest(_context);

                // this will throw if config is invalid, so we do it after HttpContext.ApplicationInstance is set
                _context.SetImpersonationEnabled();
            }
        }

        internal IAsyncResult BeginProcessRequestNotification(HttpContext context, AsyncCallback cb) {
            Debug.Trace("PipelineRuntime", "BeginProcessRequestNotification");

            HttpAsyncResult result;

            if (_context == null) {
                // 
                AssignContext(context);
            }

            //
            // everytime initialization
            //

            context.CurrentModuleEventIndex = -1;

            // Create the async result
            result = new HttpAsyncResult(cb, context);
            context.NotificationContext.AsyncResult = result;

            // enter notification execution loop

            ResumeSteps(null);

            return result;
        }

        internal RequestNotificationStatus EndProcessRequestNotification(IAsyncResult result) {
            HttpAsyncResult ar = (HttpAsyncResult)result;
            if (ar.Error != null)
                throw ar.Error;

            return ar.Status;
        }

        internal void ReleaseAppInstance() {
            if (_context != null)
            {
                if (_context.TraceIsEnabled) {
                    HttpRuntime.Profile.EndRequest(_context);
                }
                _context.ClearReferences();
                if (_timeoutManagerInitialized) {
                    HttpRuntime.RequestTimeoutManager.Remove(_context);
                    _timeoutManagerInitialized = false;
                }

                if(HttpRuntime.EnablePrefetchOptimization && 
                   HttpRuntime.InitializationException == null && 
                   _context.FirstRequest && 
                   _context.Error == null) {
                       UnsafeNativeMethods.EndPrefetchActivity((uint)StringUtil.GetNonRandomizedHashCode(HttpRuntime.AppDomainAppId));
                }
            }
            RecycleHandlers();
            if (AsyncResult != null) {
                AsyncResult = null;
            }
            _context = null;
            RaiseOnRequestCompleted();
            AppEvent = null;

            if (ApplicationInstanceConsumersCounter != null) {
                ApplicationInstanceConsumersCounter.MarkOperationCompleted(); // ReleaseAppInstance call complete
            }
            else {
                HttpApplicationFactory.RecycleApplicationInstance(this);
            }
        }

        private void AddEventMapping(string moduleName,
                                      RequestNotification requestNotification,
                                      bool isPostNotification,
                                      IExecutionStep step) {

            ThrowIfEventBindingDisallowed();

            // Add events to the IExecutionStep containers only if
            // InitSpecial has completed and InitInternal has not completed.
            if (!IsContainerInitalizationAllowed) {
                return;
            }

            Debug.Assert(!String.IsNullOrEmpty(moduleName), "!String.IsNullOrEmpty(moduleName)");
            Debug.Trace("PipelineRuntime", "AddEventMapping: for " + moduleName +
                        " for " + requestNotification + "\r\n" );


            PipelineModuleStepContainer container = GetModuleContainer(moduleName);
            //WOS 1985878: HttpModule unsubscribing an event handler causes AV in Integrated Mode
            if (container != null) {
#if DBG
                container.DebugModuleName = moduleName;
#endif
                container.AddEvent(requestNotification, isPostNotification, step);
            }
        }

        static internal List<ModuleConfigurationInfo> IntegratedModuleList {
            get {
                return _moduleConfigInfo;
            }
        }

        private HttpModuleCollection GetModuleCollection(IntPtr appContext) {
            if (_moduleConfigInfo != null) {
                return BuildIntegratedModuleCollection(_moduleConfigInfo);
            }

            List<ModuleConfigurationInfo> moduleList = null;

            IntPtr pModuleCollection = IntPtr.Zero;
            IntPtr pBstrModuleName = IntPtr.Zero;
            int cBstrModuleName = 0;
            IntPtr pBstrModuleType = IntPtr.Zero;
            int cBstrModuleType = 0;
            IntPtr pBstrModulePrecondition = IntPtr.Zero;
            int cBstrModulePrecondition = 0;
            try {
                int count = 0;
                int result = UnsafeIISMethods.MgdGetModuleCollection(IntPtr.Zero, appContext, out pModuleCollection, out count);
                if (result < 0) {
                    throw new HttpException(SR.GetString(SR.Cant_Read_Native_Modules, result.ToString("X8", CultureInfo.InvariantCulture)));
                }
                moduleList = new List<ModuleConfigurationInfo>(count);

                for (uint index = 0; index < count; index++) {
                    result = UnsafeIISMethods.MgdGetNextModule(pModuleCollection, ref index,
                                                               out pBstrModuleName, out cBstrModuleName,
                                                               out pBstrModuleType, out cBstrModuleType,
                                                               out pBstrModulePrecondition, out cBstrModulePrecondition);
                    if (result < 0) {
                        throw new HttpException(SR.GetString(SR.Cant_Read_Native_Modules, result.ToString("X8", CultureInfo.InvariantCulture)));
                    }
                    string moduleName = (cBstrModuleName > 0) ? StringUtil.StringFromWCharPtr(pBstrModuleName, cBstrModuleName) : null;
                    string moduleType = (cBstrModuleType > 0) ? StringUtil.StringFromWCharPtr(pBstrModuleType, cBstrModuleType) : null;
                    string modulePrecondition = (cBstrModulePrecondition > 0) ? StringUtil.StringFromWCharPtr(pBstrModulePrecondition, cBstrModulePrecondition) : String.Empty;
                    Marshal.FreeBSTR(pBstrModuleName);
                    pBstrModuleName = IntPtr.Zero;
                    cBstrModuleName = 0;
                    Marshal.FreeBSTR(pBstrModuleType);
                    pBstrModuleType = IntPtr.Zero;
                    cBstrModuleType = 0;
                    Marshal.FreeBSTR(pBstrModulePrecondition);
                    pBstrModulePrecondition = IntPtr.Zero;
                    cBstrModulePrecondition = 0;

                    if (!String.IsNullOrEmpty(moduleName) && !String.IsNullOrEmpty(moduleType)) {
                        moduleList.Add(new ModuleConfigurationInfo(moduleName, moduleType, modulePrecondition));
                    }
                }
            }
            finally {
                if (pModuleCollection != IntPtr.Zero) {
                    Marshal.Release(pModuleCollection);
                    pModuleCollection = IntPtr.Zero;
                }
                if (pBstrModuleName != IntPtr.Zero) {
                    Marshal.FreeBSTR(pBstrModuleName);
                    pBstrModuleName = IntPtr.Zero;
                }
                if (pBstrModuleType != IntPtr.Zero) {
                    Marshal.FreeBSTR(pBstrModuleType);
                    pBstrModuleType = IntPtr.Zero;
                }
                if (pBstrModulePrecondition != IntPtr.Zero) {
                    Marshal.FreeBSTR(pBstrModulePrecondition);
                    pBstrModulePrecondition = IntPtr.Zero;
                }
            }

            // now that the static list has been processed, add in the dynamic module list
            moduleList.AddRange(GetConfigInfoForDynamicModules());
            _moduleConfigInfo = moduleList;

            return BuildIntegratedModuleCollection(_moduleConfigInfo);
        }

        // gets configuration for modules that have been added to the dynamic registry (integrated pipeline)
        private IEnumerable<ModuleConfigurationInfo> GetConfigInfoForDynamicModules() {
            return from entry in _dynamicModuleRegistry.LockAndFetchList()
                   select new ModuleConfigurationInfo(entry.Name, entry.Type, "managedHandler" /* condition */);
        }

        HttpModuleCollection BuildIntegratedModuleCollection(List<ModuleConfigurationInfo> moduleList) {
            HttpModuleCollection modules = new HttpModuleCollection();

            foreach(ModuleConfigurationInfo mod in moduleList) {
#if DBG
                Debug.Trace("NativeConfig", "Runtime module: " + mod.Name + " of type " + mod.Type + "\n");
#endif
                ModulesEntry currentModule = new ModulesEntry(mod.Name, mod.Type, "type", null);

                modules.AddModule(currentModule.ModuleName, currentModule.Create());
            }

            return modules;
        }

        //
        // Internal classes to support [asynchronous] app execution logic
        //

        internal class AsyncAppEventHandler {
            int _count;
            ArrayList _beginHandlers;
            ArrayList _endHandlers;
            ArrayList _stateObjects;

            internal AsyncAppEventHandler() {
                _count = 0;
                _beginHandlers = new ArrayList();
                _endHandlers   = new ArrayList();
                _stateObjects  = new ArrayList();
            }

            internal void Reset() {
                _count = 0;
                _beginHandlers.Clear();
                _endHandlers.Clear();
                _stateObjects.Clear();
            }

            internal int Count {
                get {
                    return _count;
                }
            }

            internal void Add(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
                _beginHandlers.Add(beginHandler);
                _endHandlers.Add(endHandler);
                _stateObjects.Add(state);
                _count++;
            }

            internal void CreateExecutionSteps(HttpApplication app, ArrayList steps) {
                for (int i = 0; i < _count; i++) {
                    steps.Add(new AsyncEventExecutionStep(
                        app,
                        (BeginEventHandler)_beginHandlers[i],
                        (EndEventHandler)_endHandlers[i],
                        _stateObjects[i]));
                }
            }
        }

        internal class AsyncAppEventHandlersTable {
            private Hashtable _table;

            internal void AddHandler(Object eventId, BeginEventHandler beginHandler,
                                     EndEventHandler endHandler, Object state,
                                     RequestNotification requestNotification,
                                     bool isPost, HttpApplication app) {
                if (_table == null)
                    _table = new Hashtable();

                AsyncAppEventHandler asyncHandler = (AsyncAppEventHandler)_table[eventId];

                if (asyncHandler == null) {
                    asyncHandler = new AsyncAppEventHandler();
                    _table[eventId] = asyncHandler;
                }

                asyncHandler.Add(beginHandler, endHandler, state);

                if (HttpRuntime.UseIntegratedPipeline) {
                    AsyncEventExecutionStep step =
                        new AsyncEventExecutionStep(app,
                                                    beginHandler,
                                                    endHandler,
                                                    state);

                    app.AddEventMapping(app.CurrentModuleCollectionKey, requestNotification, isPost, step);
                }
            }

            internal AsyncAppEventHandler this[Object eventId] {
                get {
                    if (_table == null)
                        return null;
                    return (AsyncAppEventHandler)_table[eventId];
                }
            }
        }

        // interface to represent one execution step
        internal interface IExecutionStep {
            void Execute();
            bool CompletedSynchronously { get;}
            bool IsCancellable { get; }
        }

        // execution step -- stub
        internal class NoopExecutionStep : IExecutionStep {
            internal NoopExecutionStep() {
            }

            void IExecutionStep.Execute() {
            }

            bool IExecutionStep.CompletedSynchronously {
                get { return true;}
            }

            bool IExecutionStep.IsCancellable {
                get { return false; }
            }
        }

        // execution step -- call synchronous event
        internal class SyncEventExecutionStep : IExecutionStep {
            private HttpApplication _application;
            private EventHandler    _handler;

            internal SyncEventExecutionStep(HttpApplication app, EventHandler handler) {
                _application = app;
                _handler = handler;
            }

            internal EventHandler Handler {
                get {
                    return _handler;
                }
            }

            void IExecutionStep.Execute() {
                string targetTypeStr = null;

                if (_handler != null) {
                    if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Module)) {
                        targetTypeStr = _handler.Method.ReflectedType.ToString();

                        EtwTrace.Trace(EtwTraceType.ETW_TYPE_PIPELINE_ENTER, _application.Context.WorkerRequest, targetTypeStr);
                    }
                    _handler(_application, _application.AppEvent);
                    if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Module)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PIPELINE_LEAVE, _application.Context.WorkerRequest, targetTypeStr);
                }
            }

            bool IExecutionStep.CompletedSynchronously {
                get { return true;}
            }

            bool IExecutionStep.IsCancellable {
                get { return true; }
            }
        }

        // execution step -- call asynchronous event
        internal class AsyncEventExecutionStep : IExecutionStep {
            private HttpApplication     _application;
            private BeginEventHandler   _beginHandler;
            private EndEventHandler     _endHandler;
            private Object              _state;
            private AsyncCallback       _completionCallback;
            private AsyncStepCompletionInfo _asyncStepCompletionInfo; // per call
            private bool                _sync;          // per call
            private string              _targetTypeStr;

            internal AsyncEventExecutionStep(HttpApplication app, BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
                :this(app, beginHandler, endHandler, state, HttpRuntime.UseIntegratedPipeline)
                {
                }

            internal AsyncEventExecutionStep(HttpApplication app, BeginEventHandler beginHandler, EndEventHandler endHandler, Object state, bool useIntegratedPipeline) {

                _application = app;
                // Instrument the beginHandler method if AppVerifier is enabled.
                // If AppVerifier not enabled, we just get back the original delegate to beginHandler uninstrumented.
                _beginHandler = AppVerifier.WrapBeginMethod(_application, beginHandler);
                _endHandler = endHandler;
                _state = state;
                _completionCallback = new AsyncCallback(this.OnAsyncEventCompletion);
            }

            private void OnAsyncEventCompletion(IAsyncResult ar) {
                if (ar.CompletedSynchronously) {
                    // Synchronous completions will be handled by IExecutionStep.Execute.
                    return;
                }

                // This IAsyncResult may actually have completed synchronously (we might be on the same thread
                // which called IExecutionStep.Execute) even if CompletedSynchronously = false. Regardless,
                // we should invoke the End* method on the same thread that invoked this callback, as some
                // applications use TLS instead of the IAsyncResult object itself to convey state information.

                Debug.Trace("PipelineRuntime", "AsyncStep.OnAsyncEventCompletion");
                HttpContext context = _application.Context;
                Exception error = null;

                // The asynchronous step has completed, so we should disallow further
                // async operations until the next step.
                context.SyncContext.ProhibitVoidAsyncOperations();

                try {
                    _endHandler(ar);
                }
                catch (Exception e) {
                    error = e;
                }

                bool shouldCallResumeSteps = _asyncStepCompletionInfo.RegisterAsyncCompletion(error);
                if (!shouldCallResumeSteps) {
                    return;
                }

                if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Module)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PIPELINE_LEAVE, context.WorkerRequest, _targetTypeStr);

                // re-set start time after an async completion (see VSWhidbey 231010)
                context.SetStartTime();

                // Assert to disregard the user code up the stack
                if (HttpRuntime.IsLegacyCas) {
                    ResumeStepsWithAssert(error);
                }
                else {
                    ResumeSteps(error);
                }
            }

            [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
            void ResumeStepsWithAssert(Exception error) {
                ResumeSteps(error);
            }

            void ResumeSteps(Exception error) {
                _application.ResumeStepsFromThreadPoolThread(error);
            }

            void IExecutionStep.Execute() {
                _sync = false;

                if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Module)) {
                    _targetTypeStr = _beginHandler.Method.ReflectedType.ToString();
                    EtwTrace.Trace(EtwTraceType.ETW_TYPE_PIPELINE_ENTER, _application.Context.WorkerRequest, _targetTypeStr);
                }

                HttpContext context = _application.Context;

                _asyncStepCompletionInfo.Reset();
                context.SyncContext.AllowVoidAsyncOperations();
                IAsyncResult ar;
                try {
                    ar = _beginHandler(_application, _application.AppEvent, _completionCallback, _state);
                }
                catch {
                    // The asynchronous step has completed, so we should disallow further
                    // async operations until the next step.
                    context.SyncContext.ProhibitVoidAsyncOperations();
                    throw;
                }

                bool operationCompleted;
                bool mustCallEndHandler;
                _asyncStepCompletionInfo.RegisterBeginUnwound(ar, out operationCompleted, out mustCallEndHandler);

                if (operationCompleted) {
                    _sync = true;

                    if (mustCallEndHandler) {
                        // The asynchronous step has completed, so we should disallow further
                        // async operations until the next step.
                        context.SyncContext.ProhibitVoidAsyncOperations();
                        _endHandler(ar);
                    }

                    _asyncStepCompletionInfo.ReportError();

                    if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Module)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PIPELINE_LEAVE, _application.Context.WorkerRequest, _targetTypeStr);
                }
            }

            bool IExecutionStep.CompletedSynchronously {
                get { return _sync;}
            }

            bool IExecutionStep.IsCancellable {
                get { return false; }
            }
        }

        // execution step -- validate the path for canonicalization issues
        internal class ValidatePathExecutionStep : IExecutionStep {
            private HttpApplication _application;

            internal ValidatePathExecutionStep(HttpApplication app) {
                _application = app;
            }

            void IExecutionStep.Execute() {
                _application.Context.ValidatePath();
            }

            bool IExecutionStep.CompletedSynchronously {
                get { return true; }
            }

            bool IExecutionStep.IsCancellable {
                get { return false; }
            }
        }

        // execution step -- validate request (virtual path, query string, entity body, etc)
        internal class ValidateRequestExecutionStep : IExecutionStep {
            private HttpApplication _application;

            internal ValidateRequestExecutionStep(HttpApplication app) {
                _application = app;
            }

            void IExecutionStep.Execute() {
                _application.Context.Request.ValidateInputIfRequiredByConfig();
            }

            bool IExecutionStep.CompletedSynchronously {
                get { return true; }
            }

            bool IExecutionStep.IsCancellable {
                get { return false; }
            }
        }

        // materialize handler for integrated pipeline
        // this does not map handler, rather that's done by the core
        // this does instantiate the managed type so that things that need to
        // look at it can
        internal class MaterializeHandlerExecutionStep : IExecutionStep {
            private HttpApplication _application;

            internal MaterializeHandlerExecutionStep(HttpApplication app) {
                _application = app;
            }

            void IExecutionStep.Execute() {
                HttpContext context = _application.Context;
                HttpRequest request = context.Request;
                IHttpHandler handler = null;
                string configType = null;

                if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_MAPHANDLER_ENTER, context.WorkerRequest);

                IIS7WorkerRequest wr = context.WorkerRequest as IIS7WorkerRequest;

                // Get handler
                if (context.RemapHandlerInstance != null){
                    //RemapHandler overrides all
                    wr.SetScriptMapForRemapHandler();
                    context.Handler = context.RemapHandlerInstance;
                }
                else if (request.RewrittenUrl != null) {
                    // RewritePath, we need to re-map the handler
                    bool handlerExists;
                    configType = wr.ReMapHandlerAndGetHandlerTypeString(context, request.Path, out handlerExists);
                    if (!handlerExists) {
                        // WOS 1973590: When RewritePath is used with missing handler in Integrated Mode,an empty response 200 is returned instead of 404
                        throw new HttpException(404, SR.GetString(SR.Http_handler_not_found_for_request_type, request.RequestType));
                    }
                }
                else {
                    configType = wr.GetManagedHandlerType();
                }

                if (!String.IsNullOrEmpty(configType)) {
                    IHttpHandlerFactory factory = _application.GetFactory(configType);
                    string pathTranslated = request.PhysicalPathInternal;

                    try {
                        handler = factory.GetHandler(context, request.RequestType, request.FilePath, pathTranslated);
                    }
                    catch (FileNotFoundException e) {
                        if (HttpRuntime.HasPathDiscoveryPermission(pathTranslated))
                            throw new HttpException(404, null, e);
                        else
                            throw new HttpException(404, null);
                    }
                    catch (DirectoryNotFoundException e) {
                        if (HttpRuntime.HasPathDiscoveryPermission(pathTranslated))
                            throw new HttpException(404, null, e);
                        else
                            throw new HttpException(404, null);
                    }
                    catch (PathTooLongException e) {
                        if (HttpRuntime.HasPathDiscoveryPermission(pathTranslated))
                            throw new HttpException(414, null, e);
                        else
                            throw new HttpException(414, null);
                    }

                    context.Handler = handler;

                    // Remember for recycling
                    if (_application._handlerRecycleList == null)
                        _application._handlerRecycleList = new ArrayList();
                    _application._handlerRecycleList.Add(new HandlerWithFactory(handler, factory));
                }

                if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_MAPHANDLER_LEAVE, context.WorkerRequest);
            }

            bool IExecutionStep.CompletedSynchronously {
                get { return true;}
            }

            bool IExecutionStep.IsCancellable {
                get { return false; }
            }
        }


        // execution step -- map HTTP handler (used to be a separate module)
        internal class MapHandlerExecutionStep : IExecutionStep {
            private HttpApplication _application;

            internal MapHandlerExecutionStep(HttpApplication app) {
                _application = app;
            }

            void IExecutionStep.Execute() {
                HttpContext context = _application.Context;
                HttpRequest request = context.Request;

                if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_MAPHANDLER_ENTER, context.WorkerRequest);

                context.Handler = _application.MapHttpHandler(
                    context,
                    request.RequestType,
                    request.FilePathObject,
                    request.PhysicalPathInternal,
                    false /*useAppConfig*/);
                Debug.Assert(context.ConfigurationPath == context.Request.FilePathObject, "context.ConfigurationPath (" +
                             context.ConfigurationPath + ") != context.Request.FilePath (" + context.Request.FilePath + ")");

                if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_MAPHANDLER_LEAVE, context.WorkerRequest);
            }

            bool IExecutionStep.CompletedSynchronously {
                get { return true;}
            }

            bool IExecutionStep.IsCancellable {
                get { return false; }
            }
        }

        // execution step -- call HTTP handler (used to be a separate module)
        internal class CallHandlerExecutionStep : IExecutionStep {
            private HttpApplication   _application;
            private AsyncCallback     _completionCallback;
            private IHttpAsyncHandler _handler;       // per call
            private AsyncStepCompletionInfo _asyncStepCompletionInfo; // per call
            private bool              _sync;          // per call

            internal CallHandlerExecutionStep(HttpApplication app) {
                _application = app;
                _completionCallback = new AsyncCallback(this.OnAsyncHandlerCompletion);
            }

            private void OnAsyncHandlerCompletion(IAsyncResult ar) {
                if (ar.CompletedSynchronously) {
                    // Synchronous completions will be handled by IExecutionStep.Execute.
                    return;
                }

                // This IAsyncResult may actually have completed synchronously (we might be on the same thread
                // which called IExecutionStep.Execute) even if CompletedSynchronously = false. Regardless,
                // we should invoke the End* method on the same thread that invoked this callback, as some
                // applications use TLS instead of the IAsyncResult object itself to convey state information.

                HttpContext context = _application.Context;
                Exception error = null;

                // The asynchronous step has completed, so we should disallow further
                // async operations until the next step.
                context.SyncContext.ProhibitVoidAsyncOperations();

                try {
                    try {
                        _handler.EndProcessRequest(ar);
                    }
                    finally {
                        SuppressPostEndRequestIfNecessary(context);

                        // In Integrated mode, generate the necessary response headers
                        // after the ASP.NET handler runs.  If EndProcessRequest throws,
                        // the headers will be generated by ReportRuntimeError
                        context.Response.GenerateResponseHeadersForHandler();
                    }
                }
                catch (Exception e) {
                    if (e is ThreadAbortException || e.InnerException != null && e.InnerException is ThreadAbortException) {
                        // Response.End happened during async operation
                        _application.CompleteRequest();
                    }
                    else {
                        error = e;
                    }
                }

                bool shouldCallResumeSteps = _asyncStepCompletionInfo.RegisterAsyncCompletion(error);
                if (!shouldCallResumeSteps) {
                    return;
                }

                if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_HTTPHANDLER_LEAVE, context.WorkerRequest);

                _handler = null; // not to remember

                // re-set start time after an async completion (see VSWhidbey 231010)
                context.SetStartTime();

                // Assert to disregard the user code up the stack
                if (HttpRuntime.IsLegacyCas) {
                    ResumeStepsWithAssert(error);
                }
                else {
                    ResumeSteps(error);
                }
            }

            [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
            void ResumeStepsWithAssert(Exception error) {
                ResumeSteps(error);
            }

            void ResumeSteps(Exception error) {
                _application.ResumeStepsFromThreadPoolThread(error);
            }

            private static void SuppressPostEndRequestIfNecessary(HttpContext context) {
                // DevDiv #245124 - ASP.NET now hooks PostEndRequest in order to kick off the WebSocket pipeline.
                // If this is not a WebSocket request or the handshake was not completed, then we can suppress
                // this pipeline event. This allows us to send the appropriate cache headers to the client,
                // and it also gives a small perf boost.

                if (!context.IsWebSocketRequestUpgrading) {
                    IIS7WorkerRequest wr = context.WorkerRequest as IIS7WorkerRequest;
                    if (wr != null) {
                        wr.DisableNotifications(notifications: 0, postNotifications: RequestNotification.EndRequest);
                    }
                }
            }

            void IExecutionStep.Execute() {
                HttpContext context = _application.Context;
                IHttpHandler handler = context.Handler;

                if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_HTTPHANDLER_ENTER, context.WorkerRequest);

                if (handler != null && HttpRuntime.UseIntegratedPipeline) {
                    IIS7WorkerRequest wr = context.WorkerRequest as IIS7WorkerRequest;
                    if (wr != null && wr.IsHandlerExecutionDenied()) {
                        _sync = true;
                        HttpException error = new HttpException(403, SR.GetString(SR.Handler_access_denied));
                        error.SetFormatter(new PageForbiddenErrorFormatter(context.Request.Path, SR.GetString(SR.Handler_access_denied)));
                        throw error;
                    }
                }

                if (handler == null) {
                    _sync = true;
                }
                else if (handler is IHttpAsyncHandler) {
                    // asynchronous handler
                    IHttpAsyncHandler asyncHandler = (IHttpAsyncHandler)handler;

                    _sync = false;
                    _handler = asyncHandler;

                    // Instrument the BeginProcessRequest method if AppVerifier is enabled.
                    // If AppVerifier not enabled, we just get back the original delegate to BeginProcessRequest uninstrumented.
                    var beginProcessRequestDelegate = AppVerifier.WrapBeginMethod<HttpContext>(_application, asyncHandler.BeginProcessRequest);

                    _asyncStepCompletionInfo.Reset();
                    context.SyncContext.AllowVoidAsyncOperations();
                    IAsyncResult ar;
                    try {
                        ar = beginProcessRequestDelegate(context, _completionCallback, null);
                    }
                    catch {
                        // The asynchronous step has completed, so we should disallow further
                        // async operations until the next step.
                        context.SyncContext.ProhibitVoidAsyncOperations();
                        throw;
                    }

                    bool operationCompleted;
                    bool mustCallEndHandler;
                    _asyncStepCompletionInfo.RegisterBeginUnwound(ar, out operationCompleted, out mustCallEndHandler);

                    if (operationCompleted) {
                        _sync = true;
                        _handler = null; // not to remember

                        // The asynchronous step has completed, so we should disallow further
                        // async operations until the next step.
                        context.SyncContext.ProhibitVoidAsyncOperations();

                        try {
                            if (mustCallEndHandler) {
                                asyncHandler.EndProcessRequest(ar);
                            }

                            _asyncStepCompletionInfo.ReportError();
                        }
                        finally {
                            SuppressPostEndRequestIfNecessary(context);

                            //  In Integrated mode, generate the necessary response headers
                            //  after the ASP.NET handler runs
                            context.Response.GenerateResponseHeadersForHandler();
                        }

                        if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_HTTPHANDLER_LEAVE, context.WorkerRequest);
                    }
                }
                else {
                    // synchronous handler
                    _sync = true;

                    // disable async operations
                    //_application.SyncContext.Disable();

                    // VSWhidbey 268772 - If a synchronous handler internally kicks off an asynchronous operation and waits (blocking) for that
                    // operation to complete, the handler will deadlock since the asynchronous operation can't come back to the appropriate
                    // thread to perform the completion. The solution below was only meant to be temporary but was accidentally left in the product
                    // for v2.0 RTM, so it's now legacy behavior and cannot be changed.
                    context.SyncContext.SetSyncCaller();

                    try {
                        handler.ProcessRequest(context);
                    }
                    finally {
                        context.SyncContext.ResetSyncCaller();
                        if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_HTTPHANDLER_LEAVE, context.WorkerRequest);

                        SuppressPostEndRequestIfNecessary(context);

                        // In Integrated mode, generate the necessary response headers
                        // after the ASP.NET handler runs
                        context.Response.GenerateResponseHeadersForHandler();
                    }
                }
            }

            bool IExecutionStep.CompletedSynchronously {
                get { return _sync;}
            }

            bool IExecutionStep.IsCancellable {
                // launching of async handler should not be cancellable
                get { return (_application.Context.Handler is IHttpAsyncHandler) ? false : true; }
            }
        }

        // execution step -- initiate the transition to a WebSocket request
        internal class TransitionToWebSocketsExecutionStep : IExecutionStep {
            private readonly HttpApplication _application;

            internal TransitionToWebSocketsExecutionStep(HttpApplication app) {
                _application = app;
            }

            void IExecutionStep.Execute() {
                HttpContext context = _application.Context;

                if (context.RootedObjects == null
                    || context.RootedObjects.WebSocketPipeline == null
                    || context.Response.StatusCode != (int)HttpStatusCode.SwitchingProtocols) {

                    // If this isn't a WebSocket request or something has caused the status code
                    // not to be HTTP 101 (such as an error, redirect, or something else), no-op.
                    CompletedSynchronously = true;
                }
                else {
                    // DevDiv #273639: Let the HttpRequest instance maintain a reference to the response
                    // cookie collection, as the HttpResponse instance won't be available after the transition.
                    context.Request.StoreReferenceToResponseCookies(context.Response.GetCookiesNoCreate());

                    // If this is a WebSocket request, mark as transitioned so that asynchronous events (like SendRequest)
                    // don't execute. We also need to mark ourselves as not having completed synchronously so that the
                    // pipeline unwinds back to ProcessRequestNotification. That method special-cases WebSocket handlers
                    // and cleans up the HttpContext / HttpApplication eagerly.

                    // transition: AcceptWebSocketRequestCalled -> TransitionStarted
                    context.TransitionToWebSocketState(WebSocketTransitionState.TransitionStarted);
                    CompletedSynchronously = false;
                }
            }

            public bool CompletedSynchronously {
                get;
                private set;
            }

            public bool IsCancellable {
                // launching of async operation should not be cancellable
                get { return false; }
            }
        }

        // execution step -- call response filter
        internal class CallFilterExecutionStep : IExecutionStep {
            private HttpApplication _application;

            internal CallFilterExecutionStep(HttpApplication app) {
                _application = app;
            }

            void IExecutionStep.Execute() {
                try {
                    _application.Context.Response.FilterOutput();
                }
                finally {
                    // if this is the UpdateCache notification, then disable the LogRequest notification (which handles the error case)
                    if (HttpRuntime.UseIntegratedPipeline && (_application.Context.CurrentNotification == RequestNotification.UpdateRequestCache)) {
                        _application.Context.DisableNotifications(RequestNotification.LogRequest, 0 /*postNotifications*/);
                    }
                }
            }

            bool IExecutionStep.CompletedSynchronously {
                get { return true;}
            }

            bool IExecutionStep.IsCancellable {
                get { return true; }
            }
        }

        // integrated pipeline execution step for RaiseOnPreSendRequestHeaders and RaiseOnPreSendRequestContent
        internal class SendResponseExecutionStep : IExecutionStep {
            private HttpApplication _application;
            private EventHandler _handler;
            private bool _isHeaders;

            internal SendResponseExecutionStep(HttpApplication app, EventHandler handler, bool isHeaders) {
                _application = app;
                _handler = handler;
                _isHeaders = isHeaders;
            }

            void IExecutionStep.Execute() {

                // IIS only has a SendResponse notification, so we check the flags
                // to determine whether this notification is for headers or content.
                // The step uses _isHeaders to keep track of whether this is for headers or content.
                if (_application.Context.IsSendResponseHeaders && _isHeaders
                    || !_isHeaders) {

                    string targetTypeStr = null;

                    if (_handler != null) {
                        if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Module)) {
                            targetTypeStr = _handler.Method.ReflectedType.ToString();

                            EtwTrace.Trace(EtwTraceType.ETW_TYPE_PIPELINE_ENTER, _application.Context.WorkerRequest, targetTypeStr);
                        }
                        _handler(_application, _application.AppEvent);
                        if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Module)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PIPELINE_LEAVE, _application.Context.WorkerRequest, targetTypeStr);
                    }
                }
            }

            bool IExecutionStep.CompletedSynchronously {
                get { return true;}
            }

            bool IExecutionStep.IsCancellable {
                get { return true; }
            }
        }

        internal class UrlMappingsExecutionStep : IExecutionStep {
            private HttpApplication _application;


            internal UrlMappingsExecutionStep(HttpApplication app) {
                _application = app;
            }

            void IExecutionStep.Execute() {
                HttpContext context = _application.Context;
                UrlMappingsModule.UrlMappingRewritePath(context);
            }

            bool IExecutionStep.CompletedSynchronously {
                get { return true;}
            }

            bool IExecutionStep.IsCancellable {
                get { return false; }
            }
        }

        internal abstract class StepManager {
            protected HttpApplication _application;
            protected bool _requestCompleted;

            internal StepManager(HttpApplication application) {
                _application = application;
            }

            internal bool IsCompleted { get { return _requestCompleted; } }

            internal abstract void BuildSteps(WaitCallback stepCallback);

            internal void CompleteRequest() {
                _requestCompleted = true;
                if (HttpRuntime.UseIntegratedPipeline) {
                    HttpContext context = _application.Context;
                    if (context != null && context.NotificationContext != null) {
                        context.NotificationContext.RequestCompleted = true;
                    }
                }
            }

            internal abstract void InitRequest();

            internal abstract void ResumeSteps(Exception error);
        }

        internal class ApplicationStepManager : StepManager {
            private IExecutionStep[] _execSteps;
            private WaitCallback _resumeStepsWaitCallback;
            private int _currentStepIndex;
            private int _numStepCalls;
            private int _numSyncStepCalls;
            private int _endRequestStepIndex;

            internal ApplicationStepManager(HttpApplication app): base(app) {
            }

            internal override void BuildSteps(WaitCallback stepCallback ) {
                ArrayList steps = new ArrayList();
                HttpApplication app = _application;

                bool urlMappingsEnabled = false;
                UrlMappingsSection urlMappings = RuntimeConfig.GetConfig().UrlMappings;
                urlMappingsEnabled = urlMappings.IsEnabled && ( urlMappings.UrlMappings.Count > 0 );

                steps.Add(new ValidateRequestExecutionStep(app));
                steps.Add(new ValidatePathExecutionStep(app));

                if (urlMappingsEnabled)
                    steps.Add(new UrlMappingsExecutionStep(app)); // url mappings

                app.CreateEventExecutionSteps(HttpApplication.EventBeginRequest, steps);
                app.CreateEventExecutionSteps(HttpApplication.EventAuthenticateRequest, steps);
                app.CreateEventExecutionSteps(HttpApplication.EventDefaultAuthentication, steps);
                app.CreateEventExecutionSteps(HttpApplication.EventPostAuthenticateRequest, steps);
                app.CreateEventExecutionSteps(HttpApplication.EventAuthorizeRequest, steps);
                app.CreateEventExecutionSteps(HttpApplication.EventPostAuthorizeRequest, steps);
                app.CreateEventExecutionSteps(HttpApplication.EventResolveRequestCache, steps);
                app.CreateEventExecutionSteps(HttpApplication.EventPostResolveRequestCache, steps);
                steps.Add(new MapHandlerExecutionStep(app));     // map handler
                app.CreateEventExecutionSteps(HttpApplication.EventPostMapRequestHandler, steps);
                app.CreateEventExecutionSteps(HttpApplication.EventAcquireRequestState, steps);
                app.CreateEventExecutionSteps(HttpApplication.EventPostAcquireRequestState, steps);
                app.CreateEventExecutionSteps(HttpApplication.EventPreRequestHandlerExecute, steps);
                steps.Add(app.CreateImplicitAsyncPreloadExecutionStep()); // implict async preload step
                steps.Add(new CallHandlerExecutionStep(app));  // execute handler
                app.CreateEventExecutionSteps(HttpApplication.EventPostRequestHandlerExecute, steps);
                app.CreateEventExecutionSteps(HttpApplication.EventReleaseRequestState, steps);
                app.CreateEventExecutionSteps(HttpApplication.EventPostReleaseRequestState, steps);
                steps.Add(new CallFilterExecutionStep(app));  // filtering
                app.CreateEventExecutionSteps(HttpApplication.EventUpdateRequestCache, steps);
                app.CreateEventExecutionSteps(HttpApplication.EventPostUpdateRequestCache, steps);
                _endRequestStepIndex = steps.Count;
                app.CreateEventExecutionSteps(HttpApplication.EventEndRequest, steps);
                steps.Add(new NoopExecutionStep()); // the last is always there

                _execSteps = new IExecutionStep[steps.Count];
                steps.CopyTo(_execSteps);

                // callback for async completion when reposting to threadpool thread
                _resumeStepsWaitCallback = stepCallback;
            }

            internal override void InitRequest() {
                _currentStepIndex   = -1;
                _numStepCalls       = 0;
                _numSyncStepCalls   = 0;
                _requestCompleted   = false;
            }

            // This attribute prevents undesirable 'just-my-code' debugging behavior (VSWhidbey 404406/VSWhidbey 609188)
            [System.Diagnostics.DebuggerStepperBoundaryAttribute]
            internal override void ResumeSteps(Exception error) {
                bool appCompleted = false;
                bool stepCompletedSynchronously = true;
                HttpApplication app = _application;
                CountdownTask appInstanceConsumersCounter = app.ApplicationInstanceConsumersCounter;
                HttpContext context = app.Context;
                ThreadContext threadContext = null;
                AspNetSynchronizationContextBase syncContext = context.SyncContext;

                Debug.Trace("Async", "HttpApplication.ResumeSteps");

                try {
                    if (appInstanceConsumersCounter != null) {
                        appInstanceConsumersCounter.MarkOperationPending(); // ResumeSteps call started
                    }

                    using (syncContext.AcquireThreadLock()) {
                        // avoid ---- between the app code and fast async completion from a module


                        try {
                            threadContext = app.OnThreadEnter();
                        }
                        catch (Exception e) {
                            if (error == null)
                                error = e;
                        }

                        try {
                            try {
                                for (; ; ) {
                                    // record error

                                    if (syncContext.Error != null) {
                                        error = syncContext.Error;
                                        syncContext.ClearError();
                                    }

                                    if (error != null) {
                                        app.RecordError(error);
                                        error = null;
                                    }

                                    // check for any outstanding async operations

                                    if (syncContext.PendingCompletion(_resumeStepsWaitCallback)) {
                                        // wait until all pending async operations complete
                                        break;
                                    }

                                    // advance to next step

                                    if (_currentStepIndex < _endRequestStepIndex && (context.Error != null || _requestCompleted)) {
                                        // end request
                                        context.Response.FilterOutput();
                                        _currentStepIndex = _endRequestStepIndex;
                                    }
                                    else {
                                        _currentStepIndex++;
                                    }

                                    if (_currentStepIndex >= _execSteps.Length) {
                                        appCompleted = true;
                                        break;
                                    }

                                    // execute the current step

                                    _numStepCalls++;          // count all calls

                                    // enable launching async operations before each new step
                                    syncContext.Enable();

                                    // call to execute current step catching thread abort exception
                                    error = app.ExecuteStep(_execSteps[_currentStepIndex], ref stepCompletedSynchronously);

                                    // unwind the stack in the async case
                                    if (!stepCompletedSynchronously)
                                        break;

                                    _numSyncStepCalls++;      // count synchronous calls
                                }
                            }
                            finally {
                                if (appCompleted) {
                                    // need to raise OnRequestCompleted while within the ThreadContext so that things like User, CurrentCulture, etc. are available
                                    context.RaiseOnRequestCompleted();
                                }

                                if (threadContext != null) {
                                    try {
                                        threadContext.DisassociateFromCurrentThread();
                                    }
                                    catch {
                                    }
                                }
                            }
                        }
                        catch { // Protect against exception filters
                            throw;
                        }

                    }   // using

                    if (appCompleted) {
                        // need to raise OnPipelineCompleted outside of the ThreadContext so that HttpContext.Current, User, etc. are unavailable
                        context.RaiseOnPipelineCompleted();

                        // unroot context (async app operations ended)
                        context.Unroot();

                        // async completion
                        app.AsyncResult.Complete((_numStepCalls == _numSyncStepCalls), null, null);
                        app.ReleaseAppInstance();
                    }
                }
                finally {
                    if (appInstanceConsumersCounter != null) {
                        appInstanceConsumersCounter.MarkOperationCompleted(); // ResumeSteps call complete
                    }
                }
            }
        }

        internal class PipelineStepManager : StepManager {

            WaitCallback _resumeStepsWaitCallback;
            bool _validatePathCalled;
            bool _validateInputCalled;

            internal PipelineStepManager(HttpApplication app): base(app) {
            }

            internal override void BuildSteps(WaitCallback stepCallback) {
                Debug.Trace("PipelineRuntime", "BuildSteps");
                //ArrayList steps = new ArrayList();
                HttpApplication app = _application;

                // add special steps that don't currently
                // correspond to a configured handler

                IExecutionStep materializeStep = new MaterializeHandlerExecutionStep(app);

                // implicit map step
                app.AddEventMapping(
                    HttpApplication.IMPLICIT_HANDLER,
                    RequestNotification.MapRequestHandler,
                    false, materializeStep);

                // implicit async preload step
                app.AddEventMapping(
                    HttpApplication.IMPLICIT_HANDLER,
                    RequestNotification.ExecuteRequestHandler,
                    false, app.CreateImplicitAsyncPreloadExecutionStep());

                // implicit handler routing step
                IExecutionStep handlerStep = new CallHandlerExecutionStep(app);

                app.AddEventMapping(
                    HttpApplication.IMPLICIT_HANDLER,
                    RequestNotification.ExecuteRequestHandler,
                    false, handlerStep);

                // implicit handler WebSockets step
                IExecutionStep webSocketsStep = new TransitionToWebSocketsExecutionStep(app);

                app.AddEventMapping(
                    HttpApplication.IMPLICIT_HANDLER,
                    RequestNotification.EndRequest,
                    true /* isPostNotification */, webSocketsStep);

                // add implicit request filtering step
                IExecutionStep filterStep = new CallFilterExecutionStep(app);

                // normally, this executes during UpdateRequestCache as a high priority module
                app.AddEventMapping(
                    HttpApplication.IMPLICIT_FILTER_MODULE,
                    RequestNotification.UpdateRequestCache,
                    false, filterStep);

                // for error conditions, this executes during LogRequest as a high priority module
                app.AddEventMapping(
                    HttpApplication.IMPLICIT_FILTER_MODULE,
                    RequestNotification.LogRequest,
                    false, filterStep);

                _resumeStepsWaitCallback = stepCallback;
            }

            internal override void InitRequest() {
                _requestCompleted = false;
                _validatePathCalled = false;
                _validateInputCalled = false;
            }

            // PipelineStepManager::ResumeSteps
            // called from IIS7 (on IIS thread) via BeginProcessRequestNotification
            // or from an async completion (on CLR thread) via HttpApplication::ResumeStepsFromThreadPoolThread
            // This attribute prevents undesirable 'just-my-code' debugging behavior (VSWhidbey 404406/VSWhidbey 609188)
            [System.Diagnostics.DebuggerStepperBoundaryAttribute]
            internal override void ResumeSteps(Exception error) {
                HttpContext context = _application.Context;
                IIS7WorkerRequest wr = context.WorkerRequest as IIS7WorkerRequest;
                AspNetSynchronizationContextBase syncContext = context.SyncContext;

                RequestNotificationStatus status = RequestNotificationStatus.Continue;
                ThreadContext threadContext = null;
                bool needToDisassociateThreadContext = false;
                bool isSynchronousCompletion = false;
                bool needToComplete = false;
                bool stepCompletedSynchronously = false;
                bool isReEntry = false;
                int currentModuleLastEventIndex = -1;
                _application.GetNotifcationContextProperties(ref isReEntry, ref currentModuleLastEventIndex);

                CountdownTask appInstanceConsumersCounter = _application.ApplicationInstanceConsumersCounter;

                using (context.RootedObjects.WithinTraceBlock()) {
                    // DevDiv Bugs 187441: IIS7 Integrated Mode: Problem flushing Response from background threads in IIS7 integrated mode
                    if (!isReEntry) // currently we only re-enter for SendResponse
                    {
                        syncContext.AssociateWithCurrentThread();
                    }
                    try {
                        if (appInstanceConsumersCounter != null) {
                            appInstanceConsumersCounter.MarkOperationPending(); // ResumeSteps call started
                        }

                        bool locked = false;
                        try {
                            // As a performance optimization, ASP.NET uses the IIS IHttpContext::IndicateCompletion function to continue executing notifications
                            // on a thread that is associated with the AppDomain.  This is done by calling IndicateCompletion from within the AppDomain, instead
                            // of returning to native code.  This technique can only be used for notifications that complete synchronously.

                            // There are two cases where notifications happen on a thread that has an initialized ThreadContext, and therefore does not need
                            // to call ThreadContext.OnThreadEnter.  These include SendResponse notifications and notifications that occur within a call to
                            // IndicateCompletion.  Note that SendResponse notifications occur on-demand, i.e., they happen when another notification triggers
                            // a SendResponse, at which point it blocks until the SendResponse notification completes.

                            if (!isReEntry) { // currently we only re-enter for SendResponse
                                // DevDiv 482614 (Sharepoint 



                                if (context.InIndicateCompletion && context.ThreadInsideIndicateCompletion == Thread.CurrentThread) {
                                    // we already have a ThreadContext
                                    threadContext = context.IndicateCompletionContext;
                                    if (context.UsesImpersonation) {
                                        // UsesImpersonation is set to true after RQ_AUTHENTICATE_REQUEST
                                        threadContext.SetImpersonationContext();
                                    }
                                }
                                else {
                                    // we need to create a new ThreadContext
                                    threadContext = _application.OnThreadEnter(context.UsesImpersonation);
                                    // keep track if we need to disassociate it later
                                    needToDisassociateThreadContext = true;
                                }
                            }

                            for (; ; ) {
#if DBG
                                Debug.Trace("PipelineRuntime", "ResumeSteps: CurrentModuleEventIndex=" + context.CurrentModuleEventIndex);
#endif

                                // check and record errors into the HttpContext
                                if (syncContext.Error != null) {
                                    error = syncContext.Error;
                                    syncContext.ClearError();
                                }
                                if (error != null) {
                                    // the error can be cleared by the user
                                    _application.RecordError(error);
                                    error = null;
                                }

                                if (!_validateInputCalled || !_validatePathCalled) {
                                    error = ValidateHelper(context);
                                    if (error != null) {
                                        continue;
                                    }
                                }

                                // check for any outstanding async operations
                                // DevDiv 1020085: User code may leave pending async completions on the synchronization context
                                // while processing nested (isReEntry == true) and not nested (isReEntry == false) notifications.
                                // In both cases only the non nested notification which has proper synchronization should handle it.
                                if (!isReEntry && syncContext.PendingCompletion(_resumeStepsWaitCallback)) {
                                    // Background flushes may trigger RQ_SEND_RESPONSE notifications which will set new context.NotificationContext
                                    // Synchronize access to context.NotificationContext to make sure we update the correct NotificationContext instance
                                    _application.AcquireNotifcationContextLock(ref locked);

                                    // Since the step completed asynchronously, this thread must return RequestNotificationStatus.Pending to IIS,
                                    // and the async completion of this step must call IIS7WorkerRequest::PostCompletion.  The async completion of
                                    // this step will call ResumeSteps again.
                                    context.NotificationContext.PendingAsyncCompletion = true;
                                    break;
                                }

                                // LogRequest and EndRequest never report errors, and never return a status of FinishRequest.
                                bool needToFinishRequest = (context.NotificationContext.Error != null || context.NotificationContext.RequestCompleted)
                                    && context.CurrentNotification != RequestNotification.LogRequest
                                    && context.CurrentNotification != RequestNotification.EndRequest;

                                if (needToFinishRequest || context.CurrentModuleEventIndex == currentModuleLastEventIndex) {

                                    // if an error occured or someone completed the request, set the status to FinishRequest
                                    status = needToFinishRequest ? RequestNotificationStatus.FinishRequest : RequestNotificationStatus.Continue;

                                    // async case
                                    if (context.NotificationContext.PendingAsyncCompletion) {
                                        context.Response.SyncStatusIntegrated();
                                        context.NotificationContext.PendingAsyncCompletion = false;
                                        isSynchronousCompletion = false;
                                        needToComplete = true;
                                        break;
                                    }

                                    // sync case (we might be able to stay in managed code and execute another notification)
                                    if (needToFinishRequest || UnsafeIISMethods.MgdGetNextNotification(wr.RequestContext, RequestNotificationStatus.Continue) != 1) {
                                        isSynchronousCompletion = true;
                                        needToComplete = true;
                                        break;
                                    }

                                    int currentModuleIndex = 0;
                                    bool isPostNotification = false;
                                    int currentNotification = 0;

                                    UnsafeIISMethods.MgdGetCurrentNotificationInfo(wr.RequestContext, out currentModuleIndex, out isPostNotification, out currentNotification);

                                    // setup the HttpContext for this event/module combo
                                    context.CurrentModuleIndex = currentModuleIndex;
                                    context.IsPostNotification = isPostNotification;
                                    context.CurrentNotification = (RequestNotification)currentNotification;
                                    context.CurrentModuleEventIndex = -1;
                                    currentModuleLastEventIndex = _application.CurrentModuleContainer.GetEventCount(context.CurrentNotification, context.IsPostNotification) - 1;
                                }

                                context.CurrentModuleEventIndex++;

                                IExecutionStep step = _application.CurrentModuleContainer.GetNextEvent(context.CurrentNotification, context.IsPostNotification,
                                                                                                       context.CurrentModuleEventIndex);

                                // enable launching async operations before each new step
                                context.SyncContext.Enable();

                                stepCompletedSynchronously = false;
                                error = _application.ExecuteStep(step, ref stepCompletedSynchronously);

#if DBG
                                Debug.Trace("PipelineRuntime", "ResumeSteps: notification=" + context.CurrentNotification.ToString()
                                            + ", isPost=" + context.IsPostNotification
                                            + ", step=" + step.GetType().FullName
                                            + ", completedSync=" + stepCompletedSynchronously
                                            + ", moduleName=" + _application.CurrentModuleContainer.DebugModuleName
                                            + ", moduleIndex=" + context.CurrentModuleIndex
                                            + ", eventIndex=" + context.CurrentModuleEventIndex);
#endif


                                if (!stepCompletedSynchronously) {
                                    // Since the step completed asynchronously, this thread must return RequestNotificationStatus.Pending to IIS,
                                    // and the async completion of this step must call IIS7WorkerRequest::PostCompletion.  The async completion of
                                    // this step will call ResumeSteps again.
                                    //context.AcquireNotifcationContextLockBeforeUnwind();
                                    _application.AcquireNotifcationContextLock(ref locked);
                                    context.NotificationContext.PendingAsyncCompletion = true;
                                    break;
                                }
                                else {
                                    context.Response.SyncStatusIntegrated();
                                }
                            }
                        }
                        finally {
                            if (locked) {
                                _application.ReleaseNotifcationContextLock();
                            }
                            if (threadContext != null) {
                                if (context.InIndicateCompletion) {
                                    if (isSynchronousCompletion) {
                                        // this is a sync completion on an IIS thread
                                        threadContext.Synchronize();
                                        // Note for DevDiv 482614 fix:
                                        // If this threadContext is from IndicateCompletionContext (e.g. this thread called IndicateCompletion)
                                        // then we continue reusing this thread and only undo impersonation before unwinding back to IIS.
                                        //
                                        // If this threadContext was created while another thread was and still is in IndicateCompletion call
                                        // (e.g. sync or async flush on a background thread from native code, not managed since isReEnty==false)
                                        // then we can not reuse this thread and this threadContext will be cleaned before we leave ResumeSteps
                                        // (because needToDisassociateThreadContext was set to true when we created this threadContext)

                                        //always undo impersonation so that the token is removed before returning to IIS (DDB 156421)
                                        threadContext.UndoImpersonationContext();
                                    }
                                    else {
                                        // We're returning pending on an IIS thread in a call to IndicateCompletion.
                                        // Leave the thread context now while we're still under the lock so that the
                                        // async completion does not corrupt the state of HttpContext or IndicateCompletionContext.
                                        if (!threadContext.HasBeenDisassociatedFromThread) {
                                            lock (threadContext) {
                                                if (!threadContext.HasBeenDisassociatedFromThread) {
                                                    threadContext.DisassociateFromCurrentThread();
                                                    // remember to not disassociate again
                                                    needToDisassociateThreadContext = false;
                                                    // DevDiv 482614:
                                                    // Async steps or completions may happen while another thread is inside IndicateCompletion
                                                    // We do not clear IndicateCompletionContext if it belongs to another thread
                                                    // (otherwise future notifications on the thread that called IndicateCompletion won't have
                                                    // context.IndicateCompletionContext pointing to their not yet disassociated ThreadContext)
                                                    if (context.ThreadInsideIndicateCompletion == Thread.CurrentThread) {
                                                        context.IndicateCompletionContext = null;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else if (isSynchronousCompletion) {
                                    Debug.Assert(needToDisassociateThreadContext == true, "needToDisassociateThreadContext MUST BE true");
                                    // this is a sync completion on an IIS thread
                                    threadContext.Synchronize();
                                    // get ready to call IndicateCompletion
                                    context.IndicateCompletionContext = threadContext;
                                    // Note for DevDiv 482614 fix:
                                    // This thread created a new ThreadContext if it did not call IndicateCompletion yet or if there was 
                                    // another thread already in IndicateCompletion (a background flush from native code or a completion 
                                    // on another thread). In either case if currently there is no thread in IndicateCompletion 
                                    // then we can reuse this thread and its threadContext and call IndicateCompletion on the current thread.
                                    // In this case we will not disassociate this threadContext now
                                    needToDisassociateThreadContext = false;
                                    //always undo impersonation so that the token is removed before returning to IIS (DDB 156421)
                                    threadContext.UndoImpersonationContext();
                                }
                                else {
                                    Debug.Assert(needToDisassociateThreadContext == true, "needToDisassociateThreadContext MUST BE true");
                                    // We're not in a call to IndicateCompletion.  We're either returning pending or
                                    // we're in an async completion, and therefore we must clean-up the thread state. Impersonation is reverted
                                    threadContext.DisassociateFromCurrentThread();
                                    // remember to not disassociate again
                                    needToDisassociateThreadContext = false;
                                }

                                // Cleanup the thread state unless we prepared to call IndicateCompletion or already cleaned up
                                if (needToDisassociateThreadContext) {
                                    threadContext.DisassociateFromCurrentThread();
                                }
                            }
                        }

                        // WOS #1703315: we cannot complete until after OnThreadLeave is called.
                        if (needToComplete) {
                            // call HttpRuntime::OnRequestNotificationCompletion
                            _application.AsyncResult.Complete(isSynchronousCompletion, null /*result*/, null /*error*/, status);
                        }
                    } // end of try statement that begins after AssociateWithCurrentThread
                    finally {
                        if (!isReEntry) {
                            syncContext.DisassociateFromCurrentThread();
                        }
                        if (appInstanceConsumersCounter != null) {
                            appInstanceConsumersCounter.MarkOperationCompleted(); // ResumeSteps call completed
                        }
                    }
                }
            }
            
            private Exception ValidateHelper(HttpContext context) {
                if (!_validateInputCalled) {
                    _validateInputCalled = true;
                    try {
                        context.Request.ValidateInputIfRequiredByConfig();
                    }
                    catch(Exception e) {
                        return e;
                    }
                }
                if (!_validatePathCalled) {
                    _validatePathCalled = true;
                    try {
                        context.ValidatePath();
                    }
                    catch(Exception e) {
                        return e;
                    }
                }
                return null;
            }
        }

        // WARNING: Mutable struct for performance reasons; exercise caution when using this type.
        private struct AsyncStepCompletionInfo {
#pragma warning disable 420 // volatile passed by reference; our uses are safe
            // state for async execution steps
            private const int ASYNC_STATE_NONE = 0;
            private const int ASYNC_STATE_BEGIN_UNWOUND = 1;
            private const int ASYNC_STATE_CALLBACK_COMPLETED = 2;

            private volatile int _asyncState;
            private ExceptionDispatchInfo _error;

            // Invoked from the callback to signal that the End* method has run to completion.
            // Returns 'true' if the current thread should call ResumeSteps, 'false' if not.
            public bool RegisterAsyncCompletion(Exception error) {
                // Before the call to Exchange below, the _asyncCompletionInfo field will have the value
                // ASYNC_STATE_NONE or ASYNC_STATE_BEGIN_UNWOUND. If it's the former, then the Begin* method
                // hasn't yet returned control to IExecutionStep.Execute. From this step's point of view,
                // this can be treated as a synchronous completion, which will allow us to call ResumeSteps
                // on the original thread and save the cost of destroying  the existing ThreadContext and
                // creating a new one. If the original value is instead ASYNC_STATE_BEGIN_UNWOUND, then
                // the Begin* method already returned control to IExecutionStep.Execute and this step was
                // marked as having an asynchronous completion. The original thread will tear down the
                // ThreadContext, so the current thread should call back into ResumeSteps to resurrect it.
                //
                // If there was an error, we'll use the _error field to store it so that IExecutionStep.Execute
                // can rethrow it as it's unwinding.

                // Interlocked performs a volatile write; all processors will see the write to _error as being
                // no later than the write to _asyncState.
                _error = (error != null) ? ExceptionDispatchInfo.Capture(error) : null;
                int originalState = Interlocked.Exchange(ref _asyncState, ASYNC_STATE_CALLBACK_COMPLETED);
                if (originalState == ASYNC_STATE_NONE) {
                    return false; // IExecutionStep.Execute should call ResumeSteps
                }

                Debug.Assert(originalState == ASYNC_STATE_BEGIN_UNWOUND, "Unexpected state.");
                _error = null; // to prevent long-lived exception object; write doesn't need to be volatile since nobody reads this field anyway in this case
                return true; // this thread should call ResumeSteps
            }

            public void RegisterBeginUnwound(IAsyncResult asyncResult, out bool operationCompleted, out bool mustCallEndHandler) {
                operationCompleted = false;
                mustCallEndHandler = false;

                int originalState = Interlocked.Exchange(ref _asyncState, ASYNC_STATE_BEGIN_UNWOUND);
                if (originalState == ASYNC_STATE_NONE) {
                    if (asyncResult.CompletedSynchronously) {
                        // Synchronous completion; the callback either wasn't called or was a no-op.
                        // In either case, we should call the End* method from this thread.
                        operationCompleted = true;
                        mustCallEndHandler = true;
                    }

                    // Otherwise, this is an asynchronous completion, and the callback hasn't yet been invoked or hasn't fully completed.
                    // We'll let the thread that invokes the callback call the End* method.
                }
                else {
                    Debug.Assert(originalState == ASYNC_STATE_CALLBACK_COMPLETED, "Unexpected state.");

                    // The operation completed, and the callback already invoked the End* method.
                    // The only thing we need to do is to report to our caller that the operation completed synchronously
                    // (so that ResumeSteps runs on this thread) and to observe any exceptions that occurred.
                    operationCompleted = true;
                }

                // Interlocked performs a volatile read; if RethrowExceptionIfNecessary() is called after RegisterBeginUnwound(),
                // the thread will see the correct value for the _error field.
            }

            public void ReportError() {
                // Using ExceptionDispatchInfo preserves the Exception's stack trace when rethrowing.
                ExceptionDispatchInfo error = _error;
                if (error != null) {
                    _error = null; // prevent long-lived Exception objects on the heap
                    error.Throw();
                }
            }

            public void Reset() {
                // All processors see the _error field write as being no later than the _asyncState field write.
                _error = null;
                _asyncState = ASYNC_STATE_NONE;
            }
#pragma warning restore 420 // volatile passed by reference
        }
    }
}