download appdomain.cs
Language: C#
Copyright: (c) 2006 Microsoft Corporation. All rights reserved.
LOC: 1788
Project Info
Rotor IL Logger(rotorillogger)
Server: CodePlex1
Type: svn
...ger\svn\clr\src\bcl\system\
   __filters.cs
   __hresults.cs
   _localdatastore.cs
   _localdatastoremgr.cs
   ...ssviolationexception.cs
   activationarguments.cs
   activator.cs
   appdomain.cs
   appdomainattributes.cs
   appdomainmanager.cs
   appdomainsetup.cs
   ...ainunloadedexception.cs
   applicationactivator.cs
   applicationexception.cs
   applicationid.cs
   argiterator.cs
   argumentexception.cs
   argumentnullexception.cs
   ...toutofrangeexception.cs
   arithmeticexception.cs
   array.cs
   arraysegment.cs
   ...ypemismatchexception.cs
   asynccallback.cs
   attribute.cs
   attributetargets.cs
   attributeusageattribute.cs
   badimageformatexception.cs
   bcldebug.cs
   bitconverter.cs
   boolean.cs
   buffer.cs
   byte.cs
   ...adappdomainexception.cs
   cfgparser.cs
   char.cs
   charenumerator.cs
   clscompliantattribute.cs
   cominterfaces.cs
   compatibilityflags.cs
   ...usmethodframegeneric.cs
   console.cs
   consolecanceleventargs.cs
   consolespecialkey.cs
   contextboundobject.cs
   contextmarshalexception.cs
   contextstaticattribute.cs
   convert.cs
   currency.cs
   currenttimezone.cs
   datamisalignedexception.cs
   datetime.cs
   datetimekind.cs
   dayofweek.cs
   dbnull.cs
   decimal.cs
   defaultbinder.cs
   delegate.cs
   ...eserializationholder.cs
   dividebyzeroexception.cs
   dllnotfoundexception.cs
   double.cs
   ...ewaitobjectexception.cs
   empty.cs
   ...intnotfoundexception.cs
   enum.cs
   environment.cs
   eventargs.cs
   eventhandler.cs
   exception.cs
   ...utionengineexception.cs
   fieldaccessexception.cs
   flagsattribute.cs
   formatexception.cs
   gc.cs
   guid.cs
   iappdomain.cs
   iappdomainsetup.cs
   iasyncresult.cs
   icloneable.cs
   icomparable.cs
   iconvertible.cs
   icustomformatter.cs
   idisposable.cs
   iequatable.cs
   iformatprovider.cs
   iformattable.cs
   ...xoutofrangeexception.cs
   ...cientmemoryexception.cs
   int16.cs
   int32.cs
   int64.cs
   internal.cs
   intptr.cs
   invalidcastexception.cs
   ...idoperationexception.cs
   invalidprogramexception.cs
   iserviceobjectprovider.cs
   marshalbyrefobject.cs
   math.cs
   mda.cs
   memberaccessexception.cs
   methodaccessexception.cs
   midpointrounding.cs
   missingfieldexception.cs
   missingmemberexception.cs
   missingmethodexception.cs
   multicastdelegate.cs
   ...otsupportedexception.cs
   ndirectmethodframeex.cs
   nonserializedattribute.cs
   ...initenumberexception.cs
   notimplementedexception.cs
   notsupportedexception.cs
   nullable.cs
   nullreferenceexception.cs
   number.cs
   object.cs
   objectdisposedexception.cs
   obsoleteattribute.cs
   oleautbinder.cs
   operatingsystem.cs
   ...ioncanceledexception.cs
   outofmemoryexception.cs
   overflowexception.cs
   paramarrayattribute.cs
   parsenumbers.cs
   platformid.cs
   ...otsupportedexception.cs
   random.cs
   rankexception.cs
   resid.cs
   rttype.cs
   runtimeargumenthandle.cs
   runtimehandles.cs
   sbyte.cs
   serializableattribute.cs
   sharedstatics.cs
   single.cs
   stackoverflowexception.cs
   string.cs
   stringcomparer.cs
   stringcomparison.cs
   stringfreezingattribute.cs
   systemexception.cs
   threadattributes.cs
   threadstaticattribute.cs
   throwhelper.cs
   timeoutexception.cs
   timespan.cs
   timezone.cs
   type.cs
   typecode.cs
   typedreference.cs
   ...tializationexception.cs
   typeloadexception.cs
   typeunloadedexception.cs
   uint16.cs
   uint32.cs
   uint64.cs
   uintptr.cs
   ...rizedaccessexception.cs
   ...edexceptioneventargs.cs
   ...xceptioneventhandler.cs
   ...yserializationholder.cs
   unsafecharbuffer.cs
   valuetype.cs
   variant.cs
   version.cs
   void.cs
   weakreference.cs
   ...gnorememberattribute.cs

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
// ==++==
// 
//   
//    Copyright (c) 2006 Microsoft Corporation.  All rights reserved.
//   
//    The use and distribution terms for this software are contained in the file
//    named license.txt, which can be found in the root of this distribution.
//    By using this software in any fashion, you are agreeing to be bound by the
//    terms of this license.
//   
//    You must not remove this notice, or any other, from this software.
//   
// 
// ==--==
/*=============================================================================
**
** Class: AppDomain
**
**
** Purpose: Domains represent an application within the runtime. Objects can 
**          not be shared between domains and each domain can be configured
**          independently. 
**
**
=============================================================================*/

namespace System {
    using System;
    using System.Reflection;
    using System.Runtime;
    using System.Runtime.Hosting;
    using System.Runtime.CompilerServices;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Contexts;
    using System.Security;
    using System.Security.Permissions;
    using System.Security.Principal;
    using System.Security.Policy;
    using System.Security.Util;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Runtime.InteropServices;
    using System.Runtime.Remoting;   
    using Context = System.Runtime.Remoting.Contexts.Context;
    using System.Reflection.Emit;
    using Message = System.Runtime.Remoting.Messaging.Message;
    using CultureInfo = System.Globalization.CultureInfo;
    using System.IO;
    using BinaryFormatter = System.Runtime.Serialization.Formatters.Binary.BinaryFormatter;
    using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm;
    using System.Text;
    using Microsoft.Win32;
    using System.Runtime.ConstrainedExecution;
    using System.Runtime.Versioning;

    [ComVisible(true)]
    public class ResolveEventArgs : EventArgs
    {
        private String _Name;

        public String Name {
            get {
                return _Name;
            }
        }

        public ResolveEventArgs(String name)
        {
            _Name = name;
        }
    }

    [ComVisible(true)]
    public class AssemblyLoadEventArgs : EventArgs
    {
        private Assembly _LoadedAssembly;

        public Assembly LoadedAssembly {
            get {
                return _LoadedAssembly;
            }
        }

        public AssemblyLoadEventArgs(Assembly loadedAssembly)
        {
            _LoadedAssembly = loadedAssembly;
        }
    }


    [Serializable()]
    [ComVisible(true)]
    public delegate Assembly ResolveEventHandler(Object sender, ResolveEventArgs args);

    [Serializable()]
    [ComVisible(true)]
    public delegate void AssemblyLoadEventHandler(Object sender, AssemblyLoadEventArgs args);

    [Serializable()]
    [ComVisible(true)]
    public delegate void AppDomainInitializer(string[] args);

    internal class AppDomainInitializerInfo
    {
        internal class ItemInfo
        {
            public string TargetTypeAssembly;
            public string TargetTypeName;
            public string MethodName;
        }

        internal ItemInfo[] Info;

        internal AppDomainInitializerInfo(AppDomainInitializer init)
        {
            Info=null;
            if (init==null)
                return;
            ArrayList itemInfo=new ArrayList();
            ArrayList nestedDelegates=new ArrayList();
            nestedDelegates.Add(init);
            int idx=0;
 
            while (nestedDelegates.Count>idx)
            {
                AppDomainInitializer curr=(AppDomainInitializer)nestedDelegates[idx++];
                Delegate[] list= curr.GetInvocationList();
                for (int i=0;i<list.Length;i++)
                {
                    if (!list[i].Method.IsStatic) 
                    {
                        if(list[i].Target==null)
                            continue;
                    
                        AppDomainInitializer nested = list[i].Target as AppDomainInitializer;
                        if (nested!=null)
                            nestedDelegates.Add(nested);
                        else
                            throw new ArgumentException(Environment.GetResourceString("Arg_MustBeStatic"),
                               list[i].Method.ReflectedType.FullName+"::"+list[i].Method.Name);
                    }
                    else
                    {
                        ItemInfo info=new ItemInfo();
                        info.TargetTypeAssembly=list[i].Method.ReflectedType.Module.Assembly.FullName;
                        info.TargetTypeName=list[i].Method.ReflectedType.FullName;
                        info.MethodName=list[i].Method.Name;
                        itemInfo.Add(info);
                    }
                    
                }
            }

            Info=(ItemInfo[])itemInfo.ToArray(typeof(ItemInfo));            
        }
        
        internal AppDomainInitializer Unwrap()
        {
            if (Info==null)
                return null;
            AppDomainInitializer retVal=null;
            new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
            for (int i=0;i<Info.Length;i++)
            {
                Assembly assembly=Assembly.Load(Info[i].TargetTypeAssembly);
                AppDomainInitializer newVal=(AppDomainInitializer)Delegate.CreateDelegate(typeof(AppDomainInitializer),
                        assembly.GetType(Info[i].TargetTypeName),
                        Info[i].MethodName);
                if(retVal==null)
                    retVal=newVal;
                else
                    retVal+=newVal;
            }
            return retVal;
        }
    }


    [ClassInterface(ClassInterfaceType.None)]
    [ComDefaultInterface(typeof(System._AppDomain))]
    [ComVisible(true)]
    public sealed class AppDomain : MarshalByRefObject, _AppDomain, IEvidenceFactory
    {
        // Domain security information
        // These fields initialized from the other side only. (NOTE: order 
        // of these fields cannot be changed without changing the layout in 
        // the EE)

        private AppDomainManager _domainManager;
        private Hashtable        _LocalStore;
        private AppDomainSetup   _FusionStore;
        private Evidence         _SecurityIdentity;
#pragma warning disable 169
        private Object[]         _Policies; // Called from the VM.
#pragma warning restore 169
        
        [method:SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
        public event AssemblyLoadEventHandler AssemblyLoad;
        [method:SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
        public event ResolveEventHandler TypeResolve;
        [method:SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
        public event ResolveEventHandler ResourceResolve;
        [method:SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
        public event ResolveEventHandler AssemblyResolve;

        [method:SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
        public event ResolveEventHandler ReflectionOnlyAssemblyResolve;

        private Context          _DefaultContext;


        private IPrincipal       _DefaultPrincipal;
        private DomainSpecificRemotingData _RemotingData;
        private EventHandler     _processExit;
        private EventHandler     _domainUnload;
        private UnhandledExceptionEventHandler _unhandledException;

#pragma warning disable 169
        private IntPtr           _dummyField;                   // this is an unmanaged pointer (AppDomain * m_pDomain)` used from the VM.
#pragma warning restore 169
        private PrincipalPolicy  _PrincipalPolicy;              // this is an enum
        private bool             _HasSetPolicy;

        // this method is required so Object.GetType is not made virtual by the compiler
        public new Type GetType()
        {
            return base.GetType();
        }
        
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private static extern string nGetDomainManagerAsm ();
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private static extern string nGetDomainManagerType ();
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private static extern void nSetHostSecurityManagerFlags (HostSecurityManagerOptions flags);
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private static extern void nSetSecurityHomogeneousFlag ();

        // Called from the VM during the default domain initialization phase.
        private void SetDefaultDomainManager (string fullName, string[] manifestPaths, string[] activationData) {
            SetDomainManager(null, null, IntPtr.Zero, false);
        }

        // Called for every AppDomain (including the default domain) to initialize 
        // the AppDomainManager instance and security of the AppDomain.
        private void SetDomainManager (Evidence providedSecurityInfo, Evidence creatorsSecurityInfo, IntPtr parentSecurityDescriptor, bool publishAppDomain) {

            // Create the AppDomainManager for the AppDomain if specified.
            string domainManagerAssemblyName = nGetDomainManagerAsm ();
            string domainManagerTypeName = nGetDomainManagerType ();

            if (domainManagerAssemblyName != null && domainManagerTypeName != null)
                _domainManager = CreateDomainManager(domainManagerAssemblyName, domainManagerTypeName);

            AppDomainSetup adSetup = FusionStore;
            // Call AppDomainManager initialization -- runs host custom code.
            if (_domainManager != null) {
                // Call InitializeNewDomain and register the AppDomainManager with the host if needed.
                _domainManager.InitializeNewDomain(adSetup);
                AppDomainManagerInitializationOptions flags = _domainManager.InitializationFlags;
                if ((flags & AppDomainManagerInitializationOptions.RegisterWithHost) == AppDomainManagerInitializationOptions.RegisterWithHost)
                    _domainManager.nRegisterWithHost();
            }


            // Set the new evidence to the default loader behavior.
            Evidence newAppDomainEvidence = (providedSecurityInfo != null ? providedSecurityInfo : creatorsSecurityInfo);
            if (_domainManager != null) {
                // Give the host a chance to alter the AppDomain evidence
                HostSecurityManager securityManager = _domainManager.HostSecurityManager;
                if (securityManager != null) {
                    nSetHostSecurityManagerFlags (securityManager.Flags);
                    if ((securityManager.Flags & HostSecurityManagerOptions.HostAppDomainEvidence) == HostSecurityManagerOptions.HostAppDomainEvidence)
                        newAppDomainEvidence = securityManager.ProvideAppDomainEvidence(newAppDomainEvidence);
                }
            }

            // Set the evidence on the managed side
            _SecurityIdentity = newAppDomainEvidence;

            // Set the evidence of the AppDomain in the VM.
            // Also, now that the initialization is complete, signal that to the security system.
            // Finish the AppDomain initialization and resolve the policy for the AppDomain evidence.
            nSetupDomainSecurity(newAppDomainEvidence, parentSecurityDescriptor, publishAppDomain);

            // The AppDomain is now resolved. Go ahead and set the PolicyLevel
            // from the HostSecurityManager if specified.
            if (_domainManager != null)
                RunDomainManagerPostInitialization(_domainManager);
        }

        private AppDomainManager CreateDomainManager (string domainManagerAssemblyName, string domainManagerTypeName) {
            AppDomainManager domainManager = null;
            try {
                domainManager = CreateInstanceAndUnwrap(domainManagerAssemblyName, domainManagerTypeName) as AppDomainManager;
            }
            catch (FileNotFoundException) {}
            catch (TypeLoadException) {}
            finally {
                if (domainManager == null)
                    throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"));
            }
            return domainManager;
        }

        private void RunDomainManagerPostInitialization (AppDomainManager domainManager) {
            // force creation of the HostExecutionContextManager for the current AppDomain
            HostExecutionContextManager contextManager = domainManager.HostExecutionContextManager;

            HostSecurityManager securityManager = domainManager.HostSecurityManager;
            if (securityManager != null) {
                if ((securityManager.Flags & HostSecurityManagerOptions.HostPolicyLevel) == HostSecurityManagerOptions.HostPolicyLevel) {
                    // set AppDomain policy if specified
                    PolicyLevel level = securityManager.DomainPolicy;
                    if (level != null)
                        SetAppDomainPolicy(level);
                }
            }
        }


        // This method is called from CorHost2::ExecuteApplication to activate a ClickOnce application in the default AppDomain.
        private int ActivateApplication () {
            return 0;
        }

        public AppDomainManager DomainManager {
            [SecurityPermission(SecurityAction.LinkDemand, ControlDomainPolicy=true)]
            get {
                return _domainManager;
            }
        }

        internal HostSecurityManager HostSecurityManager {
            get {
                HostSecurityManager securityManager = null;
                AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
                if (domainManager != null)
                    securityManager = domainManager.HostSecurityManager;

                if (securityManager == null)
                    securityManager = new HostSecurityManager();
                return securityManager;
            }
        }

        private Assembly ResolveAssemblyForIntrospection(Object sender, ResolveEventArgs args)
        {
            return Assembly.ReflectionOnlyLoad(ApplyPolicy(args.Name));
        }

        private void EnableResolveAssembliesForIntrospection()
        {
            CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(ResolveAssemblyForIntrospection);
        }

       /**********************************************
        * If an AssemblyName has a public key specified, the assembly is assumed
        * to have a strong name and a hash will be computed when the assembly
        * is saved.
        **********************************************/
        public AssemblyBuilder DefineDynamicAssembly(
            AssemblyName            name,
            AssemblyBuilderAccess   access)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return InternalDefineDynamicAssembly(name, access, null,
                                                 null, null, null, null, ref stackMark);
        }
    
        public AssemblyBuilder DefineDynamicAssembly(
            AssemblyName            name,
            AssemblyBuilderAccess   access,
            String                  dir)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return InternalDefineDynamicAssembly(name, access, dir,
                                                 null, null, null, null,
                                                 ref stackMark);
        }
    
        public AssemblyBuilder DefineDynamicAssembly(
            AssemblyName            name,
            AssemblyBuilderAccess   access,
            Evidence                evidence)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return InternalDefineDynamicAssembly(name, access, null,
                                                 evidence, null, null, null,
                                                 ref stackMark);
        }
    
        public AssemblyBuilder DefineDynamicAssembly(
            AssemblyName            name,
            AssemblyBuilderAccess   access,
            PermissionSet           requiredPermissions,
            PermissionSet           optionalPermissions,
            PermissionSet           refusedPermissions)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return InternalDefineDynamicAssembly(name, access, null, null,
                                                 requiredPermissions,
                                                 optionalPermissions,
                                                 refusedPermissions,
                                                 ref stackMark);
        }
    
        public AssemblyBuilder DefineDynamicAssembly(
            AssemblyName            name,
            AssemblyBuilderAccess   access,
            String                  dir,
            Evidence                evidence)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return InternalDefineDynamicAssembly(name, access, dir, evidence,
                                                 null, null, null, ref stackMark);
        }
    
        public AssemblyBuilder DefineDynamicAssembly(
            AssemblyName            name,
            AssemblyBuilderAccess   access,
            String                  dir,
            PermissionSet           requiredPermissions,
            PermissionSet           optionalPermissions,
            PermissionSet           refusedPermissions)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return InternalDefineDynamicAssembly(name, access, dir, null,
                                                 requiredPermissions,
                                                 optionalPermissions,
                                                 refusedPermissions,
                                                 ref stackMark);
        }
    
        public AssemblyBuilder DefineDynamicAssembly(
            AssemblyName            name,
            AssemblyBuilderAccess   access,
            Evidence                evidence,
            PermissionSet           requiredPermissions,
            PermissionSet           optionalPermissions,
            PermissionSet           refusedPermissions)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return InternalDefineDynamicAssembly(name, access, null,
                                                 evidence,
                                                 requiredPermissions,
                                                 optionalPermissions,
                                                 refusedPermissions,
                                                 ref stackMark);
        }
    
        public AssemblyBuilder DefineDynamicAssembly(
            AssemblyName            name,
            AssemblyBuilderAccess   access,
            String                  dir,
            Evidence                evidence,
            PermissionSet           requiredPermissions,
            PermissionSet           optionalPermissions,
            PermissionSet           refusedPermissions)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return InternalDefineDynamicAssembly(name, access, dir,
                                                 evidence,
                                                 requiredPermissions,
                                                 optionalPermissions,
                                                 refusedPermissions,
                                                 ref stackMark);
        }


        public AssemblyBuilder DefineDynamicAssembly(
            AssemblyName            name,
            AssemblyBuilderAccess   access,
            String                  dir,
            Evidence                evidence,
            PermissionSet           requiredPermissions,
            PermissionSet           optionalPermissions,
            PermissionSet           refusedPermissions,
            bool                    isSynchronized)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            AssemblyBuilder assemblyBuilder = InternalDefineDynamicAssembly(name,
                                                                            access,
                                                                            dir,
                                                                            evidence,
                                                                            requiredPermissions,
                                                                            optionalPermissions,
                                                                            refusedPermissions,
                                                                            ref stackMark);
            assemblyBuilder.m_assemblyData.m_isSynchronized = isSynchronized;
            return assemblyBuilder;
        }


        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private extern String nApplyPolicy(AssemblyName an);
        
        // Return the assembly name that results from applying policy.
        [ComVisible(false)]
        public String ApplyPolicy(String assemblyName)
        {
            AssemblyName asmName = new AssemblyName(assemblyName);  

            byte[] pk = asmName.GetPublicKeyToken();
            if (pk == null)
                pk = asmName.GetPublicKey();

            // Simply-named assemblies cannot have policy, so for those,
            // we simply return the passed-in assembly name.
            if ((pk == null) || (pk.Length == 0))
                return assemblyName;
            else
                return nApplyPolicy(asmName);
        }


        public ObjectHandle CreateInstance(String assemblyName,
                                           String typeName)
                                         
        {
            // jit does not check for that, so we should do it ...
            if (this == null)
                throw new NullReferenceException();

            if (assemblyName == null)
                throw new ArgumentNullException("assemblyName");

            return Activator.CreateInstance(assemblyName,
                                            typeName);
        }

        internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName, string typeName) {
            PermissionSet.s_fullTrust.Assert();
            return CreateInstance(assemblyName, typeName);
        }

        public ObjectHandle CreateInstanceFrom(String assemblyFile,
                                               String typeName)
                                         
        {
            // jit does not check for that, so we should do it ...
            if (this == null)
                throw new NullReferenceException();

            return Activator.CreateInstanceFrom(assemblyFile,
                                                typeName);
        }

        internal ObjectHandle InternalCreateInstanceFromWithNoSecurity (string assemblyName, string typeName) {
            PermissionSet.s_fullTrust.Assert();
            return CreateInstanceFrom(assemblyName, typeName);
        }


        public ObjectHandle CreateInstance(String assemblyName,
                                           String typeName,
                                           Object[] activationAttributes)
                                         
        {
            // jit does not check for that, so we should do it ...
            if (this == null)
                throw new NullReferenceException();

            if (assemblyName == null)
                throw new ArgumentNullException("assemblyName");

            return Activator.CreateInstance(assemblyName,
                                            typeName,
                                            activationAttributes);
        }
                                  
        public ObjectHandle CreateInstanceFrom(String assemblyFile,
                                               String typeName,
                                               Object[] activationAttributes)
                                               
        {
            // jit does not check for that, so we should do it ...
            if (this == null)
                throw new NullReferenceException();

            return Activator.CreateInstanceFrom(assemblyFile,
                                                typeName,
                                                activationAttributes);
        }
                                         
        public ObjectHandle CreateInstance(String assemblyName, 
                                           String typeName, 
                                           bool ignoreCase,
                                           BindingFlags bindingAttr, 
                                           Binder binder,
                                           Object[] args,
                                           CultureInfo culture,
                                           Object[] activationAttributes,
                                           Evidence securityAttributes)
        {
            // jit does not check for that, so we should do it ...
            if (this == null)
                throw new NullReferenceException();
            
            if (assemblyName == null)
                throw new ArgumentNullException("assemblyName");

            return Activator.CreateInstance(assemblyName,
                                            typeName,
                                            ignoreCase,
                                            bindingAttr,
                                            binder,
                                            args,
                                            culture,
                                            activationAttributes,
                                            securityAttributes);
        }

        internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName, 
                                                                    string typeName,
                                                                    bool ignoreCase,
                                                                    BindingFlags bindingAttr,
                                                                    Binder binder,
                                                                    Object[] args,
                                                                    CultureInfo culture,
                                                                    Object[] activationAttributes,
                                                                    Evidence securityAttributes) {
            PermissionSet.s_fullTrust.Assert();
            return CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
        }

        public ObjectHandle CreateInstanceFrom(String assemblyFile,
                                               String typeName, 
                                               bool ignoreCase,
                                               BindingFlags bindingAttr, 
                                               Binder binder,
                                               Object[] args,
                                               CultureInfo culture,
                                               Object[] activationAttributes,
                                               Evidence securityAttributes)

        {
            // jit does not check for that, so we should do it ...
            if (this == null)
                throw new NullReferenceException();

            return Activator.CreateInstanceFrom(assemblyFile,
                                                typeName,
                                                ignoreCase,
                                                bindingAttr,
                                                binder,
                                                args,
                                                culture,
                                                activationAttributes,
                                                securityAttributes);
        }

        internal ObjectHandle InternalCreateInstanceFromWithNoSecurity (string assemblyName, 
                                                                        string typeName,
                                                                        bool ignoreCase,
                                                                        BindingFlags bindingAttr,
                                                                        Binder binder,
                                                                        Object[] args,
                                                                        CultureInfo culture,
                                                                        Object[] activationAttributes,
                                                                        Evidence securityAttributes) {
            PermissionSet.s_fullTrust.Assert();
            return CreateInstanceFrom(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
        }

        public Assembly Load(AssemblyName assemblyRef)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return Assembly.InternalLoad(assemblyRef, null, ref stackMark, false);
        }
        
        public Assembly Load(String assemblyString)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return Assembly.InternalLoad(assemblyString, null, ref stackMark, false);
        }

        public Assembly Load(byte[] rawAssembly)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return Assembly.nLoadImage(rawAssembly,
                                       null, // symbol store
                                       null, // evidence
                                       ref stackMark,
                                       false
                                      );

        }

        public Assembly Load(byte[] rawAssembly,
                             byte[] rawSymbolStore)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return Assembly.nLoadImage(rawAssembly,
                                       rawSymbolStore,
                                       null, // evidence
                                       ref stackMark,
                                       false // fIntrospection
                                      );
        }

        [SecurityPermissionAttribute( SecurityAction.Demand, ControlEvidence = true )]
        public Assembly Load(byte[] rawAssembly,
                             byte[] rawSymbolStore,
                             Evidence securityEvidence)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return Assembly.nLoadImage(rawAssembly,
                                       rawSymbolStore,
                                       securityEvidence,
                                       ref stackMark,
                                       false // fIntrospection
                                       );
        }

        public Assembly Load(AssemblyName assemblyRef,
                             Evidence assemblySecurity)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return Assembly.InternalLoad(assemblyRef, assemblySecurity, ref stackMark, false);
        }

        public Assembly Load(String assemblyString,
                             Evidence assemblySecurity)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return Assembly.InternalLoad(assemblyString, assemblySecurity, ref stackMark, false);
        }

        public int ExecuteAssembly(String assemblyFile)
        {
            return ExecuteAssembly(assemblyFile, null, null);
        }

        public int ExecuteAssembly(String assemblyFile,
                                   Evidence assemblySecurity)
        {
            return ExecuteAssembly(assemblyFile, assemblySecurity, null);
        }
    
        public int ExecuteAssembly(String assemblyFile,
                                   Evidence assemblySecurity,
                                   String[] args)
        {
            Assembly assembly = Assembly.LoadFrom(assemblyFile, assemblySecurity);
    
            if (args == null)
                args = new String[0];

            return nExecuteAssembly(assembly, args);
        }

        public int ExecuteAssembly(String assemblyFile,
                                   Evidence assemblySecurity,
                                   String[] args,
                                   byte[] hashValue, 
                                   AssemblyHashAlgorithm hashAlgorithm)
        {
            Assembly assembly = Assembly.LoadFrom(assemblyFile, 
                                                  assemblySecurity,
                                                  hashValue,
                                                  hashAlgorithm);
            if (args == null)
                args = new String[0];

            return nExecuteAssembly(assembly, args);
        }

        public int ExecuteAssemblyByName(String assemblyName)
        {
            return ExecuteAssemblyByName(assemblyName, null, null);
        }

        public int ExecuteAssemblyByName(String assemblyName,
                                         Evidence assemblySecurity)
        {
            return ExecuteAssemblyByName(assemblyName, assemblySecurity, null);
        }

        public int ExecuteAssemblyByName(String assemblyName,
                                         Evidence assemblySecurity,
                                         params String[] args)
        {
            Assembly assembly = Assembly.Load(assemblyName, assemblySecurity);
    
            if (args == null)
                args = new String[0];

            return nExecuteAssembly(assembly, args);
        }

        public int ExecuteAssemblyByName(AssemblyName assemblyName,
                                         Evidence assemblySecurity,
                                         params String[] args)
        {
            Assembly assembly = Assembly.Load(assemblyName, assemblySecurity);
    
            if (args == null)
                args = new String[0];

            return nExecuteAssembly(assembly, args);
        }

        public static AppDomain CurrentDomain
        {
            get { return Thread.GetDomain(); }
        }

        public Evidence Evidence
        {
            [SecurityPermissionAttribute(SecurityAction.Demand, ControlEvidence = true)]
            get {
                if (_SecurityIdentity == null) {
                    if (IsDefaultAppDomain()) {
                        //
                        // V1.x compatibility: the evidence of the default
                        // AppDomain is that of the entry assembly.
                        //
                        Assembly entryAsm = Assembly.GetEntryAssembly();
                        if (entryAsm != null)
                            return entryAsm.Evidence;
                        else
                            return new Evidence();
                    }
                    if (nIsDefaultAppDomainForSecurity()) {
                        //
                        // V1.x compatibility: If this is an AppDomain created 
                        // by the default appdomain without an explicit evidence
                        // then reuse the evidence of the default AppDomain.
                        //
                        return GetDefaultDomain().Evidence;
                    }
                }

                Evidence ev = this.InternalEvidence;
                return (ev == null ? ev : ev.Copy());
            }
        }

        internal Evidence InternalEvidence
        {
            get {
                return _SecurityIdentity;
            }
        }

        // Should return a monotonically increasing appdomain ID that is unique for
        // the lifetime of the process.
        [MethodImpl(MethodImplOptions.InternalCall)]
        internal extern uint GetAppDomainId();

        public String FriendlyName
        {
            get { return nGetFriendlyName(); }
        } 

        public String BaseDirectory
        {
            get {
                return FusionStore.ApplicationBase;
            }
        }

        public String RelativeSearchPath
        {
            get { return FusionStore.PrivateBinPath; }
        }

        public bool ShadowCopyFiles
        {
            get {
                String s = FusionStore.ShadowCopyFiles;
                if((s != null) && 
                   (String.Compare(s, "true", StringComparison.OrdinalIgnoreCase) == 0))
                    return true;
                else
                    return false;
            }
        }

        public override String ToString()
        {
            StringBuilder sb = new StringBuilder();
            
            String fn = nGetFriendlyName();
            if (fn != null) {
                sb.Append(Environment.GetResourceString("Loader_Name") + fn);
                sb.Append(Environment.NewLine);
            }
    
            if(_Policies == null || _Policies.Length == 0) 
                sb.Append(Environment.GetResourceString("Loader_NoContextPolicies")
                          + Environment.NewLine);
            else {
                sb.Append(Environment.GetResourceString("Loader_ContextPolicies")
                          + Environment.NewLine);
                for(int i = 0;i < _Policies.Length; i++) {
                    sb.Append(_Policies[i]);
                    sb.Append(Environment.NewLine);
                }
            }
    
            return sb.ToString();
        }
        
        public Assembly[] GetAssemblies()
        {
            return nGetAssemblies(false /* forIntrospection */);
        }


        public Assembly[] ReflectionOnlyGetAssemblies()
        {
            return nGetAssemblies(true /* forIntrospection */);
        }



        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private extern Assembly[] nGetAssemblies(bool forIntrospection);

    // this is true when we've nuked the handles etc so really can't do anything
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern bool IsUnloadingForcedFinalize();

    // this is true when we've just started going through the finalizers and are forcing objects to finalize
    // so must be aware that certain infrastructure may have gone away
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        public extern bool IsFinalizingForUnload();

        // Appends the following string to the private path. Valid paths
        // are of the form "bin;util/i386" etc.
        [Obsolete("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. http://go.microsoft.com/fwlink/?linkid=14202")]
        [method:SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
        public void AppendPrivatePath(String path)
        {
            if(path == null || path.Length == 0)
                return;

            String current = FusionStore.Value[(int) AppDomainSetup.LoaderInformation.PrivateBinPathValue];
            StringBuilder appendPath = new StringBuilder();

            if(current != null && current.Length > 0) {
                // See if the last character is a separator
                appendPath.Append(current);
                if((current[current.Length-1] != Path.PathSeparator) &&
                   (path[0] != Path.PathSeparator))
                    appendPath.Append(Path.PathSeparator);
            }
            appendPath.Append(path);

            String result = appendPath.ToString();
            InternalSetPrivateBinPath(result);
        }

        
        [Obsolete("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. http://go.microsoft.com/fwlink/?linkid=14202")]
        [method:SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
        public void ClearPrivatePath()
        {
            InternalSetPrivateBinPath(String.Empty);
        }

        [Obsolete("AppDomain.ClearShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. http://go.microsoft.com/fwlink/?linkid=14202")]
        [method:SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
        public void ClearShadowCopyPath()
        {
            InternalSetShadowCopyPath(String.Empty);
        }

        [Obsolete("AppDomain.SetCachePath has been deprecated. Please investigate the use of AppDomainSetup.CachePath instead. http://go.microsoft.com/fwlink/?linkid=14202")]
        [method:SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
        public void SetCachePath(String path)
        {
            InternalSetCachePath(path);
        }

        [method:SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
        [ResourceExposure(ResourceScope.AppDomain)]
        [ResourceConsumption(ResourceScope.AppDomain)]
        public void SetData (string name, object data) {
            SetDataHelper(name, data, null);
        }

        [method:SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
        [ResourceExposure(ResourceScope.AppDomain)]
        [ResourceConsumption(ResourceScope.AppDomain)]
        public void SetData (string name, object data, IPermission permission) {
            SetDataHelper(name, data, permission);
        }

        [ResourceExposure(ResourceScope.AppDomain)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.AppDomain)]
        private void SetDataHelper (string name, object data, IPermission permission) {
            if (name == null)
                throw new ArgumentNullException("name");

            //
            // Synopsis:
            //   IgnoreSystemPolicy is provided as a legacy flag to allow callers to
            //   skip enterprise, machine and user policy levels. When this flag is set,
            //   any demands triggered in this AppDomain will be evaluated against the
            //   AppDomain CAS policy level that is set on the AppDomain.
            // Security Requirements:
            //   The caller needs to be fully trusted in order to be able to set
            //   this legacy mode.
            // Remarks:
            //   There needs to be an AppDomain policy level set before this compat
            //   switch can be set on the AppDomain.
            //

            if (name.Equals("IgnoreSystemPolicy")) {
                lock (this) {
                    if (!_HasSetPolicy)
                        throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData"));
                }
                new PermissionSet(PermissionState.Unrestricted).Demand();
            }

            int key = AppDomainSetup.Locate(name);

            if(key == -1)
                LocalStore[name] = new object[] {data, permission};
            else {
                if (permission != null)
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData"));
                // Be sure to call these properties, not Value, since
                // these do more than call Value.
                switch(key) {
                case (int) AppDomainSetup.LoaderInformation.DynamicBaseValue:
                    FusionStore.DynamicBase = (string) data;
                    break;
                case (int) AppDomainSetup.LoaderInformation.DevPathValue:
                    FusionStore.DeveloperPath = (string) data;
                    break;
                case (int) AppDomainSetup.LoaderInformation.ShadowCopyDirectoriesValue:
                    FusionStore.ShadowCopyDirectories = (string) data;
                    break;
                case (int) AppDomainSetup.LoaderInformation.DisallowPublisherPolicyValue:
                    if(data != null)
                        FusionStore.DisallowPublisherPolicy = true;
                    else
                        FusionStore.DisallowPublisherPolicy = false;
                    break;
                case (int) AppDomainSetup.LoaderInformation.DisallowCodeDownloadValue:
                    if (data != null)
                         FusionStore.DisallowCodeDownload = true;
                    else
                        FusionStore.DisallowCodeDownload = false;
                    break;
                case (int) AppDomainSetup.LoaderInformation.DisallowBindingRedirectsValue:
                    if(data != null)
                        FusionStore.DisallowBindingRedirects = true;
                    else
                        FusionStore.DisallowBindingRedirects = false;
                    break;
                case (int) AppDomainSetup.LoaderInformation.DisallowAppBaseProbingValue:
                    if(data != null)
                        FusionStore.DisallowApplicationBaseProbing = true;
                    else
                        FusionStore.DisallowApplicationBaseProbing = false;
                    break;
                case (int) AppDomainSetup.LoaderInformation.ConfigurationBytesValue:
                    FusionStore.SetConfigurationBytes((byte[]) data);
                    break;
                default:
                    FusionStore.Value[key] = (string) data;
                    break;
                }
            }
        }

        [ResourceExposure(ResourceScope.AppDomain)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        public Object GetData(string name)
        {
            if(name == null)
                throw new ArgumentNullException("name");

            int key = AppDomainSetup.Locate(name);
            if(key == -1) {
                if(name.Equals(AppDomainSetup.LoaderOptimizationKey))
                    return FusionStore.LoaderOptimization;
                else {
                    object[] data = (object[]) LocalStore[name];
                    if (data == null)
                        return null;
                    if (data[1] != null) {
                        IPermission permission = (IPermission) data[1];
                        permission.Demand();
                    }
                    return data[0];
                }
            }
           else {
                // Be sure to call these properties, not Value, so
                // that the appropriate permission demand will be done
                switch(key) {
                case (int) AppDomainSetup.LoaderInformation.ApplicationBaseValue:
                    return FusionStore.ApplicationBase;
                case (int) AppDomainSetup.LoaderInformation.ConfigurationFileValue:
                    return FusionStore.ConfigurationFile;
                case (int) AppDomainSetup.LoaderInformation.DynamicBaseValue:
                    return FusionStore.DynamicBase;
                case (int) AppDomainSetup.LoaderInformation.DevPathValue:
                    return FusionStore.DeveloperPath;
                case (int) AppDomainSetup.LoaderInformation.ApplicationNameValue:
                    return FusionStore.ApplicationName;
                case (int) AppDomainSetup.LoaderInformation.PrivateBinPathValue:
                    return FusionStore.PrivateBinPath;
                case (int) AppDomainSetup.LoaderInformation.PrivateBinPathProbeValue:
                    return FusionStore.PrivateBinPathProbe;
                case (int) AppDomainSetup.LoaderInformation.ShadowCopyDirectoriesValue:
                    return FusionStore.ShadowCopyDirectories;
                case (int) AppDomainSetup.LoaderInformation.ShadowCopyFilesValue:
                    return FusionStore.ShadowCopyFiles;
                case (int) AppDomainSetup.LoaderInformation.CachePathValue:
                    return FusionStore.CachePath;
                case (int) AppDomainSetup.LoaderInformation.LicenseFileValue:
                    return FusionStore.LicenseFile;
                case (int) AppDomainSetup.LoaderInformation.DisallowPublisherPolicyValue:
                    return FusionStore.DisallowPublisherPolicy;
                case (int) AppDomainSetup.LoaderInformation.DisallowCodeDownloadValue:
                    return FusionStore.DisallowCodeDownload;
                case (int) AppDomainSetup.LoaderInformation.DisallowBindingRedirectsValue:
                    return FusionStore.DisallowBindingRedirects;
                case (int) AppDomainSetup.LoaderInformation.DisallowAppBaseProbingValue:
                    return FusionStore.DisallowApplicationBaseProbing;
                case (int) AppDomainSetup.LoaderInformation.ConfigurationBytesValue:
                    return FusionStore.GetConfigurationBytes();
                default:
#if _DEBUG
                    BCLDebug.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()");
#endif
                    return null;
                }
            }
        }
        
        [Obsolete("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread.  http://go.microsoft.com/fwlink/?linkid=14202", false)]
        [DllImport(Microsoft.Win32.Win32Native.KERNEL32)]
        public static extern int GetCurrentThreadId();

        [SecurityPermissionAttribute( SecurityAction.Demand, ControlAppDomain = true ),
         ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.MayFail)]            
        public static void Unload(AppDomain domain)
        {
            if (domain == null)
                throw new ArgumentNullException("domain");

            try {
                Int32 domainID = AppDomain.GetIdForUnload(domain);
                if (domainID==0)
                    throw new CannotUnloadAppDomainException();
                AppDomain.nUnload(domainID);
            }
            catch(Exception e) {
                throw e;    // throw it again to reset stack trace
            }
        }

        // Explicitly set policy for a domain (providing policy hasn't been set
        // previously). Making this call will guarantee that previously loaded
        // assemblies will be granted permissions based on the default machine
        // policy that was in place prior to this call.
        [SecurityPermission(SecurityAction.LinkDemand, ControlDomainPolicy=true)]
        public void SetAppDomainPolicy(PolicyLevel domainPolicy)
        {
            if (domainPolicy == null)
                throw new ArgumentNullException("domainPolicy");

            // Check that policy has not been set previously.
            lock (this) {
                if (_HasSetPolicy)
                    throw new PolicyException(Environment.GetResourceString("Policy_PolicyAlreadySet"));
                _HasSetPolicy = true;

                // Make sure that the loader allows us to change security policy
                // at this time (this will throw if not.)
                nChangeSecurityPolicy();
            }

            // Add the new policy level.
            SecurityManager.PolicyManager.AddLevel(domainPolicy);
        }


        // Set the default principal object to be attached to threads if they
        // attempt to bind to a principal while executing in this appdomain. The
        // default can only be set once.
        [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)]
        public void SetThreadPrincipal(IPrincipal principal)
        {
            if (principal == null)
                throw new ArgumentNullException("principal");

            lock (this) {
                // Check that principal has not been set previously.
                if (_DefaultPrincipal != null)
                    throw new PolicyException(Environment.GetResourceString("Policy_PrincipalTwice"));

                _DefaultPrincipal = principal;
            }
        }

        // Similar to the above, but sets the class of principal to be created
        // instead.
        [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)]
        public void SetPrincipalPolicy(PrincipalPolicy policy)
        {
            _PrincipalPolicy = policy;
        }

        // This method gives AppDomain an infinite life time by preventing a lease from being
        // created
        public override Object InitializeLifetimeService()
        {
            return null;
        }

        // This is useful for requesting execution of some code
        // in another appDomain ... the delegate may be defined 
        // on a marshal-by-value object or a marshal-by-ref or 
        // contextBound object.
        public void DoCallBack(CrossAppDomainDelegate callBackDelegate)
        {
            if (callBackDelegate == null)
                throw new ArgumentNullException("callBackDelegate");

            callBackDelegate();        
        }


        public String DynamicDirectory
        {
            get {
                String dyndir = GetDynamicDir();
                if (dyndir != null)
                    new FileIOPermission( FileIOPermissionAccess.PathDiscovery, dyndir ).Demand();

                return dyndir;
            }
        }
        
        public static AppDomain CreateDomain(String friendlyName,
                                             Evidence securityInfo) // Optional
        {
            return CreateDomain(friendlyName,
                                securityInfo,
                                null);
        }
    
        public static AppDomain CreateDomain(String friendlyName,
                                             Evidence securityInfo, // Optional
                                             String appBasePath,
                                             String appRelativeSearchPath,
                                             bool shadowCopyFiles)
        {            
            AppDomainSetup info = new AppDomainSetup();
            info.ApplicationBase = appBasePath;
            info.PrivateBinPath = appRelativeSearchPath;
            if(shadowCopyFiles)
                info.ShadowCopyFiles = "true";

            return CreateDomain(friendlyName,
                                securityInfo,
                                info);
        }

        public static AppDomain CreateDomain(String friendlyName)
        {
            return CreateDomain(friendlyName, null, null);
        }

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        extern private String GetDynamicDir();

        // Private helpers called from unmanaged code.

        // Marshal a single object into a serialized blob.
        private static byte[] MarshalObject(Object o)
        {
            CodeAccessPermission.AssertAllPossible();

            return Serialize(o);
        }

        // Marshal two objects into serialized blobs.
        private static byte[] MarshalObjects(Object o1, Object o2, out byte[] blob2)
        {
            CodeAccessPermission.AssertAllPossible();

            byte[] blob1 = Serialize(o1);
            blob2 = Serialize(o2);
            return blob1;
        }

        // Unmarshal a single object from a serialized blob.
        private static Object UnmarshalObject(byte[] blob)
        {
            CodeAccessPermission.AssertAllPossible();

            return Deserialize(blob);
        }

        // Unmarshal two objects from serialized blobs.
        private static Object UnmarshalObjects(byte[] blob1, byte[] blob2, out Object o2)
        {
            CodeAccessPermission.AssertAllPossible();

            Object o1 = Deserialize(blob1);
            o2 = Deserialize(blob2);
            return o1;
        }

        // Helper routines.
        private static byte[] Serialize(Object o)
        {
            if (o == null)
            {
                return null;
            }
            else if (o is ISecurityEncodable)
            {
                SecurityElement element = ((ISecurityEncodable)o).ToXml();
                MemoryStream ms = new MemoryStream( 4096 );
                ms.WriteByte( 0 );
                StreamWriter writer = new StreamWriter( ms, Encoding.UTF8 );
                element.ToWriter( writer );
                writer.Flush();
                return ms.ToArray();
            }
            else
            {
                MemoryStream ms = new MemoryStream();
                ms.WriteByte( 1 );
                CrossAppDomainSerializer.SerializeObject(o, ms);
                return ms.ToArray();
            }
        }

        private static Object Deserialize(byte[] blob)
        {
            if (blob == null)
                return null;

            if (blob[0] == 0)
            {
                Parser parser = new Parser( blob, Tokenizer.ByteTokenEncoding.UTF8Tokens, 1 );
                SecurityElement root = parser.GetTopElement();
                if (root.Tag.Equals( "IPermission" ) || root.Tag.Equals( "Permission" ))
                {
                    IPermission ip = System.Security.Util.XMLUtil.CreatePermission( root, PermissionState.None, false );

                    if (ip == null)
                    {
                        BCLDebug.Assert( false, "Unable to create permission type" );
                        return null;
                    }

                    ip.FromXml( root );

                    return ip;
                }
                else if (root.Tag.Equals( "PermissionSet" ))
                {
                    PermissionSet permissionSet = new PermissionSet();

                    permissionSet.FromXml( root, false, false );

                    return permissionSet;
                }
                else if (root.Tag.Equals( "PermissionToken" ))
                {
                    PermissionToken pToken = new PermissionToken();

                    pToken.FromXml( root );

                    return pToken;
                }
                else
                {
                    BCLDebug.Assert( false, "Unexpected type found" );
                    return null;
                }

            }
            else
            {
                Object obj = null;
                using(MemoryStream stream = new MemoryStream( blob, 1, blob.Length - 1 )) {
                    obj = CrossAppDomainSerializer.DeserializeObject(stream);
                }

                BCLDebug.Assert( !(obj is IPermission), "IPermission should be xml deserialized" );
                BCLDebug.Assert( !(obj is PermissionSet), "PermissionSet should be xml deserialized" );

                return obj;
            }
        }

        private AppDomain() {
            throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Constructor));
        }

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private extern AssemblyBuilder nCreateDynamicAssembly(AssemblyName name,
                               Evidence identity,
                               ref StackCrawlMark stackMark,
                               PermissionSet requiredPermissions,
                               PermissionSet optionalPermissions,
                               PermissionSet refusedPermissions,
                               AssemblyBuilderAccess access);

        internal AssemblyBuilder InternalDefineDynamicAssembly(
            AssemblyName            name,
            AssemblyBuilderAccess   access,
            String                  dir,
            Evidence                evidence,
            PermissionSet           requiredPermissions,
            PermissionSet           optionalPermissions,
            PermissionSet           refusedPermissions,
            ref StackCrawlMark      stackMark)
        {
            if (name == null)
                throw new ArgumentNullException("name");

            if (access != AssemblyBuilderAccess.Run && access != AssemblyBuilderAccess.Save &&
                access != AssemblyBuilderAccess.RunAndSave && access != AssemblyBuilderAccess.ReflectionOnly)
                throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access), "access");

            // Set the public key from the key pair if one has been provided.
            // (Overwite any public key in the Assembly name, since it's no
            // longer valid to have a disparity).
            if (name.KeyPair != null)
                name.SetPublicKey(name.KeyPair.PublicKey);

            // If the caller is trusted they can supply identity
            // evidence for the new assembly. Otherwise we copy the
            // current grant and deny sets from the caller's assembly,
            // inject them into the new assembly and mark policy as
            // resolved. If/when the assembly is persisted and
            // reloaded, the normal rules for gathering evidence will
            // be used.
            if (evidence != null)
                new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
    
            AssemblyBuilder assemblyBuilder = nCreateDynamicAssembly(name,
                                                                     evidence,
                                                                     ref stackMark,
                                                                     requiredPermissions,
                                                                     optionalPermissions,
                                                                     refusedPermissions,
                                                                     access);

            assemblyBuilder.m_assemblyData = new AssemblyBuilderData(assemblyBuilder,
                                                                     name.Name,
                                                                     access,
                                                                     dir);
            assemblyBuilder.m_assemblyData.AddPermissionRequests(requiredPermissions,
                                                                 optionalPermissions,
                                                                 refusedPermissions);
            return assemblyBuilder;
        }

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern int nExecuteAssembly(Assembly assembly, String[] args);

        internal void CreateRemotingData()
        {
                    lock(this) {
                        if (_RemotingData == null)
                            _RemotingData = new DomainSpecificRemotingData();
                    }
        }
        
        internal DomainSpecificRemotingData RemotingData
        {
            get 
            { 
                if (_RemotingData == null) 
                    CreateRemotingData();

                return _RemotingData;
            }
        }

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private extern String nGetFriendlyName();
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private extern bool nIsDefaultAppDomainForSecurity();

        // support reliability for certain event handlers, if the target
        // methods also participate in this discipline.  If caller passes
        // an existing MulticastDelegate, then we could use a MDA to indicate
        // that reliability is not guaranteed.  But if it is a single cast
        // scenario, we can make it work.

        public event EventHandler ProcessExit
        {
            [SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
            add
            {
                if (value != null)
                {
                    RuntimeHelpers.PrepareDelegate(value);
                    lock(this)
                        _processExit += value;
                }
            }
            [SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
            remove
            {
                lock(this)
                    _processExit -= value;
            }
        }


        public event EventHandler DomainUnload
        {
            [SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
            add
            {
                if (value != null)
                {
                    RuntimeHelpers.PrepareDelegate(value);
                    lock(this)
                        _domainUnload += value;
                }
            }
            [SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
            remove
            {
                lock(this)
                    _domainUnload -= value;
            }
        }


        public event UnhandledExceptionEventHandler UnhandledException
        {
            [SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
            add
            {
                if (value != null)
                {
                    RuntimeHelpers.PrepareDelegate(value);
                    lock(this)
                        _unhandledException += value;
                }
            }
            [SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
            remove
        {
                lock(this)
                    _unhandledException -= value;
            }
        }


        private void OnAssemblyLoadEvent(Assembly LoadedAssembly)
        {
            AssemblyLoadEventHandler eventHandler=AssemblyLoad;
            if (eventHandler != null) {
                AssemblyLoadEventArgs ea = new AssemblyLoadEventArgs(LoadedAssembly);
                eventHandler(this, ea);
            }
        }
    
        private Assembly OnResourceResolveEvent(String resourceName)
        {
            ResolveEventHandler eventHandler=ResourceResolve;
            if ( eventHandler == null)
                return null;

            Delegate[] ds = eventHandler.GetInvocationList();
            int len = ds.Length;
            for (int i = 0; i < len; i++) {
                Assembly ret = ((ResolveEventHandler) ds[i])(this, new ResolveEventArgs(resourceName));
                if (ret != null)
                    return ret;              
            }

            return null;
        }
        
        private Assembly OnTypeResolveEvent(String typeName)
        {
            ResolveEventHandler eventHandler=TypeResolve;
            if (eventHandler == null)
                return null;

            Delegate[] ds = eventHandler.GetInvocationList();
            int len = ds.Length;
            for (int i = 0; i < len; i++) {
                Assembly ret = ((ResolveEventHandler) ds[i])(this, new ResolveEventArgs(typeName));
                if (ret != null)
                    return ret;
            }

            return null;
        }

        private Assembly OnAssemblyResolveEvent(String assemblyFullName)
        {
            ResolveEventHandler eventHandler=AssemblyResolve;
            if (eventHandler == null)
                return null;

            Delegate[] ds = eventHandler.GetInvocationList();
            int len = ds.Length;
            for (int i = 0; i < len; i++) {
                Assembly ret = ((ResolveEventHandler) ds[i])(this, new ResolveEventArgs(assemblyFullName));
                if (ret != null)
                    return ret;
            }

            return null;
        }

        private Assembly OnReflectionOnlyAssemblyResolveEvent(String assemblyFullName)
        {
            ResolveEventHandler eventHandler = ReflectionOnlyAssemblyResolve;
            if (eventHandler != null) {

                Delegate[] ds = eventHandler.GetInvocationList();
                int len = ds.Length;
                for (int i = 0; i < len; i++) {
                    Assembly ret = ((ResolveEventHandler) ds[i])(this, new ResolveEventArgs(assemblyFullName));
                    if (ret != null)
                        return ret;              
                }
            }

            return null;
        }

        internal AppDomainSetup FusionStore
        {
            get {
#if _DEBUG
                BCLDebug.Assert(_FusionStore != null, 
                                "Fusion store has not been correctly setup in this domain");
#endif
                return _FusionStore;
            }
        }
        
        [ResourceExposure(ResourceScope.AppDomain)]
        private Hashtable LocalStore
        {
            get { 
                if (_LocalStore != null)
                    return _LocalStore;
                else {
                    _LocalStore = Hashtable.Synchronized(new Hashtable());
                    return _LocalStore;
                }
            }
        }

        private void TurnOnBindingRedirects()
        {
            _FusionStore.DisallowBindingRedirects = false;
        }

        // This will throw a CannotUnloadAppDomainException if the appdomain is
        // in another process.
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]  
        internal static Int32 GetIdForUnload(AppDomain domain)
        {
            if (RemotingServices.IsTransparentProxy(domain))
            {
                return RemotingServices.GetServerDomainIdForProxy(domain);
            }
            else
                return domain.Id;
        }

        // Used to determine if server object context is valid in
        // x-domain remoting scenarios.
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        internal static extern bool IsDomainIdValid(Int32 id);
        
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        static internal extern AppDomain GetDefaultDomain();

        // Internal routine to retrieve the default principal object. If this is
        // called before the principal has been explicitly set, it will
        // automatically allocate a default principal based on the policy set by
        // SetPrincipalPolicy.
        internal IPrincipal GetThreadPrincipal()
        {
            IPrincipal principal = null;

            lock (this) {
                if (_DefaultPrincipal == null) {
                    switch (_PrincipalPolicy) {
                    case PrincipalPolicy.NoPrincipal:
                        principal = null;
                        break;
                    case PrincipalPolicy.UnauthenticatedPrincipal:
                        principal = new GenericPrincipal(new GenericIdentity("", ""),
                                                         new String[] {""});
                        break;
                    default:
                        principal = null;
                        break;
                    }
                }
                else
                    principal = _DefaultPrincipal;

                return principal;
            }
        }

        internal void CreateDefaultContext()
        {
                lock(this) {
                    // if it has not been created we ask the Context class to 
                    // create a new default context for this appdomain.
                    if (_DefaultContext == null)
                        _DefaultContext = Context.CreateDefaultContext();
                }            
        }

        internal Context GetDefaultContext()
        {
            if (_DefaultContext == null)
                CreateDefaultContext();
            return _DefaultContext;
        }

        [SecurityPermissionAttribute( SecurityAction.Demand, ControlAppDomain = true )]
        public static AppDomain CreateDomain(String friendlyName,
                                             Evidence securityInfo,
                                             AppDomainSetup info)
        {
            AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
            if (domainManager != null)
                return domainManager.CreateDomain(friendlyName, securityInfo, info);

            // No AppDomainManager is set up for this domain
            if (friendlyName == null)
                throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_String"));
                
            // If evidence is provided, we check to make sure that is allowed.    
            if (securityInfo != null)
                new SecurityPermission( SecurityPermissionFlag.ControlEvidence ).Demand();

            return nCreateDomain(friendlyName,
                                 info,
                                 securityInfo,
                                 securityInfo == null ? AppDomain.CurrentDomain.InternalEvidence : null,
                                 AppDomain.CurrentDomain.GetSecurityDescriptor());
        }


        public static AppDomain CreateDomain(String friendlyName,
                                             Evidence securityInfo, // Optional
                                             String appBasePath,
                                             String appRelativeSearchPath,
                                             bool shadowCopyFiles,
                                             AppDomainInitializer adInit, 
                                             string[] adInitArgs) 
        {
            AppDomainSetup info = new AppDomainSetup();
            info.ApplicationBase = appBasePath;
            info.PrivateBinPath = appRelativeSearchPath;
            info.AppDomainInitializer=adInit;
            info.AppDomainInitializerArguments=adInitArgs;
            if(shadowCopyFiles)
                info.ShadowCopyFiles = "true";

            return CreateDomain(friendlyName,
                                securityInfo,
                                info);
        }

        private void SetupFusionStore(AppDomainSetup info)
        {
            // Create the application base and configuration file from the imagelocation
            // passed in or use the Win32 Image name.
            if(info.Value[(int) AppDomainSetup.LoaderInformation.ApplicationBaseValue] == null ||
               info.Value[(int) AppDomainSetup.LoaderInformation.ConfigurationFileValue] == null ) {
                AppDomain defaultDomain = GetDefaultDomain();
                if (this == defaultDomain) {
                    // The default domain gets its defaults from the main process.
                    info.SetupDefaultApplicationBase(RuntimeEnvironment.GetModuleFileName());
                }
                else {
                    // Other domains get their defaults from the default domain. This way, a host process
                    // can use AppDomainManager to set up the defaults for every domain created in the process.
                    if (info.Value[(int) AppDomainSetup.LoaderInformation.ConfigurationFileValue] == null)
                        info.ConfigurationFile = defaultDomain.FusionStore.Value[(int) AppDomainSetup.LoaderInformation.ConfigurationFileValue];
                    if (info.Value[(int) AppDomainSetup.LoaderInformation.ApplicationBaseValue] == null)
                        info.ApplicationBase = defaultDomain.FusionStore.Value[(int) AppDomainSetup.LoaderInformation.ApplicationBaseValue];
                    if (info.Value[(int) AppDomainSetup.LoaderInformation.ApplicationNameValue] == null)
                        info.ApplicationName = defaultDomain.FusionStore.Value[(int) AppDomainSetup.LoaderInformation.ApplicationNameValue];
                }
            }

            // If there is no relative path then check the
            // environment
            if(info.Value[(int) AppDomainSetup.LoaderInformation.PrivateBinPathValue] == null)
                info.PrivateBinPath = Environment.nativeGetEnvironmentVariable(AppDomainSetup.PrivateBinPathEnvironmentVariable);

            // Add the developer path if it exists on this
            // machine.
            if(info.DeveloperPath == null)
                info.DeveloperPath = RuntimeEnvironment.GetDeveloperPath();

            // Set up the fusion context
            IntPtr fusionContext = GetFusionContext();
            info.SetupFusionContext(fusionContext);

            // Set loader optimization policy
            if (info.LoaderOptimization != LoaderOptimization.NotSpecified)
                UpdateLoaderOptimization((int) info.LoaderOptimization);

            // This must be the last action taken
            _FusionStore = info;
        }

        // used to package up evidence, so it can be serialized
        //   for the call to InternalRemotelySetupRemoteDomain
        [Serializable]
        private class EvidenceCollection
        {
            public Evidence ProvidedSecurityInfo;
            public Evidence CreatorsSecurityInfo;
        }

        private static void RunInitializer(AppDomainSetup setup)
        {
            if (setup.AppDomainInitializer!=null)
            {
                string[] args=null;
                if (setup.AppDomainInitializerArguments!=null)
                    args=(string[])setup.AppDomainInitializerArguments.Clone();
                setup.AppDomainInitializer(args);
            }
        }

        // Used to switch into other AppDomain and call SetupRemoteDomain.
        //   We cannot simply call through the proxy, because if there
        //   are any remoting sinks registered, they can add non-mscorlib
        //   objects to the message (causing an assembly load exception when
        //   we try to deserialize it on the other side)
        private static object RemotelySetupRemoteDomain(AppDomain appDomainProxy,
                                                        String friendlyName,
                                                        AppDomainSetup setup,
                                                        Evidence providedSecurityInfo,
                                                        Evidence creatorsSecurityInfo,
                                                        IntPtr parentSecurityDescriptor)
        {
            BCLDebug.Assert(RemotingServices.IsTransparentProxy(appDomainProxy),
                            "Expected a proxy to the AppDomain.");

            // get context and appdomain id
            IntPtr  contextId;
            int     domainId;
            RemotingServices.GetServerContextAndDomainIdForProxy(
               appDomainProxy, out contextId, out domainId);

            if (contextId==IntPtr.Zero)
                throw new AppDomainUnloadedException();
            
            // serialize evidence
            EvidenceCollection evidenceCollection = null;
            if ((providedSecurityInfo != null) ||
                (creatorsSecurityInfo != null)) {
                evidenceCollection = new EvidenceCollection();
                evidenceCollection.ProvidedSecurityInfo = providedSecurityInfo;
                evidenceCollection.CreatorsSecurityInfo = creatorsSecurityInfo;
            }

            bool bNeedGenericFormatter = false;
            char[] serProvidedEvidence = null, serCreatorEvidence = null;
            byte[] serializedEvidence = null;
            AppDomainInitializerInfo initializerInfo=null;

            if (providedSecurityInfo != null) {
                serProvidedEvidence = PolicyManager.MakeEvidenceArray(providedSecurityInfo, true);
                if (serProvidedEvidence == null)
                    bNeedGenericFormatter = true;
            }
            if (creatorsSecurityInfo != null && !bNeedGenericFormatter) {
                serCreatorEvidence = PolicyManager.MakeEvidenceArray(creatorsSecurityInfo, true);
                if (serCreatorEvidence == null)
                    bNeedGenericFormatter = true;
            }
            if (evidenceCollection != null && bNeedGenericFormatter) {
                serProvidedEvidence = serCreatorEvidence = null;
                serializedEvidence =
                    CrossAppDomainSerializer.SerializeObject(evidenceCollection).GetBuffer();                
            }

            if (setup!=null && setup.AppDomainInitializer!=null)
                initializerInfo=new AppDomainInitializerInfo(setup.AppDomainInitializer);

            return InternalRemotelySetupRemoteDomain(contextId,
                                              domainId,
                                              friendlyName, 
                                              setup,
                                              parentSecurityDescriptor,
                                              serProvidedEvidence,
                                              serCreatorEvidence,
                                              serializedEvidence,
                                              initializerInfo);    
        } // RemotelySetupRemoteDomain

        [MethodImplAttribute(MethodImplOptions.NoInlining)]
        private static Object InternalRemotelySetupRemoteDomainHelper(Object[] args)
        {
            String           friendlyName               = (String)args[0];
            AppDomainSetup   setup                      = (AppDomainSetup)args[1];
            IntPtr           parentSecurityDescriptor   = (IntPtr)args[2];
            char[]           serProvidedEvidence        = (char[])args[3];
            char[]           serCreatorEvidence         = (char[])args[4];
            byte[]           serializedEvidence         = (byte[])args[5];
            AppDomainInitializerInfo initializerInfo    = (AppDomainInitializerInfo)args[6];

            AppDomain ad = Thread.CurrentContext.AppDomain;
            AppDomainSetup newSetup=new AppDomainSetup(setup,false);
            ad.SetupFusionStore(newSetup);

            // extract evidence
            Evidence providedSecurityInfo = null;
            Evidence creatorsSecurityInfo = null;

            if (serializedEvidence == null) {
                if (serProvidedEvidence != null)
                    providedSecurityInfo = new Evidence(serProvidedEvidence);
                if (serCreatorEvidence != null)
                    creatorsSecurityInfo = new Evidence(serCreatorEvidence);
            }
            else {
                EvidenceCollection evidenceCollection = (EvidenceCollection)
                    CrossAppDomainSerializer.DeserializeObject(new MemoryStream(serializedEvidence));
                providedSecurityInfo  = evidenceCollection.ProvidedSecurityInfo;
                creatorsSecurityInfo  = evidenceCollection.CreatorsSecurityInfo;
            }

            // set up the friendly name
            ad.nSetupFriendlyName(friendlyName);

            // set up the AppDomainManager for this domain and initialize security.
            ad.SetDomainManager(providedSecurityInfo,
                                creatorsSecurityInfo,
                                parentSecurityDescriptor,
                                true);

            // can load user code now
            if(initializerInfo!=null)
                newSetup.AppDomainInitializer=initializerInfo.Unwrap();
            RunInitializer(newSetup);

            // Activate the application if needed.
            ObjectHandle oh = null;
            return RemotingServices.MarshalInternal(oh, null, null);
        }

        [MethodImplAttribute(MethodImplOptions.NoInlining)]
        private static object InternalRemotelySetupRemoteDomain(IntPtr contextId, 
                                                              int domainId,
                                                              String friendlyName,
                                                              AppDomainSetup setup,
                                                              IntPtr parentSecurityDescriptor,
                                                              char[] serProvidedEvidence,
                                                              char[] serCreatorEvidence,
                                                              byte[] serializedEvidence,
                                                              AppDomainInitializerInfo initializerInfo)
        {
            InternalCrossContextDelegate xctxDel = 
                new InternalCrossContextDelegate(InternalRemotelySetupRemoteDomainHelper);

            Object[] args = new Object[] 
                {
                    friendlyName, 
                    setup, 
                    parentSecurityDescriptor, 
                    serProvidedEvidence,
                    serCreatorEvidence,
                    serializedEvidence,
                    initializerInfo
                };
            return Thread.CurrentThread.InternalCrossContextCallback(null, contextId, domainId, xctxDel, args);
        } // InternalSetupRemoteDomain

        // This routine is called from unmanaged code to 
        // set the default fusion context.
        private void SetupDomain(bool allowRedirects, String path, String configFile)
        {
            // It is possible that we could have multiple threads initializing
            // the default domain. We will just take the winner of these two.
            // (eg. one thread doing a com call and another doing attach for IJW)
            lock (this) {
                if(_FusionStore == null) {
                    AppDomainSetup setup = new AppDomainSetup();
                    if(path != null)
                        setup.Value[(int) AppDomainSetup.LoaderInformation.ApplicationBaseValue] = path;
                    if(configFile != null)
                        setup.Value[(int) AppDomainSetup.LoaderInformation.ConfigurationFileValue] = configFile;

                    // Default fusion context starts with binding redirects turned off.
                    if (!allowRedirects)
                        setup.DisallowBindingRedirects = true;

                    SetupFusionStore(setup);
                }
            }
        }

       private void SetupLoaderOptimization(LoaderOptimization policy)
        {
            if(policy != LoaderOptimization.NotSpecified) {
#if _DEBUG
                BCLDebug.Assert(FusionStore.LoaderOptimization == LoaderOptimization.NotSpecified,
                                "It is illegal to change the Loader optimization on a domain");
#endif
                FusionStore.LoaderOptimization = policy;
                UpdateLoaderOptimization((int) FusionStore.LoaderOptimization);
            }
        }

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern IntPtr GetFusionContext();

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern IntPtr GetSecurityDescriptor();

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal static extern AppDomain nCreateDomain(String friendlyName,
                                                      AppDomainSetup setup,
                                                      Evidence providedSecurityInfo,
                                                      Evidence creatorsSecurityInfo,
                                                      IntPtr parentSecurityDescriptor);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal static extern ObjRef nCreateInstance(String friendlyName,
                                                      AppDomainSetup setup,
                                                      Evidence providedSecurityInfo,
                                                      Evidence creatorsSecurityInfo,
                                                      IntPtr parentSecurityDescriptor);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private extern void nSetupDomainSecurity(Evidence appDomainEvidence, IntPtr creatorsSecurityDescriptor, bool publishAppDomain);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private extern void nSetupFriendlyName(string friendlyName);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern void UpdateLoaderOptimization(int optimization);

        //
        // This is just designed to prevent compiler warnings.
        // This field is used from native, but we need to prevent the compiler warnings.
        //

        [Obsolete("AppDomain.SetShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. http://go.microsoft.com/fwlink/?linkid=14202")]
        [method:SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
        public void SetShadowCopyPath(String path)
        {
            InternalSetShadowCopyPath(path);
        }

        [Obsolete("AppDomain.SetShadowCopyFiles has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyFiles instead. http://go.microsoft.com/fwlink/?linkid=14202")]
        [method:SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
        public void SetShadowCopyFiles()
        {
            InternalSetShadowCopyFiles();
        }

        [Obsolete("AppDomain.SetDynamicBase has been deprecated. Please investigate the use of AppDomainSetup.DynamicBase instead. http://go.microsoft.com/fwlink/?linkid=14202")]
        [method:SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )]
        public void SetDynamicBase(String path)
        {
            InternalSetDynamicBase(path);
        }

        public AppDomainSetup SetupInformation
        {
            get {
                return new AppDomainSetup(FusionStore,true);
            }
        }

        internal void InternalSetShadowCopyPath(String path)
        {
            IntPtr fusionContext = GetFusionContext();
            AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.ShadowCopyDirectoriesKey, path);
            FusionStore.ShadowCopyDirectories = path;
        }

        internal void InternalSetShadowCopyFiles()
        {
            IntPtr fusionContext = GetFusionContext();
            AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.ShadowCopyFilesKey, "true");
            FusionStore.ShadowCopyFiles = "true";
        }

        internal void InternalSetCachePath(String path)
        {
            IntPtr fusionContext = GetFusionContext();
            FusionStore.CachePath = path;
            AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.CachePathKey,
                                                 FusionStore.Value[(int) AppDomainSetup.LoaderInformation.CachePathValue]);
        }

        internal void InternalSetPrivateBinPath(String path)
        {
            IntPtr fusionContext = GetFusionContext();
            AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.PrivateBinPathKey, path);
            FusionStore.PrivateBinPath = path;
        }

        internal void InternalSetDynamicBase(String path)
        {
            IntPtr fusionContext = GetFusionContext();
            FusionStore.DynamicBase = path;

            AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.DynamicBaseKey,
                                                 FusionStore.Value[(int) AppDomainSetup.LoaderInformation.DynamicBaseValue]);
        }

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern String IsStringInterned(String str);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern String GetOrInternString(String str);
        
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern void nGetGrantSet( out PermissionSet granted, out PermissionSet denied );

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private extern void nChangeSecurityPolicy();

        [MethodImplAttribute(MethodImplOptions.InternalCall),
         ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.MayFail)]   
        internal static extern void nUnload(Int32 domainInternal);
           
        public Object CreateInstanceAndUnwrap(String assemblyName,
                                              String typeName)
        {
            ObjectHandle oh = CreateInstance(assemblyName, typeName);
            if (oh == null)
                return null;

            return oh.Unwrap();
        } // CreateInstanceAndUnwrap


        public Object CreateInstanceAndUnwrap(String assemblyName, 
                                              String typeName,
                                              Object[] activationAttributes)
        {
            ObjectHandle oh = CreateInstance(assemblyName, typeName, activationAttributes);
            if (oh == null)
                return null; 

            return oh.Unwrap();
        } // CreateInstanceAndUnwrap


        public Object CreateInstanceAndUnwrap(String assemblyName, 
                                              String typeName, 
                                              bool ignoreCase,
                                              BindingFlags bindingAttr, 
                                              Binder binder,
                                              Object[] args,
                                              CultureInfo culture,
                                              Object[] activationAttributes,
                                              Evidence securityAttributes)
        {
            ObjectHandle oh = CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr,
                binder, args, culture, activationAttributes, securityAttributes);
            if (oh == null)
                return null; 
            
            return oh.Unwrap();
        } // CreateInstanceAndUnwrap



        // The first parameter should be named assemblyFile, but it was incorrectly named in a previous 
        //  release, and the compatibility police won't let us change the name now.
        public Object CreateInstanceFromAndUnwrap(String assemblyName,
                                                  String typeName)
        {
            ObjectHandle oh = CreateInstanceFrom(assemblyName, typeName);
            if (oh == null)
                return null;  

            return oh.Unwrap();                
        } // CreateInstanceAndUnwrap


        // The first parameter should be named assemblyFile, but it was incorrectly named in a previous 
        //  release, and the compatibility police won't let us change the name now.
        public Object CreateInstanceFromAndUnwrap(String assemblyName,
                                                  String typeName,
                                                  Object[] activationAttributes)
        {
            ObjectHandle oh = CreateInstanceFrom(assemblyName, typeName, activationAttributes);
            if (oh == null)
                return null; 

            return oh.Unwrap();
        } // CreateInstanceAndUnwrap


        // The first parameter should be named assemblyFile, but it was incorrectly named in a previous 
        //  release, and the compatibility police won't let us change the name now.
        public Object CreateInstanceFromAndUnwrap(String assemblyName, 
                                                  String typeName, 
                                                  bool ignoreCase,
                                                  BindingFlags bindingAttr, 
                                                  Binder binder,
                                                  Object[] args,
                                                  CultureInfo culture,
                                                  Object[] activationAttributes,
                                                  Evidence securityAttributes)
        {
            ObjectHandle oh = CreateInstanceFrom(assemblyName, typeName, ignoreCase, bindingAttr,
                binder, args, culture, activationAttributes, securityAttributes);
            if (oh == null)
                return null; 

            return oh.Unwrap();
        } // CreateInstanceAndUnwrap

        public Int32 Id
        {
            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]  
            get {
                return GetId();
            }
        }

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]              
        internal extern Int32 GetId();

        public bool IsDefaultAppDomain()
        {
            if (this == GetDefaultDomain())
                return true;
            return false;
        }

        private static AppDomainSetup InternalCreateDomainSetup(String imageLocation)
        {
            int i = imageLocation.LastIndexOf('\\');
#if PLATFORM_UNIX
            int j = imageLocation.LastIndexOf('/');
            i = i > j ? i : j;
#endif
 
            BCLDebug.Assert(i != -1, "invalid image location");

            AppDomainSetup info = new AppDomainSetup();
            info.ApplicationBase = imageLocation.Substring(0, i+1);

            StringBuilder config = new StringBuilder(imageLocation.Substring(i+1));
            config.Append(AppDomainSetup.ConfigurationExtension);
            info.ConfigurationFile = config.ToString();

            return info;
        }

        // Used by the validator for testing but not executing an assembly
        private static AppDomain InternalCreateDomain(String imageLocation)
        {
            AppDomainSetup info = InternalCreateDomainSetup(imageLocation);

            return CreateDomain("Validator",
                                null,
                                info);
        }

        private void InternalSetDomainContext(String imageLocation)
        {
            SetupFusionStore(InternalCreateDomainSetup(imageLocation));
        }

        void _AppDomain.GetTypeInfoCount(out uint pcTInfo)
        {
            throw new NotImplementedException();
        }

        void _AppDomain.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
        {
            throw new NotImplementedException();
        }

        void _AppDomain.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
        {
            throw new NotImplementedException();
        }

        void _AppDomain.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
        {
            throw new NotImplementedException();
        }
    }

    //  CallBacks provide a facility to request execution of some code
    //  in another context/appDomain.
    //  CrossAppDomainDelegate type is defined for appdomain call backs. 
    //  The delegate used to request a callbak through the DoCallBack method
    //  must be of CrossContextDelegate type.
[System.Runtime.InteropServices.ComVisible(true)]
    public delegate void CrossAppDomainDelegate();
}

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us