File: HostingEnvironment.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (1977 lines) | stat: -rw-r--r-- 77,666 bytes parent folder | download | duplicates (6)
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
//------------------------------------------------------------------------------
// <copyright file="HostingEnvironment.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Web.Hosting {
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Configuration;
    using System.Configuration.Provider;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.IO;
    using System.Runtime.Caching;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Messaging;
    using System.Security;
    using System.Security.Permissions;
    using System.Security.Policy;
    using System.Security.Principal;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Caching;
    using System.Web.Compilation;
    using System.Web.Configuration;
    using System.Web.Management;
    using System.Web.Util;
    using System.Web.WebSockets;
    using Microsoft.Win32;

    [Flags]
    internal enum HostingEnvironmentFlags {
        Default = 0,
        HideFromAppManager = 1,
        ThrowHostingInitErrors = 2,
        DontCallAppInitialize = 4,
        ClientBuildManager = 8,
        SupportsMultiTargeting = 16,
    }

    [Serializable]
    internal class HostingEnvironmentParameters {
        private HostingEnvironmentFlags _hostingFlags;
        private ClientBuildManagerParameter _clientBuildManagerParameter;
        private string _precompTargetPhysicalDir;
        private string _iisExpressVersion;

        public HostingEnvironmentFlags HostingFlags {
            get { return _hostingFlags; }
            set { _hostingFlags = value; }
        }

        // Directory where the precompiled site is placed
        public string PrecompilationTargetPhysicalDirectory {
            get { return _precompTargetPhysicalDir; }
            set {
                _precompTargetPhysicalDir = FileUtil.FixUpPhysicalDirectory(value);
            }
        }

        // Determines the behavior of the precompilation
        public ClientBuildManagerParameter ClientBuildManagerParameter {
            get { return _clientBuildManagerParameter; }
            set { _clientBuildManagerParameter = value; }
        }

        // Determines which config system to load
        public string IISExpressVersion {
            get { return _iisExpressVersion; }
            set { _iisExpressVersion = value; }
        }

        // Determines what FileChangeMonitor mode to use
        public FcnMode FcnMode {
            get;
            set;
        }

        // Should FileChangesMonitor skip reading and caching DACLs?
        public bool FcnSkipReadAndCacheDacls {
            get;
            set;
        }

        public KeyValuePair<string, bool>[] ClrQuirksSwitches {
            get;
            set;
        }
    }

    public sealed class HostingEnvironment : MarshalByRefObject {

        private static HostingEnvironment _theHostingEnvironment;
        private EventHandler _onAppDomainUnload;
        private ApplicationManager _appManager;
        private HostingEnvironmentParameters _hostingParameters;
        private IApplicationHost _appHost;
        private bool _externalAppHost;
        private IConfigMapPath _configMapPath;
        private IConfigMapPath2 _configMapPath2;
        private IntPtr _configToken;

        private IdentitySection _appIdentity;
        private IntPtr _appIdentityToken;
        private bool _appIdentityTokenSet;

        private String _appId;
        private VirtualPath _appVirtualPath;
        private String _appPhysicalPath;
        private String _siteName;
        private String _siteID;
        private String _appConfigPath;

        private bool   _isBusy;
        private int    _busyCount;

        private volatile static bool _stopListeningWasCalled; // static since it's process-wide
        private bool _removedFromAppManager;
        private bool _appDomainShutdownStarted;
        private bool _shutdownInitiated;
        private bool _shutdownInProgress;
        private String _shutDownStack;

        private static NameValueCollection _cacheProviderSettings;
        private int _inTrimCache;
        private ObjectCacheHost _objectCacheHost;

        // table of well know objects keyed by type
        private Hashtable _wellKnownObjects = new Hashtable();

        // list of registered IRegisteredObject instances, suspend listeners, and background work items
        private Hashtable _registeredObjects = new Hashtable();
        private SuspendManager _suspendManager = new SuspendManager();
        private ApplicationMonitors _applicationMonitors;
        private BackgroundWorkScheduler _backgroundWorkScheduler = null; // created on demand
        private static readonly Task<object> _completedTask = Task.FromResult<object>(null);

        // callback to make InitiateShutdown non-blocking
        private WaitCallback _initiateShutdownWorkItemCallback;

        // inside app domain idle shutdown logic
        private IdleTimeoutMonitor _idleTimeoutMonitor;

        private static IProcessHostSupportFunctions _functions;
        private static bool _hasBeenRemovedFromAppManangerTable;

        private const string TemporaryVirtualPathProviderKey = "__TemporaryVirtualPathProvider__";

        // Determines what FileChangeMonitor mode to use
        internal static FcnMode FcnMode {
            get {
                if (_theHostingEnvironment != null && _theHostingEnvironment._hostingParameters != null) {
                    return _theHostingEnvironment._hostingParameters.FcnMode;
                }
                return FcnMode.NotSet;
            }
        }

        internal static bool FcnSkipReadAndCacheDacls {
            get {
                if (_theHostingEnvironment != null && _theHostingEnvironment._hostingParameters != null) {
                    return _theHostingEnvironment._hostingParameters.FcnSkipReadAndCacheDacls;
                }
                return false;
            }
        }

        public override Object InitializeLifetimeService() {
            return null; // never expire lease
        }

        /// <internalonly/>
        [SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
        public HostingEnvironment() {
            if (_theHostingEnvironment != null)
                throw new InvalidOperationException(SR.GetString(SR.Only_1_HostEnv));

            // remember singleton HostingEnvironment in a static
            _theHostingEnvironment = this;

            // start watching for app domain unloading
            _onAppDomainUnload = new EventHandler(OnAppDomainUnload);
            Thread.GetDomain().DomainUnload += _onAppDomainUnload;

            // VSO 160528: We used to listen to the default AppDomain's UnhandledException only.
            // However, non-serializable exceptions cannot be passed to the default domain. Therefore
            // we should try to log exceptions in application AppDomains.
            Thread.GetDomain().UnhandledException += new UnhandledExceptionEventHandler(ApplicationManager.OnUnhandledException);
        }

        internal static long TrimCache(int percent)
        {
            if (_theHostingEnvironment != null)
                return _theHostingEnvironment.TrimCacheInternal(percent);
            return 0;
        }

        private long TrimCacheInternal(int percent)
        {
            if (Interlocked.Exchange(ref _inTrimCache, 1) != 0)
                return 0;
            try {
                long trimmedOrExpired = 0;
                // do nothing if we're shutting down
                if (!_shutdownInitiated) {
                    var iCache = HttpRuntime.Cache.GetInternalCache(createIfDoesNotExist: false);
                    var oCache = HttpRuntime.Cache.GetObjectCache(createIfDoesNotExist: false);
                    if (oCache != null) {
                        trimmedOrExpired = oCache.Trim(percent);
                    }
                    if (iCache != null && !iCache.Equals(oCache)) {
                        trimmedOrExpired += iCache.Trim(percent);
                    }
                    if (_objectCacheHost != null && !_shutdownInitiated) {
                        trimmedOrExpired += _objectCacheHost.TrimCache(percent);
                    }
                }
                return trimmedOrExpired;
            }
            finally {
                Interlocked.Exchange(ref _inTrimCache, 0);
            }
        }

        private void OnAppDomainUnload(Object unusedObject, EventArgs unusedEventArgs) {
            Debug.Trace("PipelineRuntime", "HE.OnAppDomainUnload");

            Thread.GetDomain().DomainUnload -= _onAppDomainUnload;

            // check for unexpected shutdown
            if (!_removedFromAppManager) {
                RemoveThisAppDomainFromAppManagerTableOnce();
            }

            HttpRuntime.RecoverFromUnexceptedAppDomainUnload();

            // call Stop on all registered objects with immediate = true
            StopRegisteredObjects(true);

            // notify app manager
            if (_appManager != null) {
                // disconnect the real app host and substitute it with a bogus one
                // to avoid exceptions later when app host is called (it normally wouldn't)
                IApplicationHost originalAppHost = null;

                if (_externalAppHost) {
                    originalAppHost = _appHost;
                    _appHost = new SimpleApplicationHost(_appVirtualPath, _appPhysicalPath);
                    _externalAppHost = false;
                }

                IDisposable configSystem = _configMapPath2 as IDisposable;
                if (configSystem != null) {
                    configSystem.Dispose();
                }

                _appManager.HostingEnvironmentShutdownComplete(_appId, originalAppHost);
            }

            // free the config access token
            if (_configToken != IntPtr.Zero) {
                UnsafeNativeMethods.CloseHandle(_configToken);
                _configToken = IntPtr.Zero;
            }
        }

        //
        // Initialization
        //

        // called from app manager right after app domain (and hosting env) is created
        internal void Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel) {
            Initialize(appManager, appHost, configMapPathFactory, hostingParameters, policyLevel, null);
        }

        [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "We carefully control this method's callers.")]
        internal void Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory,
            HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel,
            Exception appDomainCreationException) {

            _hostingParameters = hostingParameters;

            HostingEnvironmentFlags hostingFlags = HostingEnvironmentFlags.Default;
            if (_hostingParameters != null) {
                hostingFlags = _hostingParameters.HostingFlags;
                if (_hostingParameters.IISExpressVersion != null) {
                    ServerConfig.IISExpressVersion = _hostingParameters.IISExpressVersion;
                }
            }

            // Keep track of the app manager, unless HideFromAppManager flag was passed
            if ((hostingFlags & HostingEnvironmentFlags.HideFromAppManager) == 0)
                _appManager = appManager;

            if ((hostingFlags & HostingEnvironmentFlags.ClientBuildManager) != 0) {
                BuildManagerHost.InClientBuildManager = true;
            }

            if ((hostingFlags & HostingEnvironmentFlags.SupportsMultiTargeting) != 0) {
                BuildManagerHost.SupportsMultiTargeting = true;
            }

            // Set CLR quirks switches before the config system is initialized since config might depend on them
            if (_hostingParameters != null && _hostingParameters.ClrQuirksSwitches != null && _hostingParameters.ClrQuirksSwitches.Length > 0) {
                SetClrQuirksSwitches(_hostingParameters.ClrQuirksSwitches);
            }

            //
            // init config system using private config if applicable
            //
            if (appHost is ISAPIApplicationHost && !ServerConfig.UseMetabase) {
                string rootWebConfigPath = ((ISAPIApplicationHost)appHost).ResolveRootWebConfigPath();
                if (!String.IsNullOrEmpty(rootWebConfigPath)) {
                    Debug.Assert(File.Exists(rootWebConfigPath), "File.Exists(rootWebConfigPath)");
                    HttpConfigurationSystem.RootWebConfigurationFilePath = rootWebConfigPath;
                }

                // we need to explicit create a COM proxy in this app domain
                // so we don't go back to the default domain or have lifetime issues
                // remember support functions
                IProcessHostSupportFunctions proxyFunctions = ((ISAPIApplicationHost)appHost).SupportFunctions;
                if (null != proxyFunctions) {
                    _functions = Misc.CreateLocalSupportFunctions(proxyFunctions);
                }
            }

            _appId = HttpRuntime.AppDomainAppId;
            _appVirtualPath = HttpRuntime.AppDomainAppVirtualPathObject;
            _appPhysicalPath = HttpRuntime.AppDomainAppPathInternal;
            _appHost = appHost;

            _configMapPath = configMapPathFactory.Create(_appVirtualPath.VirtualPathString, _appPhysicalPath);
            HttpConfigurationSystem.EnsureInit(_configMapPath, true, false);

            // attempt to cache and use IConfigMapPath2 provider
            // which supports VirtualPath's to save on conversions
            _configMapPath2 = _configMapPath as IConfigMapPath2;


            _initiateShutdownWorkItemCallback = new WaitCallback(this.InitiateShutdownWorkItemCallback);

            // notify app manager
            if (_appManager != null) {
                _appManager.HostingEnvironmentActivated();
            }

            // make sure there is always app host
            if (_appHost == null) {
                _appHost = new SimpleApplicationHost(_appVirtualPath, _appPhysicalPath);
            }
            else {
                _externalAppHost = true;
            }

            // remember the token to access config
            _configToken = _appHost.GetConfigToken();

            // Start with a MapPath based virtual path provider
            _mapPathBasedVirtualPathProvider = new MapPathBasedVirtualPathProvider();
            _virtualPathProvider = _mapPathBasedVirtualPathProvider;

            // initiaze HTTP-independent features
            HttpRuntime.InitializeHostingFeatures(hostingFlags, policyLevel, appDomainCreationException);

            // VSWhidbey 393259. Do not monitor idle timeout for CBM since Venus
            // will always restart a new appdomain if old one is shutdown.
            if (!BuildManagerHost.InClientBuildManager) {
                // start monitoring for idle inside app domain
                StartMonitoringForIdleTimeout();
            }

            // notify app manager if the app domain limit is violated
            EnforceAppDomainLimit();

            // get application identity (for explicit impersonation mode)
            GetApplicationIdentity();

            _applicationMonitors = new ApplicationMonitors();

            // call AppInitialize, unless the flag says not to do it (e.g. CBM scenario).
            // Also, don't call it if HostingInit failed (VSWhidbey 210495)
            if(!HttpRuntime.HostingInitFailed) {
                try {
                    BuildManager.ExecutePreAppStart();
                    if ((hostingFlags & HostingEnvironmentFlags.DontCallAppInitialize) == 0) {
                        BuildManager.CallAppInitializeMethod();
                    }
                }
                catch (Exception e) {
                    // could throw compilation errors in 'code' - report them with first http request
                    HttpRuntime.InitializationException = e;

                    if ((hostingFlags & HostingEnvironmentFlags.ThrowHostingInitErrors) != 0) {
                        throw;
                    }
                }
            }
        }

        private void InitializeObjectCacheHostPrivate() {
            // set ObjectCacheHost if the Host is not already set
            if (ObjectCache.Host == null) {
                ObjectCacheHost objectCacheHost = new ObjectCacheHost();
                ObjectCache.Host = objectCacheHost;
                _objectCacheHost = objectCacheHost;
            }
        }

        internal static void InitializeObjectCacheHost() {
            if (_theHostingEnvironment != null) {
                _theHostingEnvironment.InitializeObjectCacheHostPrivate();
            }
        }

        private void StartMonitoringForIdleTimeout() {
            HostingEnvironmentSection hostEnvConfig = RuntimeConfig.GetAppLKGConfig().HostingEnvironment;

            TimeSpan idleTimeout = (hostEnvConfig != null) ? hostEnvConfig.IdleTimeout : HostingEnvironmentSection.DefaultIdleTimeout;

            // always create IdleTimeoutMonitor (even if config value is TimeSpan.MaxValue (infinite)
            // IdleTimeoutMonitor is also needed to keep the last event for app domain set trimming
            // and the timer is used to trim the application instances
            _idleTimeoutMonitor = new IdleTimeoutMonitor(idleTimeout);
        }

        // enforce app domain limit
        private void EnforceAppDomainLimit() {
            if (_appManager == null)  /// detached app domain
                return;

            int limit = 0;

            try {
                ProcessModelSection pmConfig = RuntimeConfig.GetMachineConfig().ProcessModel;
                limit = pmConfig.MaxAppDomains;
            }
            catch {
            }

            if (limit > 0 && _appManager.AppDomainsCount >= limit) {
                // current app domain doesn't count yet (not in the table)
                // that's why '>=' above
                _appManager.ReduceAppDomainsCount(limit);
            }
        }

        private void GetApplicationIdentity() {
            // if the explicit impersonation is set, use it instead of UNC identity
            try {
                IdentitySection c = RuntimeConfig.GetAppConfig().Identity;
                if (c.Impersonate && c.ImpersonateToken != IntPtr.Zero) {
                    _appIdentity = c;
                    _appIdentityToken = c.ImpersonateToken;
                }
                else {
                    _appIdentityToken = _configToken;
                }
                _appIdentityTokenSet = true;
            }
            catch {
            }
        }

        private static void SetClrQuirksSwitches(KeyValuePair<string, bool>[] switches) {
            // First, see if the static API AppContext.SetSwitch even exists.
            // Type.GetType will return null if the type doesn't exist; it will throw on catastrophic failure.

            Type appContextType = Type.GetType("System.AppContext, " + AssemblyRef.Mscorlib);
            if (appContextType == null) {
                return; // wrong version of mscorlib - do nothing
            }

            Action<string, bool> setter = (Action<string, bool>)Delegate.CreateDelegate(
                typeof(Action<string, bool>),
                appContextType,
                "SetSwitch",
                ignoreCase: false,
                throwOnBindFailure: false);
            if (setter == null) {
                return; // wrong version of mscorlib - do nothing
            }

            // Finally, set each switch individually.

            foreach (var sw in switches) {
                setter(sw.Key, sw.Value);
            }
        }


        // If an exception was thrown during initialization, return it.
        public static Exception InitializationException {
            get {
                return HttpRuntime.InitializationException;
            }
        }

        // called from app manager (from management APIs)
        internal ApplicationInfo GetApplicationInfo() {
            return new ApplicationInfo(_appId, _appVirtualPath, _appPhysicalPath);
        }

        //
        // Shutdown logic
        //
        [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
        private void StopRegisteredObjects(bool immediate) {
            if (_registeredObjects.Count > 0) {
                ArrayList list = new ArrayList();

                lock (this) {
                    foreach (DictionaryEntry e in _registeredObjects) {
                        Object x = e.Key;

                        // well-known objects first
                        if (IsWellKnownObject(x)) {
                            list.Insert(0, x);
                        }
                        else {
                            list.Add(x);
                        }
                    }
                }

                foreach (IRegisteredObject obj in list) {
                    try {
                        obj.Stop(immediate);
                    }
                    catch {
                    }
                }
            }
        }

        private void InitiateShutdownWorkItemCallback(Object state /*not used*/) {
            Debug.Trace("HostingEnvironmentShutdown", "Shutting down: appId=" + _appId);

            // no registered objects -- shutdown
            if (_registeredObjects.Count == 0) {
                Debug.Trace("HostingEnvironmentShutdown", "No registered objects");
                ShutdownThisAppDomainOnce();
                return;
            }

            // call Stop on all registered objects with immediate = false
            StopRegisteredObjects(false);

            // no registered objects -- shutdown now
            if (_registeredObjects.Count == 0) {
                Debug.Trace("HostingEnvironmentShutdown", "All registered objects gone after Stop(false)");
                ShutdownThisAppDomainOnce();
                return;
            }

            // if not everything shutdown synchronously give it some time.
            int shutdownTimeoutSeconds = HostingEnvironmentSection.DefaultShutdownTimeout;
            HostingEnvironmentSection hostEnvConfig = RuntimeConfig.GetAppLKGConfig().HostingEnvironment;
            if (hostEnvConfig != null) {
                shutdownTimeoutSeconds = (int) hostEnvConfig.ShutdownTimeout.TotalSeconds;
            }
            Debug.Trace("HostingEnvironmentShutdown", "Waiting for " + shutdownTimeoutSeconds + " sec...");

            DateTime waitUntil = DateTime.UtcNow.AddSeconds(shutdownTimeoutSeconds);
            while (_registeredObjects.Count > 0 && DateTime.UtcNow < waitUntil) {
                Thread.Sleep(100);
            }

            Debug.Trace("HostingEnvironmentShutdown", "Shutdown timeout (" + shutdownTimeoutSeconds + " sec) expired");

            // call Stop on all registered objects with immediate = true
            StopRegisteredObjects(true);

            // no registered objects -- shutdown now
            if (_registeredObjects.Count == 0) {
                Debug.Trace("HostingEnvironmentShutdown", "All registered objects gone after Stop(true)");
                ShutdownThisAppDomainOnce();
                return;
            }

            // shutdown regardless
            Debug.Trace("HostingEnvironmentShutdown", "Forced shutdown: " + _registeredObjects.Count + " registered objects left");
            _registeredObjects = new Hashtable();
            ShutdownThisAppDomainOnce();
        }

        // app domain shutdown logic
        internal void InitiateShutdownInternal() {
#if DBG
            try {
#endif
            Debug.Trace("AppManager", "HostingEnvironment.InitiateShutdownInternal appId=" + _appId);

            bool proceed = false;

            if (!_shutdownInitiated) {
                lock (this) {
                    if (!_shutdownInitiated) {
                        _shutdownInProgress = true;
                        proceed = true;
                        _shutdownInitiated = true;
                    }
                }
            }

            if (!proceed) {
                return;
            }

            HttpRuntime.SetShutdownReason(ApplicationShutdownReason.HostingEnvironment, "HostingEnvironment initiated shutdown");

            // Avoid calling Environment.StackTrace if we are in the ClientBuildManager (Dev10 bug 824659)
            if (!BuildManagerHost.InClientBuildManager) {
                new EnvironmentPermission(PermissionState.Unrestricted).Assert();
                try {
                    _shutDownStack = Environment.StackTrace;
                }
                finally {
                    CodeAccessPermission.RevertAssert();
                }
            }

            // waitChangeNotification need not be honored in ClientBuildManager (Dev11 bug 264894)
            if (!BuildManagerHost.InClientBuildManager) {
                // this should only be called once, before the cache is disposed, and
                // the config records are released.
                HttpRuntime.CoalesceNotifications();
            }

            RemoveThisAppDomainFromAppManagerTableOnce();

            // stop all registered objects without blocking
            ThreadPool.QueueUserWorkItem(this._initiateShutdownWorkItemCallback);
#if DBG
            } catch (Exception ex) {
                HandleExceptionFromInitiateShutdownInternal(ex);
                throw;
            }
#endif
        }

#if DBG
        // InitiateShutdownInternal should never throw an exception, but we have seen cases where
        // CLR bugs can cause it to fail without running to completion. This could cause an ASP.NET
        // AppDomain never to unload. If we detect that an exception is thrown, we should DebugBreak
        // so that the fundamentals team can investigate. Taking the Exception object as a parameter
        // makes it easy to locate when looking at a stack dump.
        [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
        private static void HandleExceptionFromInitiateShutdownInternal(Exception ex) {
            Debug.Break();
        }
#endif

        internal bool HasBeenRemovedFromAppManagerTable {
            get {
                return _hasBeenRemovedFromAppManangerTable;
            }
            set {
                _hasBeenRemovedFromAppManangerTable = value;
            }
        }

        private void RemoveThisAppDomainFromAppManagerTableOnce() {
            bool proceed = false;
            if (!_removedFromAppManager) {
                lock (this) {
                    if (!_removedFromAppManager) {
                        proceed = true;
                        _removedFromAppManager = true;
                    }
                }
            }

            if (!proceed)
                return;

            if (_appManager != null) {
                Debug.Trace("AppManager", "Removing HostingEnvironment from AppManager table, appId=" + _appId);
                _appManager.HostingEnvironmentShutdownInitiated(_appId, this);
            }
#if DBG
            Debug.Trace("FileChangesMonitorIgnoreSubdirChange", 
                        "*** REMOVE APPMANAGER TABLE" + DateTime.Now.ToString("hh:mm:ss.fff", CultureInfo.InvariantCulture) 
                        + ": _appId=" + _appId);
#endif
        }

        private void ShutdownThisAppDomainOnce() {
            bool proceed = false;

            if (!_appDomainShutdownStarted) {
                lock (this) {
                    if (!_appDomainShutdownStarted) {
                        proceed = true;
                        _appDomainShutdownStarted = true;
                    }
                }
            }

            if (!proceed)
                return;

            Debug.Trace("AppManager", "HostingEnvironment - shutting down AppDomain, appId=" + _appId);

            // stop the timer used for idle timeout
            if (_idleTimeoutMonitor != null) {
                _idleTimeoutMonitor.Stop();
                _idleTimeoutMonitor = null;
            }

            while (_inTrimCache == 1) {
                Thread.Sleep(100);
            }

            // close all outstanding WebSocket connections and begin winding down code that consumes them
            AspNetWebSocketManager.Current.AbortAllAndWait();

            // 
            HttpRuntime.SetUserForcedShutdown();

            //WOS 1400290: CantUnloadAppDomainException in ISAPI mode, wait until HostingEnvironment.ShutdownThisAppDomainOnce completes
            _shutdownInProgress = false;

            HttpRuntime.ShutdownAppDomainWithStackTrace(ApplicationShutdownReason.HostingEnvironment,
                                                        SR.GetString(SR.Hosting_Env_Restart),
                                                        _shutDownStack);
        }

        //
        // internal methods called by app manager
        //

        // helper for app manager to implement AppHost.CreateAppHost
        [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
        internal ObjectHandle CreateInstance(String assemblyQualifiedName) {
            Type type = Type.GetType(assemblyQualifiedName, true);
            return new ObjectHandle(Activator.CreateInstance(type));
        }

        // start well known object
        [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
        internal ObjectHandle CreateWellKnownObjectInstance(String assemblyQualifiedName, bool failIfExists) {
            Type type = Type.GetType(assemblyQualifiedName, true);
            IRegisteredObject obj = null;
            String key = type.FullName;
            bool exists = false;

            lock (this) {
                obj = _wellKnownObjects[key] as IRegisteredObject;

                if (obj == null) {
                    obj = (IRegisteredObject)Activator.CreateInstance(type);
                    _wellKnownObjects[key] = obj;
                }
                else {
                    exists = true;
                }
            }

            if (exists && failIfExists) {
                throw new InvalidOperationException(SR.GetString(SR.Wellknown_object_already_exists, key));
            }

            return new ObjectHandle(obj);
        }

        // check if well known object
        private bool IsWellKnownObject(Object obj) {
            bool found = false;
            String key = obj.GetType().FullName;

            lock (this) {
                if (_wellKnownObjects[key] == obj) {
                    found = true;
                }
            }

            return found;
        }

        // find well known object by type
        internal ObjectHandle FindWellKnownObject(String assemblyQualifiedName) {
            Type type = Type.GetType(assemblyQualifiedName, true);
            IRegisteredObject obj = null;
            String key = type.FullName;

            lock (this) {
                obj = _wellKnownObjects[key] as IRegisteredObject;
            }

            return (obj != null) ? new ObjectHandle(obj) : null;
        }

        // stop well known object by type
        [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
        internal void StopWellKnownObject(String assemblyQualifiedName) {
            Type type = Type.GetType(assemblyQualifiedName, true);
            IRegisteredObject obj = null;
            String key = type.FullName;

            lock (this) {
                obj = _wellKnownObjects[key] as IRegisteredObject;
                if (obj != null) {
                    _wellKnownObjects.Remove(key);
                    obj.Stop(false);
                }
            }
        }

        internal bool IsIdle() {
            bool isBusy = _isBusy;
            _isBusy = false;
            return (!isBusy && _busyCount == 0);
        }

        internal bool GetIdleValue() {
            return (!_isBusy && _busyCount == 0);
        }

        internal void IncrementBusyCountInternal() {
            _isBusy = true;
            Interlocked.Increment(ref _busyCount);
        }

        internal void DecrementBusyCountInternal() {
            _isBusy = true;
            Interlocked.Decrement(ref _busyCount);

            // Notify idle timeout monitor
            IdleTimeoutMonitor itm = _idleTimeoutMonitor;
            if (itm != null) {
                itm.LastEvent = DateTime.UtcNow;
            }
        }
        internal void IsUnloaded()
        {
            return;
        }

        private void MessageReceivedInternal() {
            _isBusy = true;

            IdleTimeoutMonitor itm = _idleTimeoutMonitor;
            if (itm != null) {
                itm.LastEvent = DateTime.UtcNow;
            }
        }

        // the busier the app domain the higher the score
        internal int LruScore {
            get {
                if (_busyCount > 0)
                    return _busyCount;

                IdleTimeoutMonitor itm = _idleTimeoutMonitor;

                if (itm == null)
                    return 0;

                // return negative number of seconds since last activity
                return -(int)(DateTime.UtcNow - itm.LastEvent).TotalSeconds;
            }
        }

        internal static ApplicationManager GetApplicationManager() {
            if (_theHostingEnvironment == null)
                return null;

            return _theHostingEnvironment._appManager;
        }

        //
        // private helpers
        //

        // register protocol handler with hosting environment
        private void RegisterRunningObjectInternal(IRegisteredObject obj) {
            lock (this) {
                _registeredObjects[obj] = obj;

                ISuspendibleRegisteredObject suspendibleObject = obj as ISuspendibleRegisteredObject;
                if (suspendibleObject != null) {
                    _suspendManager.RegisterObject(suspendibleObject);
                }
            }
        }

        // unregister protocol handler from hosting environment
        private void UnregisterRunningObjectInternal(IRegisteredObject obj) {
            bool lastOne = false;

            lock (this) {
                // if it is a well known object, remove it from that table as well
                String key = obj.GetType().FullName;
                if (_wellKnownObjects[key] == obj) {
                    _wellKnownObjects.Remove(key);
                }

                // remove from running objects list
                _registeredObjects.Remove(obj);

                ISuspendibleRegisteredObject suspendibleObject = obj as ISuspendibleRegisteredObject;
                if (suspendibleObject != null) {
                    _suspendManager.UnregisterObject(suspendibleObject);
                }

                if (_registeredObjects.Count == 0)
                    lastOne = true;
            }

            if (!lastOne)
                return;

            // shutdown app domain after last protocol handler is gone

            InitiateShutdownInternal();
        }

        // site name
        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This method is not dangerous.")]
        private String GetSiteName() {
            if (_siteName == null) {
                lock (this) {
                    if (_siteName == null) {
                        String s = null;

                        if (_appHost != null) {
                            // 
                            InternalSecurityPermissions.Unrestricted.Assert();
                            try {
                                s = _appHost.GetSiteName();
                            }
                            finally {
                                CodeAccessPermission.RevertAssert();
                            }
                        }

                        if (s == null)
                            s = WebConfigurationHost.DefaultSiteName;

                        _siteName = s;
                    }
                }
            }

            return _siteName;
        }

        // site ID
        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This method is not dangerous.")]
        private String GetSiteID() {
            if (_siteID == null) {
                lock (this) {
                    if (_siteID == null) {
                        String s = null;

                        if (_appHost != null) {
                            // 
                            InternalSecurityPermissions.Unrestricted.Assert();
                            try {
                                s = _appHost.GetSiteID();
                            }
                            finally {
                                CodeAccessPermission.RevertAssert();
                            }
                        }

                        if (s == null)
                            s = WebConfigurationHost.DefaultSiteID;

                        _siteID = s.ToLower(CultureInfo.InvariantCulture);
                    }
                }
            }

            return _siteID;
        }

        // Return the configPath for the app, e.g. "machine/webroot/1/myapp"
        private String GetAppConfigPath() {
            if (_appConfigPath == null) {
                _appConfigPath = WebConfigurationHost.GetConfigPathFromSiteIDAndVPath(SiteID, ApplicationVirtualPathObject);
            }

            return _appConfigPath;
        }

        // Return the call context slot name to use for a virtual path
        private static string GetFixedMappingSlotName(VirtualPath virtualPath) {
            return "MapPath_" + virtualPath.VirtualPathString.ToLowerInvariant().GetHashCode().ToString(CultureInfo.InvariantCulture);
        }

        /*
         * Map a virtual path to a physical path.  i.e. the physicalPath will be returned
         * when MapPath is called on the virtual path, bypassing the IApplicationHost
         */
        private static string GetVirtualPathToFileMapping(VirtualPath virtualPath) {
            return CallContext.GetData(GetFixedMappingSlotName(virtualPath)) as string;
        }

        /*
         * Map a virtual path to a physical path.  i.e. the physicalPath will be returned
         * when MapPath is called on the virtual path, bypassing the IApplicationHost
         */
        internal static object AddVirtualPathToFileMapping(
            VirtualPath virtualPath, string physicalPath) {

            // Save the mapping in the call context, using a key derived from the
            // virtual path.  The mapping is only valid for the duration of the request.
            CallContext.SetData(GetFixedMappingSlotName(virtualPath), physicalPath);

            // Return a mapping object to keep track of the virtual path, and of the current
            // virtualPathProvider.
            VirtualPathToFileMappingState state = new VirtualPathToFileMappingState();
            state.VirtualPath = virtualPath;
            state.VirtualPathProvider = _theHostingEnvironment._virtualPathProvider;

            // Always use the MapPathBasedVirtualPathProvider, otherwise the mapping mechanism
            // doesn't work (VSWhidbey 420702)
            // Set/Get the VPP on the call context so as not to affect other concurrent requests  (Dev10 852255)
            CallContext.SetData(TemporaryVirtualPathProviderKey, _theHostingEnvironment._mapPathBasedVirtualPathProvider);

            return state;
        }

        internal static void ClearVirtualPathToFileMapping(object state) {

            VirtualPathToFileMappingState mapping = (VirtualPathToFileMappingState)state;

            // Clear the mapping from the call context
            CallContext.SetData(GetFixedMappingSlotName(mapping.VirtualPath), null);

            // Restore the previous VirtualPathProvider
            // Set/Get the VPP on the call context so as not to affect other concurrent requests  (Dev10 852255)
            CallContext.SetData(TemporaryVirtualPathProviderKey, null);
        }

        private string MapPathActual(VirtualPath virtualPath, bool permitNull)
        {
            string result = null;

            Debug.Assert(virtualPath != null);

            virtualPath.FailIfRelativePath();

            VirtualPath reqpath = virtualPath;

            if (String.CompareOrdinal(reqpath.VirtualPathString, _appVirtualPath.VirtualPathString) == 0) {
                // for application path don't need to call app host
                Debug.Trace("MapPath", reqpath  +" is the app path");
                result = _appPhysicalPath;
            }
            else {
                using (new ProcessImpersonationContext()) {
                    // If there is a mapping for this virtual path in the call context, use it
                    result = GetVirtualPathToFileMapping(reqpath);

                    if (result == null) {
                        // call host's mappath
                        if (_configMapPath == null) {
                            Debug.Trace("MapPath", "Missing _configMapPath");
                            throw new InvalidOperationException(SR.GetString(SR.Cannot_map_path, reqpath));
                        }
                        Debug.Trace("MapPath", "call ConfigMapPath (" + reqpath + ")");

                        // see if the IConfigMapPath provider implements the interface
                        // with VirtualPath
                        try {
                            if (null != _configMapPath2) {
                                result = _configMapPath2.MapPath(GetSiteID(), reqpath);
                            }
                            else {
                                result = _configMapPath.MapPath(GetSiteID(), reqpath.VirtualPathString);
                            }
                            if (HttpRuntime.IsMapPathRelaxed)
                                result = HttpRuntime.GetRelaxedMapPathResult(result);
                        } catch {
                            if (HttpRuntime.IsMapPathRelaxed)
                                result = HttpRuntime.GetRelaxedMapPathResult(null);
                            else
                                throw;
                        }
                    }
                }
            }

            if (String.IsNullOrEmpty(result)) {
                Debug.Trace("MapPath", "null Result");
                if (!permitNull) {
                    if (HttpRuntime.IsMapPathRelaxed)
                        result = HttpRuntime.GetRelaxedMapPathResult(null);
                    else
                        throw new InvalidOperationException(SR.GetString(SR.Cannot_map_path, reqpath));
                }
            }
            else {
                // ensure extra '\\' in the physical path if the virtual path had extra '/'
                // and the other way -- no extra '\\' in physical if virtual didn't have it.
                if (virtualPath.HasTrailingSlash) {
                    if (!UrlPath.PathEndsWithExtraSlash(result) && !UrlPath.PathIsDriveRoot(result))
                        result = result + "\\";
                }
                else {
                    if (UrlPath.PathEndsWithExtraSlash(result) && !UrlPath.PathIsDriveRoot(result))
                        result = result.Substring(0, result.Length - 1);
                }

                Debug.Trace("MapPath", "    result=" + result);
            }

            return result;
        }

        //
        // public static methods
        //


        // register protocol handler with hosting environment
        [SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
        public static void RegisterObject(IRegisteredObject obj) {
            if (_theHostingEnvironment != null)
                _theHostingEnvironment.RegisterRunningObjectInternal(obj);
        }


        // unregister protocol handler from hosting environment
        [SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
        public static void UnregisterObject(IRegisteredObject obj) {
            if (_theHostingEnvironment != null)
                _theHostingEnvironment.UnregisterRunningObjectInternal(obj);
        }

        // Schedules a task which can run in the background, independent of any request.
        // This differs from a normal ThreadPool work item in that ASP.NET can keep track
        // of how many work items registered through this API are currently running, and
        // the ASP.NET runtime will try not to delay AppDomain shutdown until these work
        // items have finished executing.
        //
        // Usage notes:
        // - This API cannot be called outside of an ASP.NET-managed AppDomain.
        // - The caller's ExecutionContext is not flowed to the work item.
        // - Scheduled work items are not guaranteed to ever execute, e.g., when AppDomain
        //   shutdown has already started by the time this API was called.
        // - The provided CancellationToken will be signaled when the application is
        //   shutting down. The work item should make every effort to honor this token.
        //   If a work item does not honor this token and continues executing it will
        //   eventually be considered rogue, and the ASP.NET runtime will rudely unload
        //   the AppDomain without waiting for the work item to finish.
        //
        // This overload of QueueBackgroundWorkItem takes a void-returning callback; the
        // work item will be considered finished when the callback returns.
        [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
        public static void QueueBackgroundWorkItem(Action<CancellationToken> workItem) {
            if (workItem == null) {
                throw new ArgumentNullException("workItem");
            }

            QueueBackgroundWorkItem(ct => { workItem(ct); return _completedTask; });
        }

        // See documentation on the other overload for a general API overview.
        //
        // This overload of QueueBackgroundWorkItem takes a Task-returning callback; the
        // work item will be considered finished when the returned Task transitions to a
        // terminal state.
        [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
        public static void QueueBackgroundWorkItem(Func<CancellationToken, Task> workItem) {
            if (workItem == null) {
                throw new ArgumentNullException("workItem");
            }
            if (_theHostingEnvironment == null) {
                throw new InvalidOperationException(); // can only be called within an ASP.NET AppDomain
            }

            _theHostingEnvironment.QueueBackgroundWorkItemInternal(workItem);
        }

        private void QueueBackgroundWorkItemInternal(Func<CancellationToken, Task> workItem) {
            Debug.Assert(workItem != null);

            BackgroundWorkScheduler scheduler = Volatile.Read(ref _backgroundWorkScheduler);

            // If the scheduler doesn't exist, lazily create it, but only allow one instance to ever be published to the backing field
            if (scheduler == null) {
                BackgroundWorkScheduler newlyCreatedScheduler = new BackgroundWorkScheduler(UnregisterObject, Misc.WriteUnhandledExceptionToEventLog);
                scheduler = Interlocked.CompareExchange(ref _backgroundWorkScheduler, newlyCreatedScheduler, null) ?? newlyCreatedScheduler;
                if (scheduler == newlyCreatedScheduler) {
                    RegisterObject(scheduler); // Only call RegisterObject if we just created the "winning" one
                }
            }

            scheduler.ScheduleWorkItem(workItem);
        }

        // This event is a simple way to hook IStopListeningRegisteredObject.StopListening
        // without needing to call RegisterObject. The same restrictions which apply to
        // that method apply to this event.
        public static event EventHandler StopListening;

        //
        // public static methods for the user code to call
        //


        public static void IncrementBusyCount() {
            if (_theHostingEnvironment != null)
                _theHostingEnvironment.IncrementBusyCountInternal();
        }


        public static void DecrementBusyCount() {
            if (_theHostingEnvironment != null)
                _theHostingEnvironment.DecrementBusyCountInternal();
        }


        public static void MessageReceived() {
            if (_theHostingEnvironment != null)
                _theHostingEnvironment.MessageReceivedInternal();
        }

        public static bool InClientBuildManager {
            get {
                return BuildManagerHost.InClientBuildManager;
            }
        }

        public static bool IsHosted {
            get {
                return (_theHostingEnvironment != null);
            }
        }

        internal static bool IsUnderIISProcess {
            get {
                String process = VersionInfo.ExeName;

                return process == "aspnet_wp" ||
                       process == "w3wp" ||
                       process == "inetinfo";
            }
        }

        internal static bool IsUnderIIS6Process {
            get {
                return VersionInfo.ExeName == "w3wp";
            }
        }

        public static IApplicationHost ApplicationHost {
            //DevDivBugs 109864: ASP.NET: path discovery issue - In low trust, it is possible to get the physical path of any virtual path on the machine
            [SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
            get {
                if (_theHostingEnvironment == null)
                    return null;

                return _theHostingEnvironment._appHost;
            }
        }

       internal static IApplicationHost ApplicationHostInternal {
            get {
                if (_theHostingEnvironment == null)
                    return null;

                return _theHostingEnvironment._appHost;
            }
        }

        internal IApplicationHost InternalApplicationHost {
            get {
                return _appHost;
            }
        }

        /// <devdoc>
        ///    <para>A group of repleacable monitor objects used by ASP.Net subsystems to maintain
        ///       application health.</para>
        /// </devdoc>
        public static ApplicationMonitors ApplicationMonitors {
            get {
                if (_theHostingEnvironment == null)
                    return null;

                return _theHostingEnvironment._applicationMonitors;
            }
        }

        internal static int BusyCount {
            get {
                if (_theHostingEnvironment == null)
                    return 0;

                return _theHostingEnvironment._busyCount;
            }
        }

        internal static bool ShutdownInitiated {
            get {
                if (_theHostingEnvironment == null)
                    return false;

                return _theHostingEnvironment._shutdownInitiated;
            }
        }


        internal static bool ShutdownInProgress {
            get {
                if (_theHostingEnvironment == null)
                    return false;

                return _theHostingEnvironment._shutdownInProgress;
            }
        }


        /// <devdoc>
        ///    <para>The application ID (metabase path in IIS hosting).</para>
        /// </devdoc>
        public static String ApplicationID {
            get {
                if (_theHostingEnvironment == null)
                    return null;

                InternalSecurityPermissions.AspNetHostingPermissionLevelHigh.Demand();
                return _theHostingEnvironment._appId;
            }
        }

        internal static String ApplicationIDNoDemand {
            get {
                if (_theHostingEnvironment == null) {
                    return null;
                }

                return _theHostingEnvironment._appId;
            }
        }


        /// <devdoc>
        ///    <para>Physical path to the application root.</para>
        /// </devdoc>
        public static String ApplicationPhysicalPath {
            get {
                if (_theHostingEnvironment == null)
                    return null;

                InternalSecurityPermissions.AppPathDiscovery.Demand();
                return _theHostingEnvironment._appPhysicalPath;
            }
        }


        /// <devdoc>
        ///    <para>Virtual path to the application root.</para>
        /// </devdoc>
        public static String ApplicationVirtualPath {
            get {
                return VirtualPath.GetVirtualPathStringNoTrailingSlash(ApplicationVirtualPathObject);
            }
        }

        internal static VirtualPath ApplicationVirtualPathObject {
            get {
                if (_theHostingEnvironment == null)
                    return null;

                return _theHostingEnvironment._appVirtualPath;
            }
        }


        /// <devdoc>
        ///    <para>Site name.</para>
        /// </devdoc>
        public static String SiteName {
            get {
                if (_theHostingEnvironment == null)
                    return null;

                InternalSecurityPermissions.AspNetHostingPermissionLevelMedium.Demand();
                return _theHostingEnvironment.GetSiteName();
            }
        }

        internal static String SiteNameNoDemand {
            get {
                if (_theHostingEnvironment == null)
                    return null;

                return _theHostingEnvironment.GetSiteName();
            }
        }

        internal static String SiteID {
            get {
                if (_theHostingEnvironment == null)
                    return null;

                return _theHostingEnvironment.GetSiteID();
            }
        }

        internal static IConfigMapPath ConfigMapPath {
            get {
                if (_theHostingEnvironment == null)
                    return null;

                return _theHostingEnvironment._configMapPath;
            }
        }

        internal static String AppConfigPath {
            get {
                if (_theHostingEnvironment == null) {
                    return null;
                }

                return _theHostingEnvironment.GetAppConfigPath();
            }
        }

        // See comments in ApplicationManager.CreateAppDomainWithHostingEnvironment. This is the public API to access the
        // information we determined in that method. Defaults to 'false' if our AppDomain data isn't present.
        public static bool IsDevelopmentEnvironment {
            get {
                return (AppDomain.CurrentDomain.GetData(".devEnvironment") as bool?) == true;
            }
        }


        /// <devdoc>
        ///    <para>
        ///       Gets a reference to the System.Web.Cache.Cache object for the current request.
        ///    </para>
        /// </devdoc>
        public static Cache Cache {
            get { return HttpRuntime.Cache; }
        }

        internal static NameValueCollection CacheStoreProviderSettings {
            get {
                if (_cacheProviderSettings == null) {
                    if (AppDomain.CurrentDomain.IsDefaultAppDomain()) {
                        Configuration webConfig = WebConfigurationManager.OpenWebConfiguration(null /* root web.config */);
                        CacheSection cacheConfig = (CacheSection)webConfig.GetSection("system.web/caching/cache");
                        if (cacheConfig != null && cacheConfig.DefaultProvider != null && !String.IsNullOrWhiteSpace(cacheConfig.DefaultProvider)) {
                            ProviderSettingsCollection cacheProviders = cacheConfig.Providers;
                            if (cacheProviders == null || cacheProviders.Count < 1) {
                                throw new ProviderException(SR.GetString(SR.Def_provider_not_found));
                            }

                            ProviderSettings cacheProviderSettings = cacheProviders[cacheConfig.DefaultProvider];
                            if (cacheProviderSettings == null) {
                                throw new ProviderException(SR.GetString(SR.Def_provider_not_found));
                            }

                            NameValueCollection settings = cacheProviderSettings.Parameters;
                            settings["name"] = cacheProviderSettings.Name;
                            settings["type"] = cacheProviderSettings.Type;
                            _cacheProviderSettings = settings;
                        }
                    }
                    else {
                        _cacheProviderSettings = AppDomain.CurrentDomain.GetData(".defaultObjectCacheProvider") as NameValueCollection;
                    }
                }

                // Return a copy, so the consumer can't mess with our copy of the settings
                if (_cacheProviderSettings != null)
                    return new NameValueCollection(_cacheProviderSettings);

                return null;
            }
        }

        // count of all app domain from app manager
        internal static int AppDomainsCount {
            get {
                ApplicationManager appManager = GetApplicationManager();
                return (appManager != null) ? appManager.AppDomainsCount : 0;
            }
        }

        internal static HostingEnvironmentParameters HostingParameters {
            get {
                if (_theHostingEnvironment == null)
                    return null;

                return _theHostingEnvironment._hostingParameters;
            }
        }

        // Return an integer that is unique for each appdomain.  This can be used
        // to create things like once-per-appdomain temp files without having different
        // processes/appdomains step on each other
        private static int s_appDomainUniqueInteger;
        internal static int AppDomainUniqueInteger {
            get {
                if (s_appDomainUniqueInteger == 0) {
                    s_appDomainUniqueInteger = Guid.NewGuid().GetHashCode();
                }

                return s_appDomainUniqueInteger;
            }
        }

        public static ApplicationShutdownReason ShutdownReason {
            get { return HttpRuntime.ShutdownReason; }
        }

        // Was CGlobalModule::OnGlobalStopListening called?
        internal static bool StopListeningWasCalled {
            get {
                return _stopListeningWasCalled;
            }
        }

        [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive", Justification = "See comment in function.")]
        internal static void SetupStopListeningHandler() {
            StopListeningWaitHandle waitHandle = new StopListeningWaitHandle();

            RegisteredWaitHandle registeredWaitHandle = null;
            registeredWaitHandle = ThreadPool.UnsafeRegisterWaitForSingleObject(waitHandle, (_, __) => {
                // Referencing the field from within the callback should be sufficient to keep the GC
                // from reclaiming the RegisteredWaitHandle; the race condition is fine.
                GC.KeepAlive(registeredWaitHandle);
                OnGlobalStopListening();
            }, null, Timeout.Infinite, executeOnlyOnce: true);
        }

        private static void OnGlobalStopListening() {
            _stopListeningWasCalled = true;

            EventHandler eventHandler = StopListening;
            if (eventHandler != null) {
                eventHandler(null /* static means no sender */, EventArgs.Empty);
            }

            if (_theHostingEnvironment != null) {
                _theHostingEnvironment.FireStopListeningHandlers();
            }
        }

        [SuppressMessage("Microsoft.Reliability", "CA2002:DoNotLockOnObjectsWithWeakIdentity", Justification = "'this' always has strong identity.")]
        private void FireStopListeningHandlers() {
            List<IStopListeningRegisteredObject> listeners = new List<IStopListeningRegisteredObject>();
            lock (this) {
                foreach (DictionaryEntry e in _registeredObjects) {
                    IStopListeningRegisteredObject listener = e.Key as IStopListeningRegisteredObject;
                    if (listener != null) {
                        listeners.Add(listener);
                    }
                }
            }

            foreach (var listener in listeners) {
                listener.StopListening();
            }
        }

        /// <devdoc>
        ///    <para>Initiate app domain unloading for the current app.</para>
        /// </devdoc>
        [SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
        public static void InitiateShutdown() {
            if (_theHostingEnvironment != null)
                _theHostingEnvironment.InitiateShutdownInternal();
        }

        internal static void InitiateShutdownWithoutDemand() {
            if (_theHostingEnvironment != null)
                _theHostingEnvironment.InitiateShutdownInternal();
        }

        //
        // Internal methods for the ApplicationManager to suspend / resume this application.
        // Using GCHandle instead of ObjectHandle means we don't need to worry about lease lifetimes.
        //

        internal IntPtr SuspendApplication() {
            var state = _suspendManager.Suspend();
            return GCUtil.RootObject(state);
        }

        internal void ResumeApplication(IntPtr state) {
            var unwrappedState = GCUtil.UnrootObject(state);
            _suspendManager.Resume(unwrappedState);
        }

        /// <devdoc>
        ///    <para>Maps a virtual path to a physical path.</para>
        /// </devdoc>
        public static string MapPath(string virtualPath) {
            return MapPath(VirtualPath.Create(virtualPath));
        }

        internal static string MapPath(VirtualPath virtualPath) {
            if (_theHostingEnvironment == null)
                return null;

            String path = MapPathInternal(virtualPath);

            if (path != null)
                InternalSecurityPermissions.PathDiscovery(path).Demand();

            return path;
        }

        internal static String MapPathInternal(string virtualPath) {
            return MapPathInternal(VirtualPath.Create(virtualPath));
        }

        internal static String MapPathInternal(VirtualPath virtualPath) {
            if (_theHostingEnvironment == null) {
                return null;
            }

            return _theHostingEnvironment.MapPathActual(virtualPath, false);
        }

        internal static String MapPathInternal(string virtualPath, bool permitNull) {
            return MapPathInternal(VirtualPath.Create(virtualPath), permitNull);
        }

        internal static String MapPathInternal(VirtualPath virtualPath, bool permitNull) {
            if (_theHostingEnvironment == null) {
                return null;
            }

            return _theHostingEnvironment.MapPathActual(virtualPath, permitNull);
        }

        internal static string MapPathInternal(string virtualPath, string baseVirtualDir, bool allowCrossAppMapping) {
            return MapPathInternal(VirtualPath.Create(virtualPath),
                VirtualPath.CreateNonRelative(baseVirtualDir), allowCrossAppMapping);
        }

        internal static string MapPathInternal(VirtualPath virtualPath, VirtualPath baseVirtualDir, bool allowCrossAppMapping) {
            Debug.Assert(baseVirtualDir != null, "baseVirtualDir != null");

            // Combine it with the base and reduce
            virtualPath = baseVirtualDir.Combine(virtualPath);

            if (!allowCrossAppMapping && !virtualPath.IsWithinAppRoot)
                throw new ArgumentException(SR.GetString(SR.Cross_app_not_allowed, virtualPath));

            return MapPathInternal(virtualPath);
        }

        internal static WebApplicationLevel GetPathLevel(String path) {
            WebApplicationLevel pathLevel = WebApplicationLevel.AboveApplication;

            if (_theHostingEnvironment != null && !String.IsNullOrEmpty(path)) {
                String appPath = ApplicationVirtualPath;

                if (appPath == "/") {
                    if (path == "/") {
                        pathLevel = WebApplicationLevel.AtApplication;
                    }
                    else if (path[0] == '/') {
                        pathLevel = WebApplicationLevel.BelowApplication;
                    }
                }
                else {
                    if (StringUtil.EqualsIgnoreCase(appPath, path)) {
                        pathLevel = WebApplicationLevel.AtApplication;
                    }
                    else if (path.Length > appPath.Length && path[appPath.Length] == '/' &&
                        StringUtil.StringStartsWithIgnoreCase(path, appPath)) {

                        pathLevel = WebApplicationLevel.BelowApplication;
                    }
                }
            }

            return pathLevel;
        }


        //
        // Impersonation helpers
        //
        // user token for the app (hosting / unc)
        internal static IntPtr ApplicationIdentityToken {
            get {
                if (_theHostingEnvironment == null) {
                    return IntPtr.Zero;
                }
                else {
                    if (_theHostingEnvironment._appIdentityTokenSet)
                        return _theHostingEnvironment._appIdentityToken;
                    else
                        return _theHostingEnvironment._configToken;
                }
            }
        }


        // check if application impersonation != process impersonation
        internal static bool HasHostingIdentity {
            get {
                return (ApplicationIdentityToken != IntPtr.Zero);
            }
        }

        // impersonate application identity
        [SecurityPermission(SecurityAction.Demand, ControlPrincipal = true)]
        public static IDisposable Impersonate() {
            return new ApplicationImpersonationContext();
        }

        // impersonate the given user identity
        [SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
        public static IDisposable Impersonate(IntPtr token) {
            if (token == IntPtr.Zero) {
                return new ProcessImpersonationContext();
            }
            else {
                return new ImpersonationContext(token);
            }
        }

        // impersonate as configured for a given path
        [SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
        public static IDisposable Impersonate(IntPtr userToken, String virtualPath) {
            virtualPath = UrlPath.MakeVirtualPathAppAbsoluteReduceAndCheck(virtualPath);

            if (_theHostingEnvironment == null) {
                return Impersonate(userToken);
            }

            IdentitySection c = RuntimeConfig.GetConfig(virtualPath).Identity;
            if (c.Impersonate) {
                if (c.ImpersonateToken != IntPtr.Zero) {
                    return new ImpersonationContext(c.ImpersonateToken);
                }
                else {
                    return new ImpersonationContext(userToken);
                }
            }
            else {
                return new ApplicationImpersonationContext();
            }
        }

        //
        //  Culture helpers
        //

        public static IDisposable SetCultures() {
            return SetCultures(RuntimeConfig.GetAppLKGConfig().Globalization);
        }

        public static IDisposable SetCultures(string virtualPath) {
            virtualPath = UrlPath.MakeVirtualPathAppAbsoluteReduceAndCheck(virtualPath);
            return SetCultures(RuntimeConfig.GetConfig(virtualPath).Globalization);
        }

        private static IDisposable SetCultures(GlobalizationSection gs) {
            CultureContext c = new CultureContext();

            if (gs != null) {
                CultureInfo culture = null;
                CultureInfo uiCulture = null;

                if (gs.Culture != null && gs.Culture.Length > 0) {
                    try {
                        culture = HttpServerUtility.CreateReadOnlyCultureInfo(gs.Culture);
                    }
                    catch {
                    }
                }

                if (gs.UICulture != null && gs.UICulture.Length > 0) {
                    try {
                        uiCulture = HttpServerUtility.CreateReadOnlyCultureInfo(gs.UICulture);
                    }
                    catch {
                    }
                }

                c.SetCultures(culture, uiCulture);
            }

            return c;
        }


        class CultureContext : IDisposable {
            CultureInfo _savedCulture;
            CultureInfo _savedUICulture;

            internal CultureContext() {
            }

            void IDisposable.Dispose() {
                RestoreCultures();
            }

            internal void SetCultures(CultureInfo culture, CultureInfo uiCulture) {
                CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
                CultureInfo currentUICulture = Thread.CurrentThread.CurrentUICulture;

                if (culture != null && culture != currentCulture) {
                    Thread.CurrentThread.CurrentCulture = culture;
                    _savedCulture = currentCulture;
                }

                if (uiCulture != null && uiCulture != currentCulture) {
                    Thread.CurrentThread.CurrentUICulture = uiCulture;
                    _savedUICulture = currentUICulture;
                }
            }

            internal void RestoreCultures() {
                if (_savedCulture != null && _savedCulture != Thread.CurrentThread.CurrentCulture) {
                    Thread.CurrentThread.CurrentCulture = _savedCulture;
                    _savedCulture = null;
                }

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

        //
        // VirtualPathProvider related code
        //

        private VirtualPathProvider _virtualPathProvider;
        private VirtualPathProvider _mapPathBasedVirtualPathProvider;


        public static VirtualPathProvider VirtualPathProvider {
            get {
                if (_theHostingEnvironment == null)
                    return null;

                // Set/Get the VPP on the call context so as not to affect other concurrent requests  (Dev10 852255)
                var tempVPP = CallContext.GetData(TemporaryVirtualPathProviderKey);
                if (tempVPP != null) {
                    return tempVPP as VirtualPathProvider;
                }

                return _theHostingEnvironment._virtualPathProvider;
            }
        }

        internal static bool UsingMapPathBasedVirtualPathProvider {
            get {
                if (_theHostingEnvironment == null)
                    return true;

                return (_theHostingEnvironment._virtualPathProvider ==
                    _theHostingEnvironment._mapPathBasedVirtualPathProvider);
            }
        }

        // [AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.High)]
        // Removed the above LinkDemand for AspNetHostingPermissionLevel.High. If we decide to add VPP
        // support for config in the future, we should have a separate API with a demand for registering
        // VPPs supporting configuration.
        public static void RegisterVirtualPathProvider(VirtualPathProvider virtualPathProvider) {

            if (_theHostingEnvironment == null)
                throw new InvalidOperationException();

            // Ignore the VirtualPathProvider on precompiled sites (VSWhidbey 368169,404844)
            if (BuildManager.IsPrecompiledApp)
                return;

            RegisterVirtualPathProviderInternal(virtualPathProvider);
        }

        internal static void RegisterVirtualPathProviderInternal(VirtualPathProvider virtualPathProvider) {
            VirtualPathProvider previous = _theHostingEnvironment._virtualPathProvider;
            _theHostingEnvironment._virtualPathProvider = virtualPathProvider;

            // Give it the previous provider so it can delegate if needed
            virtualPathProvider.Initialize(previous);
        }

        // Helper class used to keep track of state when using
        // AddVirtualPathToFileMapping & ClearVirtualPathToFileMapping
        internal class VirtualPathToFileMappingState {
            internal VirtualPath VirtualPath;
            internal VirtualPathProvider VirtualPathProvider;
        }

        internal static IProcessHostSupportFunctions SupportFunctions {
            get {
                return _functions;
            }
            set {
                _functions = value;
            }
        }

        [SuppressMessage("Microsoft.Naming", "CA1705:LongAcronymsShouldBePascalCased", 
                         Justification="matches casing of config attribute")]
        public static int MaxConcurrentRequestsPerCPU {
            get {
                if (!HttpRuntime.UseIntegratedPipeline) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }
                return UnsafeIISMethods.MgdGetMaxConcurrentRequestsPerCPU();
            }
            [SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
            set {
                if (!HttpRuntime.UseIntegratedPipeline) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }
                int hr = UnsafeIISMethods.MgdSetMaxConcurrentRequestsPerCPU(value);
                switch (hr) {
                    case HResults.S_FALSE:
                        // Because "maxConcurrentRequestsPerCPU" is currently zero, we cannot set the value, since that would
                        // enable the feature, which can only be done via configuration.
                        throw new InvalidOperationException(SR.GetString(SR.Queue_limit_is_zero, "maxConcurrentRequestsPerCPU"));
                    case HResults.E_INVALIDARG:
                        // The value must be greater than zero.  A value of zero would disable the feature, but this can only be done via configuration.
                        throw new ArgumentException(SR.GetString(SR.Invalid_queue_limit));
                }
            }
        }

        [SuppressMessage("Microsoft.Naming", "CA1705:LongAcronymsShouldBePascalCased",
                         Justification="matches casing of config attribute")]
        public static int MaxConcurrentThreadsPerCPU {
            get {
                if (!HttpRuntime.UseIntegratedPipeline) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }
                return UnsafeIISMethods.MgdGetMaxConcurrentThreadsPerCPU();
            }
            [SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
            set {
                if (!HttpRuntime.UseIntegratedPipeline) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }
                int hr = UnsafeIISMethods.MgdSetMaxConcurrentThreadsPerCPU(value);
                switch (hr) {
                    case HResults.S_FALSE:
                        // Because "maxConcurrentThreadsPerCPU" is currently zero, we cannot set the value, since that would
                        // enable the feature, which can only be done via configuration.
                        throw new InvalidOperationException(SR.GetString(SR.Queue_limit_is_zero, "maxConcurrentThreadsPerCPU"));
                    case HResults.E_INVALIDARG:
                        // The value must be greater than zero.  A value of zero would disable the feature, but this can only be done via configuration.
                        throw new ArgumentException(SR.GetString(SR.Invalid_queue_limit));
                }
            }
        }

        /// <summary>
        /// Returns the ASP.NET hosted domain.
        /// </summary>
        internal AppDomain HostedAppDomain {
            get {
                return AppDomain.CurrentDomain;
            }
        }

    }
}