1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559
|
//------------------------------------------------------------------------------
// <copyright file="WebEvents.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Management {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Configuration.Provider;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Remoting.Messaging;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Caching;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Security;
using System.Web.UI;
using System.Web.Util;
using Debug = System.Web.Util.Debug;
// This enum matches the native one enum WebEventType (in webevent.h).
internal enum WebEventType : int {
WEBEVENT_BASE_EVENT = 0,
WEBEVENT_MANAGEMENT_EVENT,
WEBEVENT_APP_LIFETIME_EVENT,
WEBEVENT_REQUEST_EVENT,
WEBEVENT_HEARTBEAT_EVENT,
WEBEVENT_BASE_ERROR_EVENT,
WEBEVENT_REQUEST_ERROR_EVENT,
WEBEVENT_ERROR_EVENT,
WEBEVENT_AUDIT_EVENT,
WEBEVENT_SUCCESS_AUDIT_EVENT,
WEBEVENT_AUTHENTICATION_SUCCESS_AUDIT_EVENT,
WEBEVENT_FAILURE_AUDIT_EVENT,
WEBEVENT_AUTHENTICATION_FAILURE_AUDIT_EVENT,
WEBEVENT_VIEWSTATE_FAILURE_AUDIT_EVENT,
};
internal enum WebEventFieldType : int {
String = 0,
Int = 1,
Bool = 2,
Long = 3,
Date = 4,
}
// Used for marshalling over to IIS Trace
internal class WebEventFieldData {
string _name;
public string Name {
get {
return _name;
}
}
string _data;
public string Data {
get {
return _data;
}
}
WebEventFieldType _type;
public WebEventFieldType Type {
get {
return _type;
}
}
public WebEventFieldData(string name, string data, WebEventFieldType type) {
_name = name;
_data = data;
_type = type;
}
}
// Interface for event provider
public abstract class WebEventProvider : ProviderBase {
// methods
public abstract void ProcessEvent(WebBaseEvent raisedEvent);
public abstract void Shutdown();
public abstract void Flush();
int _exceptionLogged;
internal void LogException(Exception e) {
// In order to not overflow the eventlog, we only log one exception per provider instance.
if (Interlocked.CompareExchange( ref _exceptionLogged, 1, 0) == 0) {
// Log all errors in eventlog
UnsafeNativeMethods.LogWebeventProviderFailure(
HttpRuntime.AppDomainAppVirtualPath,
Name,
e.ToString());
}
}
}
// Interface for custom event evaluator
public interface IWebEventCustomEvaluator {
bool CanFire(WebBaseEvent raisedEvent, RuleFiringRecord record);
}
////////////////
// Events
////////////////
public class WebBaseEvent {
DateTime _eventTimeUtc;
int _code;
int _detailCode;
Object _source;
string _message;
long _sequenceNumber;
long _occurrenceNumber;
Guid _id = Guid.Empty;
static long s_globalSequenceNumber = 0;
static WebApplicationInformation s_applicationInfo = new WebApplicationInformation();
const string WEBEVENT_RAISE_IN_PROGRESS = "_WEvtRIP";
// A array that cache the result of eventCode to SystemEventType mapping.
static readonly SystemEventType[,] s_eventCodeToSystemEventTypeMappings = new SystemEventType[WebEventCodes.GetEventArrayDimensionSize(0),
WebEventCodes.GetEventArrayDimensionSize(1)];
// A array that store the # of occurrence per custom event code.
static readonly long[,] s_eventCodeOccurrence = new long[WebEventCodes.GetEventArrayDimensionSize(0),
WebEventCodes.GetEventArrayDimensionSize(1)];
static Hashtable s_customEventCodeOccurrence = new Hashtable();
#pragma warning disable 0649
static ReadWriteSpinLock s_lockCustomEventCodeOccurrence;
#pragma warning restore 0649
static WebBaseEvent() {
// Initialize the mappings. We will fill up each entry on demand by calling
// SystemEventTypeFromEventCode().
for (int i = 0; i < s_eventCodeToSystemEventTypeMappings.GetLength(0); i++) {
for (int j = 0; j < s_eventCodeToSystemEventTypeMappings.GetLength(1); j++) {
s_eventCodeToSystemEventTypeMappings[i,j] = SystemEventType.Unknown;
}
}
for (int i = 0; i < s_eventCodeOccurrence.GetLength(0); i++) {
for (int j = 0; j < s_eventCodeOccurrence.GetLength(1); j++) {
s_eventCodeOccurrence[i,j] = 0;
}
}
}
void Init(string message, Object eventSource, int eventCode, int eventDetailCode) {
if (eventCode < 0) {
throw new ArgumentOutOfRangeException("eventCode",
SR.GetString(SR.Invalid_eventCode_error));
}
if (eventDetailCode < 0) {
throw new ArgumentOutOfRangeException("eventDetailCode",
SR.GetString(SR.Invalid_eventDetailCode_error));
}
_code = eventCode;
_detailCode = eventDetailCode;
_source = eventSource;
_eventTimeUtc = DateTime.UtcNow;
_message = message;
// Creation of _id is always delayed until it's needed.
}
// ctors
internal protected WebBaseEvent(string message, Object eventSource, int eventCode) {
Init(message, eventSource, eventCode, WebEventCodes.UndefinedEventDetailCode);
}
internal protected WebBaseEvent(string message, Object eventSource, int eventCode, int eventDetailCode) {
Init(message, eventSource, eventCode, eventDetailCode);
}
internal WebBaseEvent() {
// For creating dummy event. See GetSystemDummyEvent()
}
internal bool IsSystemEvent {
get {
return (_code < WebEventCodes.WebExtendedBase);
}
}
// Properties
public DateTime EventTime { get { return _eventTimeUtc.ToLocalTime(); } }
public DateTime EventTimeUtc { get { return _eventTimeUtc; } }
public String Message { get { return _message; } }
public Object EventSource { get { return _source; } }
public long EventSequence { get { return _sequenceNumber; } }
public long EventOccurrence { get { return _occurrenceNumber; } }
public int EventCode { get { return _code; } }
public int EventDetailCode { get { return _detailCode; } }
public Guid EventID {
get {
if (_id == Guid.Empty) {
lock(this) {
if (_id == Guid.Empty) {
_id = Guid.NewGuid();
}
}
}
return _id;
}
}
public static WebApplicationInformation ApplicationInformation {
get { return s_applicationInfo; }
}
virtual internal void FormatToString(WebEventFormatter formatter, bool includeAppInfo) {
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_code, EventCode.ToString(CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_message, Message));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_time, EventTime.ToString(CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_time_Utc, EventTimeUtc.ToString(CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_id, EventID.ToString("N", CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_sequence, EventSequence.ToString(CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_occurrence, EventOccurrence.ToString(CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_detail_code, EventDetailCode.ToString(CultureInfo.InstalledUICulture)));
if (includeAppInfo) {
formatter.AppendLine(String.Empty);
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_application_information));
formatter.IndentationLevel += 1;
ApplicationInformation.FormatToString(formatter);
formatter.IndentationLevel -= 1;
}
}
public override string ToString() {
return ToString(true, true);
}
public virtual string ToString(bool includeAppInfo, bool includeCustomEventDetails) {
WebEventFormatter formatter = new WebEventFormatter();
FormatToString(formatter, includeAppInfo);
if (!IsSystemEvent && includeCustomEventDetails) {
formatter.AppendLine(String.Empty);
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_custom_event_details));
formatter.IndentationLevel += 1;
FormatCustomEventDetails(formatter);
formatter.IndentationLevel -= 1;
}
return formatter.ToString();
}
virtual public void FormatCustomEventDetails(WebEventFormatter formatter) {
}
internal int InferEtwTraceVerbosity() {
WebEventType type = WebBaseEvent.WebEventTypeFromWebEvent(this);
switch (type) {
case WebEventType.WEBEVENT_VIEWSTATE_FAILURE_AUDIT_EVENT:
case WebEventType.WEBEVENT_BASE_ERROR_EVENT:
case WebEventType.WEBEVENT_REQUEST_ERROR_EVENT:
case WebEventType.WEBEVENT_FAILURE_AUDIT_EVENT:
case WebEventType.WEBEVENT_AUTHENTICATION_FAILURE_AUDIT_EVENT:
case WebEventType.WEBEVENT_ERROR_EVENT:
return EtwTraceLevel.Warning;
case WebEventType.WEBEVENT_AUDIT_EVENT:
case WebEventType.WEBEVENT_SUCCESS_AUDIT_EVENT:
case WebEventType.WEBEVENT_AUTHENTICATION_SUCCESS_AUDIT_EVENT:
return EtwTraceLevel.Information;
case WebEventType.WEBEVENT_BASE_EVENT:
case WebEventType.WEBEVENT_MANAGEMENT_EVENT:
case WebEventType.WEBEVENT_REQUEST_EVENT:
default:
return EtwTraceLevel.Verbose;
}
}
internal void DeconstructWebEvent(out int eventType, out int fieldCount, out string[] fieldNames, out int[] fieldTypes, out string[] fieldData) {
List<WebEventFieldData> fields = new List<WebEventFieldData>();
eventType = (int)WebBaseEvent.WebEventTypeFromWebEvent(this);
GenerateFieldsForMarshal(fields);
fieldCount = fields.Count;
fieldNames = new string[fieldCount];
fieldData = new string[fieldCount];
fieldTypes = new int[fieldCount];
for (int i = 0; i < fieldCount; ++i) {
fieldNames[i] = fields[i].Name;
fieldData[i] = fields[i].Data;
fieldTypes[i] = (int)fields[i].Type;
}
}
internal virtual void GenerateFieldsForMarshal(List<WebEventFieldData> fields) {
fields.Add(new WebEventFieldData("EventTime", EventTimeUtc.ToString(), WebEventFieldType.String));
fields.Add(new WebEventFieldData("EventID", EventID.ToString(), WebEventFieldType.String));
fields.Add(new WebEventFieldData("EventMessage", Message, WebEventFieldType.String));
fields.Add(new WebEventFieldData("ApplicationDomain", WebBaseEvent.ApplicationInformation.ApplicationDomain, WebEventFieldType.String));
fields.Add(new WebEventFieldData("TrustLevel", WebBaseEvent.ApplicationInformation.TrustLevel, WebEventFieldType.String));
fields.Add(new WebEventFieldData("ApplicationVirtualPath", WebBaseEvent.ApplicationInformation.ApplicationVirtualPath, WebEventFieldType.String));
fields.Add(new WebEventFieldData("ApplicationPath", WebBaseEvent.ApplicationInformation.ApplicationPath, WebEventFieldType.String));
fields.Add(new WebEventFieldData("MachineName", WebBaseEvent.ApplicationInformation.MachineName, WebEventFieldType.String));
fields.Add(new WebEventFieldData("EventCode", EventCode.ToString(CultureInfo.InstalledUICulture), WebEventFieldType.Int));
fields.Add(new WebEventFieldData("EventDetailCode", EventDetailCode.ToString(CultureInfo.InstalledUICulture), WebEventFieldType.Int));
fields.Add(new WebEventFieldData("SequenceNumber", EventSequence.ToString(CultureInfo.InstalledUICulture), WebEventFieldType.Long));
fields.Add(new WebEventFieldData("Occurrence", EventOccurrence.ToString(CultureInfo.InstalledUICulture), WebEventFieldType.Long));
}
internal virtual void PreProcessEventInit() {
}
static void FindEventCode(Exception e, ref int eventCode, ref int eventDetailsCode, ref Exception eStack) {
eventDetailsCode = WebEventCodes.UndefinedEventDetailCode;
if (e is ConfigurationException) {
eventCode = WebEventCodes.WebErrorConfigurationError;
}
else if (e is HttpRequestValidationException) {
eventCode = WebEventCodes.RuntimeErrorValidationFailure;
}
else if (e is HttpCompileException) {
eventCode = WebEventCodes.WebErrorCompilationError;
}
else if (e is SecurityException) {
eventCode = WebEventCodes.AuditUnhandledSecurityException;
}
else if (e is UnauthorizedAccessException) {
eventCode = WebEventCodes.AuditUnhandledAccessException;
}
else if (e is HttpParseException) {
eventCode = WebEventCodes.WebErrorParserError;
}
else if (e is HttpException && e.InnerException is ViewStateException) {
ViewStateException vse = (ViewStateException)e.InnerException;
eventCode = WebEventCodes.AuditInvalidViewStateFailure;
if (vse._macValidationError) {
eventDetailsCode = WebEventCodes.InvalidViewStateMac;
}
else {
eventDetailsCode = WebEventCodes.InvalidViewState;
}
eStack = vse;
}
else if (e is HttpException && ((HttpException)e).WebEventCode != WebEventCodes.UndefinedEventCode) {
eventCode = ((HttpException)e).WebEventCode;
}
else {
// We don't know what it is. Let's see if we can find it out by using the inner exception.
if (e.InnerException != null) {
// We will call FindEventCode recusively to find out if e.InnerException is the real one.
if (eStack == null) {
// Set eStack here. If the recursive call ends up landing in
// WebEventCodes.RuntimeErrorUnhandledException, we'll use the original
// inner exception as our final result.
eStack = e.InnerException;
}
FindEventCode(e.InnerException, ref eventCode, ref eventDetailsCode, ref eStack);
}
else {
// It doesn't have an inner exception. Just return the generic unhandled-exception
eventCode = WebEventCodes.RuntimeErrorUnhandledException;
}
}
if (eStack == null) {
eStack = e;
}
}
static internal void RaiseRuntimeError(Exception e, object source) {
Debug.Trace("WebEventRaiseError", "Error Event is raised; type=" + e.GetType().Name);
if (!HealthMonitoringManager.Enabled) {
return;
}
try {
int eventCode = WebEventCodes.UndefinedEventCode;
int eventDetailsCode = WebEventCodes.UndefinedEventDetailCode;
HttpContext context = HttpContext.Current;
Exception eStack = null;
if (context != null) {
Page page = context.Handler as Page;
// Errors from Transacted pages can be wrapped by a
// HttpException
if (page != null &&
page.IsTransacted &&
e.GetType() == typeof(HttpException) &&
e.InnerException != null) {
e = e.InnerException;
}
}
FindEventCode(e, ref eventCode, ref eventDetailsCode, ref eStack);
WebBaseEvent.RaiseSystemEvent(source, eventCode, eventDetailsCode, eStack);
}
catch {
}
}
virtual internal protected void IncrementPerfCounters() {
PerfCounters.IncrementCounter(AppPerfCounter.EVENTS_TOTAL);
}
class CustomEventCodeOccurrence {
internal long _occurrence;
}
internal void IncrementTotalCounters(int index0, int index1) {
_sequenceNumber = Interlocked.Increment(ref s_globalSequenceNumber);
if (index0 != -1) {
_occurrenceNumber = Interlocked.Increment(ref s_eventCodeOccurrence[index0, index1]);
}
else {
CustomEventCodeOccurrence ceco = (CustomEventCodeOccurrence)s_customEventCodeOccurrence[_code];
if (ceco == null) {
s_lockCustomEventCodeOccurrence.AcquireWriterLock();
try {
ceco = (CustomEventCodeOccurrence)s_customEventCodeOccurrence[_code];
if (ceco == null) {
ceco = new CustomEventCodeOccurrence();
s_customEventCodeOccurrence[_code] = ceco;
}
}
finally {
s_lockCustomEventCodeOccurrence.ReleaseWriterLock();
}
}
_occurrenceNumber = Interlocked.Increment(ref ceco._occurrence);
}
}
[AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Medium)]
virtual public void Raise() {
Raise(this);
}
// Internally raised events don't go thru this method. They go directly to RaiseSystemEvent --> RaiseInternal
[AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Medium)]
static public void Raise(WebBaseEvent eventRaised) {
if (eventRaised.EventCode < WebEventCodes.WebExtendedBase) {
throw new HttpException(SR.GetString(SR.System_eventCode_not_allowed,
eventRaised.EventCode.ToString(CultureInfo.CurrentCulture),
WebEventCodes.WebExtendedBase.ToString(CultureInfo.CurrentCulture)));
}
if (!HealthMonitoringManager.Enabled) {
Debug.Trace(
"WebEventRaiseDetails", "Can't fire event because we are disabled or we can't configure HealthMonManager");
return;
}
RaiseInternal(eventRaised, null, -1, -1);
}
static internal void RaiseInternal(WebBaseEvent eventRaised, ArrayList firingRuleInfos, int index0, int index1) {
bool preProcessEventInitCalled = false;
bool inProgressSet = false;
object o;
ProcessImpersonationContext ictx = null;
HttpContext context = HttpContext.Current;
Debug.Trace(
"WebEventRaiseDetails", "Event is raised; event class = " + eventRaised.GetType().Name);
// Use CallContext to make sure we detect an infinite loop where a provider calls Raise().
o = CallContext.GetData(WEBEVENT_RAISE_IN_PROGRESS);
if (o != null && (bool)o) {
Debug.Trace(
"WebEventRaiseDetails", "An event is raised while we're raising an event. Ignore it.");
return;
}
eventRaised.IncrementPerfCounters();
eventRaised.IncrementTotalCounters(index0, index1);
// Find the list of rules that match this event
if (firingRuleInfos == null) {
HealthMonitoringManager manager = HealthMonitoringManager.Manager();
Debug.Assert(manager != null, "manager != null");
firingRuleInfos = manager._sectionHelper.FindFiringRuleInfos(eventRaised.GetType(), eventRaised.EventCode);
}
if (firingRuleInfos.Count == 0) {
return;
}
try {
bool[] matchingProviderArray = null;
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure) && context != null)
EtwTrace.Trace(EtwTraceType.ETW_TYPE_WEB_EVENT_RAISE_START,
context.WorkerRequest,
eventRaised.GetType().FullName,
eventRaised.EventCode.ToString(CultureInfo.InstalledUICulture),
eventRaised.EventDetailCode.ToString(CultureInfo.InstalledUICulture),
null);
try {
foreach (HealthMonitoringSectionHelper.FiringRuleInfo firingRuleInfo in firingRuleInfos) {
HealthMonitoringSectionHelper.RuleInfo ruleInfo = firingRuleInfo._ruleInfo;
RuleFiringRecord record = ruleInfo._ruleFiringRecord;
// Check if we should fire the event based on its throttling settings
if (!record.CheckAndUpdate(eventRaised)) {
Debug.Trace("WebEventRaiseDetails",
"Throttling settings not met; not fired");
continue;
}
// It's valid for a rule to have no referenced provider
if (ruleInfo._referencedProvider != null) {
if (!preProcessEventInitCalled) {
// The event may need to do pre-ProcessEvent initialization
eventRaised.PreProcessEventInit();
preProcessEventInitCalled = true;
}
// For rule infos that share the same provider, the _indexOfFirstRuleInfoWithSameProvider field
// is the index of the first ruleInfo among them. We use that index in the boolean array
// matchingProviderArray to remember if we've already fired that provider.
// This is for the scenario where several rules are pointing to the same provider,
// and even if >1 rule actually fire and pass all throttling check,
// the provider is stilled fired only once.
if (firingRuleInfo._indexOfFirstRuleInfoWithSameProvider != -1) {
if (matchingProviderArray == null) {
matchingProviderArray = new bool[firingRuleInfos.Count];
}
if (matchingProviderArray[firingRuleInfo._indexOfFirstRuleInfoWithSameProvider]) {
Debug.Trace("WebEventRaiseDetails",
"Rule with a matching provider already fired.");
continue;
}
matchingProviderArray[firingRuleInfo._indexOfFirstRuleInfoWithSameProvider] = true;
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure) && context != null)
EtwTrace.Trace(EtwTraceType.ETW_TYPE_WEB_EVENT_DELIVER_START,
context.WorkerRequest,
ruleInfo._ruleSettings.Provider,
ruleInfo._ruleSettings.Name,
ruleInfo._ruleSettings.EventName,
null);
// In retail build, ignore errors from provider
try {
if (ictx == null) {
ictx = new ProcessImpersonationContext();
}
if (!inProgressSet) {
CallContext.SetData(WEBEVENT_RAISE_IN_PROGRESS, true);
inProgressSet = true;
}
Debug.Trace("WebEventRaiseDetails", "Calling ProcessEvent under " + HttpApplication.GetCurrentWindowsIdentityWithAssert().Name);
ruleInfo._referencedProvider.ProcessEvent(eventRaised);
}
catch (Exception e) {
try {
ruleInfo._referencedProvider.LogException(e);
}
catch {
// ignore all errors
}
}
finally {
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure) && context != null)
EtwTrace.Trace(EtwTraceType.ETW_TYPE_WEB_EVENT_DELIVER_END,
context.WorkerRequest);
}
}
}
}
finally {
// Resume client impersonation
if (ictx != null) {
ictx.Undo();
}
if (inProgressSet) {
CallContext.FreeNamedDataSlot(WEBEVENT_RAISE_IN_PROGRESS);
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure) && context != null)
EtwTrace.Trace(EtwTraceType.ETW_TYPE_WEB_EVENT_RAISE_END,
context.WorkerRequest);
}
}
catch { throw; } // Prevent Exception Filter Security Issue (ASURT 122835)
}
internal static void RaiseSystemEvent(string message, object source, int eventCode, int eventDetailCode, Exception exception) {
RaiseSystemEventInternal(message, source, eventCode, eventDetailCode, exception, null);
}
internal static void RaiseSystemEvent(object source, int eventCode) {
RaiseSystemEventInternal(null, source, eventCode, WebEventCodes.UndefinedEventDetailCode, null, null);
}
internal static void RaiseSystemEvent(object source, int eventCode, int eventDetailCode) {
RaiseSystemEventInternal(null, source, eventCode, eventDetailCode, null, null);
}
internal static void RaiseSystemEvent(object source, int eventCode, int eventDetailCode, Exception exception) {
RaiseSystemEventInternal(null, source, eventCode, eventDetailCode, exception, null);
}
internal static void RaiseSystemEvent(object source, int eventCode, string nameToAuthenticate) {
RaiseSystemEventInternal(null, source, eventCode, WebEventCodes.UndefinedEventDetailCode, null, nameToAuthenticate);
}
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
static void RaiseSystemEventInternal(string message, object source,
int eventCode, int eventDetailCode, Exception exception,
string nameToAuthenticate) {
HealthMonitoringManager manager;
ArrayList firingRuleInfos;
SystemEventTypeInfo typeInfo;
SystemEventType systemEventType;
int index0, index1;
Debug.Trace(
"WebEventRaiseDetails", "RaiseSystemEventInternal called; eventCode=" + eventCode + "; eventDetailCode=" + eventDetailCode);
if (!HealthMonitoringManager.Enabled) {
Debug.Trace(
"WebEventRaiseDetails", "Can't fire event because we are disabled or we can't configure HealthMonManager");
return;
}
WebEventCodes.GetEventArrayIndexsFromEventCode(eventCode, out index0, out index1);
GetSystemEventTypeInfo(eventCode, index0, index1, out typeInfo, out systemEventType);
if (typeInfo == null) {
Debug.Assert(false, "Unexpected system event code = " + eventCode);
return;
}
manager = HealthMonitoringManager.Manager();
// Figure out if there is any provider that subscribes to it
firingRuleInfos = manager._sectionHelper.FindFiringRuleInfos(typeInfo._type, eventCode);
if (firingRuleInfos.Count == 0) {
// Even if we're not firing it, we still have to increment some global counters
typeInfo._dummyEvent.IncrementPerfCounters();
typeInfo._dummyEvent.IncrementTotalCounters(index0, index1);
}
else {
// We will fire the event
WebBaseEvent.RaiseInternal(
NewEventFromSystemEventType(false, systemEventType, message, source, eventCode, eventDetailCode,
exception, nameToAuthenticate),
firingRuleInfos, index0, index1);
}
}
// An enum of all the types of web event we will fire
enum SystemEventType {
Unknown = -1,
WebApplicationLifetimeEvent,
WebHeartbeatEvent,
WebRequestEvent,
WebRequestErrorEvent,
WebErrorEvent,
WebAuthenticationSuccessAuditEvent,
WebSuccessAuditEvent,
WebAuthenticationFailureAuditEvent,
WebFailureAuditEvent,
WebViewStateFailureAuditEvent,
Last
};
class SystemEventTypeInfo {
internal WebBaseEvent _dummyEvent; // For calling IncrementPerfCounters. See RaiseSystemEventInternal for details.
internal Type _type;
internal SystemEventTypeInfo(WebBaseEvent dummyEvent) {
_dummyEvent = dummyEvent;
_type = dummyEvent.GetType();
}
};
// An array to cache the event type info for each system event type
static SystemEventTypeInfo[] s_systemEventTypeInfos = new SystemEventTypeInfo[(int)SystemEventType.Last];
static void GetSystemEventTypeInfo(int eventCode, int index0, int index1,
out SystemEventTypeInfo info, out SystemEventType systemEventType) {
// Figure out what SystemEventType this eventCode maps to.
// For each eventCode, we store the result in a cache.
systemEventType = s_eventCodeToSystemEventTypeMappings[index0, index1];
if (systemEventType == SystemEventType.Unknown) {
systemEventType = SystemEventTypeFromEventCode(eventCode);
s_eventCodeToSystemEventTypeMappings[index0, index1] = systemEventType;
}
// Based on the systemEventType, we read the SystemEventTypeInfo. For each
// event type, we also cache the info
info = s_systemEventTypeInfos[(int)systemEventType];
if (info != null) {
return;
}
info = new SystemEventTypeInfo(CreateDummySystemEvent(systemEventType));
s_systemEventTypeInfos[(int)systemEventType] = info;
}
static SystemEventType SystemEventTypeFromEventCode(int eventCode) {
if (eventCode >= WebEventCodes.ApplicationCodeBase &&
eventCode <= WebEventCodes.ApplicationCodeBaseLast) {
switch(eventCode) {
case WebEventCodes.ApplicationStart:
case WebEventCodes.ApplicationShutdown:
case WebEventCodes.ApplicationCompilationStart:
case WebEventCodes.ApplicationCompilationEnd:
return SystemEventType.WebApplicationLifetimeEvent;
case WebEventCodes.ApplicationHeartbeat:
return SystemEventType.WebHeartbeatEvent;
}
}
if (eventCode >= WebEventCodes.RequestCodeBase &&
eventCode <= WebEventCodes.RequestCodeBaseLast) {
switch(eventCode) {
case WebEventCodes.RequestTransactionComplete:
case WebEventCodes.RequestTransactionAbort:
return SystemEventType.WebRequestEvent;
}
}
if (eventCode >= WebEventCodes.ErrorCodeBase &&
eventCode <= WebEventCodes.ErrorCodeBaseLast) {
switch(eventCode) {
case WebEventCodes.RuntimeErrorRequestAbort:
case WebEventCodes.RuntimeErrorViewStateFailure:
case WebEventCodes.RuntimeErrorValidationFailure:
case WebEventCodes.RuntimeErrorPostTooLarge:
case WebEventCodes.RuntimeErrorUnhandledException:
case WebEventCodes.RuntimeErrorWebResourceFailure:
return SystemEventType.WebRequestErrorEvent;
case WebEventCodes.WebErrorParserError:
case WebEventCodes.WebErrorCompilationError:
case WebEventCodes.WebErrorConfigurationError:
case WebEventCodes.WebErrorOtherError:
case WebEventCodes.WebErrorPropertyDeserializationError:
case WebEventCodes.WebErrorObjectStateFormatterDeserializationError:
return SystemEventType.WebErrorEvent;
}
}
if (eventCode >= WebEventCodes.AuditCodeBase &&
eventCode <= WebEventCodes.AuditCodeBaseLast) {
switch(eventCode) {
case WebEventCodes.AuditFormsAuthenticationSuccess:
case WebEventCodes.AuditMembershipAuthenticationSuccess:
return SystemEventType.WebAuthenticationSuccessAuditEvent;
case WebEventCodes.AuditUrlAuthorizationSuccess:
case WebEventCodes.AuditFileAuthorizationSuccess:
return SystemEventType.WebSuccessAuditEvent;
case WebEventCodes.AuditFormsAuthenticationFailure:
case WebEventCodes.AuditMembershipAuthenticationFailure:
return SystemEventType.WebAuthenticationFailureAuditEvent;
case WebEventCodes.AuditUrlAuthorizationFailure:
case WebEventCodes.AuditFileAuthorizationFailure:
case WebEventCodes.AuditUnhandledSecurityException:
case WebEventCodes.AuditUnhandledAccessException:
return SystemEventType.WebFailureAuditEvent;
case WebEventCodes.AuditInvalidViewStateFailure:
return SystemEventType.WebViewStateFailureAuditEvent;
}
}
if (eventCode >= WebEventCodes.MiscCodeBase &&
eventCode <= WebEventCodes.MiscCodeBaseLast) {
switch(eventCode) {
case WebEventCodes.WebEventProviderInformation:
Debug.Assert(false, "WebEventProviderInformation shouldn't be used to Raise an event");
return SystemEventType.Unknown;
}
}
return SystemEventType.Unknown;
}
static WebBaseEvent CreateDummySystemEvent(SystemEventType systemEventType) {
return NewEventFromSystemEventType(true, systemEventType, null,
null, 0, 0, null, null);
}
static WebBaseEvent NewEventFromSystemEventType(bool createDummy, SystemEventType systemEventType, string message,
object source,int eventCode, int eventDetailCode, Exception exception,
string nameToAuthenticate) {
// If createDummy == true, it means we're only creating a dummy event for the sake of using
// it to call IncrementPerfCounters()
if (!createDummy && message == null) {
message = WebEventCodes.MessageFromEventCode(eventCode, eventDetailCode);
}
// Code view note for the future:
// If the number of systemEventType increases tremendoulsy, we may need to
// avoid using switch, and change to use a "factory" to create new event.
switch(systemEventType) {
case SystemEventType.WebApplicationLifetimeEvent:
return createDummy ? new WebApplicationLifetimeEvent() : new WebApplicationLifetimeEvent(message, source, eventCode, eventDetailCode);
case SystemEventType.WebHeartbeatEvent:
return createDummy ? new WebHeartbeatEvent() : new WebHeartbeatEvent(message, eventCode);
case SystemEventType.WebRequestEvent:
return createDummy ? new WebRequestEvent() : new WebRequestEvent(message, source, eventCode, eventDetailCode);
case SystemEventType. WebRequestErrorEvent:
return createDummy ? new WebRequestErrorEvent() : new WebRequestErrorEvent(message, source, eventCode, eventDetailCode, exception);
case SystemEventType.WebErrorEvent:
return createDummy ? new WebErrorEvent() : new WebErrorEvent(message, source, eventCode, eventDetailCode, exception);
case SystemEventType.WebAuthenticationSuccessAuditEvent:
return createDummy ? new WebAuthenticationSuccessAuditEvent() : new WebAuthenticationSuccessAuditEvent(message, source, eventCode, eventDetailCode, nameToAuthenticate);
case SystemEventType.WebSuccessAuditEvent:
return createDummy ? new WebSuccessAuditEvent() : new WebSuccessAuditEvent(message, source, eventCode, eventDetailCode);
case SystemEventType.WebAuthenticationFailureAuditEvent:
return createDummy ? new WebAuthenticationFailureAuditEvent() : new WebAuthenticationFailureAuditEvent(message, source, eventCode, eventDetailCode, nameToAuthenticate);
case SystemEventType.WebFailureAuditEvent:
return createDummy ? new WebFailureAuditEvent() : new WebFailureAuditEvent(message, source, eventCode, eventDetailCode);
case SystemEventType.WebViewStateFailureAuditEvent:
return createDummy ? new WebViewStateFailureAuditEvent() : new WebViewStateFailureAuditEvent(message, source, eventCode, eventDetailCode, (System.Web.UI.ViewStateException)exception);
default:
Debug.Assert(false, "Unexpected event type = " + systemEventType);
return null;
}
}
static string CreateWebEventResourceCacheKey(String key) {
return CacheInternal.PrefixWebEventResource + key;
}
internal static String FormatResourceStringWithCache(String key) {
// HealthMonitoring, in some scenarios, can call into the cache hundreds of
// times during shutdown, after the cache has been disposed. To improve
// shutdown performance, skip the cache when it is disposed.
if (HealthMonitoringManager.IsCacheDisposed) {
return SR.Resources.GetString(key, CultureInfo.InstalledUICulture);
}
CacheStoreProvider cacheInternal = HttpRuntime.Cache.InternalCache;
string s;
string cacheKey = CreateWebEventResourceCacheKey(key);
s = (string) cacheInternal.Get(cacheKey);
if (s != null) {
return s;
}
s = SR.Resources.GetString(key, CultureInfo.InstalledUICulture);
if (s != null) {
cacheInternal.Insert(cacheKey, s, null);
}
return s;
}
internal static String FormatResourceStringWithCache(String key, String arg0) {
string fmt = FormatResourceStringWithCache(key);
return(fmt != null) ? String.Format(fmt, arg0) : null;
}
internal static WebEventType WebEventTypeFromWebEvent(WebBaseEvent eventRaised) {
// Note:
// eventRaised can belong to one of the following classes, or can inherit from one of them.
// In order to figure out precisely the WebEventType closest to the type of eventRaised,
// we will start our comparison from the leaf nodes in the class hierarchy and work our
// way up.
// Webevent class hierarchy (with the info contained in each class):
/*
- WebBaseEvent (basic)
- WebManagementEvent (+ WebProcessInformation)
- WebHeartbeatEvent (+ WebProcessStatistics)
- WebApplicationLifetimeEvent
- WebRequestEvent (+ WebRequestInformation)
- WebBaseErrorEvent (+ Exception)
- WebRequestErrorEvent (+ WebRequestInformation + WebThreadInformation)
- WebErrorEvent (+ WebRequestInformation + WebThreadInformation)
- WebAuditEvent (+ WebRequestInformation)
- WebSuccessAuditEvent
- WebAuthenticationSuccessAuditEvent (+ NameToAuthenticate)
- WebFailureAuditEvent
- WebAuthenticationFailureAuditEvent (+ NameToAuthenticate)
- WebViewStateFailureAuditEvent (+ ViewStateException)
*/
// Hierarchy level 5
if (eventRaised is WebAuthenticationSuccessAuditEvent) {
return WebEventType.WEBEVENT_AUTHENTICATION_SUCCESS_AUDIT_EVENT;
}
if (eventRaised is WebAuthenticationFailureAuditEvent) {
return WebEventType.WEBEVENT_AUTHENTICATION_FAILURE_AUDIT_EVENT;
}
if (eventRaised is WebViewStateFailureAuditEvent) {
return WebEventType.WEBEVENT_VIEWSTATE_FAILURE_AUDIT_EVENT;
}
// Hierarchy level 4
if (eventRaised is WebRequestErrorEvent) {
return WebEventType.WEBEVENT_REQUEST_ERROR_EVENT;
}
if (eventRaised is WebErrorEvent) {
return WebEventType.WEBEVENT_ERROR_EVENT;
}
if (eventRaised is WebSuccessAuditEvent) {
return WebEventType.WEBEVENT_SUCCESS_AUDIT_EVENT;
}
if (eventRaised is WebFailureAuditEvent) {
return WebEventType.WEBEVENT_FAILURE_AUDIT_EVENT;
}
// Hierarchy level 3
if (eventRaised is WebHeartbeatEvent) {
return WebEventType.WEBEVENT_HEARTBEAT_EVENT;
}
if (eventRaised is WebApplicationLifetimeEvent) {
return WebEventType.WEBEVENT_APP_LIFETIME_EVENT;
}
if (eventRaised is WebRequestEvent) {
return WebEventType.WEBEVENT_REQUEST_EVENT;
}
if (eventRaised is WebBaseErrorEvent) {
return WebEventType.WEBEVENT_BASE_ERROR_EVENT;
}
if (eventRaised is WebAuditEvent) {
return WebEventType.WEBEVENT_AUDIT_EVENT;
}
// Hierarchy level 2
if (eventRaised is WebManagementEvent) {
return WebEventType.WEBEVENT_MANAGEMENT_EVENT;
}
// Hierarchy level 1
return WebEventType.WEBEVENT_BASE_EVENT;
}
static internal void RaisePropertyDeserializationWebErrorEvent(SettingsProperty property, object source, Exception exception) {
if (HttpContext.Current == null) {
return;
}
WebBaseEvent.RaiseSystemEvent(
SR.GetString(SR.Webevent_msg_Property_Deserialization,
property.Name, property.SerializeAs.ToString(), property.PropertyType.AssemblyQualifiedName ),
source,
WebEventCodes.WebErrorPropertyDeserializationError,
WebEventCodes.UndefinedEventDetailCode,
exception);
}
}
public class WebEventFormatter {
int _level;
StringBuilder _sb;
int _tabSize;
void AddTab() {
int level = _level;
while (level > 0) {
_sb.Append(' ', _tabSize);
level--;
}
}
internal WebEventFormatter() {
_level = 0;
_sb = new StringBuilder();
_tabSize = 4;
}
public void AppendLine(string s) {
AddTab();
_sb.Append(s);
_sb.Append('\n');
}
new public string ToString() {
return _sb.ToString();
}
public int IndentationLevel {
get { return _level; }
set { _level = Math.Max(value, 0); }
}
public int TabSize {
get { return _tabSize; }
set { _tabSize = Math.Max(value, 0); }
}
}
// This class is a base class for all events that require application and process information.
//
// WebManagementEvent is the base class for all our webevent classes (except for WebBaseEvent)
// Please note that we allow customer to inherit from our webevent classes to make it easier to
// create custom webevent that contains useful information.
// However, WebManagementEvent (and other child events) contains sensitive information (e.g. process id, process account name)
// that cannot be obtained unless in full-trust.
//
// In non-fulltrust app, we still want code inside system.web.dll to create these webevents
// even if there is user code on the stack (we either assert or call unmanaged code to get those info).
// So to protect these full-trust information from non-fulltrust app, we InheritanceDemand FullTrust
// if the customer wants to inherit from WebManagementEvent.
//
// For details, see VSWhidbey 256684.
//
[PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
public class WebManagementEvent : WebBaseEvent {
static WebProcessInformation s_processInfo = new WebProcessInformation();
internal protected WebManagementEvent(string message, object eventSource, int eventCode)
:base(message, eventSource, eventCode) {
}
internal protected WebManagementEvent(string message, object eventSource, int eventCode, int eventDetailCode)
:base(message, eventSource, eventCode, eventDetailCode) {
}
internal WebManagementEvent() {
// For creating dummy event. See GetSystemDummyEvent()
}
// properties
public WebProcessInformation ProcessInformation {
get { return s_processInfo; }
}
internal override void GenerateFieldsForMarshal(List<WebEventFieldData> fields) {
base.GenerateFieldsForMarshal(fields);
fields.Add(new WebEventFieldData("AccountName", ProcessInformation.AccountName, WebEventFieldType.String));
fields.Add(new WebEventFieldData("ProcessName", ProcessInformation.ProcessName, WebEventFieldType.String));
fields.Add(new WebEventFieldData("ProcessID", ProcessInformation.ProcessID.ToString(CultureInfo.InstalledUICulture), WebEventFieldType.Int));
}
override internal void FormatToString(WebEventFormatter formatter, bool includeAppInfo) {
base.FormatToString(formatter, includeAppInfo);
formatter.AppendLine(String.Empty);
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_process_information));
formatter.IndentationLevel += 1;
ProcessInformation.FormatToString(formatter);
formatter.IndentationLevel -= 1;
}
}
// This event is raised at periodic intervals (default 30 seconds) and provides information
// relative to the state of the running appdomin.
public class WebHeartbeatEvent : WebManagementEvent {
static WebProcessStatistics s_procStats = new WebProcessStatistics();
internal protected WebHeartbeatEvent(string message, int eventCode)
:base(message, null, eventCode)
{
}
internal WebHeartbeatEvent() {
// For creating dummy event. See GetSystemDummyEvent()
}
public WebProcessStatistics ProcessStatistics {get {return s_procStats;}}
override internal void FormatToString(WebEventFormatter formatter, bool includeAppInfo) {
base.FormatToString(formatter, includeAppInfo);
formatter.AppendLine(String.Empty);
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_process_statistics));
formatter.IndentationLevel += 1;
s_procStats.FormatToString(formatter);
formatter.IndentationLevel -= 1;
}
}
// This event represents a notable event in the lifetime of an application (app domain)
// including startup and shutdown events. When an app domain is terminated, the reason
// will be expressed in the Message field (e.g. compilation threshold exceed, Shutdown
// called explicitly, etc.).
public class WebApplicationLifetimeEvent : WebManagementEvent {
internal protected WebApplicationLifetimeEvent(string message, object eventSource, int eventCode)
:base(message, eventSource, eventCode)
{
}
internal protected WebApplicationLifetimeEvent(string message, object eventSource, int eventCode, int eventDetailCode)
:base(message, eventSource, eventCode, eventDetailCode)
{
}
internal WebApplicationLifetimeEvent() {
// For creating dummy event. See GetSystemDummyEvent()
}
static internal int DetailCodeFromShutdownReason(ApplicationShutdownReason reason) {
switch (reason) {
case ApplicationShutdownReason.HostingEnvironment:
return WebEventCodes.ApplicationShutdownHostingEnvironment;
case ApplicationShutdownReason.ChangeInGlobalAsax:
return WebEventCodes.ApplicationShutdownChangeInGlobalAsax;
case ApplicationShutdownReason.ConfigurationChange:
return WebEventCodes.ApplicationShutdownConfigurationChange;
case ApplicationShutdownReason.UnloadAppDomainCalled:
return WebEventCodes.ApplicationShutdownUnloadAppDomainCalled;
case ApplicationShutdownReason.ChangeInSecurityPolicyFile:
return WebEventCodes.ApplicationShutdownChangeInSecurityPolicyFile;
case ApplicationShutdownReason.BinDirChangeOrDirectoryRename:
return WebEventCodes.ApplicationShutdownBinDirChangeOrDirectoryRename;
case ApplicationShutdownReason.BrowsersDirChangeOrDirectoryRename:
return WebEventCodes.ApplicationShutdownBrowsersDirChangeOrDirectoryRename;
case ApplicationShutdownReason.CodeDirChangeOrDirectoryRename:
return WebEventCodes.ApplicationShutdownCodeDirChangeOrDirectoryRename;
case ApplicationShutdownReason.ResourcesDirChangeOrDirectoryRename:
return WebEventCodes.ApplicationShutdownResourcesDirChangeOrDirectoryRename;
case ApplicationShutdownReason.IdleTimeout:
return WebEventCodes.ApplicationShutdownIdleTimeout;
case ApplicationShutdownReason.PhysicalApplicationPathChanged:
return WebEventCodes.ApplicationShutdownPhysicalApplicationPathChanged;
case ApplicationShutdownReason.HttpRuntimeClose:
return WebEventCodes.ApplicationShutdownHttpRuntimeClose;
case ApplicationShutdownReason.InitializationError:
return WebEventCodes.ApplicationShutdownInitializationError;
case ApplicationShutdownReason.MaxRecompilationsReached:
return WebEventCodes.ApplicationShutdownMaxRecompilationsReached;
case ApplicationShutdownReason.BuildManagerChange:
return WebEventCodes.ApplicationShutdownBuildManagerChange;
default:
return WebEventCodes.ApplicationShutdownUnknown;
}
}
override internal protected void IncrementPerfCounters() {
base.IncrementPerfCounters();
PerfCounters.IncrementCounter(AppPerfCounter.EVENTS_APP);
}
}
// This class serves as a base for non-error events that provide
public class WebRequestEvent : WebManagementEvent {
WebRequestInformation _requestInfo;
override internal void PreProcessEventInit() {
base.PreProcessEventInit();
InitRequestInformation();
}
internal protected WebRequestEvent(string message, object eventSource, int eventCode)
:base(message, eventSource, eventCode)
{
}
internal protected WebRequestEvent(string message, object eventSource, int eventCode, int eventDetailCode)
:base(message, eventSource, eventCode, eventDetailCode)
{
}
internal WebRequestEvent() {
// For creating dummy event. See GetSystemDummyEvent()
}
void InitRequestInformation() {
if (_requestInfo == null) {
_requestInfo = new WebRequestInformation();
}
}
public WebRequestInformation RequestInformation {
get {
InitRequestInformation();
return _requestInfo;
}
}
internal override void GenerateFieldsForMarshal(List<WebEventFieldData> fields) {
base.GenerateFieldsForMarshal(fields);
fields.Add(new WebEventFieldData("RequestUrl", RequestInformation.RequestUrl, WebEventFieldType.String));
fields.Add(new WebEventFieldData("RequestPath", RequestInformation.RequestPath, WebEventFieldType.String));
fields.Add(new WebEventFieldData("UserHostAddress", RequestInformation.UserHostAddress, WebEventFieldType.String));
fields.Add(new WebEventFieldData("UserName", RequestInformation.Principal.Identity.Name, WebEventFieldType.String));
fields.Add(new WebEventFieldData("UserAuthenticated", RequestInformation.Principal.Identity.IsAuthenticated.ToString(), WebEventFieldType.Bool));
fields.Add(new WebEventFieldData("UserAuthenticationType", RequestInformation.Principal.Identity.AuthenticationType, WebEventFieldType.String));
fields.Add(new WebEventFieldData("RequestThreadAccountName", RequestInformation.ThreadAccountName, WebEventFieldType.String));
}
override internal void FormatToString(WebEventFormatter formatter, bool includeAppInfo) {
base.FormatToString(formatter, includeAppInfo);
formatter.AppendLine(String.Empty);
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_request_information));
formatter.IndentationLevel += 1;
RequestInformation.FormatToString(formatter);
formatter.IndentationLevel -= 1;
}
override internal protected void IncrementPerfCounters() {
base.IncrementPerfCounters();
PerfCounters.IncrementCounter(AppPerfCounter.EVENTS_WEB_REQ);
}
}
// This is the base class for all error events.
public class WebBaseErrorEvent : WebManagementEvent {
Exception _exception;
void Init(Exception e) {
_exception = e;
}
internal protected WebBaseErrorEvent(string message, object eventSource, int eventCode, Exception e)
:base(message, eventSource, eventCode)
{
Init(e);
}
internal protected WebBaseErrorEvent(string message, object eventSource, int eventCode, int eventDetailCode, Exception e)
:base(message, eventSource, eventCode, eventDetailCode)
{
Init(e);
}
internal WebBaseErrorEvent() {
// For creating dummy event. See GetSystemDummyEvent()
}
public Exception ErrorException {
get { return _exception; }
}
override internal void FormatToString(WebEventFormatter formatter, bool includeAppInfo) {
base.FormatToString(formatter, includeAppInfo);
if (_exception == null) {
return;
}
Exception ex = _exception;
// Please note we arbitrary pick a level limit per bug VSWhidbey 143859
for (int level = 0;
ex != null && level <= 2;
ex = ex.InnerException, level++) {
formatter.AppendLine(String.Empty);
if (level == 0) {
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_exception_information));
}
else {
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_inner_exception_information, level.ToString(CultureInfo.InstalledUICulture)));
}
formatter.IndentationLevel += 1;
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_exception_type, ex.GetType().ToString()));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_exception_message, ex.Message));
formatter.IndentationLevel -= 1;
}
}
internal override void GenerateFieldsForMarshal(List<WebEventFieldData> fields) {
base.GenerateFieldsForMarshal(fields);
fields.Add(new WebEventFieldData("ExceptionType", ErrorException.GetType().ToString(), WebEventFieldType.String));
fields.Add(new WebEventFieldData("ExceptionMessage", ErrorException.Message, WebEventFieldType.String));
}
override internal protected void IncrementPerfCounters() {
base.IncrementPerfCounters();
PerfCounters.IncrementCounter(AppPerfCounter.EVENTS_ERROR);
PerfCounters.IncrementGlobalCounter(GlobalPerfCounter.GLOBAL_EVENTS_ERROR);
}
}
// This class contains information about systemic errors, e.g. things related to
// configuration or application code (parser errors, compilation errors).
public class WebErrorEvent : WebBaseErrorEvent {
WebRequestInformation _requestInfo;
WebThreadInformation _threadInfo;
void Init(Exception e) {
}
override internal void PreProcessEventInit() {
base.PreProcessEventInit();
InitRequestInformation();
InitThreadInformation();
}
internal protected WebErrorEvent(string message, object eventSource, int eventCode, Exception exception)
:base(message, eventSource, eventCode, exception)
{
Init(exception);
}
internal protected WebErrorEvent(string message, object eventSource, int eventCode, int eventDetailCode, Exception exception)
:base(message, eventSource, eventCode, eventDetailCode, exception)
{
Init(exception);
}
internal WebErrorEvent() {
// For creating dummy event. See GetSystemDummyEvent()
}
void InitRequestInformation() {
if (_requestInfo == null) {
_requestInfo = new WebRequestInformation();
}
}
public WebRequestInformation RequestInformation {
get {
InitRequestInformation();
return _requestInfo;
}
}
void InitThreadInformation() {
if (_threadInfo == null) {
_threadInfo = new WebThreadInformation(base.ErrorException);
}
}
public WebThreadInformation ThreadInformation {
get {
InitThreadInformation();
return _threadInfo;
}
}
override internal void FormatToString(WebEventFormatter formatter, bool includeAppInfo) {
base.FormatToString(formatter, includeAppInfo);
formatter.AppendLine(String.Empty);
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_request_information));
formatter.IndentationLevel += 1;
RequestInformation.FormatToString(formatter);
formatter.IndentationLevel -= 1;
formatter.AppendLine(String.Empty);
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_thread_information));
formatter.IndentationLevel += 1;
ThreadInformation.FormatToString(formatter);
formatter.IndentationLevel -= 1;
}
internal override void GenerateFieldsForMarshal(List<WebEventFieldData> fields) {
base.GenerateFieldsForMarshal(fields);
fields.Add(new WebEventFieldData("RequestUrl", RequestInformation.RequestUrl, WebEventFieldType.String));
fields.Add(new WebEventFieldData("RequestPath", RequestInformation.RequestPath, WebEventFieldType.String));
fields.Add(new WebEventFieldData("UserHostAddress", RequestInformation.UserHostAddress, WebEventFieldType.String));
fields.Add(new WebEventFieldData("UserName", RequestInformation.Principal.Identity.Name, WebEventFieldType.String));
fields.Add(new WebEventFieldData("UserAuthenticated", RequestInformation.Principal.Identity.IsAuthenticated.ToString(), WebEventFieldType.Bool));
fields.Add(new WebEventFieldData("UserAuthenticationType", RequestInformation.Principal.Identity.AuthenticationType, WebEventFieldType.String));
fields.Add(new WebEventFieldData("RequestThreadAccountName", RequestInformation.ThreadAccountName, WebEventFieldType.String));
fields.Add(new WebEventFieldData("ThreadID", ThreadInformation.ThreadID.ToString(CultureInfo.InstalledUICulture), WebEventFieldType.Int));
fields.Add(new WebEventFieldData("ThreadAccountName", ThreadInformation.ThreadAccountName, WebEventFieldType.String));
fields.Add(new WebEventFieldData("StackTrace", ThreadInformation.StackTrace, WebEventFieldType.String));
fields.Add(new WebEventFieldData("IsImpersonating", ThreadInformation.IsImpersonating.ToString(), WebEventFieldType.Bool));
}
override internal protected void IncrementPerfCounters() {
base.IncrementPerfCounters();
PerfCounters.IncrementCounter(AppPerfCounter.EVENTS_HTTP_INFRA_ERROR);
PerfCounters.IncrementGlobalCounter(GlobalPerfCounter.GLOBAL_EVENTS_HTTP_INFRA_ERROR);
}
}
// This class provides information about errors that occur while servicing a request.
// This include unhandled exceptions, viewstate errors, input validation errors, etc.
public class WebRequestErrorEvent : WebBaseErrorEvent {
WebRequestInformation _requestInfo;
WebThreadInformation _threadInfo;
void Init(Exception e) {
}
override internal void PreProcessEventInit() {
base.PreProcessEventInit();
InitRequestInformation();
InitThreadInformation();
}
internal protected WebRequestErrorEvent(string message, object eventSource, int eventCode, Exception exception)
:base(message, eventSource, eventCode, exception)
{
Init(exception);
}
internal protected WebRequestErrorEvent(string message, object eventSource, int eventCode, int eventDetailCode, Exception exception)
:base(message, eventSource, eventCode, eventDetailCode, exception)
{
Init(exception);
}
internal WebRequestErrorEvent() {
// For creating dummy event. See GetSystemDummyEvent()
}
// properties
void InitRequestInformation() {
if (_requestInfo == null) {
_requestInfo = new WebRequestInformation();
}
}
public WebRequestInformation RequestInformation {
get {
InitRequestInformation();
return _requestInfo;
}
}
void InitThreadInformation() {
if (_threadInfo == null) {
_threadInfo = new WebThreadInformation(base.ErrorException);
}
}
public WebThreadInformation ThreadInformation {
get {
InitThreadInformation();
return _threadInfo;
}
}
override internal void FormatToString(WebEventFormatter formatter, bool includeAppInfo) {
base.FormatToString(formatter, includeAppInfo);
formatter.AppendLine(String.Empty);
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_request_information));
formatter.IndentationLevel += 1;
RequestInformation.FormatToString(formatter);
formatter.IndentationLevel -= 1;
formatter.AppendLine(String.Empty);
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_thread_information));
formatter.IndentationLevel += 1;
ThreadInformation.FormatToString(formatter);
formatter.IndentationLevel -= 1;
}
internal override void GenerateFieldsForMarshal(List<WebEventFieldData> fields) {
base.GenerateFieldsForMarshal(fields);
fields.Add(new WebEventFieldData("RequestUrl", RequestInformation.RequestUrl, WebEventFieldType.String));
fields.Add(new WebEventFieldData("RequestPath", RequestInformation.RequestPath, WebEventFieldType.String));
fields.Add(new WebEventFieldData("UserHostAddress", RequestInformation.UserHostAddress, WebEventFieldType.String));
fields.Add(new WebEventFieldData("UserName", RequestInformation.Principal.Identity.Name, WebEventFieldType.String));
fields.Add(new WebEventFieldData("UserAuthenticated", RequestInformation.Principal.Identity.IsAuthenticated.ToString(), WebEventFieldType.Bool));
fields.Add(new WebEventFieldData("UserAuthenticationType", RequestInformation.Principal.Identity.AuthenticationType, WebEventFieldType.String));
fields.Add(new WebEventFieldData("RequestThreadAccountName", RequestInformation.ThreadAccountName, WebEventFieldType.String));
fields.Add(new WebEventFieldData("ThreadID", ThreadInformation.ThreadID.ToString(CultureInfo.InstalledUICulture), WebEventFieldType.Int));
fields.Add(new WebEventFieldData("ThreadAccountName", ThreadInformation.ThreadAccountName, WebEventFieldType.String));
fields.Add(new WebEventFieldData("StackTrace", ThreadInformation.StackTrace, WebEventFieldType.String));
fields.Add(new WebEventFieldData("IsImpersonating", ThreadInformation.IsImpersonating.ToString(), WebEventFieldType.Bool));
}
override internal protected void IncrementPerfCounters() {
base.IncrementPerfCounters();
PerfCounters.IncrementCounter(AppPerfCounter.EVENTS_HTTP_REQ_ERROR);
PerfCounters.IncrementGlobalCounter(GlobalPerfCounter.GLOBAL_EVENTS_HTTP_REQ_ERROR);
}
}
// The base class for all audit events.
public class WebAuditEvent : WebManagementEvent {
WebRequestInformation _requestInfo;
override internal void PreProcessEventInit() {
base.PreProcessEventInit();
InitRequestInformation();
}
internal protected WebAuditEvent(string message, object eventSource, int eventCode)
:base(message, eventSource, eventCode)
{
}
internal protected WebAuditEvent(string message, object eventSource, int eventCode, int eventDetailCode)
:base(message, eventSource, eventCode, eventDetailCode)
{
}
internal WebAuditEvent() {
// For creating dummy event. See GetSystemDummyEvent()
}
void InitRequestInformation() {
if (_requestInfo == null) {
_requestInfo = new WebRequestInformation();
}
}
public WebRequestInformation RequestInformation {
get {
InitRequestInformation();
return _requestInfo;
}
}
internal override void GenerateFieldsForMarshal(List<WebEventFieldData> fields) {
base.GenerateFieldsForMarshal(fields);
fields.Add(new WebEventFieldData("RequestUrl", RequestInformation.RequestUrl, WebEventFieldType.String));
fields.Add(new WebEventFieldData("RequestPath", RequestInformation.RequestPath, WebEventFieldType.String));
fields.Add(new WebEventFieldData("UserHostAddress", RequestInformation.UserHostAddress, WebEventFieldType.String));
fields.Add(new WebEventFieldData("UserName", RequestInformation.Principal.Identity.Name, WebEventFieldType.String));
fields.Add(new WebEventFieldData("UserAuthenticated", RequestInformation.Principal.Identity.IsAuthenticated.ToString(), WebEventFieldType.Bool));
fields.Add(new WebEventFieldData("UserAuthenticationType", RequestInformation.Principal.Identity.AuthenticationType, WebEventFieldType.String));
fields.Add(new WebEventFieldData("RequestThreadAccountName", RequestInformation.ThreadAccountName, WebEventFieldType.String));
}
override internal void FormatToString(WebEventFormatter formatter, bool includeAppInfo) {
base.FormatToString(formatter, includeAppInfo);
formatter.AppendLine(String.Empty);
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_request_information));
formatter.IndentationLevel += 1;
RequestInformation.FormatToString(formatter);
formatter.IndentationLevel -= 1;
}
}
// This class provides information about all failure audits. In most cases,
// applications will only want to enable failure audits.
public class WebFailureAuditEvent : WebAuditEvent {
internal protected WebFailureAuditEvent(string message, object eventSource, int eventCode)
:base(message, eventSource, eventCode)
{
}
internal protected WebFailureAuditEvent(string message, object eventSource, int eventCode, int eventDetailCode)
:base(message, eventSource, eventCode, eventDetailCode)
{
}
internal WebFailureAuditEvent() {
// For creating dummy event. See GetSystemDummyEvent()
}
override internal protected void IncrementPerfCounters() {
base.IncrementPerfCounters();
PerfCounters.IncrementCounter(AppPerfCounter.AUDIT_FAIL);
PerfCounters.IncrementGlobalCounter(GlobalPerfCounter.GLOBAL_AUDIT_FAIL);
}
}
public class WebAuthenticationFailureAuditEvent : WebFailureAuditEvent {
string _nameToAuthenticate;
void Init(string name) {
_nameToAuthenticate = name;
}
internal protected WebAuthenticationFailureAuditEvent(string message, object eventSource, int eventCode, string nameToAuthenticate)
:base(message, eventSource, eventCode)
{
Init(nameToAuthenticate);
}
internal protected WebAuthenticationFailureAuditEvent(string message, object eventSource, int eventCode, int eventDetailCode, string nameToAuthenticate)
:base(message, eventSource, eventCode, eventDetailCode)
{
Init(nameToAuthenticate);
}
internal WebAuthenticationFailureAuditEvent() {
// For creating dummy event. See GetSystemDummyEvent()
}
public string NameToAuthenticate {
get { return _nameToAuthenticate; }
}
internal override void GenerateFieldsForMarshal(List<WebEventFieldData> fields) {
base.GenerateFieldsForMarshal(fields);
fields.Add(new WebEventFieldData("NameToAuthenticate", NameToAuthenticate, WebEventFieldType.String));
}
override internal void FormatToString(WebEventFormatter formatter, bool includeAppInfo) {
base.FormatToString(formatter, includeAppInfo);
formatter.AppendLine(String.Empty);
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_name_to_authenticate, _nameToAuthenticate));
}
}
public class WebViewStateFailureAuditEvent : WebFailureAuditEvent {
ViewStateException _viewStateException;
internal protected WebViewStateFailureAuditEvent(string message, object eventSource, int eventCode, ViewStateException viewStateException)
:base(message, eventSource, eventCode)
{
_viewStateException = viewStateException;
}
internal protected WebViewStateFailureAuditEvent(string message, object eventSource, int eventCode, int eventDetailCode, ViewStateException viewStateException)
:base(message, eventSource, eventCode, eventDetailCode)
{
_viewStateException = viewStateException;
}
internal WebViewStateFailureAuditEvent() {
// For creating dummy event. See GetSystemDummyEvent()
}
public ViewStateException ViewStateException {
get { return _viewStateException; }
}
internal override void GenerateFieldsForMarshal(List<WebEventFieldData> fields) {
base.GenerateFieldsForMarshal(fields);
fields.Add(new WebEventFieldData("ViewStateExceptionMessage", ViewStateException.Message, WebEventFieldType.String));
fields.Add(new WebEventFieldData("RemoteAddress", ViewStateException.RemoteAddress, WebEventFieldType.String));
fields.Add(new WebEventFieldData("RemotePort", ViewStateException.RemotePort, WebEventFieldType.String));
fields.Add(new WebEventFieldData("UserAgent", ViewStateException.UserAgent, WebEventFieldType.String));
fields.Add(new WebEventFieldData("PersistedState", ViewStateException.PersistedState, WebEventFieldType.String));
fields.Add(new WebEventFieldData("Path", ViewStateException.Path, WebEventFieldType.String));
fields.Add(new WebEventFieldData("Referer", ViewStateException.Referer, WebEventFieldType.String));
}
override internal void FormatToString(WebEventFormatter formatter, bool includeAppInfo) {
base.FormatToString(formatter, includeAppInfo);
formatter.AppendLine(String.Empty);
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_ViewStateException_information));
formatter.IndentationLevel += 1;
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_exception_message, _viewStateException.Message));
formatter.IndentationLevel -= 1;
}
}
// This class provides information about all success audits. In most cases,
// applications will only want to enable failure audits.
public class WebSuccessAuditEvent : WebAuditEvent {
internal protected WebSuccessAuditEvent(string message, object eventSource, int eventCode)
:base(message, eventSource, eventCode)
{
}
internal protected WebSuccessAuditEvent(string message, object eventSource, int eventCode, int eventDetailCode)
:base(message, eventSource, eventCode, eventDetailCode)
{
}
internal WebSuccessAuditEvent() {
// For creating dummy event. See GetSystemDummyEvent()
}
override internal protected void IncrementPerfCounters() {
base.IncrementPerfCounters();
PerfCounters.IncrementCounter(AppPerfCounter.AUDIT_SUCCESS);
PerfCounters.IncrementGlobalCounter(GlobalPerfCounter.GLOBAL_AUDIT_SUCCESS);
}
}
public class WebAuthenticationSuccessAuditEvent : WebSuccessAuditEvent {
string _nameToAuthenticate;
void Init(string name) {
_nameToAuthenticate = name;
}
internal protected WebAuthenticationSuccessAuditEvent(string message, object eventSource, int eventCode, string nameToAuthenticate)
:base(message, eventSource, eventCode)
{
Init(nameToAuthenticate);
}
internal protected WebAuthenticationSuccessAuditEvent(string message, object eventSource, int eventCode, int eventDetailCode, string nameToAuthenticate)
:base(message, eventSource, eventCode, eventDetailCode)
{
Init(nameToAuthenticate);
}
internal WebAuthenticationSuccessAuditEvent() {
// For creating dummy event. See GetSystemDummyEvent()
}
public string NameToAuthenticate {
get { return _nameToAuthenticate; }
}
internal override void GenerateFieldsForMarshal(List<WebEventFieldData> fields) {
base.GenerateFieldsForMarshal(fields);
fields.Add(new WebEventFieldData("NameToAuthenticate", NameToAuthenticate, WebEventFieldType.String));
}
override internal void FormatToString(WebEventFormatter formatter, bool includeAppInfo) {
base.FormatToString(formatter, includeAppInfo);
formatter.AppendLine(String.Empty);
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_name_to_authenticate, _nameToAuthenticate));
}
}
////////////////
// Information
////////////////
public sealed class WebProcessInformation {
// The information is per worker process instance.
int _processId;
string _processName;
string _accountName;
internal WebProcessInformation() {
// Can't use Process.ProcessName because it requires the running
// account to be part of the Performance Monitor Users group.
StringBuilder buf = new StringBuilder(256);
if (UnsafeNativeMethods.GetModuleFileName(IntPtr.Zero, buf, 256) == 0) {
_processName = String.Empty;
}
else {
int lastIndex;
_processName = buf.ToString();
lastIndex = _processName.LastIndexOf('\\');
if (lastIndex != -1) {
_processName = _processName.Substring(lastIndex + 1);
}
}
_processId = SafeNativeMethods.GetCurrentProcessId() ;
_accountName = HttpRuntime.WpUserId;
}
public int ProcessID { get { return _processId; } }
public string ProcessName { get { return _processName; } }
public string AccountName { get { return (_accountName != null ? _accountName : String.Empty); } }
public void FormatToString(WebEventFormatter formatter) {
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_process_id, ProcessID.ToString(CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_process_name, ProcessName));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_account_name, AccountName));
}
}
public sealed class WebApplicationInformation {
// The information is per appdomain.
string _appDomain;
string _trustLevel;
string _appUrl;
string _appPath;
string _machineName;
internal WebApplicationInformation() {
_appDomain = Thread.GetDomain().FriendlyName;
_trustLevel = HttpRuntime.TrustLevel;
_appUrl = HttpRuntime.AppDomainAppVirtualPath;
try {
// We will get an exception if it's a non-ASP.NET app.
_appPath = HttpRuntime.AppDomainAppPathInternal;
}
catch {
_appPath = null;
}
#if FEATURE_PAL // FEATURE_PAL does not fully implement Environment.MachineName
_machineName = "dummymachinename";
#else // FEATURE_PAL
_machineName = GetMachineNameWithAssert();
#endif // FEATURE_PAL
}
public string ApplicationDomain { get { return _appDomain; } }
public string TrustLevel { get { return _trustLevel; } }
public string ApplicationVirtualPath { get { return _appUrl; } }
public string ApplicationPath { get { return _appPath; } }
public string MachineName { get { return _machineName; } }
public void FormatToString(WebEventFormatter formatter) {
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_application_domain, ApplicationDomain));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_trust_level, TrustLevel));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_application_virtual_path, ApplicationVirtualPath));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_application_path, ApplicationPath));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_machine_name, MachineName));
}
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
private string GetMachineNameWithAssert() {
return Environment.MachineName;
}
public override string ToString() {
WebEventFormatter formatter = new WebEventFormatter();
FormatToString(formatter);
return formatter.ToString();
}
}
public sealed class WebRequestInformation {
string _requestUrl;
string _requestPath;
IPrincipal _iprincipal;
string _userHostAddress = null;
string _accountName;
internal WebRequestInformation() {
// Need to Assert() in order to get request information regardless of trust level. See VSWhidbey 416733
InternalSecurityPermissions.ControlPrincipal.Assert();
HttpContext context = HttpContext.Current;
HttpRequest request = null;
if (context != null) {
bool hideRequestResponseOriginal = context.HideRequestResponse;
context.HideRequestResponse = false;
request = context.Request;
context.HideRequestResponse = hideRequestResponseOriginal;
_iprincipal = context.User;
// Dev11 #80084 - DTS Bug
// In integrated pipeline, we are very aggressive about disposing
// WindowsIdentity's. If this WebRequestInformation is being used
// post-request (eg, while formatting data for an email provider
// that is reporting batched events), then the User.Identity is
// likely to be disposed. So lets create a clone that will stick
// around. This condition should vaguely match that found in
// HttpContext.DisposePrincipal().
if (_iprincipal is WindowsPrincipal
&& _iprincipal != WindowsAuthenticationModule.AnonymousPrincipal
&& (context.WorkerRequest is IIS7WorkerRequest)) {
WindowsIdentity winIdentity = _iprincipal.Identity as WindowsIdentity;
if (winIdentity != null) {
_iprincipal = new WindowsPrincipal(new WindowsIdentity(winIdentity.Token, winIdentity.AuthenticationType));
}
}
} else {
_iprincipal = null;
}
if (request == null) {
_requestUrl = String.Empty;
_requestPath = String.Empty;
_userHostAddress = String.Empty;
}
else {
_requestUrl = request.UrlInternal;
_requestPath = request.Path;
_userHostAddress = request.UserHostAddress;
}
_accountName = WindowsIdentity.GetCurrent().Name;
}
// The information is per request.
public string RequestUrl {get {return _requestUrl;}}
public string RequestPath {get {return _requestPath;}}
public IPrincipal Principal {get {return _iprincipal;}}
public string UserHostAddress { get { return _userHostAddress;} }
public string ThreadAccountName {get {return _accountName;}}
public void FormatToString(WebEventFormatter formatter) {
string user;
string authType;
bool authed;
if (Principal == null) {
user = String.Empty;
authType = String.Empty;
authed = false;
}
else {
IIdentity id = Principal.Identity;
user = id.Name;
authed = id.IsAuthenticated;
authType = id.AuthenticationType;
}
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_request_url, RequestUrl));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_request_path, RequestPath));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_user_host_address, UserHostAddress));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_user, user));
if (authed) {
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_is_authenticated));
}
else {
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_is_not_authenticated));
}
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_authentication_type, authType));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_thread_account_name, ThreadAccountName));
}
}
// Note that even all the information contained in WebProcessStatistics is obtained from static variables,
// but we still don't want this class to be static.
//
// Currently, WebProcessStatistics can be obtained only thru WebHeartbeatEvent, which in turn can be
// created only by Full-trust app thru class inheritance. (System.Web.dll will also internally create it
// and the object will be available to our provider.) Thus, WebProcessStatistics is available only
// to Full-trust app or provider.
//
// But if we make WebProcessStatistics static, then all its public methods have to be static, and
// they'll be fully available to all users. No good.
public class WebProcessStatistics {
static DateTime s_startTime = DateTime.MinValue;
static DateTime s_lastUpdated = DateTime.MinValue;
static int s_threadCount;
static long s_workingSet;
static long s_peakWorkingSet;
static long s_managedHeapSize;
static int s_appdomainCount;
static int s_requestsExecuting;
static int s_requestsQueued;
static int s_requestsRejected;
static bool s_getCurrentProcFailed = false;
static object s_lockObject = new object();
static TimeSpan TS_ONE_SECOND = new TimeSpan(0, 0, 1);
static WebProcessStatistics() {
try {
#if !FEATURE_PAL // FEATURE_PAL does not support this. Make into a noop.
s_startTime = Process.GetCurrentProcess().StartTime;
#endif // !FEATURE_PAL
}
catch {
s_getCurrentProcFailed = true;
}
}
void Update() {
DateTime now = DateTime.Now;
if (now - s_lastUpdated < TS_ONE_SECOND) {
return;
}
lock (s_lockObject) {
if (now - s_lastUpdated < TS_ONE_SECOND) {
return;
}
if (!s_getCurrentProcFailed) {
Process process = Process.GetCurrentProcess();
#if !FEATURE_PAL // FEATURE_PAL does not support these Process properties
s_threadCount = process.Threads.Count;
s_workingSet = (long)process.WorkingSet64;
s_peakWorkingSet = (long)process.PeakWorkingSet64;
#else
throw new NotImplementedException ("ROTORTODO");
#endif
}
s_managedHeapSize = GC.GetTotalMemory(false);
s_appdomainCount = HostingEnvironment.AppDomainsCount;
s_requestsExecuting = PerfCounters.GetGlobalCounter(GlobalPerfCounter.REQUESTS_CURRENT);
s_requestsQueued = PerfCounters.GetGlobalCounter(GlobalPerfCounter.REQUESTS_QUEUED);
s_requestsRejected = PerfCounters.GetGlobalCounter(GlobalPerfCounter.REQUESTS_REJECTED);
s_lastUpdated = now;
}
}
public DateTime ProcessStartTime {get {Update(); return s_startTime;}}
public int ThreadCount {get {Update(); return s_threadCount;}}
public long WorkingSet {get {Update(); return s_workingSet;}}
public long PeakWorkingSet {get {Update(); return s_peakWorkingSet;}}
public long ManagedHeapSize {get {Update(); return s_managedHeapSize;}}
public int AppDomainCount {get {Update(); return s_appdomainCount;}}
public int RequestsExecuting {get {Update(); return s_requestsExecuting;}}
public int RequestsQueued {get {Update(); return s_requestsQueued;}}
public int RequestsRejected {get {Update(); return s_requestsRejected;}}
virtual public void FormatToString(WebEventFormatter formatter) {
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_process_start_time, ProcessStartTime.ToString(CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_thread_count, ThreadCount.ToString(CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_working_set, WorkingSet.ToString(CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_peak_working_set, PeakWorkingSet.ToString(CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_managed_heap_size, ManagedHeapSize.ToString(CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_application_domain_count, AppDomainCount.ToString(CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_requests_executing, RequestsExecuting.ToString(CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_request_queued, RequestsQueued.ToString(CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_request_rejected, RequestsRejected.ToString(CultureInfo.InstalledUICulture)));
}
}
public sealed class WebThreadInformation {
int _threadId;
string _accountName;
string _stackTrace;
bool _isImpersonating;
internal const string IsImpersonatingKey = "ASPIMPERSONATING";
internal WebThreadInformation(Exception exception) {
_threadId = Thread.CurrentThread.ManagedThreadId;
_accountName = HttpApplication.GetCurrentWindowsIdentityWithAssert().Name;
if (exception != null) {
_stackTrace = new StackTrace(exception, true).ToString();
_isImpersonating = exception.Data.Contains(IsImpersonatingKey);
}
else {
_stackTrace = String.Empty;
_isImpersonating = false;
}
}
public int ThreadID {get {return _threadId;}}
public string ThreadAccountName {get {return _accountName;}}
public string StackTrace {get {return _stackTrace;}}
public bool IsImpersonating {get {return _isImpersonating;}}
public void FormatToString(WebEventFormatter formatter) {
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_thread_id, ThreadID.ToString(CultureInfo.InstalledUICulture)));
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_thread_account_name, ThreadAccountName));
if (IsImpersonating) {
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_is_impersonating));
}
else {
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_is_not_impersonating));
}
formatter.AppendLine(WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_event_stack_trace, StackTrace));
}
}
// Class that represents the firing record (how many times, last firing time, etc)
// for each rule that inherits from WebBaseEvent.
public sealed class RuleFiringRecord {
internal DateTime _lastFired;
internal int _timesRaised;
internal int _updatingLastFired;
static TimeSpan TS_ONE_SECOND = new TimeSpan(0, 0, 1);
public DateTime LastFired { get { return _lastFired; } }
public int TimesRaised { get { return _timesRaised; } }
// Point to the ruleInfo that is used by this class
internal HealthMonitoringSectionHelper.RuleInfo _ruleInfo;
internal RuleFiringRecord(HealthMonitoringSectionHelper.RuleInfo ruleInfo) {
Debug.Assert(ruleInfo != null, "ruleInfo != null");
_ruleInfo = ruleInfo;
_lastFired = DateTime.MinValue;
_timesRaised = 0;
_updatingLastFired = 0;
}
void UpdateLastFired(DateTime now, bool alreadyLocked) {
TimeSpan tsDiff = now - _lastFired;
if (tsDiff < TS_ONE_SECOND) {
// If _lastFired was updated within one second, don't bother.
return;
}
if (!alreadyLocked) {
// If several threads are firing at the same time, only one thread will
// update record._lastFired.
if (Interlocked.CompareExchange(ref _updatingLastFired, 1, 0) == 0) {
try {
_lastFired = now;
}
finally {
Interlocked.Exchange(ref _updatingLastFired, 0);
}
}
}
else {
_lastFired = now;
}
}
// Note: this method is thread safe
internal bool CheckAndUpdate(WebBaseEvent eventRaised) {
DateTime now = DateTime.Now;
int timesRaised;
HealthMonitoringManager manager = HealthMonitoringManager.Manager();
timesRaised = Interlocked.Increment(ref _timesRaised);
if (manager == null) {
// Won't fire because we cannot configure healthmonitor
Debug.Trace("RuleFiringRecord", "Can't configure healthmonitor");
return false;
}
// Call custom evaluator first
if (_ruleInfo._customEvaluatorType != null) {
IWebEventCustomEvaluator icustom = (IWebEventCustomEvaluator)
manager._sectionHelper._customEvaluatorInstances[_ruleInfo._customEvaluatorType];
#if (!DBG)
try {
#endif
// The event may need to do pre-ProcessEvent initialization
eventRaised.PreProcessEventInit();
if (!icustom.CanFire(eventRaised, this)) {
Debug.Trace("RuleFiringRecord", "Custom evaluator returns false.");
return false;
}
#if (!DBG)
}
catch {
Debug.Trace("RuleFiringRecord", "Hit an exception when calling Custom evaluator");
// Return if we hit an error
return false;
}
#endif
}
if (timesRaised < _ruleInfo._minInstances) {
Debug.Trace("RuleFiringRecord",
"MinInterval not met; timesRaised=" + timesRaised +
"; _minInstances=" + _ruleInfo._minInstances);
return false;
}
if (timesRaised > _ruleInfo._maxLimit) {
Debug.Trace("RuleFiringRecord",
"MaxLimit exceeded; timesRaised=" + timesRaised +
"; _maxLimit=" + _ruleInfo._maxLimit);
return false;
}
// Last step: Check MinInterval and update _lastFired
if (_ruleInfo._minInterval == TimeSpan.Zero) {
UpdateLastFired(now, false);
return true;
}
if ((now - _lastFired) <= _ruleInfo._minInterval) {
Debug.Trace("RuleFiringRecord",
"MinInterval not met; now=" + now +
"; _lastFired=" + _lastFired +
"; _ruleInfo._minInterval=" + _ruleInfo._minInterval);
return false;
}
// The lock is to prevent multiple threads from passing the
// same test simultaneously.
lock (this) {
if ((now - _lastFired) <= _ruleInfo._minInterval) {
Debug.Trace("RuleFiringRecord",
"MinInterval not met; now=" + now +
"; _lastFired=" + _lastFired +
"; _ruleInfo._tsMinInterval=" + _ruleInfo._minInterval);
return false;
}
UpdateLastFired(now, true);
return true;
}
}
}
internal class HealthMonitoringManager {
internal HealthMonitoringSectionHelper _sectionHelper;
internal bool _enabled = false;
static Timer s_heartbeatTimer = null;
static HealthMonitoringManager s_manager = null;
static bool s_inited = false;
static bool s_initing = false;
static object s_lockObject = new object();
static bool s_isCacheDisposed = false;
// If this method returns null, it means we failed during configuration.
internal static HealthMonitoringManager Manager() {
if (s_initing) {
Debug.Assert(!s_inited);
// If this is true, that means we are calling WebEventBase.Raise while
// we are initializing. That means Init() has caused a config exception.
return null;
}
if (s_inited) {
return s_manager;
}
lock (s_lockObject) {
if (s_inited) {
return s_manager;
}
try {
Debug.Assert(s_manager == null);
s_initing = true;
s_manager = new HealthMonitoringManager();;
}
finally {
s_initing = false;
s_inited = true;
}
}
return s_manager;
}
internal static bool Enabled {
get {
// DevDiv 92252: Visual Studio 2010 freezes when opening .cs file in App_Code directory
// Never raise webevents from CBM process
if (HostingEnvironment.InClientBuildManager) {
return false;
}
HealthMonitoringManager manager = HealthMonitoringManager.Manager();
if (manager == null) {
return false;
}
return manager._enabled;
}
}
internal static bool IsCacheDisposed { get { return s_isCacheDisposed; } set { s_isCacheDisposed = value; } }
internal static void StartHealthMonitoringHeartbeat() {
HealthMonitoringManager manager = Manager();
if (manager == null) {
Debug.Trace(
"HealthMonitoringManager", "Can't fire heartbeat because we cannot configure HealthMon");
return;
}
if (!manager._enabled) {
Debug.Trace(
"WebEventRaiseDetails", "Can't fire heartbeat because we are disabled");
return;
}
manager.StartHeartbeatTimer();
}
private HealthMonitoringManager() {
_sectionHelper = HealthMonitoringSectionHelper.GetHelper();
_enabled = _sectionHelper.Enabled;
if (!_enabled) {
return;
}
}
internal static void Shutdown() {
WebEventManager.Shutdown();
Dispose();
}
internal static void Dispose() {
// Make sure this function won't throw
try {
if (s_heartbeatTimer != null) {
s_heartbeatTimer.Dispose();
s_heartbeatTimer = null;
}
}
catch {
}
}
internal void HeartbeatCallback(object state) {
Debug.Assert(HealthMonitoringManager.Enabled);
WebBaseEvent.RaiseSystemEvent(null, WebEventCodes.ApplicationHeartbeat);
}
internal void StartHeartbeatTimer() {
TimeSpan interval = _sectionHelper.HealthMonitoringSection.HeartbeatInterval;
if (interval == TimeSpan.Zero) {
return;
}
#if DBG
if (!Debug.IsTagPresent("Timer") || Debug.IsTagEnabled("Timer"))
#endif
{
s_heartbeatTimer = new Timer(new TimerCallback(this.HeartbeatCallback), null,
TimeSpan.Zero, interval);
}
}
internal static HealthMonitoringSectionHelper.ProviderInstances ProviderInstances {
get {
HealthMonitoringManager manager = Manager();
if (manager == null) {
return null;
}
if (!manager._enabled) {
return null;
}
return manager._sectionHelper._providerInstances;
}
}
}
public sealed class WebBaseEventCollection : ReadOnlyCollectionBase
{
public WebBaseEventCollection(ICollection events) {
if (events == null) {
throw new ArgumentNullException("events");
}
foreach (WebBaseEvent eventRaised in events) {
InnerList.Add(eventRaised);
}
}
internal WebBaseEventCollection(WebBaseEvent eventRaised) {
if (eventRaised == null) {
throw new ArgumentNullException("eventRaised");
}
InnerList.Add(eventRaised);
}
// overloaded collection access methods
public WebBaseEvent this[int index] {
get {
return (WebBaseEvent) InnerList[index];
}
}
public int IndexOf(WebBaseEvent value) {
return InnerList.IndexOf(value);
}
public bool Contains(WebBaseEvent value) {
return InnerList.Contains(value);
}
}
public static class WebEventManager
{
[SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
public static void Flush(string providerName) {
HealthMonitoringSectionHelper.ProviderInstances providers = HealthMonitoringManager.ProviderInstances;
if (providers == null) {
return;
}
if (!providers.ContainsKey(providerName)) {
throw new ArgumentException(SR.GetString(SR.Health_mon_provider_not_found, providerName));
}
using (new ApplicationImpersonationContext()) {
providers[providerName].Flush();
}
}
[SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
public static void Flush() {
HealthMonitoringSectionHelper.ProviderInstances providers = HealthMonitoringManager.ProviderInstances;
if (providers == null) {
return;
}
using (new ApplicationImpersonationContext()) {
foreach(DictionaryEntry de in providers) {
WebEventProvider provider = (WebEventProvider)de.Value;
Debug.Trace("WebEventManager", "Flushing provider " + provider.Name);
provider.Flush();
}
}
}
internal static void Shutdown() {
HealthMonitoringSectionHelper.ProviderInstances providers = HealthMonitoringManager.ProviderInstances;
if (providers == null) {
return;
}
foreach(DictionaryEntry de in providers) {
WebEventProvider provider = (WebEventProvider)de.Value;
Debug.Trace("WebEventManager", "Shutting down provider " + provider.Name);
provider.Shutdown();
}
}
}
}
|