1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508
|
//------------------------------------------------------------------------------
// <copyright file="Page.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
// Uncomment out this line to display rare field statistics at the end of the page
//#define DISPLAYRAREFIELDSTATISTICS
/*
* Page class definition
*
* Copyright (c) 1998 Microsoft Corporation
*/
namespace System.Web.UI {
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Configuration;
using System.EnterpriseServices;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Web.Compilation;
using System.Web.Configuration;
using System.Web.Handlers;
using System.Web.Hosting;
using System.Web.Management;
using System.Web.RegularExpressions;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.UI.Adapters;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.Util;
using System.Xml;
using System.Web.Routing;
using System.Web.ModelBinding;
using System.Web.Security.Cryptography;
/// <devdoc>
/// Default ControlBuilder used to parse page files.
/// </devdoc>
public class FileLevelPageControlBuilder: RootBuilder {
private ArrayList _contentBuilderEntries;
private ControlBuilder _firstControlBuilder;
private int _firstLiteralLineNumber;
private bool _containsContentPage;
private string _firstLiteralText;
internal ICollection ContentBuilderEntries {
get {
return _contentBuilderEntries;
}
}
public override void AppendLiteralString(string text) {
if (_firstLiteralText == null) {
if (!Util.IsWhiteSpaceString(text)) {
int iFirstNonWhiteSpace = Util.FirstNonWhiteSpaceIndex(text);
if (iFirstNonWhiteSpace < 0) iFirstNonWhiteSpace = 0;
_firstLiteralLineNumber = Parser._lineNumber - Util.LineCount(text, iFirstNonWhiteSpace, text.Length);
_firstLiteralText = text;
if (_containsContentPage) {
throw new HttpException(SR.GetString(SR.Only_Content_supported_on_content_page));
}
}
}
base.AppendLiteralString(text);
}
public override void AppendSubBuilder(ControlBuilder subBuilder) {
// Tell the sub builder that it's about to be appended to its parent
if (subBuilder is ContentBuilderInternal) {
ContentBuilderInternal contentBuilder = (ContentBuilderInternal)subBuilder;
_containsContentPage = true;
if (_contentBuilderEntries == null) {
_contentBuilderEntries = new ArrayList();
}
if (_firstLiteralText != null) {
throw new HttpParseException(SR.GetString(SR.Only_Content_supported_on_content_page),
null, Parser.CurrentVirtualPath, _firstLiteralText, _firstLiteralLineNumber);
}
if (_firstControlBuilder != null) {
Parser._lineNumber = _firstControlBuilder.Line;
throw new HttpException(SR.GetString(SR.Only_Content_supported_on_content_page));
}
TemplatePropertyEntry entry = new TemplatePropertyEntry();
entry.Filter = contentBuilder.ContentPlaceHolderFilter;
entry.Name = contentBuilder.ContentPlaceHolder;
entry.Builder = contentBuilder;
_contentBuilderEntries.Add(entry);
}
else {
if (_firstControlBuilder == null) {
if (_containsContentPage) {
throw new HttpException(SR.GetString(SR.Only_Content_supported_on_content_page));
}
_firstControlBuilder = subBuilder;
}
}
base.AppendSubBuilder(subBuilder);
}
internal override void InitObject(object obj) {
base.InitObject(obj);
if (_contentBuilderEntries == null)
return;
ICollection entries = GetFilteredPropertyEntrySet(_contentBuilderEntries);
foreach(TemplatePropertyEntry entry in entries) {
ContentBuilderInternal contentBuilder = (ContentBuilderInternal)entry.Builder;
try {
contentBuilder.SetServiceProvider(ServiceProvider);
// Note that 'obj' can be either a Page or a MasterPage,
// hence the need for this virtual method.
AddContentTemplate(obj, contentBuilder.ContentPlaceHolder, contentBuilder.BuildObject() as ITemplate);
}
finally {
contentBuilder.SetServiceProvider(null);
}
}
}
internal virtual void AddContentTemplate(object obj, string templateName, ITemplate template) {
Page page = (Page)obj;
page.AddContentTemplate(templateName, template);
}
internal override void SortEntries() {
base.SortEntries();
FilteredPropertyEntryComparer comparer = null;
ProcessAndSortPropertyEntries(_contentBuilderEntries, ref comparer);
}
}
/// <devdoc>
/// <para>
/// Defines the properties, methods, and events common to
/// all pages that are processed on the server by the Web Forms page framework.
/// <see langword='Page '/>
/// objects are compiled and cached in
/// memory when any ASP.NET page is
/// requested.</para>
/// <para>This class is not marked as abstract, because the VS designer
/// needs to instantiate it when opening .ascx files</para>
/// </devdoc>
[
DefaultEvent("Load"),
Designer("Microsoft.VisualStudio.Web.WebForms.WebFormDesigner, " + AssemblyRef.MicrosoftVisualStudioWeb, typeof(IRootDesigner)),
DesignerCategory("ASPXCodeBehind"),
DesignerSerializer("Microsoft.VisualStudio.Web.WebForms.WebFormCodeDomSerializer, " + AssemblyRef.MicrosoftVisualStudioWeb, "System.ComponentModel.Design.Serialization.TypeCodeDomSerializer, " + AssemblyRef.SystemDesign),
ToolboxItem(false)
]
public class Page: TemplateControl, IHttpHandler {
private const string HiddenClassName = "aspNetHidden";
private const string PageID = "__Page";
private const string PageScrollPositionScriptKey = "PageScrollPositionScript";
private const string PageSubmitScriptKey = "PageSubmitScript";
private const string PageReEnableControlsScriptKey = "PageReEnableControlsScript";
// NOTE: Make sure this stays in sync with MobilePage.PageRegisteredControlsThatRequirePostBackKey
//
private const string PageRegisteredControlsThatRequirePostBackKey = "__ControlsRequirePostBackKey__";
private const string EnabledControlArray = "__enabledControlArray";
//used by TemplateControl to hookup auto-events
internal static readonly object EventPreRenderComplete = new Object();
internal static readonly object EventPreLoad = new object();
internal static readonly object EventLoadComplete = new object();
internal static readonly object EventPreInit = new object();
internal static readonly object EventInitComplete = new object();
internal static readonly object EventSaveStateComplete = new object();
private static readonly Version FocusMinimumEcmaVersion = new Version("1.4");
private static readonly Version FocusMinimumJScriptVersion = new Version("3.0");
private static readonly Version JavascriptMinimumVersion = new Version("1.0");
private static readonly Version MSDomScrollMinimumVersion = new Version("4.0");
// Review: this is consistent with MMIT legacy -do we prefer two underscores?
private static readonly string UniqueFilePathSuffixID = "__ufps";
private string _uniqueFilePathSuffix;
internal static readonly int DefaultMaxPageStateFieldLength = -1;
internal static readonly int DefaultAsyncTimeoutSeconds = 45;
private int _maxPageStateFieldLength = DefaultMaxPageStateFieldLength;
private string _requestViewState;
private bool _cachedRequestViewState;
private PageAdapter _pageAdapter;
// Has the page layout changed since last request
private bool _fPageLayoutChanged;
private bool _haveIdSeparator;
private char _idSeparator;
// Session state
private bool _sessionRetrieved;
private HttpSessionState _session;
private int _transactionMode; /* 0 = TransactionOption.Disabled*/
private bool _aspCompatMode;
private bool _asyncMode;
// Async related
private static readonly TimeSpan _maxAsyncTimeout = TimeSpan.FromMilliseconds(Int32.MaxValue);
private TimeSpan _asyncTimeout;
private bool _asyncTimeoutSet;
private PageAsyncTaskManager _asyncTaskManager;
private LegacyPageAsyncTaskManager _legacyAsyncTaskManager;
private LegacyPageAsyncInfo _legacyAsyncInfo;
// Page culture and uiculture set dynamically
private CultureInfo _dynamicCulture;
private CultureInfo _dynamicUICulture;
// ViewState
private string _clientState;
private PageStatePersister _persister;
internal ControlSet _registeredControlsRequiringControlState;
private StringSet _controlStateLoadedControlIds;
internal HybridDictionary _registeredControlsRequiringClearChildControlState;
internal const ViewStateEncryptionMode EncryptionModeDefault = ViewStateEncryptionMode.Auto;
private ViewStateEncryptionMode _encryptionMode = EncryptionModeDefault;
private bool _viewStateEncryptionRequested;
private ArrayList _enabledControls;
// Http Intrinsics
internal HttpRequest _request;
internal HttpResponse _response;
internal HttpApplicationState _application;
internal Cache _cache;
internal string _errorPage;
private string _clientTarget;
// Form related fields
private HtmlForm _form;
private bool _inOnFormRender;
private bool _fOnFormRenderCalled;
private bool _fRequireWebFormsScript;
private bool _fWebFormsScriptRendered;
private bool _fRequirePostBackScript;
private bool _fPostBackScriptRendered;
private bool _containsCrossPagePost;
private RenderMethod _postFormRenderDelegate;
internal Dictionary<String, String> _hiddenFieldsToRender;
private bool _requireFocusScript;
private bool _profileTreeBuilt;
internal const bool MaintainScrollPositionOnPostBackDefault = false;
private bool _maintainScrollPosition = MaintainScrollPositionOnPostBackDefault;
private ClientScriptManager _clientScriptManager;
// Needed to support Validators in AJAX 1.0 (Windows OS Bugs 2015831)
private static Type _scriptManagerType;
internal const bool EnableViewStateMacDefault = true;
internal const bool EnableEventValidationDefault = true;
internal const string systemPostFieldPrefix = "__";
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
public const string postEventSourceID = systemPostFieldPrefix + "EVENTTARGET";
private const string lastFocusID = systemPostFieldPrefix + "LASTFOCUS";
private const string _scrollPositionXID = systemPostFieldPrefix + "SCROLLPOSITIONX";
private const string _scrollPositionYID = systemPostFieldPrefix + "SCROLLPOSITIONY";
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
public const string postEventArgumentID = systemPostFieldPrefix + "EVENTARGUMENT";
internal const string ViewStateFieldPrefixID = systemPostFieldPrefix + "VIEWSTATE";
internal const string ViewStateFieldCountID = ViewStateFieldPrefixID + "FIELDCOUNT";
internal const string ViewStateGeneratorFieldID = ViewStateFieldPrefixID + "GENERATOR";
internal const string ViewStateEncryptionID = systemPostFieldPrefix + "VIEWSTATEENCRYPTED";
internal const string EventValidationPrefixID = systemPostFieldPrefix + "EVENTVALIDATION";
// Any change in this constant must be duplicated in DetermineIsExportingWebPart
internal const string WebPartExportID = systemPostFieldPrefix + "WEBPARTEXPORT";
private bool _requireScrollScript;
private bool _isCallback;
private bool _isCrossPagePostBack;
private bool _containsEncryptedViewState;
private bool _enableEventValidation = EnableEventValidationDefault;
internal const string callbackID = systemPostFieldPrefix + "CALLBACKID";
internal const string callbackParameterID = systemPostFieldPrefix + "CALLBACKPARAM";
internal const string callbackLoadScriptID = systemPostFieldPrefix + "CALLBACKLOADSCRIPT";
internal const string callbackIndexID = systemPostFieldPrefix + "CALLBACKINDEX";
internal const string previousPageID = systemPostFieldPrefix + "PREVIOUSPAGE";
// BasePartialCachingControl's currently on the stack
private Stack _partialCachingControlStack;
private ArrayList _controlsRequiringPostBack;
private ArrayList _registeredControlsThatRequirePostBack;
private NameValueCollection _leftoverPostData;
private IPostBackEventHandler _registeredControlThatRequireRaiseEvent;
private ArrayList _changedPostDataConsumers;
private bool _needToPersistViewState;
private bool _enableViewStateMac;
private string _viewStateUserKey;
private string _themeName;
private PageTheme _theme;
private string _styleSheetName;
private PageTheme _styleSheet;
private VirtualPath _masterPageFile;
private MasterPage _master;
private IDictionary _contentTemplateCollection;
private SmartNavigationSupport _smartNavSupport;
internal HttpContext _context;
private ValidatorCollection _validators;
private bool _validated;
private HtmlHead _header;
private int _supportsStyleSheets;
private Control _autoPostBackControl;
private string _focusedControlID;
private Control _focusedControl;
private string _validatorInvalidControl;
private int _scrollPositionX;
private int _scrollPositionY;
private Page _previousPage;
private VirtualPath _previousPagePath;
private bool _preInitWorkComplete;
private bool _clientSupportsJavaScriptChecked;
private bool _clientSupportsJavaScript;
private string _titleToBeSet;
private string _descriptionToBeSet;
private string _keywordsToBeSet;
private ICallbackEventHandler _callbackControl;
// DevDiv 33149, 43258: A backward compat. switch for Everett rendering,
private bool _xhtmlConformanceModeSet;
private XhtmlConformanceMode _xhtmlConformanceMode;
// const masks into the BitVector32
private const int styleSheetInitialized = 0x00000001;
private const int isExportingWebPart = 0x00000002;
private const int isExportingWebPartShared = 0x00000004;
private const int isCrossPagePostRequest = 0x00000008;
// Needed to support Validators in AJAX 1.0 (Windows OS Bugs 2015831)
private const int isPartialRenderingSupported = 0x00000010;
private const int isPartialRenderingSupportedSet = 0x00000020;
private const int skipFormActionValidation = 0x00000040;
private const int wasViewStateMacErrorSuppressed = 0x00000080;
// Todo: Move boolean fields into _pageFlags.
#pragma warning disable 0649
private SimpleBitVector32 _pageFlags;
#pragma warning restore 0649
// Can be either Context.Request.Form or Context.Request.QueryString
// depending on the method used.
private NameValueCollection _requestValueCollection;
// The unvalidated version of _requestValueCollection
private NameValueCollection _unvalidatedRequestValueCollection;
private ModelStateDictionary _modelState;
private ModelBindingExecutionContext _modelBindingExecutionContext;
private UnobtrusiveValidationMode? _unobtrusiveValidationMode;
private bool _executingAsyncTasks = false;
private static StringSet s_systemPostFields;
static Page() {
// Create a static hashtable with all the names that should be
// ignored in ProcessPostData().
s_systemPostFields = new StringSet();
s_systemPostFields.Add(postEventSourceID);
s_systemPostFields.Add(postEventArgumentID);
s_systemPostFields.Add(ViewStateFieldCountID);
s_systemPostFields.Add(ViewStateGeneratorFieldID);
s_systemPostFields.Add(ViewStateFieldPrefixID);
s_systemPostFields.Add(ViewStateEncryptionID);
s_systemPostFields.Add(previousPageID);
s_systemPostFields.Add(callbackID);
s_systemPostFields.Add(callbackParameterID);
s_systemPostFields.Add(lastFocusID);
s_systemPostFields.Add(UniqueFilePathSuffixID);
s_systemPostFields.Add(HttpResponse.RedirectQueryStringVariable);
s_systemPostFields.Add(EventValidationPrefixID);
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Web.UI.Page'/> class.</para>
/// </devdoc>
public Page() {
_page = this; // Set the page to ourselves
_enableViewStateMac = EnableViewStateMacDefault;
// Ensure that the page has an ID, for things like trace
ID = PageID;
_supportsStyleSheets = -1;
// Set the default ValidateRequestMode of a page to Enabled since the value Inherit
// does not make sense as the page has nobody to inherit from.
// Also, since this is the default value for Page, we do not want this value to be
// stored in ViewState , so we set the value here but do not set the property changed
// flag so that it's not stored in ViewState by default.
SetValidateRequestModeInternal(ValidateRequestMode.Enabled, setDirty: false);
}
public ModelStateDictionary ModelState {
get {
if (_modelState == null) {
_modelState = new ModelStateDictionary();
}
return _modelState;
}
}
private IValueProvider ActiveValueProvider {
get;
set;
}
internal bool IsExecutingAsyncTasks {
get {
return _executingAsyncTasks;
}
set {
_executingAsyncTasks = value;
}
}
public ModelBindingExecutionContext ModelBindingExecutionContext {
get {
if (_modelBindingExecutionContext == null) {
_modelBindingExecutionContext = new ModelBindingExecutionContext(new HttpContextWrapper(Context), this.ModelState);
//This is used to query the ViewState in ViewStateValueProvider later.
_modelBindingExecutionContext.PublishService<StateBag>(ViewState);
//This is used to query RouteData in RouteDataValueProvider later.
_modelBindingExecutionContext.PublishService<RouteData>(RouteData);
}
return _modelBindingExecutionContext;
}
}
/// <summary>
/// We support calling TryUpdateModel only within a Data Method of DataBoundControl.
/// So this method provides a way to enfore that.
/// This sets the active value provider which is used to provide the values for
/// TryUpdateModel. This method should be called before calling TryUpdateModel otherwise the latter
/// would throw. Also it's callers responsibility to reset the active value Provider by calling this
/// method again with null values. (Currently this is all done by ModelDataSourceView).
/// </summary>
internal void SetActiveValueProvider(IValueProvider valueProvider) {
ActiveValueProvider = valueProvider;
}
/// <summary>
/// Attempts to update the model object from the values within a databound control. This
/// must be invoked within the Select/Update/Delete/InsertMethods used for data binding.
/// </summary>
/// <returns>True if the model object is updated succesfully with valid values. False otherwise.</returns>
public virtual bool TryUpdateModel<TModel>(TModel model) where TModel : class {
if (ActiveValueProvider == null) {
throw new InvalidOperationException(SR.GetString(SR.Page_InvalidUpdateModelAttempt, "TryUpdateModel"));
}
return TryUpdateModel<TModel>(model, ActiveValueProvider);
}
/// <summary>
/// Attempts to update the model object from the values provided by given valueProvider.
/// </summary>
/// <returns>True if the model object is updated succesfully with valid values. False otherwise.</returns>
public virtual bool TryUpdateModel<TModel>(TModel model, IValueProvider valueProvider) where TModel : class {
if (model == null) {
throw new ArgumentNullException("model");
}
if (valueProvider == null) {
throw new ArgumentNullException("valueProvider");
}
IModelBinder binder = ModelBinders.Binders.DefaultBinder;
ModelBindingContext bindingContext = new ModelBindingContext() {
ModelBinderProviders = ModelBinderProviders.Providers,
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(TModel)),
ModelState = ModelState,
ValueProvider = valueProvider
};
if (binder.BindModel(ModelBindingExecutionContext, bindingContext)) {
return ModelState.IsValid;
}
//ModelBinding failed!!!
return false;
}
/// <summary>
/// Updates the model object from the values within a databound control. This must be invoked
/// within the Select/Update/Delete/InsertMethods used for data binding.
/// Throws an exception if the update fails.
/// </summary>
public virtual void UpdateModel<TModel>(TModel model) where TModel : class {
if (ActiveValueProvider == null) {
throw new InvalidOperationException(SR.GetString(SR.Page_InvalidUpdateModelAttempt, "UpdateModel"));
}
UpdateModel<TModel>(model, ActiveValueProvider);
}
/// <summary>
/// Updates the model object from the values provided by given valueProvider.
/// Throws an exception if the update fails.
/// </summary>
public virtual void UpdateModel<TModel>(TModel model, IValueProvider valueProvider) where TModel : class {
if (!TryUpdateModel(model, valueProvider)) {
throw new InvalidOperationException(SR.GetString(SR.Page_UpdateModel_UpdateUnsuccessful, typeof(TModel).FullName));
}
}
[
DefaultValue(UnobtrusiveValidationMode.None),
WebCategory("Behavior"),
WebSysDescription(SR.Page_UnobtrusiveValidationMode)
]
public UnobtrusiveValidationMode UnobtrusiveValidationMode {
get {
return _unobtrusiveValidationMode ?? ValidationSettings.UnobtrusiveValidationMode;
}
set {
if (value < UnobtrusiveValidationMode.None || value > UnobtrusiveValidationMode.WebForms) {
throw new ArgumentOutOfRangeException("value");
}
_unobtrusiveValidationMode = value;
}
}
/// <devdoc>
/// <para>Gets the <see langword='Application'/> object provided by the HTTP Runtime.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public HttpApplicationState Application {
get {
return _application;
}
}
/// <devdoc>
/// <para>Gets the HttpContext for the Page.</para>
/// </devdoc>
protected internal override HttpContext Context {
get {
if (_context == null) {
_context = HttpContext.Current;
}
return _context;
}
}
// Set of unique control ids which have already loaded control state
private StringSet ControlStateLoadedControlIds {
get {
if (_controlStateLoadedControlIds == null) {
_controlStateLoadedControlIds = new StringSet();
}
return _controlStateLoadedControlIds;
}
}
/// <devdoc>
/// The value to be written to the __VIEWSTATE hidden fields. Getter is exposed through a protected property in
/// PageAdapter.
/// </devdoc>
internal string ClientState {
get {
return _clientState;
}
set {
_clientState = value;
}
}
/*
* Any onsubmit statment to hook up by the form. The HtmlForm object calls this
* during RenderAttributes.
*/
internal string ClientOnSubmitEvent {
get {
if (ClientScript.HasSubmitStatements ||
(Form != null && Form.SubmitDisabledControls && (EnabledControls.Count > 0))) {
// to avoid being affected by earlier instructions we must
// write out the language as well
return "javascript:return WebForm_OnSubmit();";
}
return string.Empty;
}
}
public ClientScriptManager ClientScript {
get {
if (_clientScriptManager == null) {
_clientScriptManager = new ClientScriptManager(this);
}
return _clientScriptManager;
}
}
/// <devdoc>
/// <para>Indicates whether the requesting browser is uplevel or downlevel so that the appropriate behavior can be
/// generated for the request.</para>
/// </devdoc>
[
DefaultValue(""),
WebSysDescription(SR.Page_ClientTarget),
Browsable(false),
EditorBrowsable(EditorBrowsableState.Advanced),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public string ClientTarget {
get {
return (_clientTarget == null) ? String.Empty : _clientTarget;
}
set {
_clientTarget = value;
if (_request != null) {
_request.ClientTarget = value;
}
}
}
private string _clientQueryString = null;
public String ClientQueryString {
get {
if (_clientQueryString == null) {
if (RequestInternal != null && Request.HasQueryString) {
// Eliminate system post fields (generated by the framework) from the
// querystring used for adaptive rendering.
Hashtable ht = new Hashtable();
foreach (string systemPostField in s_systemPostFields) {
ht.Add(systemPostField, true);
}
//
HttpValueCollection httpValueCollection = (HttpValueCollection)((SkipFormActionValidation) ? Request.Unvalidated.QueryString : Request.QueryString);
_clientQueryString = httpValueCollection.ToString(urlencoded: true, excludeKeys: ht);
}
else {
_clientQueryString = String.Empty;
}
}
return _clientQueryString;
}
}
internal bool ContainsEncryptedViewState {
get {
return _containsEncryptedViewState;
}
set {
_containsEncryptedViewState = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the error page to which the requesting browser should be
/// redirected in the event of an unhandled page exception.
/// </para>
/// </devdoc>
[
DefaultValue(""),
WebSysDescription(SR.Page_ErrorPage),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public string ErrorPage {
get {
return _errorPage;
}
set {
_errorPage = value;
}
}
/// <devdoc>
/// Gets a value indicating whether the page is being loaded in response to a client callback.
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public bool IsCallback {
get {
return _isCallback;
}
}
/// <internalonly/>
/// <devdoc>Page class can be cached/reused</devdoc>
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never)
]
public bool IsReusable {
get { return false; }
}
/// <devdoc>
/// Required for small browsers that cache too aggressively.
/// </devdoc>
protected internal virtual String UniqueFilePathSuffix {
get {
if (_uniqueFilePathSuffix != null) {
return _uniqueFilePathSuffix;
}
// Only need a few digits, so save space by modulo'ing by a prime.
// The chosen prime is the highest of six digits.
long ticks = DateTime.Now.Ticks % 999983;
_uniqueFilePathSuffix = String.Concat(UniqueFilePathSuffixID + "=", ticks.ToString("D6", CultureInfo.InvariantCulture));
_uniqueFilePathSuffix = _uniqueFilePathSuffix.PadLeft(6, '0');
return _uniqueFilePathSuffix;
}
}
// This property should be public. (DevDiv Bugs 161340)
public Control AutoPostBackControl {
get {
return _autoPostBackControl;
}
set {
_autoPostBackControl = value;
}
}
internal bool ClientSupportsFocus {
get {
return (_request != null) &&
((_request.Browser.EcmaScriptVersion >= FocusMinimumEcmaVersion) || (_request.Browser.JScriptVersion >= FocusMinimumJScriptVersion));
}
}
internal bool ClientSupportsJavaScript {
get {
if (!_clientSupportsJavaScriptChecked) {
_clientSupportsJavaScript = (_request != null) &&
(_request.Browser.EcmaScriptVersion >= JavascriptMinimumVersion);
_clientSupportsJavaScriptChecked = true;
}
return _clientSupportsJavaScript;
}
}
private ArrayList EnabledControls {
get {
if (_enabledControls == null) {
_enabledControls = new ArrayList();
}
return _enabledControls;
}
}
internal string FocusedControlID {
get {
if (_focusedControlID == null) {
return String.Empty;
}
return _focusedControlID;
}
}
/// <devdoc>
/// The control that has been set to be focused (empty if there was no such control)
/// </devdoc>
internal Control FocusedControl {
get {
return _focusedControl;
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public HtmlHead Header {
get {
return _header;
}
}
/// <internalonly/>
/// <devdoc>
/// VSWhidbey 80467: Need to adapt Id separator.
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
EditorBrowsable(EditorBrowsableState.Never)
]
public new virtual char IdSeparator {
get {
if (!_haveIdSeparator) {
if (AdapterInternal != null) {
_idSeparator = PageAdapter.IdSeparator;
}
else {
_idSeparator = IdSeparatorFromConfig;
}
_haveIdSeparator = true;
}
return _idSeparator;
}
}
/// <devdoc>
/// The control that has was last focused (empty if there was no such control)
/// </devdoc>
// We
internal string LastFocusedControl {
[AspNetHostingPermission(SecurityAction.Assert, Level = AspNetHostingPermissionLevel.Low)]
get {
if (RequestInternal != null) {
// SECURITY: Change this to just check form + query string
string lastFocus = Request[lastFocusID];
if (lastFocus != null) {
return lastFocus;
}
}
return String.Empty;
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public bool MaintainScrollPositionOnPostBack {
get {
if (RequestInternal != null && RequestInternal.Browser != null && !RequestInternal.Browser.SupportsMaintainScrollPositionOnPostback)
return false;
return _maintainScrollPosition;
}
set {
if (_maintainScrollPosition != value) {
_maintainScrollPosition = value;
if (_maintainScrollPosition) LoadScrollPosition();
}
}
}
/// <devdoc>
/// <para>The MasterPage used by the Page.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
WebSysDescription(SR.MasterPage_MasterPage)
]
public MasterPage Master {
get {
if (_master == null && !_preInitWorkComplete) {
_master = MasterPage.CreateMaster(this, Context, _masterPageFile, _contentTemplateCollection);
}
return _master;
}
}
/// <devdoc>
/// <para>Gets and sets the masterPageFile of this Page.</para>
/// </devdoc>
[
DefaultValue(""),
WebCategory("Behavior"),
WebSysDescription(SR.MasterPage_MasterPageFile)
]
public virtual string MasterPageFile {
get {
return VirtualPath.GetVirtualPathString(_masterPageFile);
}
set {
if (_preInitWorkComplete) {
throw new InvalidOperationException(SR.GetString(SR.PropertySetBeforePageEvent, "MasterPageFile", "Page_PreInit"));
}
if (value != VirtualPath.GetVirtualPathString(_masterPageFile)) {
_masterPageFile = VirtualPath.CreateAllowNull(value);
if (_master != null && Controls.Contains(_master)) {
Controls.Remove(_master);
}
_master = null;
}
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
EditorBrowsable(EditorBrowsableState.Never)
]
public int MaxPageStateFieldLength {
get {
return _maxPageStateFieldLength;
}
set {
if (this.ControlState > ControlState.FrameworkInitialized) {
throw new InvalidOperationException(SR.GetString(SR.PropertySetAfterFrameworkInitialize, "MaxPageStateFieldLength"));
}
if (value == 0 || value < -1) {
throw new ArgumentException(SR.GetString(SR.Page_Illegal_MaxPageStateFieldLength), "MaxPageStateFieldLength");
}
_maxPageStateFieldLength = value;
}
}
/// <devdoc>
/// Indicates whether page requires cross post script
/// </devdoc>
internal bool ContainsCrossPagePost {
get {
return _containsCrossPagePost;
}
set {
_containsCrossPagePost = value;
}
}
/// <devdoc>
/// True if the form should render a reference to the focus script.
/// </devdoc>
internal bool RenderFocusScript {
get {
return _requireFocusScript;
}
}
internal Stack PartialCachingControlStack {
get {
return _partialCachingControlStack;
}
}
/// <devdoc>
/// Returns the page state persister associated with the page.
/// </devdoc>
protected virtual PageStatePersister PageStatePersister {
get {
if (_persister == null) {
PageAdapter adapter = PageAdapter;
if (adapter != null) {
_persister = adapter.GetStatePersister();
}
if (_persister == null) {
_persister = new HiddenFieldPageStatePersister(this);
}
}
return _persister;
}
}
// Reconstructs the view state string from the view state fields in the request
internal string RequestViewStateString {
get {
if (!_cachedRequestViewState) {
StringBuilder state = new StringBuilder();
try {
NameValueCollection requestValueCollection = RequestValueCollection;
if (requestValueCollection != null) {
// If ViewStateChunking is disabled(-1) or there is no ViewStateFieldCount, return the __VIEWSTATE field
string fieldCountStr = RequestValueCollection[ViewStateFieldCountID];
if (MaxPageStateFieldLength == -1 || fieldCountStr == null) {
_cachedRequestViewState = true;
_requestViewState = RequestValueCollection[ViewStateFieldPrefixID];
return _requestViewState;
}
// Build up the entire persisted state from all the viewstate fields
int numViewStateFields = Convert.ToInt32(fieldCountStr, CultureInfo.InvariantCulture);
if (numViewStateFields < 0) {
throw new HttpException(SR.GetString(SR.ViewState_InvalidViewState));
}
// The view state is split into __VIEWSTATE, __VIEWSTATE1, __VIEWSTATE2, ... fields
for (int i=0; i<numViewStateFields; ++i) {
string key = ViewStateFieldPrefixID;
// For backwards compat we always need the first chunk to be __VIEWSTATE
if (i > 0) key += i.ToString(CultureInfo.InvariantCulture);
string viewStateChunk = RequestValueCollection[key];
if (viewStateChunk == null) {
throw new HttpException(SR.GetString(SR.ViewState_MissingViewStateField, key));
}
state.Append(viewStateChunk);
}
}
_cachedRequestViewState = true;
_requestViewState = state.ToString();
} catch (Exception e) {
ViewStateException.ThrowViewStateError(e, state.ToString());
}
}
return _requestViewState;
}
}
internal string ValidatorInvalidControl {
get {
if (_validatorInvalidControl == null) {
return String.Empty;
}
return _validatorInvalidControl;
}
}
/// <devdoc>
/// <para>Gets the <see cref='System.Web.TraceContext'/> object for the current Web
/// request. Tracing tracks and presents the execution details about a Web request. </para>
/// For trace data to be visible in a rendered page, you must
/// turn tracing on for that page.
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public TraceContext Trace {
get {
return Context.Trace;
}
}
/// <devdoc>
/// <para>Gets the <see langword='Request'/> object provided by the HTTP Runtime, which
/// allows you to access data from incoming HTTP requests.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public HttpRequest Request {
get {
if (_request == null)
throw new HttpException(SR.GetString(SR.Request_not_available));
return _request;
}
}
internal HttpRequest RequestInternal {
get {
return _request;
}
}
/// <devdoc>
/// <para>Gets the <see langword='Response '/>object provided by the HTTP Runtime, which
/// allows you to send HTTP response data to a client browser.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public HttpResponse Response {
get {
if (_response == null)
throw new HttpException(SR.GetString(SR.Response_not_available));
return _response;
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public RouteData RouteData {
get {
if (Context != null && Context.Request != null) {
// RequestContext is created on demand if not set so it should never be null
return Context.Request.RequestContext.RouteData;
}
return null;
}
}
/// <devdoc>
/// <para>Gets the <see langword='Server'/> object supplied by the HTTP runtime.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public HttpServerUtility Server {
get { return Context.Server;}
}
/// <devdoc>
/// <para>Retrieves a <see langword='Cache'/> object in which to store the page for
/// subsequent requests. This property is read-only.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public Cache Cache {
get {
if (_cache == null)
throw new HttpException(SR.GetString(SR.Cache_not_available));
return _cache;
}
}
/// <devdoc>
/// <para>Gets the <see langword='Session'/>
/// object provided by the HTTP Runtime. This object provides information about the current request's session.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public virtual HttpSessionState Session {
get {
if (!_sessionRetrieved) {
/* try just once to retrieve it */
_sessionRetrieved = true;
try {
_session = Context.Session;
}
catch {
// Just ignore exceptions, return null.
}
}
if (_session == null) {
throw new HttpException(SR.GetString(SR.Session_not_enabled));
}
return _session;
}
}
[
Bindable(true),
Localizable(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public string Title {
get {
if ((Page.Header == null) && (this.ControlState >= ControlState.ChildrenInitialized)) {
throw new InvalidOperationException(SR.GetString(SR.Page_Title_Requires_Head));
}
if (_titleToBeSet != null) {
return _titleToBeSet;
}
return Page.Header.Title;
}
set {
if (Page.Header == null) {
if (this.ControlState >= ControlState.ChildrenInitialized) {
throw new InvalidOperationException(SR.GetString(SR.Page_Title_Requires_Head));
}
else {
_titleToBeSet = value;
}
}
else {
Page.Header.Title = value;
}
}
}
[
Bindable(true),
Localizable(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public string MetaDescription {
get {
if ((Page.Header == null) && (this.ControlState >= ControlState.ChildrenInitialized)) {
throw new InvalidOperationException(SR.GetString(SR.Page_Description_Requires_Head));
}
if (_descriptionToBeSet != null) {
return _descriptionToBeSet;
}
return Page.Header.Description;
}
set {
if (Page.Header == null) {
if (this.ControlState >= ControlState.ChildrenInitialized) {
throw new InvalidOperationException(SR.GetString(SR.Page_Description_Requires_Head));
}
else {
_descriptionToBeSet = value;
}
}
else {
Page.Header.Description = value;
}
}
}
[
Bindable(true),
Localizable(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public string MetaKeywords {
get {
if ((Page.Header == null) && (this.ControlState >= ControlState.ChildrenInitialized)) {
throw new InvalidOperationException(SR.GetString(SR.Page_Keywords_Requires_Head));
}
if (_keywordsToBeSet != null) {
return _keywordsToBeSet;
}
return Page.Header.Keywords;
}
set {
if (Page.Header == null) {
if (this.ControlState >= ControlState.ChildrenInitialized) {
throw new InvalidOperationException(SR.GetString(SR.Page_Keywords_Requires_Head));
}
else {
_keywordsToBeSet = value;
}
}
else {
Page.Header.Keywords = value;
}
}
}
/// <devdoc>
/// indicates whether the Page has PageTheme defined.
/// </devdoc>
internal bool ContainsTheme {
get {
Debug.Assert(_preInitWorkComplete || DesignMode, "ContainsTheme should not be accessed before Page's PreInit.");
return _theme != null;
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public virtual String Theme {
get {
return _themeName;
}
set {
if (_preInitWorkComplete) {
throw new InvalidOperationException(SR.GetString(SR.PropertySetBeforePageEvent, "Theme", "Page_PreInit"));
}
if (!String.IsNullOrEmpty(value) && !FileUtil.IsValidDirectoryName(value)) {
throw new ArgumentException(SR.GetString(SR.Page_theme_invalid_name, value), "Theme");
}
_themeName = value;
}
}
internal bool SupportsStyleSheets {
get {
if (_supportsStyleSheets == -1) {
if (Header != null &&
Header.StyleSheet != null &&
RequestInternal != null &&
Request.Browser != null &&
(string)Request.Browser["preferredRenderingType"] != "xhtml-mp" &&
Request.Browser.SupportsCss &&
!Page.IsCallback &&
(ScriptManager == null || !ScriptManager.IsInAsyncPostBack)) {
// We don't want to render the style sheet for XHTML mobile profile devices even though
// SupportsCss may be true because they need the CSS to be in a separate file.
// We don't want embedded styles sheet to render during a callback (VSWhidbey 420743)
_supportsStyleSheets = 1;
return true;
}
_supportsStyleSheets = 0;
return false;
}
return (_supportsStyleSheets == 1);
}
}
[
Browsable(false),
Filterable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public virtual String StyleSheetTheme {
get {
return _styleSheetName;
}
set {
if (_pageFlags[styleSheetInitialized]) {
throw new InvalidOperationException(SR.GetString(SR.SetStyleSheetThemeCannotBeSet));
}
_styleSheetName = value;
}
}
/// <devdoc>
/// <para>Indicates the user making the page request. This property uses the
/// Context.User property to determine where the request originates. This property
/// is read-only.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public IPrincipal User {
get { return Context.User;}
}
internal XhtmlConformanceMode XhtmlConformanceMode {
get {
// We only want the evaluation of conformance mode to be done at most once per page request.
if (!_xhtmlConformanceModeSet) {
// The conformance mode is used to determine if backward compatible markup should
// be generated as in pre-Whidbey versions. So if an adapter is assigned, we can
// assume this is Whidbey rendering and we return the default mode that doesn't do
// backward compatible rendering.
if (DesignMode) {
_xhtmlConformanceMode = XhtmlConformanceSection.DefaultMode;
}
else {
_xhtmlConformanceMode = GetXhtmlConformanceSection().Mode;
}
_xhtmlConformanceModeSet = true;
}
return _xhtmlConformanceMode;
}
}
/*
* This protected virtual method is called by the Page to create the HtmlTextWriter
* to use for rendering. The class created is based on the TagWriter property on
* the browser capabilities.
*/
/// <devdoc>
/// <para>Creates an <see cref='System.Web.UI.HtmlTextWriter'/> object to render the page's
/// content. If the <see langword='IsUplevel'/> property is set to
/// <see langword='false'/>, an <see langword='Html32TextWriter'/> object is created
/// to render requests originating from downlevel browsers. For derived pages, you
/// can override this method to create a custom text writer.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected internal virtual HtmlTextWriter CreateHtmlTextWriter(TextWriter tw) {
// Use Context.Request (rather than Request) to avoid exception in get_Request when
// Request is not available.
if (Context != null && Context.Request != null && Context.Request.Browser != null) {
return Context.Request.Browser.CreateHtmlTextWriter(tw);
}
HtmlTextWriter writer = CreateHtmlTextWriterInternal(tw, _request );
if (writer == null) {
writer = new HtmlTextWriter(tw);
}
return writer;
}
internal static HtmlTextWriter CreateHtmlTextWriterInternal(TextWriter tw, HttpRequest request) {
if (request != null && request.Browser != null) {
return request.Browser.CreateHtmlTextWriterInternal(tw);
}
// Fall back to Html 3.2
return new Html32TextWriter(tw);
}
public static HtmlTextWriter CreateHtmlTextWriterFromType(TextWriter tw, Type writerType) {
if (writerType == typeof(HtmlTextWriter)) {
return new HtmlTextWriter(tw);
}
else if (writerType == typeof(Html32TextWriter)) {
return new Html32TextWriter(tw);
}
else {
try {
// Make sure the type has the correct base class (ASURT 123677)
Util.CheckAssignableType(typeof(HtmlTextWriter), writerType);
return (HtmlTextWriter)HttpRuntime.CreateNonPublicInstance(writerType, new object[] { tw });
}
catch {
throw new HttpException(SR.GetString(SR.Invalid_HtmlTextWriter, writerType.FullName));
}
}
}
/// <devdoc>
/// Overridden to check the Page's own ID against the one being searched.
/// </devdoc>
public override Control FindControl(String id) {
if (StringUtil.EqualsIgnoreCase(id, PageID)) {
return this;
}
return base.FindControl(id, 0);
}
/*
* This method is implemented by the Page classes that we generate on
* the fly. It returns a has code unique to the control layout.
*/
/// <devdoc>
/// <para>Retrieves a hash code that is generated by <see langword='Page'/> objects that
/// are generated at runtime. This hash code is unique to the page's control
/// layout.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual int GetTypeHashCode() {
return 0;
}
/*
* Override for small efficiency win: page doesn't prepend its name
*/
internal override string GetUniqueIDPrefix() {
// Only overridde if we're at the top level
if (Parent == null)
return String.Empty;
// Use base implementation for interior nodes
return base.GetUniqueIDPrefix();
}
// This is a non-cryptographic hash code that can be used to identify which Page generated
// a __VIEWSTATE field. It shouldn't be considered sensitive information since its inputs
// are assumed to be known by all parties.
internal uint GetClientStateIdentifier() {
// Use non-randomized hash code algorithms instead of String.GetHashCode.
// Use the page's directory and class name as part of the key (ASURT 64044)
// We need to make sure that the hash is case insensitive, since the file system
// is, and strange view state errors could otherwise happen (ASURT 128657)
int pageHashCode = StringUtil.GetNonRandomizedHashCode(TemplateSourceDirectory, ignoreCase:true);
pageHashCode += StringUtil.GetNonRandomizedHashCode(GetType().Name, ignoreCase:true);
return (uint)pageHashCode;
}
/*
* Called when an exception occurs in ProcessRequest
*/
/// <devdoc>
/// <para>Throws an <see cref='System.Web.HttpException'/> object when an error occurs during a call to the
/// <see cref='System.Web.UI.Page.ProcessRequest'/> method. If there is a custom error page, and
/// custom error page handling is enabled, the method redirects to the specified
/// custom error page.</para>
/// </devdoc>
private bool HandleError(Exception e) {
try {
// Remember the exception to be accessed via Server.GetLastError/ClearError
Context.TempError = e;
// Raise the error event
OnError(EventArgs.Empty);
// If the error has been cleared by the event handler, nothing else to do
if (Context.TempError == null)
return true;
} finally {
Context.TempError = null;
}
// If an error page was specified, redirect to it
if (!String.IsNullOrEmpty(_errorPage)) {
// only redirect if custom errors are enabled:
if (Context.IsCustomErrorEnabled) {
_response.RedirectToErrorPage(_errorPage, CustomErrorsSection.GetSettings(Context).RedirectMode);
return true;
}
}
// Increment all of the appropriate error counters
PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_UNHANDLED);
string traceString = null;
if (Context.TraceIsEnabled) {
Trace.Warn(SR.GetString(SR.Unhandled_Err_Error), null, e);
if (Trace.PageOutput) {
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
// Try to build the profile tree so the control hierarchy will show up
BuildPageProfileTree(false);
// these three calls will happen again at the end of the request, but
// in order to have the full trace log on the rendered page, we need
// to call them now.
Trace.EndRequest();
Trace.StopTracing();
Trace.StatusCode = 500;
Trace.Render(htw);
traceString = sw.ToString();
}
}
// If the exception is an HttpException with a formatter, just
// rethrow it instead of a new one (ASURT 45479)
if (HttpException.GetErrorFormatter(e) != null) {
return false;
}
// Don't touch security exceptions (ASURT 78366)
if (e is System.Security.SecurityException)
return false;
throw new HttpUnhandledException(null, traceString, e);
}
/// <devdoc>
/// <para>Gets a value indicating whether the page is being created in response to a
/// cross page postback.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public bool IsCrossPagePostBack {
get {
return _isCrossPagePostBack;
}
}
internal bool IsExportingWebPart {
get {
return _pageFlags[isExportingWebPart];
}
}
internal bool IsExportingWebPartShared {
get {
return _pageFlags[isExportingWebPartShared];
}
}
/*
* Returns true if this is a postback, which means it has some
* previous viewstate to reload. Use this in the Load method to differentiate
* an initial load from a postback reload.
*/
/// <devdoc>
/// <para>Gets a value indicating whether the page is being loaded in response to a
/// client postback, or if it is being loaded and accessed for the first time.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public bool IsPostBack {
get {
if (_requestValueCollection == null)
return false;
// Treat it as postback if the page is created thru cross page postback.
if (_isCrossPagePostBack)
return true;
// Don't treat it as a postback if the page is posted from cross page
if (_pageFlags[isCrossPagePostRequest])
return false;
// Don't treat it as a postback if a view state MAC check failed and we
// simply ate the exception.
if (ViewStateMacValidationErrorWasSuppressed)
return false;
// If we're in a Transfer/Execute, never treat as postback (ASURT 121000)
// Unless we are being transfered back to the original page, in which case
// it is ok to treat it as a postback (VSWhidbey 117747)
// Note that Context.Handler could be null (VSWhidbey 159775)
if (Context.ServerExecuteDepth > 0 &&
(Context.Handler == null || GetType() != Context.Handler.GetType())) {
return false;
}
// If the page control layout has changed, pretend that we are in
// a non-postback situation.
return !_fPageLayoutChanged;
}
}
internal NameValueCollection RequestValueCollection {
get { return _requestValueCollection; }
}
[
Browsable(false),
DefaultValue(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
EditorBrowsable(EditorBrowsableState.Never),
]
public virtual bool EnableEventValidation {
get {
return _enableEventValidation;
}
set {
if (this.ControlState > ControlState.FrameworkInitialized) {
throw new InvalidOperationException(SR.GetString(SR.PropertySetAfterFrameworkInitialize, "EnableEventValidation"));
}
_enableEventValidation = value;
}
}
[
Browsable(false)
]
public override bool EnableViewState {
get {
return base.EnableViewState;
}
set {
base.EnableViewState = value;
}
}
[
Browsable(false),
DefaultValue(ViewStateEncryptionMode.Auto),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
EditorBrowsable(EditorBrowsableState.Never),
]
public ViewStateEncryptionMode ViewStateEncryptionMode {
get {
return _encryptionMode;
}
set {
if (this.ControlState > ControlState.FrameworkInitialized) {
throw new InvalidOperationException(SR.GetString(SR.PropertySetAfterFrameworkInitialize, "ViewStateEncryptionMode"));
}
if (value < ViewStateEncryptionMode.Auto || value > ViewStateEncryptionMode.Never) {
throw new ArgumentOutOfRangeException("value");
}
_encryptionMode = value;
}
}
/// <devdoc>
/// <para>Setting this property helps prevent one-click attacks (ASURT 126375)</para>
/// </devdoc>
[
Browsable(false)
]
public string ViewStateUserKey {
get {
return _viewStateUserKey;
}
set {
// Make sure it's not called too late
if (ControlState >= ControlState.Initialized) {
throw new HttpException(SR.GetString(SR.Too_late_for_ViewStateUserKey));
}
_viewStateUserKey = value;
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never)
]
public override string ID {
get {
return base.ID;
}
set {
base.ID = value;
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DefaultValue(ValidateRequestMode.Enabled)
]
public override ValidateRequestMode ValidateRequestMode {
get {
return base.ValidateRequestMode;
}
set {
base.ValidateRequestMode = value;
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[DefaultValue(false)]
// If this property is false, then
// - we eagerly validate RawUrl at the appropriate point in ProcessRequestMain / ProcessRequestTransacted, and
// - the ClientQueryString property is populated from Request.QueryString (and might be validated) instead of Request.Unvalidated.QueryString.
public bool SkipFormActionValidation {
get {
return _pageFlags[skipFormActionValidation];
}
set {
// Clear the cached ClientQueryString value if the value of this property changes
if (value != SkipFormActionValidation) {
_clientQueryString = null;
}
_pageFlags[skipFormActionValidation] = value;
}
}
[
Browsable(false)
]
public override bool Visible {
get {
return base.Visible;
}
set {
base.Visible = value;
}
}
/// <devdoc>
/// <para>Decrypt the string using symmetric algorithm defined in config.</para>
/// </devdoc>
internal static string DecryptString(string s, Purpose purpose) {
if (s == null)
return null;
byte[] protectedData = HttpServerUtility.UrlTokenDecode(s);
// DevDiv Bugs 137864: IVType.Hash is necessary for WebResource / ScriptResource URLs
// so that client and server caching will continue to work. MS AJAX also caches these
// client-side, and switching to a different IV type could potentially break MS AJAX
// due to loading the same Javascript resource multiple times.
// MSRC 10405: Crypto board approves of this usage of IVType.Hash.
byte[] clearData = null;
if (protectedData != null) {
if (AspNetCryptoServiceProvider.Instance.IsDefaultProvider) {
// ASP.NET 4.5 Crypto DCR: Go through the new AspNetCryptoServiceProvider
// if we're configured to do so.
ICryptoService cryptoService = AspNetCryptoServiceProvider.Instance.GetCryptoService(purpose, CryptoServiceOptions.CacheableOutput);
clearData = cryptoService.Unprotect(protectedData);
}
else {
// If we're not configured to go through the new crypto routines,
// fall back to the standard MachineKey crypto routines.
#pragma warning disable 618 // calling obsolete methods
clearData = MachineKeySection.EncryptOrDecryptData(fEncrypt: false, buf: protectedData, modifier: null, start: 0, length: protectedData.Length, useValidationSymAlgo: false, useLegacyMode: false, ivType: IVType.Hash);
#pragma warning restore 618 // calling obsolete methods
}
}
if (clearData == null)
throw new HttpException(SR.GetString(SR.ViewState_InvalidViewState));
return Encoding.UTF8.GetString(clearData);
}
/*
* Performs intialization of the page required by the designer.
*/
/// <devdoc>
/// <para>Performs any initialization of the page that is required by RAD designers.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Never)]
public void DesignerInitialize() {
InitRecursive(null);
}
internal NameValueCollection GetCollectionBasedOnMethod(bool dontReturnNull) {
// Get the right NameValueCollection base on the method
if (_request.HttpVerb == HttpVerb.POST) {
return (dontReturnNull || _request.HasForm) ? _request.Form : null;
}
else {
return (dontReturnNull || _request.HasQueryString) ? _request.QueryString : null;
}
}
private bool DetermineIsExportingWebPart() {
byte[] queryString = Request.QueryStringBytes;
if ((queryString == null) || (queryString.Length < 28)) {
return false;
}
// query string is never unicode - it can be UTF-8, in which case it's fine to compare character by character
// because what we're looking for is only in the low-ASCII range.
if ((queryString[0] != '_') ||
(queryString[1] != '_') ||
(queryString[2] != 'W') ||
(queryString[3] != 'E') ||
(queryString[4] != 'B') ||
(queryString[5] != 'P') ||
(queryString[6] != 'A') ||
(queryString[7] != 'R') ||
(queryString[8] != 'T') ||
(queryString[9] != 'E') ||
(queryString[10] != 'X') ||
(queryString[11] != 'P') ||
(queryString[12] != 'O') ||
(queryString[13] != 'R') ||
(queryString[14] != 'T') ||
(queryString[15] != '=') ||
(queryString[16] != 't') ||
(queryString[17] != 'r') ||
(queryString[18] != 'u') ||
(queryString[19] != 'e') ||
(queryString[20] != '&')) {
return false;
}
// Setting the export flag so that personalization can know not to toggle modes,
// which would create a new subrequest and kill the export.
_pageFlags.Set(isExportingWebPart);
return true;
}
/*
* Determine which of the following three cases we're in:
* - Initial request. No postback, return null
* - GET postback request. Return Context.Request.QueryString
* - POST postback request. Return Context.Request.Form
*/
/// <devdoc>
/// <para>Determines the type of request made for the page based on if the page was a
/// postback, and whether a GET or POST method was used for the request.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected internal virtual NameValueCollection DeterminePostBackMode() {
if (Context.Request == null)
return null;
// If PreventPostback is set, don't treat as postback (VSWhidbey 181013).
if (Context.PreventPostback)
return null;
NameValueCollection ret = GetCollectionBasedOnMethod(dontReturnNull: false);
if (ret == null)
return null;
// Some devices may send incorrect POST strings without trailing equal signs
// if the last field is empty. Detecting this:
bool isPostback = false;
String [] nullValues = ret.GetValues(null);
if (nullValues != null) {
int numNull = nullValues.Length;
for (int i = 0; i < numNull; i++) {
if (nullValues[i].StartsWith(ViewStateFieldPrefixID, StringComparison.Ordinal) || nullValues[i] == postEventSourceID) {
isPostback = true;
break;
}
}
}
// If there is no state or postEventSourceID in the request,
// it's an initial request
//
if (ret[ViewStateFieldPrefixID] == null &&
ret[ViewStateFieldCountID] == null &&
ret[postEventSourceID] == null &&
!isPostback)
ret = null;
// If page was posted due to a HttpResponse.Redirect, ignore the postback.
else if (Request.QueryStringText.IndexOf(HttpResponse.RedirectQueryStringAssignment, StringComparison.Ordinal) != -1)
ret = null;
return ret;
}
/// <summary>
/// Returns an unvalidated name/value collection of the postback variables. This method will
/// only be called if DeterminePostBackMode() returns a non-null value.
/// This method exists to support the granular request validation feature added in .NET 4.5
/// </summary>
/// <returns>An unvalidated name/value collection of the postback variables.</returns>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected internal virtual NameValueCollection DeterminePostBackModeUnvalidated() {
// Get the right NameValueCollection base on the method. This is modeled on GetCollectionBasedOnMethod()
return _request.HttpVerb == HttpVerb.POST ? _request.Unvalidated.Form : _request.Unvalidated.QueryString;
}
/// <devdoc>
/// <para>This method is used to encrypt previous page hidden form variable that is sent to the client
/// during cross page post. This is to prevent spoofed previous pages from being instantiated and executed.</para>
/// This is also used by the AssemblyResourceLoader to prevent tampering of URLs.
/// </devdoc>
internal static string EncryptString(string s, Purpose purpose) {
Debug.Assert(s != null);
// DevDiv Bugs 137864: IVType.Hash is necessary for WebResource / ScriptResource URLs
// so that client and server caching will continue to work. MS AJAX also caches these
// client-side, and switching to a different IV type could potentially break MS AJAX
// due to loading the same Javascript resource multiple times.
// MSRC 10405: Crypto board approves of this usage of IVType.Hash.
byte[] clearData = Encoding.UTF8.GetBytes(s);
byte[] protectedData;
if (AspNetCryptoServiceProvider.Instance.IsDefaultProvider) {
// ASP.NET 4.5 Crypto DCR: Go through the new AspNetCryptoServiceProvider
// if we're configured to do so.
ICryptoService cryptoService = AspNetCryptoServiceProvider.Instance.GetCryptoService(purpose, CryptoServiceOptions.CacheableOutput);
protectedData = cryptoService.Protect(clearData);
}
else {
// If we're not configured to go through the new crypto routines,
// fall back to the standard MachineKey crypto routines.
#pragma warning disable 618 // calling obsolete methods
protectedData = MachineKeySection.EncryptOrDecryptData(fEncrypt: true, buf: clearData, modifier: null, start: 0, length: clearData.Length, useValidationSymAlgo: false, useLegacyMode: false, ivType: IVType.Hash);
#pragma warning restore 618 // calling obsolete methods
}
return HttpServerUtility.UrlTokenEncode(protectedData);
}
private void LoadAllState() {
object state = LoadPageStateFromPersistenceMedium();
IDictionary controlStates = null;
Pair allSavedViewState = null;
Pair statePair = state as Pair;
if (state != null) {
controlStates = statePair.First as IDictionary;
allSavedViewState = statePair.Second as Pair;
}
// The control state (controlStatePair) was saved as an dictionary of objects:
// 1. A list of controls that require postback[under the page id]
// 2. A dictionary of control states
if (controlStates != null) {
_controlsRequiringPostBack = (ArrayList)controlStates[PageRegisteredControlsThatRequirePostBackKey];
if (_registeredControlsRequiringControlState != null) {
foreach (Control ctl in _registeredControlsRequiringControlState) {
ctl.LoadControlStateInternal(controlStates[ctl.UniqueID]);
}
}
}
// The view state (allSavedViewState) was saved as an array of objects:
// 1. The hash code string
// 2. The state of the entire control hierarchy
// Is there any state?
if (allSavedViewState != null) {
// Get the hash code from the state
string hashCode = (string) allSavedViewState.First;
// If it's different from the current one, the layout has changed
int viewhash = Int32.Parse(hashCode, NumberFormatInfo.InvariantInfo);
_fPageLayoutChanged = viewhash != GetTypeHashCode();
// If the page control layout has changed, don't attempt to
// load any more state.
if (!_fPageLayoutChanged) {
// UNCOMMENT FOR DEBUG OUTPUT
// WalkViewState(allSavedViewState.Second, null, 0);
LoadViewStateRecursive(allSavedViewState.Second);
}
}
}
/*
* Override this method to persist view state to something other
* than hidden fields (
*/
/// <devdoc>
/// <para>Loads any saved view state information to the page. Override this method if
/// you want to load the page view state in anything other than a hidden field.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected internal virtual object LoadPageStateFromPersistenceMedium() {
PageStatePersister persister = PageStatePersister;
try {
persister.Load();
}
catch (HttpException e) {
//VSWhidbey 201601. Ignore the exception in cross-page post
//since this might be a cross application postback.
if (_pageFlags[isCrossPagePostRequest]) {
return null;
}
// DevDiv #461378: Ignore validation errors for cross-page postbacks.
if (ShouldSuppressMacValidationException(e)) {
if (Context != null && Context.TraceIsEnabled) {
Trace.Write("aspx.page", "Ignoring page state", e);
}
ViewStateMacValidationErrorWasSuppressed = true;
return null;
}
e.WebEventCode = WebEventCodes.RuntimeErrorViewStateFailure;
throw;
}
return new Pair(persister.ControlState, persister.ViewState);
}
private bool ViewStateMacValidationErrorWasSuppressed {
get { return _pageFlags[wasViewStateMacErrorSuppressed]; }
set { _pageFlags[wasViewStateMacErrorSuppressed] = value; }
}
internal bool ShouldSuppressMacValidationException(Exception e) {
// If the patch isn't active, don't suppress anything, as it would be a change in behavior.
if (!EnableViewStateMacRegistryHelper.SuppressMacValidationErrorsFromCrossPagePostbacks) {
return false;
}
// We check the __VIEWSTATEGENERATOR field for an identifier that matches the current Page.
// If the generator field exists and says that the current Page generated the incoming
// __VIEWSTATE field, then a validation failure represents a real error and we need to
// surface this information to the developer for resolution. Otherwise we assume this
// view state was not meant for us, so if validation fails we'll just ignore __VIEWSTATE.
if (ViewStateException.IsMacValidationException(e)) {
if (EnableViewStateMacRegistryHelper.SuppressMacValidationErrorsAlways) {
return true;
}
// DevDiv #841854: VSUK is often used for CSRF checks, so we can't ---- MAC exceptions by default in this case.
if (!String.IsNullOrEmpty(ViewStateUserKey)) {
return false;
}
if (_requestValueCollection == null) {
return true;
}
if (!VerifyClientStateIdentifier(_requestValueCollection[ViewStateGeneratorFieldID])) {
return true;
}
}
return false;
}
private bool VerifyClientStateIdentifier(string identifier) {
// Returns true iff we can parse the incoming identifier and it matches our own.
// If we can't parse the identifier, then by definition we didn't generate it.
uint parsedIdentifier;
return identifier != null
&& UInt32.TryParse(identifier, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out parsedIdentifier)
&& parsedIdentifier == GetClientStateIdentifier();
}
internal void LoadScrollPosition() {
// Don't load scroll position if the previous page was a crosspage postback
if (_previousPagePath != null) {
return;
}
// Load the scroll positions from the request if they exist
if (_requestValueCollection != null) {
double doubleValue;
string xpos = _requestValueCollection[_scrollPositionXID];
if (xpos != null) {
_scrollPositionX = HttpUtility.TryParseCoordinates(xpos, out doubleValue) ? (int)doubleValue : 0 ;
}
string ypos = _requestValueCollection[_scrollPositionYID];
if (ypos != null) {
_scrollPositionY = HttpUtility.TryParseCoordinates(ypos, out doubleValue) ? (int)doubleValue : 0 ;
}
}
}
internal IStateFormatter2 CreateStateFormatter() {
return new ObjectStateFormatter(this, true);
}
// Decomposes the large view state string into pieces of size <= MaxPageStateFieldLength
internal ICollection DecomposeViewStateIntoChunks() {
string state = ClientState;
if (state == null) return null;
// Any value less than or equal to 0 turns off chunking
if (MaxPageStateFieldLength <= 0) {
ArrayList chunks = new ArrayList(1);
chunks.Add(state);
return chunks;
}
// Break up the view state into the correctly sized chunks
int numFullChunks = ClientState.Length / MaxPageStateFieldLength;
ArrayList viewStateChunks = new ArrayList(numFullChunks+1);
int curPos = 0;
for (int i=0; i<numFullChunks; i++) {
viewStateChunks.Add(state.Substring(curPos, MaxPageStateFieldLength));
curPos += MaxPageStateFieldLength;
}
// Add the leftover characters
if (curPos < state.Length) {
viewStateChunks.Add(state.Substring(curPos));
}
// Always want to return at least one empty chunk
if (viewStateChunks.Count == 0) {
viewStateChunks.Add(String.Empty);
}
return viewStateChunks;
}
internal void RenderViewStateFields(HtmlTextWriter writer) {
if (_hiddenFieldsToRender == null) {
_hiddenFieldsToRender = new Dictionary<string, string>();
}
if (ClientState != null) {
ICollection viewStateChunks = DecomposeViewStateIntoChunks();
writer.WriteLine();
// Don't write out a view state field count if there is only 1 viewstate field
if (viewStateChunks.Count > 1) {
string value = viewStateChunks.Count.ToString(CultureInfo.InvariantCulture);
writer.Write("<input type=\"hidden\" name=\"");
writer.Write(ViewStateFieldCountID);
writer.Write("\" id=\"");
writer.Write(ViewStateFieldCountID);
writer.Write("\" value=\"");
writer.Write(value);
writer.WriteLine("\" />");
_hiddenFieldsToRender[ViewStateFieldCountID] = value;
}
int count = 0;
foreach (string stateChunk in viewStateChunks) {
writer.Write("<input type=\"hidden\" name=\"");
string name = ViewStateFieldPrefixID;
writer.Write(ViewStateFieldPrefixID);
string countString = null;
if (count > 0) {
countString = count.ToString(CultureInfo.InvariantCulture);
name += countString;
writer.Write(countString);
}
writer.Write("\" id=\"");
writer.Write(name);
writer.Write("\" value=\"");
writer.Write(stateChunk);
writer.WriteLine("\" />");
++count;
_hiddenFieldsToRender[name] = stateChunk;
}
// DevDiv #461378: Write out an identifier so we know who generated this __VIEWSTATE field.
// It doesn't need to be MACed since the only thing we use it for is error suppression,
// similar to how __PREVIOUSPAGE works.
if (EnableViewStateMacRegistryHelper.WriteViewStateGeneratorField) {
// hex is easier than base64 to work with and consumes only one extra byte on the wire
ClientScript.RegisterHiddenField(ViewStateGeneratorFieldID, GetClientStateIdentifier().ToString("X8", CultureInfo.InvariantCulture));
}
}
else {
// ASURT 106992
// Need to always render out the viewstate field so alternate viewstate persistence will get called
writer.Write("\r\n<input type=\"hidden\" name=\"");
writer.Write(ViewStateFieldPrefixID);
// Dev10 Bug 486494
// Remove previously rendered NewLine
writer.Write("\" id=\"");
writer.Write(ViewStateFieldPrefixID);
writer.WriteLine("\" value=\"\" />");
_hiddenFieldsToRender[ViewStateFieldPrefixID] = String.Empty;
}
}
/// <devdoc>
/// Default markup for begin form.
/// </devdoc>
internal void BeginFormRender(HtmlTextWriter writer, string formUniqueID) {
// DevDiv 27324: Form should render div tag around hidden inputs
// DevDiv 33149: backward compat. switch for obsolete rendering
// Dev10 705089: in 4.0 mode or later, we render the div block with class="aspNetHidden" for xHTML conformance.
bool renderDivAroundHiddenInputs = RenderDivAroundHiddenInputs(writer);
if (renderDivAroundHiddenInputs) {
writer.WriteLine();
if (RenderingCompatibility >= VersionUtil.Framework40) {
writer.Write("<div class=\"" + HiddenClassName + "\">");
}
else {
writer.Write("<div>");
}
}
ClientScript.RenderHiddenFields(writer);
RenderViewStateFields(writer);
if (renderDivAroundHiddenInputs) {
writer.WriteLine("</div>");
}
if (ClientSupportsJavaScript) {
if (MaintainScrollPositionOnPostBack && _requireScrollScript == false) {
ClientScript.RegisterHiddenField(_scrollPositionXID, _scrollPositionX.ToString(CultureInfo.InvariantCulture));
ClientScript.RegisterHiddenField(_scrollPositionYID, _scrollPositionY.ToString(CultureInfo.InvariantCulture));
ClientScript.RegisterStartupScript(typeof(Page), PageScrollPositionScriptKey, @"
theForm.oldSubmit = theForm.submit;
theForm.submit = WebForm_SaveScrollPositionSubmit;
theForm.oldOnSubmit = theForm.onsubmit;
theForm.onsubmit = WebForm_SaveScrollPositionOnSubmit;
" + (IsPostBack ? @"
theForm.oldOnLoad = window.onload;
window.onload = WebForm_RestoreScrollPosition;
" : String.Empty), true);
RegisterWebFormsScript();
_requireScrollScript = true;
}
// VSWhidbey 375885, Render the focus script later (specifically for interaction with scrollposition)
if (ClientSupportsFocus && Form != null && (RenderFocusScript || (Form.DefaultFocus.Length > 0) || (Form.DefaultButton.Length > 0))) {
string focusedControlId = String.Empty;
// Someone calling SetFocus(controlId) is the most precendent
if (FocusedControlID.Length > 0) {
focusedControlId = FocusedControlID;
}
else if (FocusedControl != null) {
if (FocusedControl.Visible) {
focusedControlId = FocusedControl.ClientID;
}
}
else if (ValidatorInvalidControl.Length > 0) {
focusedControlId = ValidatorInvalidControl;
}
// AutoPostBack focus is the second least precendent
else if (LastFocusedControl.Length > 0) {
// This doesn't have to be an ASP.NET control
focusedControlId = LastFocusedControl;
}
// DefaultFocus is the next
else if (Form.DefaultFocus.Length > 0) {
// VSWhidbey 379627: Always render the default focus, regardless if we can find it, or if its visible
focusedControlId = Form.DefaultFocus;
}
// DefaultButton is the least precendent
else if (Form.DefaultButton.Length > 0) {
focusedControlId = Form.DefaultButton;
}
// If something got focused, render some script to focus it only if its safe
int match;
if (focusedControlId.Length > 0 && !CrossSiteScriptingValidation.IsDangerousString(focusedControlId, out match) &&
CrossSiteScriptingValidation.IsValidJavascriptId(focusedControlId)) {
ClientScript.RegisterClientScriptResource(typeof(HtmlForm), "Focus.js");
if (!ClientScript.IsClientScriptBlockRegistered(typeof(HtmlForm), "Focus")) {
RegisterWebFormsScript();
ClientScript.RegisterStartupScript(
typeof(HtmlForm),
"Focus",
"WebForm_AutoFocus('" + Util.QuoteJScriptString(focusedControlId) + "');",
true);
}
IScriptManager scriptManager = ScriptManager;
if (scriptManager != null) {
scriptManager.SetFocusInternal(focusedControlId);
}
}
}
// Set the necessary stuff to re-enable disabled controls on the client
if (RenderDisabledControlsScript) {
ClientScript.RegisterOnSubmitStatement(typeof(Page), PageReEnableControlsScriptKey, "WebForm_ReEnableControls();");
RegisterWebFormsScript();
}
if (_fRequirePostBackScript) {
RenderPostBackScript(writer, formUniqueID);
}
if (_fRequireWebFormsScript) {
RenderWebFormsScript(writer);
}
}
ClientScript.RenderClientScriptBlocks(writer);
}
internal void EndFormRenderArrayAndExpandoAttribute(HtmlTextWriter writer, string formUniqueID) {
if (ClientSupportsJavaScript) {
// Devdiv 9409 - Register the array for reenabling only after the controls have been processed,
// so that list controls can have their children registered.
if (RenderDisabledControlsScript) {
foreach (Control control in EnabledControls) {
ClientScript.RegisterArrayDeclaration(EnabledControlArray, "'" + control.ClientID + "'");
}
}
ClientScript.RenderArrayDeclares(writer);
ClientScript.RenderExpandoAttribute(writer);
}
}
private bool RenderDisabledControlsScript {
get {
return Form.SubmitDisabledControls && (EnabledControls.Count > 0) &&
(_request.Browser.W3CDomVersion.Major > 0);
}
}
internal void EndFormRenderHiddenFields(HtmlTextWriter writer, string formUniqueID) {
if (RequiresViewStateEncryptionInternal) {
ClientScript.RegisterHiddenField(ViewStateEncryptionID, String.Empty);
}
if (_containsCrossPagePost) {
string path = EncryptString(Request.CurrentExecutionFilePath, Purpose.WebForms_Page_PreviousPageID);
ClientScript.RegisterHiddenField(previousPageID, path);
}
if (EnableEventValidation) {
ClientScript.SaveEventValidationField();
}
if (ClientScript.HasRegisteredHiddenFields) {
bool renderDivAroundHiddenInputs = RenderDivAroundHiddenInputs(writer);
if (renderDivAroundHiddenInputs) {
writer.WriteLine();
if (RenderingCompatibility >= VersionUtil.Framework40) {
writer.AddAttribute(HtmlTextWriterAttribute.Class, HiddenClassName);
}
writer.RenderBeginTag(HtmlTextWriterTag.Div);
}
ClientScript.RenderHiddenFields(writer);
if (renderDivAroundHiddenInputs) {
writer.RenderEndTag(); // DIV
}
}
}
internal void EndFormRenderPostBackAndWebFormsScript(HtmlTextWriter writer, string formUniqueID) {
if (ClientSupportsJavaScript) {
if (_fRequirePostBackScript && !_fPostBackScriptRendered) {
RenderPostBackScript(writer, formUniqueID);
}
if (_fRequireWebFormsScript && !_fWebFormsScriptRendered)
RenderWebFormsScript(writer);
}
ClientScript.RenderClientStartupScripts(writer);
}
/// <devdoc>
/// Default markup for end form.
/// </devdoc>
internal void EndFormRender(HtmlTextWriter writer, string formUniqueID) {
EndFormRenderArrayAndExpandoAttribute(writer, formUniqueID);
EndFormRenderHiddenFields(writer, formUniqueID);
EndFormRenderPostBackAndWebFormsScript(writer, formUniqueID);
}
// VSWhidbey 475945: For ClientScriptManager.GetPostBackEventReference() to check if '$' should be used for id separator
internal bool IsInOnFormRender {
get {
return _inOnFormRender;
}
}
/// <devdoc>
/// Called by both adapters and default rendering prior to form rendering.
/// </devdoc>
internal void OnFormRender() {
// Make sure there is only one form tag (ASURT 18891, 18894)
if (_fOnFormRenderCalled) {
throw new HttpException(SR.GetString(SR.Multiple_forms_not_allowed));
}
_fOnFormRenderCalled = true;
_inOnFormRender = true;
}
/// <devdoc>
/// Called by both adapters and default rendering after form rendering.
/// </devdoc>
internal void OnFormPostRender(HtmlTextWriter writer) {
_inOnFormRender = false;
if (_postFormRenderDelegate != null) {
_postFormRenderDelegate(writer, null);
}
}
/// <devdoc>
/// Needed by adapters which do more than one pass, so that OnFormRender can be called more than once.
/// </devdoc>
//
internal void ResetOnFormRenderCalled() {
_fOnFormRenderCalled = false;
}
/// <devdoc>
/// Sets focus to the specified control
/// </devdoc>
public void SetFocus(Control control) {
if (control == null) {
throw new ArgumentNullException("control");
}
if (Form == null) {
throw new InvalidOperationException(SR.GetString(SR.Form_Required_For_Focus));
}
if (Form.ControlState == ControlState.PreRendered) {
throw new InvalidOperationException(SR.GetString(SR.Page_MustCallBeforeAndDuringPreRender, "SetFocus"));
}
_focusedControl = control;
_focusedControlID = null;
RegisterFocusScript();
}
/// <devdoc>
/// Sets focus to the specified client id
/// </devdoc>
public void SetFocus(string clientID) {
if ((clientID == null) || (clientID.Trim().Length == 0)) {
throw new ArgumentNullException("clientID");
}
if (Form == null) {
throw new InvalidOperationException(SR.GetString(SR.Form_Required_For_Focus));
}
if (Form.ControlState == ControlState.PreRendered) {
throw new InvalidOperationException(SR.GetString(SR.Page_MustCallBeforeAndDuringPreRender, "SetFocus"));
}
_focusedControlID = clientID.Trim();
_focusedControl = null;
RegisterFocusScript();
}
internal void SetValidatorInvalidControlFocus(string clientID) {
if (String.IsNullOrEmpty(_validatorInvalidControl)) {
_validatorInvalidControl = clientID;
RegisterFocusScript();
}
}
//Note: BCL should provide a way to abort threads without asserting ControlThread for platform internal code.
[SecurityPermission(SecurityAction.Assert, ControlThread = true)]
internal static void ThreadResetAbortWithAssert() {
Thread.ResetAbort();
}
/*
* Enables controls to obtain client-side script function that will cause
* (when invoked) a server post-back to the form.
*/
/// <devdoc>
/// <para>
/// Associates the reference to the control that will
/// process the postback on the server.
/// </para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[Obsolete("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
public string GetPostBackEventReference(Control control) {
return ClientScript.GetPostBackEventReference(control, String.Empty);
}
/*
* Enables controls to obtain client-side script function that will cause
* (when invoked) a server post-back to the form.
* argument: Parameter that will be passed to control on server
*/
/// <devdoc>
/// <para>Passes a parameter to the control that will do the postback processing on the
/// server.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[Obsolete("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
public string GetPostBackEventReference(Control control,
string argument) {
return ClientScript.GetPostBackEventReference(control, argument);
}
/// <devdoc>
/// <para>This returs a string that can be put in client event to post back to the named control</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[Obsolete("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
public string GetPostBackClientEvent(Control control, string argument) {
return ClientScript.GetPostBackEventReference(control, argument);
}
/// <devdoc>
/// <para>This returs a string that can be put in client event to post back to the named control</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[Obsolete("The recommended alternative is ClientScript.GetPostBackClientHyperlink. http://go.microsoft.com/fwlink/?linkid=14202")]
public string GetPostBackClientHyperlink(Control control, string argument) {
return ClientScript.GetPostBackClientHyperlink(control, argument, false);
}
internal void InitializeStyleSheet() {
if (_pageFlags[styleSheetInitialized]) {
return;
}
String styleSheetName = StyleSheetTheme;
if (!String.IsNullOrEmpty(styleSheetName)) {
BuildResultCompiledType resultType = ThemeDirectoryCompiler.GetThemeBuildResultType(
Context, styleSheetName);
if (resultType != null) {
_styleSheet = (PageTheme)resultType.CreateInstance();
_styleSheet.Initialize(this, true);
}
else {
throw new HttpException(SR.GetString(SR.Page_theme_not_found, styleSheetName));
}
}
_pageFlags.Set(styleSheetInitialized);
}
private void InitializeThemes() {
String themeName = Theme;
if (!String.IsNullOrEmpty(themeName)) {
BuildResultCompiledType resultType = ThemeDirectoryCompiler.GetThemeBuildResultType(
Context, themeName);
if (resultType != null) {
_theme = (PageTheme)resultType.CreateInstance();
_theme.Initialize(this, false);
}
else {
throw new HttpException(SR.GetString(SR.Page_theme_not_found, themeName));
}
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
protected internal void AddContentTemplate(string templateName, ITemplate template) {
if (_contentTemplateCollection == null) {
_contentTemplateCollection = new Hashtable(11, StringComparer.OrdinalIgnoreCase);
}
try {
_contentTemplateCollection.Add(templateName, template);
}
catch (ArgumentException) {
throw new HttpException(SR.GetString(SR.MasterPage_Multiple_content, templateName));
}
}
private void ApplyMasterPage() {
if (Master != null) {
ArrayList appliedMasterPages = new ArrayList();
appliedMasterPages.Add(_masterPageFile.VirtualPathString.ToLower(CultureInfo.InvariantCulture));
MasterPage.ApplyMasterRecursive(Master, appliedMasterPages);
}
}
internal void ApplyControlSkin(Control ctrl) {
if (_theme != null) {
_theme.ApplyControlSkin(ctrl);
}
}
internal bool ApplyControlStyleSheet(Control ctrl) {
if (_styleSheet != null) {
_styleSheet.ApplyControlSkin(ctrl);
return true;
}
return false;
}
internal void RegisterFocusScript() {
if (ClientSupportsFocus && (_requireFocusScript == false)) {
ClientScript.RegisterHiddenField(lastFocusID, String.Empty);
_requireFocusScript = true;
// If there are any partial caching controls on the stack, forward the call to them
if (_partialCachingControlStack != null) {
foreach(BasePartialCachingControl c in _partialCachingControlStack) {
c.RegisterFocusScript();
}
}
}
}
internal void RegisterPostBackScript() {
if (!ClientSupportsJavaScript) {
return;
}
if (_fPostBackScriptRendered) {
return;
}
if (!_fRequirePostBackScript) {
ClientScript.RegisterHiddenField(postEventSourceID, String.Empty);
ClientScript.RegisterHiddenField(postEventArgumentID, String.Empty);
_fRequirePostBackScript = true;
}
// If there are any partial caching controls on the stack, forward the call to them
if (_partialCachingControlStack != null) {
foreach(BasePartialCachingControl c in _partialCachingControlStack) {
c.RegisterPostBackScript();
}
}
}
private void RenderPostBackScript(HtmlTextWriter writer, string formUniqueID) {
writer.Write(EnableLegacyRendering ?
ClientScriptManager.ClientScriptStartLegacy :
ClientScriptManager.ClientScriptStart);
if (PageAdapter != null) {
writer.Write("var theForm = ");
writer.Write(PageAdapter.GetPostBackFormReference(formUniqueID));
writer.WriteLine(";");
}
else {
writer.Write("var theForm = document.forms['");
writer.Write(formUniqueID);
writer.WriteLine("'];");
// VSWhidbey 392597: Try to use the document._ctl00 syntax since PocketPC doesn't support document.forms[id]
writer.Write("if (!theForm) {\r\n theForm = document.");
writer.Write(formUniqueID);
writer.WriteLine(";\r\n}");
}
writer.WriteLine(@"function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}");
writer.WriteLine(EnableLegacyRendering ?
ClientScriptManager.ClientScriptEndLegacy :
ClientScriptManager.ClientScriptEnd);
_fPostBackScriptRendered = true;
}
/// <devdoc>
/// Allows controls on a page to access to the _doPostBack and _doCallback JavaScript handlers on the
/// client. This method can be called multiple times by multiple controls. It should
/// render only one instance of the WebForms script.
/// </devdoc>
internal void RegisterWebFormsScript() {
if (ClientSupportsJavaScript) {
if (_fWebFormsScriptRendered) {
return;
}
RegisterPostBackScript();
_fRequireWebFormsScript = true;
// If there are any partial caching controls on the stack, forward the call to them
if (_partialCachingControlStack != null) {
foreach(BasePartialCachingControl c in _partialCachingControlStack) {
c.RegisterWebFormsScript();
}
}
}
}
private void RenderWebFormsScript(HtmlTextWriter writer) {
ClientScript.RenderWebFormsScript(writer);
_fWebFormsScriptRendered = true;
}
/// <devdoc>
/// <para>Determines if the client script block is registered with the page.</para>
/// </devdoc>
[Obsolete("The recommended alternative is ClientScript.IsClientScriptBlockRegistered(string key). http://go.microsoft.com/fwlink/?linkid=14202")]
public bool IsClientScriptBlockRegistered(string key) {
return ClientScript.IsClientScriptBlockRegistered(typeof(Page), key);
}
/// <devdoc>
/// <para>Determines if the client startup script is registered with the
/// page.</para>
/// </devdoc>
[Obsolete("The recommended alternative is ClientScript.IsStartupScriptRegistered(string key). http://go.microsoft.com/fwlink/?linkid=14202")]
public bool IsStartupScriptRegistered(string key) {
return ClientScript.IsStartupScriptRegistered(typeof(Page), key);
}
/// <devdoc>
/// <para>Declares a value that will be declared as a JavaScript array declaration
/// when the page renders. This can be used by script-based controls to declare
/// themselves within an array so that a client script library can work with
/// all the controls of the same type.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[Obsolete("The recommended alternative is ClientScript.RegisterArrayDeclaration(string arrayName, string arrayValue). http://go.microsoft.com/fwlink/?linkid=14202")]
public void RegisterArrayDeclaration(string arrayName, string arrayValue) {
ClientScript.RegisterArrayDeclaration(arrayName, arrayValue);
}
/// <devdoc>
/// <para>
/// Allows controls to automatically register a hidden field on the form. The
/// field will be emitted when the form control renders itself.
/// </para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[Obsolete("The recommended alternative is ClientScript.RegisterHiddenField(string hiddenFieldName, string hiddenFieldInitialValue). http://go.microsoft.com/fwlink/?linkid=14202")]
public virtual void RegisterHiddenField(string hiddenFieldName, string hiddenFieldInitialValue) {
ClientScript.RegisterHiddenField(hiddenFieldName, hiddenFieldInitialValue);
}
/// <devdoc>
/// <para> Prevents controls from sending duplicate blocks of
/// client-side script to the client. Any script blocks with the same <paramref name="key"/> parameter
/// values are considered duplicates.</para>
/// </devdoc>
[Obsolete("The recommended alternative is ClientScript.RegisterClientScriptBlock(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public virtual void RegisterClientScriptBlock(string key, string script) {
ClientScript.RegisterClientScriptBlock(typeof(Page), key, script);
}
/// <devdoc>
/// <para>
/// Allows controls to keep duplicate blocks of client-side script code from
/// being sent to the client. Any script blocks with the same <paramref name="key"/> parameter
/// value are considered duplicates.
/// </para>
/// </devdoc>
[Obsolete("The recommended alternative is ClientScript.RegisterStartupScript(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public virtual void RegisterStartupScript(string key, string script) {
ClientScript.RegisterStartupScript(typeof(Page), key, script, false);
}
/// <devdoc>
/// <para>Allows a control to access a the client
/// <see langword='onsubmit'/> event.
/// The script should be a function call to client code registered elsewhere.</para>
/// </devdoc>
[Obsolete("The recommended alternative is ClientScript.RegisterOnSubmitStatement(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void RegisterOnSubmitStatement(string key, string script) {
ClientScript.RegisterOnSubmitStatement(typeof(Page), key, script);
}
internal void RegisterEnabledControl(Control control) {
EnabledControls.Add(control);
}
/// <devdoc>
/// <para>If called, Control State for this control will be persisted.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void RegisterRequiresControlState(Control control) {
if (control == null) {
throw new ArgumentException(SR.GetString(SR.Page_ControlState_ControlCannotBeNull));
}
if (control.ControlState == ControlState.PreRendered) {
throw new InvalidOperationException(SR.GetString(SR.Page_MustCallBeforeAndDuringPreRender, "RegisterRequiresControlState"));
}
if (_registeredControlsRequiringControlState == null) {
_registeredControlsRequiringControlState = new ControlSet();
}
// Don't do anything if RegisterRequiresControlState is called multiple times on the same control.
if (!_registeredControlsRequiringControlState.Contains(control)) {
_registeredControlsRequiringControlState.Add(control);
IDictionary controlState = (IDictionary)PageStatePersister.ControlState;
if (controlState != null) {
string uniqueID = control.UniqueID;
// VSWhidbey 422416: We allow control state loaded only once, to
// match the same behavior of ViewState loading in Control.AddedControl
// method which ViewState is removed after applied once. The
// scenario is having a control to be re-parented multiple times.
// Note: We can't call remove here, because we may be in the middle of iterating thru
// the keys of controlState(within in a call to RegisterRequiresClearChildControlState),
// so we just remember that we loaded this control's control state
if (!ControlStateLoadedControlIds.Contains(uniqueID)) {
control.LoadControlStateInternal(controlState[uniqueID]);
ControlStateLoadedControlIds.Add(uniqueID);
}
}
}
}
public bool RequiresControlState(Control control) {
return (_registeredControlsRequiringControlState != null && _registeredControlsRequiringControlState.Contains(control));
}
/// <devdoc>
/// <para>If called, Control State for this control will no longer persisted.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void UnregisterRequiresControlState(Control control) {
if (control == null) {
throw new ArgumentException(SR.GetString(SR.Page_ControlState_ControlCannotBeNull));
}
if (_registeredControlsRequiringControlState == null) {
return;
}
_registeredControlsRequiringControlState.Remove(control);
}
internal bool ShouldLoadControlState(Control control) {
if (_registeredControlsRequiringClearChildControlState == null) return true;
foreach (Control cleared in _registeredControlsRequiringClearChildControlState.Keys) {
if (control != cleared && control.IsDescendentOf(cleared)) return false;
}
return true;
}
internal void RegisterRequiresClearChildControlState(Control control) {
if (_registeredControlsRequiringClearChildControlState == null) {
_registeredControlsRequiringClearChildControlState = new HybridDictionary();
_registeredControlsRequiringClearChildControlState.Add(control, true);
}
else if (_registeredControlsRequiringClearChildControlState[control] == null) {
_registeredControlsRequiringClearChildControlState.Add(control, true);
}
IDictionary controlState = (IDictionary)PageStatePersister.ControlState;
if (controlState != null) {
// Clear out the control state for children of this control
List<string> controlsToClear = new List<string>(controlState.Count);
foreach (string id in controlState.Keys) {
Control controlWithState = FindControl(id);
if (controlWithState != null && controlWithState.IsDescendentOf(control)) {
controlsToClear.Add(id);
}
}
foreach (string id in controlsToClear) {
controlState[id] = null;
}
}
}
/// <devdoc>
/// <para>Registers a control as one that requires postback handling.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void RegisterRequiresPostBack(Control control) {
// Fail if the control is not an IPostBackDataHandler (VSWhidbey 184483)
if (!(control is IPostBackDataHandler)) {
IPostBackDataHandler dataHandler = control.AdapterInternal as IPostBackDataHandler;
if (dataHandler == null)
throw new HttpException(SR.GetString(SR.Ctrl_not_data_handler));
}
if (_registeredControlsThatRequirePostBack == null)
_registeredControlsThatRequirePostBack = new ArrayList();
_registeredControlsThatRequirePostBack.Add(control.UniqueID);
}
// Push a BasePartialCachingControl on the stack of registered caching controls
internal void PushCachingControl(BasePartialCachingControl c) {
// Create the stack on demand
if (_partialCachingControlStack == null) {
_partialCachingControlStack = new Stack();
}
_partialCachingControlStack.Push(c);
}
// Pop a BasePartialCachingControl from the stack of registered caching controls
internal void PopCachingControl() {
Debug.Assert(_partialCachingControlStack != null);
_partialCachingControlStack.Pop();
}
/*
* This method will process the data posted back in the request header.
* The collection of posted data keys consists of three types :
* 1. Fully qualified ids of controls. The associated value is the data
* posted back by the browser for an intrinsic html element.
* 2. Fully qualified ids of controls that have explicitly registered that
* they want to be notified on postback. This is required for intrinsic
* html elements that for some states do not postback data ( e.g. a select
* when there is no selection, a checkbox or radiobutton that is not checked )
* The associated value for these keys is not relevant.
* 3. Framework generated hidden fields for event processing, whose values are
* set by client-side script prior to postback.
*
* This method handles the process of notifying the relevant controls that a postback
* has occurred, via the IPostBackDataHandler interface.
*
* It can potentially be called twice: before and after LoadControl. This is to
* handle the case where users programmatically add controls in Page_Load (ASURT 29045).
*/
private void ProcessPostData(NameValueCollection postData, bool fBeforeLoad) {
if (_changedPostDataConsumers == null)
_changedPostDataConsumers = new ArrayList();
// identify controls that have postback data
if (postData != null) {
foreach (string postKey in postData) {
if (postKey != null) {
// Ignore system post fields
if (IsSystemPostField(postKey))
continue;
Control ctrl = FindControl(postKey);
if (ctrl == null) {
if (fBeforeLoad) {
// It was not found, so keep track of it for the post load attempt
if (_leftoverPostData == null)
_leftoverPostData = new NameValueCollection();
_leftoverPostData.Add(postKey, null);
}
continue;
}
IPostBackDataHandler consumer = ctrl.PostBackDataHandler;
// Ignore controls that are not IPostBackDataHandler (see ASURT 13581)
if (consumer == null) {
// If it's a IPostBackEventHandler (which doesn't implement IPostBackDataHandler),
// register it (ASURT 39040)
if(ctrl.PostBackEventHandler != null)
RegisterRequiresRaiseEvent(ctrl.PostBackEventHandler);
continue;
}
bool changed;
if(consumer != null) {
NameValueCollection postCollection = ctrl.CalculateEffectiveValidateRequest() ? _requestValueCollection : _unvalidatedRequestValueCollection;
changed = consumer.LoadPostData(postKey, postCollection);
if(changed)
_changedPostDataConsumers.Add(ctrl);
}
// ensure controls are only notified of postback once
if (_controlsRequiringPostBack != null)
_controlsRequiringPostBack.Remove(postKey);
}
}
}
// Keep track of the leftover for the post-load attempt
ArrayList leftOverControlsRequiringPostBack = null;
// process controls that explicitly registered to be notified of postback
if (_controlsRequiringPostBack != null) {
foreach (string controlID in _controlsRequiringPostBack) {
Control c = FindControl(controlID);
if (c != null) {
IPostBackDataHandler consumer = c.AdapterInternal as IPostBackDataHandler;
if(consumer == null) {
consumer = c as IPostBackDataHandler;
}
// Give a helpful error if the control is not a IPostBackDataHandler (ASURT 128532)
if (consumer == null) {
throw new HttpException(SR.GetString(SR.Postback_ctrl_not_found, controlID));
}
NameValueCollection postCollection = c.CalculateEffectiveValidateRequest() ? _requestValueCollection : _unvalidatedRequestValueCollection;
bool changed = consumer.LoadPostData(controlID, postCollection);
if (changed)
_changedPostDataConsumers.Add(c);
}
else {
if (fBeforeLoad) {
if (leftOverControlsRequiringPostBack == null)
leftOverControlsRequiringPostBack = new ArrayList();
leftOverControlsRequiringPostBack.Add(controlID);
}
}
}
_controlsRequiringPostBack = leftOverControlsRequiringPostBack;
}
}
// Operations like FindControl and LoadPostData call EnsureDataBound, which may fire up
// async model binding methods. Therefore we make ProcessPostData method to be async so that we can await
// async data bindings.
// The differences between ProcessPostData and ProcessPostDataAsync are:
// 1. ProcessPostDataAsync awaits GetWaitForPreviousStepCompletionAwaitable after FindControl();
// 2. ProcessPostDataAsync calls LoadPostDataAsync() instead of LoadPostData().
private async Task ProcessPostDataAsync(NameValueCollection postData, bool fBeforeLoad) {
if (_changedPostDataConsumers == null)
_changedPostDataConsumers = new ArrayList();
// identify controls that have postback data
if (postData != null) {
foreach (string postKey in postData) {
if (postKey != null) {
// Ignore system post fields
if (IsSystemPostField(postKey))
continue;
Control ctrl = null;
using (Context.SyncContext.AllowVoidAsyncOperationsBlock()) {
ctrl = FindControl(postKey);
await GetWaitForPreviousStepCompletionAwaitable();
}
if (ctrl == null) {
if (fBeforeLoad) {
// It was not found, so keep track of it for the post load attempt
if (_leftoverPostData == null)
_leftoverPostData = new NameValueCollection();
_leftoverPostData.Add(postKey, null);
}
continue;
}
IPostBackDataHandler consumer = ctrl.PostBackDataHandler;
// Ignore controls that are not IPostBackDataHandler (see ASURT 13581)
if (consumer == null) {
// If it's a IPostBackEventHandler (which doesn't implement IPostBackDataHandler),
// register it (ASURT 39040)
if (ctrl.PostBackEventHandler != null)
RegisterRequiresRaiseEvent(ctrl.PostBackEventHandler);
continue;
}
if (consumer != null) {
NameValueCollection postCollection = ctrl.CalculateEffectiveValidateRequest() ? _requestValueCollection : _unvalidatedRequestValueCollection;
bool changed = await LoadPostDataAsync(consumer, postKey, postCollection);
if (changed)
_changedPostDataConsumers.Add(ctrl);
}
// ensure controls are only notified of postback once
if (_controlsRequiringPostBack != null)
_controlsRequiringPostBack.Remove(postKey);
}
}
}
// Keep track of the leftover for the post-load attempt
ArrayList leftOverControlsRequiringPostBack = null;
// process controls that explicitly registered to be notified of postback
if (_controlsRequiringPostBack != null) {
foreach (string controlID in _controlsRequiringPostBack) {
Control c = null;
using (Context.SyncContext.AllowVoidAsyncOperationsBlock()) {
c = FindControl(controlID);
await GetWaitForPreviousStepCompletionAwaitable();
}
if (c != null) {
IPostBackDataHandler consumer = c.AdapterInternal as IPostBackDataHandler;
if (consumer == null) {
consumer = c as IPostBackDataHandler;
}
// Give a helpful error if the control is not a IPostBackDataHandler (ASURT 128532)
if (consumer == null) {
throw new HttpException(SR.GetString(SR.Postback_ctrl_not_found, controlID));
}
NameValueCollection postCollection = c.CalculateEffectiveValidateRequest() ? _requestValueCollection : _unvalidatedRequestValueCollection;
bool changed = await LoadPostDataAsync(consumer, controlID, postCollection);
if (changed)
_changedPostDataConsumers.Add(c);
}
else {
if (fBeforeLoad) {
if (leftOverControlsRequiringPostBack == null)
leftOverControlsRequiringPostBack = new ArrayList();
leftOverControlsRequiringPostBack.Add(controlID);
}
}
}
_controlsRequiringPostBack = leftOverControlsRequiringPostBack;
}
}
private async Task<bool> LoadPostDataAsync(IPostBackDataHandler consumer, string postKey, NameValueCollection postCollection) {
bool changed;
// ListControl family controls call EnsureDataBound in consumer.LoadPostData, which could be an async call in 4.6.
// LoadPostData, however, is a sync method, which means we cannot await EnsureDataBound in the method.
// To workaround this, for ListControl family controls, we call EnsureDataBound before we call into LoadPostData.
if (AppSettings.EnableAsyncModelBinding && consumer is ListControl) {
var listControl = consumer as ListControl;
listControl.SkipEnsureDataBoundInLoadPostData = true;
using (Context.SyncContext.AllowVoidAsyncOperationsBlock()) {
listControl.InternalEnsureDataBound();
await GetWaitForPreviousStepCompletionAwaitable();
}
}
changed = consumer.LoadPostData(postKey, postCollection);
return changed;
}
/*
* This method will raise change events for those controls that indicated
* during PostProcessData that their data has changed.
*/
// !! IMPORTANT !!
// If you change this method, also change RaiseChangedEventsAsync.
internal void RaiseChangedEvents() {
if (_changedPostDataConsumers != null) {
// fire change notifications for those controls that changed as a result of postback
for (int i=0; i < _changedPostDataConsumers.Count; i++) {
Control c = (Control)_changedPostDataConsumers[i];
IPostBackDataHandler changedPostDataConsumer;
if(c != null) {
changedPostDataConsumer = c.PostBackDataHandler;
}
else {
continue;
}
// Make sure the IPostBackDataHandler is still in the tree (ASURT 82495)
if (c != null && !c.IsDescendentOf(this))
continue;
if(c != null && c.PostBackDataHandler != null) {
changedPostDataConsumer.RaisePostDataChangedEvent();
}
}
}
}
// TAP version of RaiseChangedEvents.
// !! IMPORTANT !!
// If you change this method, also change RaiseChangedEvents.
internal async Task RaiseChangedEventsAsync() {
if (_changedPostDataConsumers != null) {
// fire change notifications for those controls that changed as a result of postback
for (int i = 0; i < _changedPostDataConsumers.Count; i++) {
Control c = (Control)_changedPostDataConsumers[i];
IPostBackDataHandler changedPostDataConsumer;
if (c != null) {
changedPostDataConsumer = c.PostBackDataHandler;
}
else {
continue;
}
// Make sure the IPostBackDataHandler is still in the tree (ASURT 82495)
if (c != null && !c.IsDescendentOf(this))
continue;
if (c != null && c.PostBackDataHandler != null) {
using (Context.SyncContext.AllowVoidAsyncOperationsBlock()) {
changedPostDataConsumer.RaisePostDataChangedEvent();
await GetWaitForPreviousStepCompletionAwaitable();
}
}
}
}
}
private void RaisePostBackEvent(NameValueCollection postData) {
// first check if there is a register control needing the postback event
// if we don't have one of those, fall back to the hidden field
// Note: this must happen before we look at postData[postEventArgumentID] (ASURT 50106)
if (_registeredControlThatRequireRaiseEvent != null) {
RaisePostBackEvent(_registeredControlThatRequireRaiseEvent, null);
}
else {
string eventSource = postData[postEventSourceID];
bool hasEventSource = (!String.IsNullOrEmpty(eventSource));
// VSWhidbey 204824: We also need to check if the postback is submitted
// by an autopostback control in mobile browsers which cannot set
// event target in markup
if (hasEventSource || AutoPostBackControl != null) {
Control sourceControl = null;
if (hasEventSource) {
sourceControl = FindControl(eventSource);
}
if (sourceControl != null && sourceControl.PostBackEventHandler != null) {
string eventArgument = postData[postEventArgumentID];
RaisePostBackEvent((sourceControl.PostBackEventHandler), eventArgument);
}
}
else {
Validate();
}
}
}
// Overridable method that just calls RaisePostBackEvent on controls (ASURT 48154)
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArgument) {
sourceControl.RaisePostBackEvent(eventArgument);
}
//
/// <devdoc>
/// <para>Registers a control as requiring an event to be raised when it is processed
/// on the page.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public virtual void RegisterRequiresRaiseEvent(IPostBackEventHandler control) {
_registeredControlThatRequireRaiseEvent = control;
}
// VSWhidbey 402530
// This property should be public. (DevDiv Bugs 161340)
public bool IsPostBackEventControlRegistered {
get {
return (_registeredControlThatRequireRaiseEvent != null);
}
}
/// <devdoc>
/// <para> Indicates whether page validation succeeded.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public bool IsValid {
get {
if (!_validated)
throw new HttpException(SR.GetString(SR.IsValid_Cant_Be_Called));
if (_validators != null) {
ValidatorCollection vc = Validators;
int count = vc.Count;
for (int i = 0; i < count; i++) {
if (!vc[i].IsValid) {
return false;
}
}
}
return true;
}
}
/// <devdoc>
/// <para>Gets a collection of all validation controls contained on the requested page.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public ValidatorCollection Validators {
get {
if (_validators == null) {
_validators = new ValidatorCollection();
}
return _validators;
}
}
/// <devdoc>
/// <para>Gets the PreviousPage of current Page, it could be either the original Page from
/// Server.Transfer or cross page posting.
/// </para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public Page PreviousPage {
get {
// check _previousPage first since _previousPagePath could be null in case of Server.Transfer
if (_previousPage == null) {
if (_previousPagePath != null) {
if (!Util.IsUserAllowedToPath(Context, _previousPagePath)) {
throw new InvalidOperationException(SR.GetString(SR.Previous_Page_Not_Authorized));
}
ITypedWebObjectFactory result =
(ITypedWebObjectFactory)BuildManager.GetVPathBuildResult(Context, _previousPagePath);
// Make sure it has the correct base type
if (typeof(Page).IsAssignableFrom(result.InstantiatedType)) {
_previousPage = (Page)result.CreateInstance();
_previousPage._isCrossPagePostBack = true;
Server.Execute(_previousPage, TextWriter.Null,
true /*preserveForm*/, false /*setPreviousPage*/);
}
}
}
return _previousPage;
}
}
/*
* Map virtual path (absolute or relative) to physical path
*/
/// <devdoc>
/// <para>Assigns a virtual path, either absolute or relative, to a physical path.</para>
/// </devdoc>
public string MapPath(string virtualPath) {
return _request.MapPath(VirtualPath.CreateAllowNull(virtualPath), TemplateControlVirtualDirectory,
true/*allowCrossAppMapping*/);
}
/*
* The following members should only be set by derived class through codegen.
*
*/
static char[] s_varySeparator = new char[] {';'};
/// <devdoc>
/// <para>[To be supplied.]</para>
/// Note: this methods needs to be virtual because the Mobile control team
/// overrides it (ASURT 66157)
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Never)]
protected virtual void InitOutputCache(int duration, string varyByHeader,
string varyByCustom, OutputCacheLocation location, string varyByParam) {
InitOutputCache(duration, null, varyByHeader, varyByCustom, location, varyByParam);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// Note: this methods needs to be virtual because the Mobile control team
/// overrides it (ASURT 66157)
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Never)]
protected virtual void InitOutputCache(int duration, string varyByContentEncoding, string varyByHeader,
string varyByCustom, OutputCacheLocation location, string varyByParam) {
// DevDivBugs 18348: for a cross-page postback, use cache policy for
// original page and ignore cache policy for this page.
if (_isCrossPagePostBack) {
return;
}
OutputCacheParameters cacheSettings = new OutputCacheParameters();
cacheSettings.Duration = duration;
cacheSettings.VaryByContentEncoding = varyByContentEncoding;
cacheSettings.VaryByHeader = varyByHeader;
cacheSettings.VaryByCustom = varyByCustom;
cacheSettings.Location = location;
cacheSettings.VaryByParam = varyByParam;
InitOutputCache(cacheSettings);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// Note: this methods needs to be virtual because the Mobile control team
/// overrides it (ASURT 66157)
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Never)]
protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
{
// DevDivBugs 18348: for a cross-page postback, use cache policy for
// original page and ignore cache policy for this page.
if (_isCrossPagePostBack) {
return;
}
OutputCacheSettingsSection outputCacheSettings;
OutputCacheProfile profile = null;
HttpCachePolicy cache = Response.Cache;
HttpCacheability cacheability;
OutputCacheLocation location = (OutputCacheLocation) (-1);
int duration = 0;
string varyByContentEncoding = null;
string varyByHeader = null;
string varyByCustom = null;
string varyByParam = null;
string sqlDependency = null;
string varyByControl = null;
bool noStore = false;
RuntimeConfig config;
config = RuntimeConfig.GetAppConfig();
OutputCacheSection outputCacheConfig = config.OutputCache;
// If output cache is not enabled, then don't do anything and return.
if (! outputCacheConfig.EnableOutputCache)
{
return;
}
if (cacheSettings.CacheProfile != null && cacheSettings.CacheProfile.Length != 0)
{
outputCacheSettings = config.OutputCacheSettings;
profile = (OutputCacheProfile) outputCacheSettings.OutputCacheProfiles[cacheSettings.CacheProfile];
if (profile == null) {
throw new HttpException(SR.GetString(SR.CacheProfile_Not_Found, cacheSettings.CacheProfile));
}
// If the profile disables it, then bail out
if (!profile.Enabled) {
return;
}
}
// If a cache profile was set above, the settings below will override the set defaults from config
// Pick up the settings from the configuration settings profile first
if (profile != null) {
duration = profile.Duration;
varyByContentEncoding = profile.VaryByContentEncoding;
varyByHeader = profile.VaryByHeader;
varyByCustom = profile.VaryByCustom;
varyByParam = profile.VaryByParam;
sqlDependency = profile.SqlDependency;
noStore = profile.NoStore;
varyByControl = profile.VaryByControl;
location = profile.Location;
if (String.IsNullOrEmpty(varyByContentEncoding)) {
varyByContentEncoding = null;
}
if (String.IsNullOrEmpty(varyByHeader)) {
varyByHeader = null;
}
if (String.IsNullOrEmpty(varyByCustom)) {
varyByCustom = null;
}
if (String.IsNullOrEmpty(varyByParam)) {
varyByParam = null;
}
if (String.IsNullOrEmpty(varyByControl)) {
varyByControl = null;
}
if (StringUtil.EqualsIgnoreCase(varyByParam, "none")) {
varyByParam = null;
}
if (StringUtil.EqualsIgnoreCase(varyByControl, "none")) {
varyByControl = null;
}
}
// Start overriding options from the directive
if (cacheSettings.IsParameterSet(OutputCacheParameter.Duration)) {
duration = cacheSettings.Duration;
}
if (cacheSettings.IsParameterSet(OutputCacheParameter.VaryByContentEncoding)) {
varyByContentEncoding = cacheSettings.VaryByContentEncoding;
}
if (cacheSettings.IsParameterSet(OutputCacheParameter.VaryByHeader)) {
varyByHeader = cacheSettings.VaryByHeader;
}
if (cacheSettings.IsParameterSet(OutputCacheParameter.VaryByCustom)) {
varyByCustom = cacheSettings.VaryByCustom;
}
if (cacheSettings.IsParameterSet(OutputCacheParameter.VaryByControl)) {
varyByControl = cacheSettings.VaryByControl;
}
if (cacheSettings.IsParameterSet(OutputCacheParameter.VaryByParam)) {
varyByParam = cacheSettings.VaryByParam;
}
if (cacheSettings.IsParameterSet(OutputCacheParameter.SqlDependency)) {
sqlDependency = cacheSettings.SqlDependency;
}
if (cacheSettings.IsParameterSet(OutputCacheParameter.NoStore)) {
noStore = cacheSettings.NoStore;
}
if (cacheSettings.IsParameterSet(OutputCacheParameter.Location)) {
location = cacheSettings.Location;
}
//
// Make some checks here and see if a configuration exception needs to be thrown:
// If location wasn't specified in the profile or in the directive, set a default one
if (location == (OutputCacheLocation) (-1)) {
location = OutputCacheLocation.Any;
}
// Skip all checks if Location is "None" or we are disabled
if ((location != OutputCacheLocation.None) &&
(profile == null || profile.Enabled)) {
// Check and see if duration is specified in the profile or in the directives
if ((profile == null || profile.Duration == -1) &&
(cacheSettings.IsParameterSet(OutputCacheParameter.Duration) == false)) {
throw new HttpException(SR.GetString(SR.Missing_output_cache_attr, "duration"));
}
// Check and see if varyByParam is specified in the profile or in the directives
if ((profile == null || ((profile.VaryByParam == null) && (profile.VaryByControl == null))) &&
(cacheSettings.IsParameterSet(OutputCacheParameter.VaryByParam) == false &&
cacheSettings.IsParameterSet(OutputCacheParameter.VaryByControl) == false)) {
throw new HttpException(SR.GetString(SR.Missing_output_cache_attr, "varyByParam"));
}
}
// Set the cache policy based upon these settings
if (noStore) {
Response.Cache.SetNoStore();
}
switch (location) {
case OutputCacheLocation.Any:
cacheability = HttpCacheability.Public;
break;
case OutputCacheLocation.Server:
cacheability = HttpCacheability.ServerAndNoCache;
break;
case OutputCacheLocation.ServerAndClient:
cacheability = HttpCacheability.ServerAndPrivate;
break;
case OutputCacheLocation.Client:
cacheability = HttpCacheability.Private;
break;
case OutputCacheLocation.Downstream:
cacheability = HttpCacheability.Public;
cache.SetNoServerCaching();
break;
case OutputCacheLocation.None:
cacheability = HttpCacheability.NoCache;
break;
default:
throw new ArgumentOutOfRangeException("cacheSettings", SR.GetString(SR.Invalid_cache_settings_location));
}
cache.SetCacheability(cacheability);
if (location != OutputCacheLocation.None) {
cache.SetExpires(Context.Timestamp.AddSeconds(duration));
cache.SetMaxAge(new TimeSpan(0, 0, duration));
cache.SetValidUntilExpires(true);
cache.SetLastModified(Context.Timestamp);
//
// A client cache'd item won't be cached on
// the server or a proxy, so it doesn't need
// a Varies header.
//
if (location != OutputCacheLocation.Client) {
if (varyByContentEncoding != null) {
string[] a = varyByContentEncoding.Split(s_varySeparator);
foreach (string s in a) {
cache.VaryByContentEncodings[s.Trim()] = true;
}
}
if (varyByHeader != null) {
string[] a = varyByHeader.Split(s_varySeparator);
foreach (string s in a) {
cache.VaryByHeaders[s.Trim()] = true;
}
}
if(PageAdapter != null) {
StringCollection adapterVaryByHeaders = PageAdapter.CacheVaryByHeaders;
if(adapterVaryByHeaders != null) {
foreach(string header in adapterVaryByHeaders) {
cache.VaryByHeaders[header] = true;
}
}
}
//
// Only items cached on the server need VaryByCustom and
// VaryByParam
//
if (location != OutputCacheLocation.Downstream) {
if (varyByCustom != null) {
cache.SetVaryByCustom(varyByCustom);
}
if (String.IsNullOrEmpty(varyByParam) &&
String.IsNullOrEmpty(varyByControl) &&
(PageAdapter == null || PageAdapter.CacheVaryByParams == null)) {
cache.VaryByParams.IgnoreParams = true;
}
else {
if (!String.IsNullOrEmpty(varyByParam)) {
string[] a = varyByParam.Split(s_varySeparator);
foreach (string s in a) {
cache.VaryByParams[s.Trim()] = true;
}
}
if (!String.IsNullOrEmpty(varyByControl)) {
string[] a = varyByControl.Split(s_varySeparator);
foreach (string s in a) {
cache.VaryByParams[s.Trim()] = true;
}
}
if(PageAdapter != null) {
IList adapterVaryByParams = PageAdapter.CacheVaryByParams;
if(adapterVaryByParams != null) {
foreach(string p in adapterVaryByParams) {
cache.VaryByParams[p] = true;
}
}
}
}
#if !FEATURE_PAL // FEATURE_PAL does not fully SQL dependencies
if (!String.IsNullOrEmpty(sqlDependency)) {
Response.AddCacheDependency(SqlCacheDependency.CreateOutputCacheDependency(sqlDependency));
}
#endif // !FEATURE_PAL
}
}
}
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("The recommended alternative is HttpResponse.AddFileDependencies. http://go.microsoft.com/fwlink/?linkid=14202")]
protected ArrayList FileDependencies {
set { Response.AddFileDependencies(value); }
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
protected object GetWrappedFileDependencies(string[] virtualFileDependencies) {
Debug.Assert(virtualFileDependencies != null);
return virtualFileDependencies;
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
protected internal void AddWrappedFileDependencies(object virtualFileDependencies) {
Response.AddVirtualPathDependencies((string[])virtualFileDependencies);
}
internal const bool BufferDefault = true;
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Buffer {
set { Response.BufferOutput = value; }
get { return Response.BufferOutput; }
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ContentType {
set { Response.ContentType = value; }
get { return Response.ContentType; }
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int CodePage {
set { Response.ContentEncoding = Encoding.GetEncoding(value); }
get { return Response.ContentEncoding.CodePage; }
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ResponseEncoding {
set { Response.ContentEncoding = Encoding.GetEncoding(value); }
get { return Response.ContentEncoding.EncodingName; }
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Culture {
set {
CultureInfo newCulture = null;
if(StringUtil.EqualsIgnoreCase(value, HttpApplication.AutoCulture)) {
CultureInfo browserCulture = CultureFromUserLanguages(true);
if(browserCulture != null) {
newCulture = browserCulture;
}
}
else if(StringUtil.StringStartsWithIgnoreCase(value, HttpApplication.AutoCulture)) {
CultureInfo browserCulture = CultureFromUserLanguages(true);
if(browserCulture != null) {
newCulture = browserCulture;
}
else {
try {
newCulture = HttpServerUtility.CreateReadOnlyCultureInfo(value.Substring(5));
}
catch {}
}
}
else {
newCulture = HttpServerUtility.CreateReadOnlyCultureInfo(value);
}
if (newCulture != null) {
Thread.CurrentThread.CurrentCulture = newCulture;
_dynamicCulture = newCulture;
}
}
get { return Thread.CurrentThread.CurrentCulture.DisplayName; }
}
internal CultureInfo DynamicCulture {
get { return _dynamicCulture; }
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int LCID {
set {
CultureInfo newCulture = HttpServerUtility.CreateReadOnlyCultureInfo(value);
Thread.CurrentThread.CurrentCulture = newCulture;
_dynamicCulture = newCulture;
}
get { return Thread.CurrentThread.CurrentCulture.LCID; }
}
private CultureInfo CultureFromUserLanguages(bool specific) {
if(_context != null &&
_context.Request != null &&
_context.Request.UserLanguages != null) {
try {
return CultureUtil.CreateReadOnlyCulture(_context.Request.UserLanguages, specific);
}
catch {
}
}
return null;
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string UICulture {
set {
CultureInfo newUICulture = null;
if(StringUtil.EqualsIgnoreCase(value, HttpApplication.AutoCulture)) {
CultureInfo browserCulture = CultureFromUserLanguages(false);
if(browserCulture != null) {
newUICulture = browserCulture;
}
}
else if(StringUtil.StringStartsWithIgnoreCase(value, HttpApplication.AutoCulture)) {
CultureInfo browserCulture = CultureFromUserLanguages(false);
if(browserCulture != null) {
newUICulture = browserCulture;
}
else {
try {
newUICulture = HttpServerUtility.CreateReadOnlyCultureInfo(value.Substring(5));
}
catch {}
}
}
else {
newUICulture = HttpServerUtility.CreateReadOnlyCultureInfo(value);
}
if (newUICulture != null) {
Thread.CurrentThread.CurrentUICulture = newUICulture;
_dynamicUICulture = newUICulture;
}
}
get { return Thread.CurrentThread.CurrentUICulture.DisplayName; }
}
internal CultureInfo DynamicUICulture {
get { return _dynamicUICulture; }
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public TimeSpan AsyncTimeout {
set {
if (value < TimeSpan.Zero) {
throw new ArgumentException(SR.GetString(SR.Page_Illegal_AsyncTimeout), "AsyncTimeout");
}
_asyncTimeout = value;
_asyncTimeoutSet = true;
}
get {
if (!_asyncTimeoutSet) {
if (Context != null) {
PagesSection pagesSection = RuntimeConfig.GetConfig(Context).Pages;
if (pagesSection != null) {
AsyncTimeout = pagesSection.AsyncTimeout;
}
}
if (!_asyncTimeoutSet) {
AsyncTimeout = TimeSpan.FromSeconds((double)Page.DefaultAsyncTimeoutSeconds);
}
}
return _asyncTimeout;
}
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
protected int TransactionMode {
set { _transactionMode = value; }
get { return _transactionMode; }
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
protected bool AspCompatMode {
set { _aspCompatMode = value; }
get { return _aspCompatMode; }
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
protected bool AsyncMode {
set { _asyncMode = value; }
get { return _asyncMode; }
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool TraceEnabled {
set { Trace.IsEnabled = value; }
get { return Trace.IsEnabled; }
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public System.Web.TraceMode TraceModeValue {
set { Trace.TraceMode = value; }
get { return Trace.TraceMode; }
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool EnableViewStateMac {
get { return _enableViewStateMac; }
set {
// DevDiv #461378: EnableViewStateMac=false can lead to remote code execution, so we
// have an mechanism that forces this to keep its default value of 'true'. We only
// allow actually setting the value if this enforcement mechanism is inactive.
if (!EnableViewStateMacRegistryHelper.EnforceViewStateMac) {
_enableViewStateMac = value;
}
}
}
internal const bool SmartNavigationDefault = false;
/// <devdoc>
/// <para>Is the SmartNavigation feature in use</para>
/// </devdoc>
[
Browsable(false),
Filterable(false)
]
[Obsolete("The recommended alternative is Page.SetFocus and Page.MaintainScrollPositionOnPostBack. http://go.microsoft.com/fwlink/?linkid=14202")]
public bool SmartNavigation {
get {
// If it's not supported or asked for, return false
if (_smartNavSupport == SmartNavigationSupport.NotDesiredOrSupported)
return false;
// Otherwise, determine what the browser supports
if (_smartNavSupport == SmartNavigationSupport.Desired) {
// *** We need to check the current context here since
// we check SmartNavigation when the context == null.
HttpContext currentContext = HttpContext.Current;
// Make sure that there is a current context
if (currentContext == null) {
// If there isn't one, assume SmartNavigation is off
return false;
}
// *** We CANNOT just check Request.Browser since Request will be null and throw an exception
HttpBrowserCapabilities browser = currentContext.Request.Browser;
// If it's not IE6+ on Windows, we don't support Smart Navigation
if (!String.Equals(browser.Browser, "ie", StringComparison.OrdinalIgnoreCase) || browser.MajorVersion < 6 ||
!browser.Win32) {
_smartNavSupport = SmartNavigationSupport.NotDesiredOrSupported;
}
else
_smartNavSupport = SmartNavigationSupport.IE6OrNewer;
}
return (_smartNavSupport != SmartNavigationSupport.NotDesiredOrSupported);
}
set {
if (value)
_smartNavSupport = SmartNavigationSupport.Desired;
else
_smartNavSupport = SmartNavigationSupport.NotDesiredOrSupported;
}
}
internal bool IsTransacted { get { return (_transactionMode != 0 /*TransactionOption.Disabled*/); } }
internal bool IsInAspCompatMode { get { return _aspCompatMode; } }
public bool IsAsync {
get { return _asyncMode; }
}
/// <devdoc>
/// Occurs when the control is done handling postback data, and before PreRender.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public event EventHandler LoadComplete {
add {
Events.AddHandler(EventLoadComplete, value);
}
remove {
Events.RemoveHandler(EventLoadComplete, value);
}
}
/// <devdoc>
/// Raised after postback data is handled, and before PreRender.
/// </devdoc>
protected virtual void OnLoadComplete(EventArgs e) {
EventHandler handler = (EventHandler)Events[EventLoadComplete];
if (handler != null) {
handler(this, e);
}
}
/// <devdoc>
/// Raised after PreRender is complete
/// </devdoc>
protected virtual void OnPreRenderComplete(EventArgs e) {
EventHandler handler = (EventHandler)Events[EventPreRenderComplete];
if (handler != null) {
handler(this, e);
}
}
/// <devdoc>
/// Heres where all the 'final' page-level framework stuff happens.
/// Raise the PreRenderComplete event giving the user the first (and last)
/// chance to do certain things that affect page behavior, and
/// then perform the processing steps.
/// </devdoc>
private void PerformPreRenderComplete() {
OnPreRenderComplete(EventArgs.Empty);
}
/// <devdoc>
/// Occurs before controls' OnInit
/// </devdoc>
public event EventHandler PreInit {
add {
Events.AddHandler(EventPreInit, value);
}
remove {
Events.RemoveHandler(EventPreInit, value);
}
}
/// <devdoc>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public event EventHandler PreLoad {
add {
Events.AddHandler(EventPreLoad, value);
}
remove {
Events.RemoveHandler(EventPreLoad, value);
}
}
/// <devdoc>
/// Occurs after all controls have completed PreRender
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public event EventHandler PreRenderComplete {
add {
Events.AddHandler(EventPreRenderComplete, value);
}
remove {
Events.RemoveHandler(EventPreRenderComplete, value);
}
}
/// <devdoc>
/// Override this method to apply stylesheet before building controls
/// </devdoc>
protected override void FrameworkInitialize() {
base.FrameworkInitialize();
InitializeStyleSheet();
}
/// <devdoc>
/// Override this method to initialize culture properties.
/// </devdoc>
protected virtual void InitializeCulture() {
}
/// <devdoc>
/// </devdoc>
protected internal override void OnInit(EventArgs e) {
base.OnInit(e);
if (_theme != null) {
_theme.SetStyleSheet();
}
if (_styleSheet != null) {
_styleSheet.SetStyleSheet();
}
}
/// <devdoc>
/// Raised before OnInit.
/// </devdoc>
protected virtual void OnPreInit(EventArgs e) {
EventHandler handler = (EventHandler)Events[EventPreInit];
if (handler != null) {
handler(this, e);
}
}
/// <devdoc>
/// Heres where all the 'early' page initialization happens.
/// Raise the PreInit event giving the user the first (and last)
/// chance to do certain things that affect page behavior, and
/// then perform the initialization steps.
///
/// For now this early initialization includes
/// theme loading.
///
private void PerformPreInit() {
OnPreInit(EventArgs.Empty);
InitializeThemes();
ApplyMasterPage();
_preInitWorkComplete = true;
}
// TAP version of the PerformPreInit routine.
// !! IMPORTANT !!
// If you change this method, also change PerformPreInit.
private async Task PerformPreInitAsync() {
using (Context.SyncContext.AllowVoidAsyncOperationsBlock()) {
OnPreInit(EventArgs.Empty);
await GetWaitForPreviousStepCompletionAwaitable();
}
InitializeThemes();
ApplyMasterPage();
_preInitWorkComplete = true;
}
/// <devdoc>
/// Occurs when the page is done initializing, and before loading viewstate data.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public event EventHandler InitComplete {
add {
Events.AddHandler(EventInitComplete, value);
}
remove {
Events.RemoveHandler(EventInitComplete, value);
}
}
/// <devdoc>
/// Raised after page is initialized, and before loading viewstate.
/// </devdoc>
protected virtual void OnInitComplete(EventArgs e) {
EventHandler handler = (EventHandler)Events[EventInitComplete];
if (handler != null) {
handler(this, e);
}
}
/// <devdoc>
/// Raises the PreLoad event
/// </devdoc>
protected virtual void OnPreLoad(EventArgs e) {
EventHandler handler = (EventHandler)Events[EventPreLoad];
if (handler != null) {
handler(this, e);
}
}
public void RegisterRequiresViewStateEncryption() {
if (ControlState >= ControlState.PreRendered) {
throw new InvalidOperationException(SR.GetString(SR.Too_late_for_RegisterRequiresViewStateEncryption));
}
_viewStateEncryptionRequested = true;
}
internal bool RequiresViewStateEncryptionInternal {
get {
return ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
_viewStateEncryptionRequested && ViewStateEncryptionMode == ViewStateEncryptionMode.Auto;
}
}
/// <devdoc>
/// Occurs when the page has completed saving view state and control state.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public event EventHandler SaveStateComplete {
add {
Events.AddHandler(EventSaveStateComplete, value);
}
remove {
Events.RemoveHandler(EventSaveStateComplete, value);
}
}
/// <devdoc>
/// Raises the SaveStateComplete event
/// </devdoc>
protected virtual void OnSaveStateComplete(EventArgs e) {
EventHandler handler = (EventHandler)Events[EventSaveStateComplete];
if (handler != null) {
handler(this, e);
}
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual void ProcessRequest(HttpContext context) {
// If running in non-full trust, call PermitOnly to cause the following code
// to run as if there were user code on the stack.
// Check if we're running in non-full trust
if (HttpRuntime.NamedPermissionSet != null && !HttpRuntime.DisableProcessRequestInApplicationTrust) {
// Are we supposed to execute process request without full trust?
if (HttpRuntime.ProcessRequestInApplicationTrust) {
// If so, we don't normally need to do anything, because this ProcessRequest method
// is being called from an override in the generated code (so there is user code
// on the stack).
// However, if the page is no-compile, there won't be any user code on the stack,
// so we need to explicitely call PermitOnly to make it happen
if (NoCompile) {
HttpRuntime.NamedPermissionSet.PermitOnly();
}
}
else {
// Here, we want to run the request in full trust, so the situation is reversed.
// i.e. in the no-compile case, there is no user code on the stack, so we don't need to
// do anything. But in the compiled case, the ProcessRequest override is on the stack,
// so we need to nullify it using an Assert.
ProcessRequestWithAssert(context);
return;
}
}
ProcessRequestWithNoAssert(context);
}
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
private void ProcessRequestWithAssert(HttpContext context) {
ProcessRequestWithNoAssert(context);
}
private void ProcessRequestWithNoAssert(HttpContext context) {
SetIntrinsics(context);
ProcessRequest();
}
// assert SecurityPermission, for ASURT #112116
[SecurityPermission(SecurityAction.Assert, ControlThread=true)]
void SetCultureWithAssert(Thread currentThread, CultureInfo currentCulture, CultureInfo currentUICulture) {
SetCulture(currentThread, currentCulture, currentUICulture);
}
void SetCulture(Thread currentThread, CultureInfo currentCulture, CultureInfo currentUICulture) {
currentThread.CurrentCulture = currentCulture;
currentThread.CurrentUICulture = currentUICulture;
}
//
// ProcessRequestXXX methods are there because
// transacted pages require some code (ProcessRequestMain)
// to run inside the transaction and some outside
//
// Another reason - support for async pages
//
private void ProcessRequest() {
// culture needs to be saved/restored only on synchronous pages (if at all)
// save culture
Thread currentThread = Thread.CurrentThread;
CultureInfo prevCulture = currentThread.CurrentCulture;
CultureInfo prevUICulture = currentThread.CurrentUICulture;
try {
ProcessRequest(true /*includeStagesBeforeAsyncPoint*/, true /*includeStagesAfterAsyncPoint*/);
}
finally {
// restore culture
RestoreCultures(currentThread, prevCulture, prevUICulture);
}
}
// !! IMPORTANT !!
// If you change this method, also change ProcessRequestAsync(bool, bool).
private void ProcessRequest(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint) {
// Initialize the object and build the tree of controls.
// This must happen *after* the intrinsics have been set.
// On async pages only call Initialize once (ProcessRequest is called twice)
if (includeStagesBeforeAsyncPoint) {
FrameworkInitialize();
this.ControlState = ControlState.FrameworkInitialized;
}
bool needToCallEndTrace = Context.WorkerRequest is IIS7WorkerRequest;
try {
try {
if (IsTransacted) {
ProcessRequestTransacted();
}
else {
// No transactions
ProcessRequestMain(includeStagesBeforeAsyncPoint, includeStagesAfterAsyncPoint);
}
if (includeStagesAfterAsyncPoint) {
needToCallEndTrace = false;
ProcessRequestEndTrace();
}
}
catch (ThreadAbortException) {
try {
if (needToCallEndTrace)
ProcessRequestEndTrace();
} catch {}
}
finally {
if (includeStagesAfterAsyncPoint) {
ProcessRequestCleanup();
}
}
}
catch { throw; } // Prevent Exception Filter Security Issue (ASURT 122835)
}
// TAP version of ProcessRequest(bool, bool)
// !! IMPORTANT !!
// If you change this method, also change ProcessRequest(bool, bool).
private async Task ProcessRequestAsync(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint) {
// Initialize the object and build the tree of controls.
// This must happen *after* the intrinsics have been set.
// On async pages only call Initialize once (ProcessRequest is called twice)
if (includeStagesBeforeAsyncPoint) {
FrameworkInitialize();
this.ControlState = ControlState.FrameworkInitialized;
}
bool needToCallEndTrace = Context.WorkerRequest is IIS7WorkerRequest;
try {
try {
if (IsTransacted) {
ProcessRequestTransacted();
}
else {
// No transactions
await ProcessRequestMainAsync(includeStagesBeforeAsyncPoint, includeStagesAfterAsyncPoint).WithinCancellableCallback(Context);
}
if (includeStagesAfterAsyncPoint) {
needToCallEndTrace = false;
ProcessRequestEndTrace();
}
}
catch (ThreadAbortException) {
try {
if (needToCallEndTrace)
ProcessRequestEndTrace();
} catch {}
}
finally {
if (includeStagesAfterAsyncPoint) {
ProcessRequestCleanup();
}
}
}
catch { throw; } // Prevent Exception Filter Security Issue (ASURT 122835)
}
private void RestoreCultures(Thread currentThread, CultureInfo prevCulture, CultureInfo prevUICulture) {
if (prevCulture != currentThread.CurrentCulture || prevUICulture != currentThread.CurrentUICulture) {
if (HttpRuntime.IsFullTrust) {
SetCulture(currentThread, prevCulture, prevUICulture);
}
else {
SetCultureWithAssert(currentThread, prevCulture, prevUICulture);
}
}
}
// This must be in its own method to avoid jitting System.EnterpriseServices.dll
// when it is not needed (ASURT 71868)
private void ProcessRequestTransacted() {
bool transactionAborted = false;
TransactedCallback processRequestCallback = new TransactedCallback(ProcessRequestMain);
// Part of the request needs to be done under transacted context
Transactions.InvokeTransacted(processRequestCallback,
(TransactionOption) _transactionMode, ref transactionAborted);
// The remainder has to be done outside
try {
if (transactionAborted) {
OnAbortTransaction(EventArgs.Empty);
WebBaseEvent.RaiseSystemEvent(this, WebEventCodes.RequestTransactionAbort);
}
else {
OnCommitTransaction(EventArgs.Empty);
WebBaseEvent.RaiseSystemEvent(this, WebEventCodes.RequestTransactionComplete);
}
// Make sure Request.RawUrl gets validated.
ValidateRawUrlIfRequired();
}
catch (ThreadAbortException) {
// Don't go into HandleError logic for ThreadAbortException's, since they
// are expected (e.g. when Response.Redirect() is called).
throw;
}
catch (Exception e) {
// Increment all of the appropriate error counters
PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_DURING_REQUEST);
PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_TOTAL);
// If it hasn't been handled, rethrow it
if (!HandleError(e))
throw;
}
}
private void ProcessRequestCleanup() {
if (_request == null) {
// ProcessRequestCleanup() has already been called
return;
}
#if DISPLAYRAREFIELDSTATISTICS
// Display rare field statistics at the end of the page (for debugging purpose)
DisplayRareFieldStatistics();
#endif
_request = null;
_response = null;
if (!IsCrossPagePostBack) {
UnloadRecursive(true);
}
if (Context.TraceIsEnabled) {
Trace.StopTracing();
}
}
private void ProcessRequestEndTrace() {
if (Context.TraceIsEnabled) {
Trace.EndRequest();
// DevDiv Bugs 154103: Do not write trace output while in an async postback
if (Trace.PageOutput && !IsCallback &&
(ScriptManager == null || !ScriptManager.IsInAsyncPostBack)) {
Trace.Render(CreateHtmlTextWriter(Response.Output));
// responses with trace should not be cached
Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
}
}
#if DEBUG
private void DisplayRareFieldStatistics() {
int totalControls = 0;
int withOccasionalFields = 0;
int withRareFields = 0;
GetRareFieldStatistics(ref totalControls, ref withOccasionalFields, ref withRareFields);
_response.Write("<hr><b><p>Total controls: " + totalControls + "<br>");
_response.Write("With Occasional Fields: " + withOccasionalFields + "<br>");
_response.Write("With Rare Fields: " + withRareFields + "</p></b>");
}
#endif
internal void SetPreviousPage(Page previousPage) {
_previousPage = previousPage;
}
private void ProcessRequestMain() {
ProcessRequestMain(true /*includeStagesBeforeAsyncPoint*/, true /*includeStagesAfterAsyncPoint*/);
}
// !! IMPORTANT !!
// If you make changes to this method, also make changes to ProcessRequestMainAsync.
private void ProcessRequestMain(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint) {
try {
HttpContext con = Context;
string exportedWebPartID = null;
if (includeStagesBeforeAsyncPoint) {
// For ASPCOMPAT need to call OnPageStart for each Session object
#if !FEATURE_PAL // FEATURE_PAL does not enable COM
if (IsInAspCompatMode)
AspCompatApplicationStep.OnPageStartSessionObjects();
#else // !FEATURE_PAL
throw new NotImplementedException ("ROTORTODO");
#endif // !FEATURE_PAL
// Is it a GET, POST or initial request?
if(PageAdapter != null) {
_requestValueCollection = PageAdapter.DeterminePostBackMode();
if (_requestValueCollection != null) {
_unvalidatedRequestValueCollection = PageAdapter.DeterminePostBackModeUnvalidated();
}
}
else {
_requestValueCollection = DeterminePostBackMode();
// The contract for DeterminePostBackModeUnvalidated() is that it will only be called when
// DeterminePostBackMode() returns a non-null result. This was done so that the implementation
// of DeterminePostBackModeUnvalidated() can be kep simple, without having to duplicate the
// same logic as DeterminePostBackMode().
if (_requestValueCollection != null) {
_unvalidatedRequestValueCollection = DeterminePostBackModeUnvalidated();
}
}
// It's possible that someone incorrectly implements DeterminePostBackModeUnvalidated() such that it
// returns null when DeterminePostBackMode() a non-null value. This could cause NullRefExceptions later on.
// However since few customers would override these methods we assume that this won't happen very often.
// A customer overriding DeterminePostBackModeUnvalidated() should understand what they are doing.
string callbackControlId = String.Empty;
// Special-case Web Part Export so it executes in the same security context as the page itself (VSWhidbey 426574)
if (DetermineIsExportingWebPart()) {
if (!RuntimeConfig.GetAppConfig().WebParts.EnableExport) {
throw new InvalidOperationException(SR.GetString(SR.WebPartExportHandler_DisabledExportHandler));
}
exportedWebPartID = Request.QueryString["webPart"];
if (String.IsNullOrEmpty(exportedWebPartID)) {
throw new InvalidOperationException(SR.GetString(SR.WebPartExportHandler_InvalidArgument));
}
if (String.Equals(Request.QueryString["scope"], "shared", StringComparison.OrdinalIgnoreCase)) {
_pageFlags.Set(isExportingWebPartShared);
}
string queryString = Request.QueryString["query"];
if (queryString == null) {
queryString = String.Empty;
}
Request.QueryStringText = queryString;
con.Trace.IsEnabled = false;
}
if (_requestValueCollection != null) {
// Determine if viewstate was encrypted.
if (_requestValueCollection[ViewStateEncryptionID] != null) {
ContainsEncryptedViewState = true;
}
// Determine if this is a callback.
callbackControlId = _requestValueCollection[callbackID];
// Only accepting POST callbacks to reduce mail attack possibilities (VSWhidbey 417355)
if ((callbackControlId != null) && (_request.HttpVerb == HttpVerb.POST)) {
_isCallback = true;
}
else { // Otherwise, determine if this is cross-page posting(callsbacks can never be cross page posts)
if (!IsCrossPagePostBack) {
VirtualPath previousPagePath = null;
if (_requestValueCollection[previousPageID] != null) {
try {
previousPagePath = VirtualPath.CreateNonRelativeAllowNull(
DecryptString(_requestValueCollection[previousPageID], Purpose.WebForms_Page_PreviousPageID));
}
catch {
// VSWhidbey 493209 If we fails to decrypt the previouspageid, still
// treat this as a cross page post, not a regular postback. Otherwise
// the viewstate cannot be decrypted properly. This will happen during
// cross page post between different applications.
_pageFlags[isCrossPagePostRequest] = true;
// do nothing, ignore CryptographicException.
}
// Process if the page is posted from cross-page that still exists and the target page is not same as source page.
if (previousPagePath != null &&
previousPagePath != Request.CurrentExecutionFilePathObject) {
_pageFlags[isCrossPagePostRequest] = true;
_previousPagePath = previousPagePath;
Debug.Assert(_previousPagePath != null);
}
}
}
}
}
// Load the scroll position data now that we have the request value collection
if (MaintainScrollPositionOnPostBack) {
LoadScrollPosition();
}
// we can't cache the value of IsEnabled because it could change during any phase.
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin PreInit");
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_PRE_INIT_ENTER, _context.WorkerRequest);
PerformPreInit();
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_PRE_INIT_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End PreInit");
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin Init");
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_INIT_ENTER, _context.WorkerRequest);
InitRecursive(null);
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_INIT_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End Init");
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin InitComplete");
OnInitComplete(EventArgs.Empty);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End InitComplete");
if (IsPostBack) {
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin LoadState");
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_VIEWSTATE_ENTER, _context.WorkerRequest);
LoadAllState();
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_VIEWSTATE_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) {
Trace.Write("aspx.page", "End LoadState");
Trace.Write("aspx.page", "Begin ProcessPostData");
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_POSTDATA_ENTER, _context.WorkerRequest);
ProcessPostData(_requestValueCollection, true /* fBeforeLoad */);
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_POSTDATA_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End ProcessPostData");
}
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin PreLoad");
OnPreLoad(EventArgs.Empty);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End PreLoad");
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin Load");
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_ENTER, _context.WorkerRequest);
LoadRecursive();
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End Load");
if (IsPostBack) {
// Try process the post data again (ASURT 29045)
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin ProcessPostData Second Try");
ProcessPostData(_leftoverPostData, false /* !fBeforeLoad */);
if (con.TraceIsEnabled) {
Trace.Write("aspx.page", "End ProcessPostData Second Try");
Trace.Write("aspx.page", "Begin Raise ChangedEvents");
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_POST_DATA_CHANGED_ENTER, _context.WorkerRequest);
RaiseChangedEvents();
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_POST_DATA_CHANGED_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) {
Trace.Write("aspx.page", "End Raise ChangedEvents");
Trace.Write("aspx.page", "Begin Raise PostBackEvent");
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_RAISE_POSTBACK_ENTER, _context.WorkerRequest);
RaisePostBackEvent(_requestValueCollection);
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_RAISE_POSTBACK_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End Raise PostBackEvent");
}
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin LoadComplete");
OnLoadComplete(EventArgs.Empty);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End LoadComplete");
if (IsPostBack && IsCallback) {
PrepareCallback(callbackControlId);
}
else if (!IsCrossPagePostBack) {
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin PreRender");
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_PRE_RENDER_ENTER, _context.WorkerRequest);
PreRenderRecursiveInternal();
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_PRE_RENDER_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End PreRender");
}
}
/// Async Point here
if (_legacyAsyncInfo == null || _legacyAsyncInfo.CallerIsBlocking) {
// for non-async pages with registered async tasks - run the tasks here
// also when running async page via server.execute - run the tasks here
ExecuteRegisteredAsyncTasks();
}
// Make sure RawUrl gets validated.
ValidateRawUrlIfRequired();
if (includeStagesAfterAsyncPoint) {
if (IsCallback) {
RenderCallback();
return;
}
if (IsCrossPagePostBack) {
return;
}
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin PreRenderComplete");
PerformPreRenderComplete();
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End PreRenderComplete");
if (con.TraceIsEnabled) {
BuildPageProfileTree(EnableViewState);
Trace.Write("aspx.page", "Begin SaveState");
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_SAVE_VIEWSTATE_ENTER, _context.WorkerRequest);
SaveAllState();
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_SAVE_VIEWSTATE_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) {
Trace.Write("aspx.page", "End SaveState");
Trace.Write("aspx.page", "Begin SaveStateComplete");
}
OnSaveStateComplete(EventArgs.Empty);
if (con.TraceIsEnabled) {
Trace.Write("aspx.page", "End SaveStateComplete");
Trace.Write("aspx.page", "Begin Render");
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_RENDER_ENTER, _context.WorkerRequest);
// Special-case Web Part Export so it executes in the same security context as the page itself (VSWhidbey 426574)
if (exportedWebPartID != null) {
ExportWebPart(exportedWebPartID);
}
else {
RenderControl(CreateHtmlTextWriter(Response.Output));
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_RENDER_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End Render");
CheckRemainingAsyncTasks(false);
}
}
catch (ThreadAbortException e) {
// Don't go into HandleError logic for ThreadAbortExceptions, since they
// are expected (e.g. when Response.Redirect() is called).
// VSWhidbey 500309: perf improvement. We can safely cancel the thread abort here
// to avoid re-throwing the exception if this is a redirect and we're not being executed
// under the context of a Server.Execute call (i.e. _context.Handler == this). Otherwise,
// re-throw so this can be handled lower in the stack (see HttpApplication.ExecuteStep).
// This perf optimization can only be applied if we are executing the entire page
// lifecycle within this method call (otherwise, in async pages) calling ResetAbort
// would only skip part of the lifecycle, not the entire page (as Response.End is supposed to)
HttpApplication.CancelModuleException cancelException = e.ExceptionState as HttpApplication.CancelModuleException;
if (includeStagesBeforeAsyncPoint && includeStagesAfterAsyncPoint && // executing entire page
_context.Handler == this && // not in server execute
_context.ApplicationInstance != null && // application must be non-null so we can complete the request
cancelException != null && !cancelException.Timeout) { // this is Response.End
_context.ApplicationInstance.CompleteRequest();
ThreadResetAbortWithAssert();
}
else {
CheckRemainingAsyncTasks(true);
throw;
}
}
catch (System.Configuration.ConfigurationException) {
throw;
}
catch (Exception e) {
// Increment all of the appropriate error counters
PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_DURING_REQUEST);
PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_TOTAL);
// If it hasn't been handled, rethrow it
if (!HandleError(e))
throw;
}
}
// TAP version of ProcessRequestMain routine.
// !! IMPORTANT !!
// If you make changes to this method, also make changes to ProcessRequestMain.
private async Task ProcessRequestMainAsync(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint) {
try {
HttpContext con = Context;
string exportedWebPartID = null;
if (includeStagesBeforeAsyncPoint) {
// For ASPCOMPAT need to call OnPageStart for each Session object
#if !FEATURE_PAL // FEATURE_PAL does not enable COM
if (IsInAspCompatMode)
AspCompatApplicationStep.OnPageStartSessionObjects();
#else // !FEATURE_PAL
throw new NotImplementedException ("ROTORTODO");
#endif // !FEATURE_PAL
// Is it a GET, POST or initial request?
if(PageAdapter != null) {
_requestValueCollection = PageAdapter.DeterminePostBackMode();
if (_requestValueCollection != null) {
_unvalidatedRequestValueCollection = PageAdapter.DeterminePostBackModeUnvalidated();
}
}
else {
_requestValueCollection = DeterminePostBackMode();
// The contract for DeterminePostBackModeUnvalidated() is that it will only be called when
// DeterminePostBackMode() returns a non-null result. This was done so that the implementation
// of DeterminePostBackModeUnvalidated() can be kep simple, without having to duplicate the
// same logic as DeterminePostBackMode().
if (_requestValueCollection != null) {
_unvalidatedRequestValueCollection = DeterminePostBackModeUnvalidated();
}
}
// It's possible that someone incorrectly implements DeterminePostBackModeUnvalidated() such that it
// returns null when DeterminePostBackMode() a non-null value. This could cause NullRefExceptions later on.
// However since few customers would override these methods we assume that this won't happen very often.
// A customer overriding DeterminePostBackModeUnvalidated() should understand what they are doing.
string callbackControlId = String.Empty;
// Special-case Web Part Export so it executes in the same security context as the page itself (VSWhidbey 426574)
if (DetermineIsExportingWebPart()) {
if (!RuntimeConfig.GetAppConfig().WebParts.EnableExport) {
throw new InvalidOperationException(SR.GetString(SR.WebPartExportHandler_DisabledExportHandler));
}
exportedWebPartID = Request.QueryString["webPart"];
if (String.IsNullOrEmpty(exportedWebPartID)) {
throw new InvalidOperationException(SR.GetString(SR.WebPartExportHandler_InvalidArgument));
}
if (String.Equals(Request.QueryString["scope"], "shared", StringComparison.OrdinalIgnoreCase)) {
_pageFlags.Set(isExportingWebPartShared);
}
string queryString = Request.QueryString["query"];
if (queryString == null) {
queryString = String.Empty;
}
Request.QueryStringText = queryString;
con.Trace.IsEnabled = false;
}
if (_requestValueCollection != null) {
// Determine if viewstate was encrypted.
if (_requestValueCollection[ViewStateEncryptionID] != null) {
ContainsEncryptedViewState = true;
}
// Determine if this is a callback.
callbackControlId = _requestValueCollection[callbackID];
// Only accepting POST callbacks to reduce mail attack possibilities (VSWhidbey 417355)
if ((callbackControlId != null) && (_request.HttpVerb == HttpVerb.POST)) {
_isCallback = true;
}
else { // Otherwise, determine if this is cross-page posting(callsbacks can never be cross page posts)
if (!IsCrossPagePostBack) {
VirtualPath previousPagePath = null;
if (_requestValueCollection[previousPageID] != null) {
try {
previousPagePath = VirtualPath.CreateNonRelativeAllowNull(
DecryptString(_requestValueCollection[previousPageID], Purpose.WebForms_Page_PreviousPageID));
}
catch {
// VSWhidbey 493209 If we fails to decrypt the previouspageid, still
// treat this as a cross page post, not a regular postback. Otherwise
// the viewstate cannot be decrypted properly. This will happen during
// cross page post between different applications.
_pageFlags[isCrossPagePostRequest] = true;
// do nothing, ignore CryptographicException.
}
// Process if the page is posted from cross-page that still exists and the target page is not same as source page.
if (previousPagePath != null &&
previousPagePath != Request.CurrentExecutionFilePathObject) {
_pageFlags[isCrossPagePostRequest] = true;
_previousPagePath = previousPagePath;
Debug.Assert(_previousPagePath != null);
}
}
}
}
}
// Load the scroll position data now that we have the request value collection
if (MaintainScrollPositionOnPostBack) {
LoadScrollPosition();
}
// we can't cache the value of IsEnabled because it could change during any phase.
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin PreInit");
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_PRE_INIT_ENTER, _context.WorkerRequest);
await PerformPreInitAsync().WithinCancellableCallback(con);
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_PRE_INIT_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End PreInit");
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin Init");
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_INIT_ENTER, _context.WorkerRequest);
Task initRecursiveTask = InitRecursiveAsync(null, this);
await initRecursiveTask.WithinCancellableCallback(con);
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_INIT_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End Init");
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin InitComplete");
using (con.SyncContext.AllowVoidAsyncOperationsBlock()) {
OnInitComplete(EventArgs.Empty);
await GetWaitForPreviousStepCompletionAwaitable();
}
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End InitComplete");
if (IsPostBack) {
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin LoadState");
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_VIEWSTATE_ENTER, _context.WorkerRequest);
LoadAllState();
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_VIEWSTATE_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) {
Trace.Write("aspx.page", "End LoadState");
Trace.Write("aspx.page", "Begin ProcessPostData");
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_POSTDATA_ENTER, _context.WorkerRequest);
if (AppSettings.EnableAsyncModelBinding) {
await ProcessPostDataAsync(_requestValueCollection, true /* fBeforeLoad */).WithinCancellableCallback(con);
}
else {
ProcessPostData(_requestValueCollection, true /* fBeforeLoad */);
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_POSTDATA_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End ProcessPostData");
}
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin PreLoad");
using (con.SyncContext.AllowVoidAsyncOperationsBlock()) {
OnPreLoad(EventArgs.Empty);
await GetWaitForPreviousStepCompletionAwaitable();
}
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End PreLoad");
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin Load");
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_ENTER, _context.WorkerRequest);
await LoadRecursiveAsync(this).WithinCancellableCallback(con);
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End Load");
if (IsPostBack) {
// Try process the post data again (ASURT 29045)
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin ProcessPostData Second Try");
if (AppSettings.EnableAsyncModelBinding) {
await ProcessPostDataAsync(_leftoverPostData, false /* !fBeforeLoad */).WithinCancellableCallback(con);
}
else {
ProcessPostData(_leftoverPostData, false /* !fBeforeLoad */);
}
if (con.TraceIsEnabled) {
Trace.Write("aspx.page", "End ProcessPostData Second Try");
Trace.Write("aspx.page", "Begin Raise ChangedEvents");
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_POST_DATA_CHANGED_ENTER, _context.WorkerRequest);
await RaiseChangedEventsAsync().WithinCancellableCallback(con);
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_POST_DATA_CHANGED_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) {
Trace.Write("aspx.page", "End Raise ChangedEvents");
Trace.Write("aspx.page", "Begin Raise PostBackEvent");
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_RAISE_POSTBACK_ENTER, _context.WorkerRequest);
using (con.SyncContext.AllowVoidAsyncOperationsBlock()) {
RaisePostBackEvent(_requestValueCollection);
await GetWaitForPreviousStepCompletionAwaitable();
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_RAISE_POSTBACK_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End Raise PostBackEvent");
}
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin LoadComplete");
using (con.SyncContext.AllowVoidAsyncOperationsBlock()) {
OnLoadComplete(EventArgs.Empty);
await GetWaitForPreviousStepCompletionAwaitable();
}
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End LoadComplete");
if (IsPostBack && IsCallback) {
await PrepareCallbackAsync(callbackControlId).WithinCancellableCallback(con);
}
else if (!IsCrossPagePostBack) {
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin PreRender");
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_PRE_RENDER_ENTER, _context.WorkerRequest);
await PreRenderRecursiveInternalAsync(this).WithinCancellableCallback(con);
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_PRE_RENDER_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End PreRender");
}
}
/// Async Point here
if (_legacyAsyncInfo == null || _legacyAsyncInfo.CallerIsBlocking) {
// for non-async pages with registered async tasks - run the tasks here
// also when running async page via server.execute - run the tasks here
ExecuteRegisteredAsyncTasks();
}
// Make sure RawUrl gets validated.
ValidateRawUrlIfRequired();
if (includeStagesAfterAsyncPoint) {
if (IsCallback) {
RenderCallback();
return;
}
if (IsCrossPagePostBack) {
return;
}
if (con.TraceIsEnabled) Trace.Write("aspx.page", "Begin PreRenderComplete");
PerformPreRenderComplete();
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End PreRenderComplete");
if (con.TraceIsEnabled) {
BuildPageProfileTree(EnableViewState);
Trace.Write("aspx.page", "Begin SaveState");
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_SAVE_VIEWSTATE_ENTER, _context.WorkerRequest);
SaveAllState();
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_SAVE_VIEWSTATE_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) {
Trace.Write("aspx.page", "End SaveState");
Trace.Write("aspx.page", "Begin SaveStateComplete");
}
OnSaveStateComplete(EventArgs.Empty);
if (con.TraceIsEnabled) {
Trace.Write("aspx.page", "End SaveStateComplete");
Trace.Write("aspx.page", "Begin Render");
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_RENDER_ENTER, _context.WorkerRequest);
// Special-case Web Part Export so it executes in the same security context as the page itself (VSWhidbey 426574)
if (exportedWebPartID != null) {
ExportWebPart(exportedWebPartID);
}
else {
RenderControl(CreateHtmlTextWriter(Response.Output));
}
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Page)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_RENDER_LEAVE, _context.WorkerRequest);
if (con.TraceIsEnabled) Trace.Write("aspx.page", "End Render");
CheckRemainingAsyncTasks(false);
}
}
catch (ThreadAbortException e) {
// Don't go into HandleError logic for ThreadAbortExceptions, since they
// are expected (e.g. when Response.Redirect() is called).
// VSWhidbey 500309: perf improvement. We can safely cancel the thread abort here
// to avoid re-throwing the exception if this is a redirect and we're not being executed
// under the context of a Server.Execute call (i.e. _context.Handler == this). Otherwise,
// re-throw so this can be handled lower in the stack (see HttpApplication.ExecuteStep).
// This perf optimization can only be applied if we are executing the entire page
// lifecycle within this method call (otherwise, in async pages) calling ResetAbort
// would only skip part of the lifecycle, not the entire page (as Response.End is supposed to)
HttpApplication.CancelModuleException cancelException = e.ExceptionState as HttpApplication.CancelModuleException;
if (includeStagesBeforeAsyncPoint && includeStagesAfterAsyncPoint && // executing entire page
_context.Handler == this && // not in server execute
_context.ApplicationInstance != null && // application must be non-null so we can complete the request
cancelException != null && !cancelException.Timeout) { // this is Response.End
_context.ApplicationInstance.CompleteRequest();
ThreadResetAbortWithAssert();
}
else {
CheckRemainingAsyncTasks(true);
throw;
}
}
catch (System.Configuration.ConfigurationException) {
throw;
}
catch (Exception e) {
// Increment all of the appropriate error counters
PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_DURING_REQUEST);
PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_TOTAL);
// If it hasn't been handled, rethrow it
if (!HandleError(e))
throw;
}
}
internal WithinCancellableCallbackTaskAwaitable GetWaitForPreviousStepCompletionAwaitable() {
AspNetSynchronizationContext syncContext = SynchronizationContext.Current as AspNetSynchronizationContext;
if (syncContext != null) {
return syncContext.WaitForPendingOperationsAsync().WithinCancellableCallback(Context);
}
else {
// If the SynchronizationContext has been replaced, we can't query for previous step completion, so just assume it completed.
return WithinCancellableCallbackTaskAwaitable.Completed;
}
}
private void BuildPageProfileTree(bool enableViewState) {
if (!_profileTreeBuilt) {
_profileTreeBuilt = true;
BuildProfileTree("ROOT", enableViewState);
}
}
private void ExportWebPart(string exportedWebPartID) {
WebPart webPartToExport = null;
WebPartManager webPartManager = WebPartManager.GetCurrentWebPartManager(this);
if (webPartManager != null) {
webPartToExport = webPartManager.WebParts[exportedWebPartID];
}
if (webPartToExport == null || webPartToExport.IsClosed || webPartToExport is ProxyWebPart) {
// If there is no WebPartManager, or the web part is not on the page, or has been replaced
// by a ProxyWebPart, we should perform a Response.Redirect() back to the page with the
// Export query string removed. The Export query string has already been removed in
// ProcessRequestMain().
// (VSWhidbey 358464, 496050, 504819, 515472)
Response.Redirect(Request.RawUrl, false);
}
else {
// We'll be writing Xml to the response -> Prepare the response
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Expires = 0;
Response.ContentType = "application/mswebpart";
string title = webPartToExport.DisplayTitle;
if (String.IsNullOrEmpty(title)) {
title = SR.GetString(SR.Part_Untitled);
}
NonWordRegex nonWordRegex = new NonWordRegex();
Response.AddHeader("content-disposition", "attachment; filename=" +
nonWordRegex.Replace(title, "") +
".WebPart");
using (XmlTextWriter writer = new XmlTextWriter(Response.Output)) {
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
// Export to the response stream
webPartManager.ExportWebPart(webPartToExport, writer);
writer.WriteEndDocument();
}
}
}
private void InitializeWriter(HtmlTextWriter writer) {
Html32TextWriter h32tw = writer as Html32TextWriter;
if (h32tw != null && Request.Browser != null) {
h32tw.ShouldPerformDivTableSubstitution = Request.Browser.Tables;
}
}
protected internal override void Render(HtmlTextWriter writer) {
InitializeWriter(writer);
base.Render(writer);
}
// !! IMPORTANT !!
// If you change this method, also change PrepareCallbackAsync.
private void PrepareCallback(string callbackControlID) {
Response.Cache.SetNoStore();
try {
string param = _requestValueCollection[callbackParameterID];
_callbackControl = FindControl(callbackControlID) as ICallbackEventHandler;
if (_callbackControl != null) {
_callbackControl.RaiseCallbackEvent(param);
}
else {
throw new InvalidOperationException(SR.GetString(SR.Page_CallBackTargetInvalid, callbackControlID));
}
}
catch (Exception e) {
Response.Clear();
Response.Write('e');
if (Context.IsCustomErrorEnabled) {
Response.Write(SR.GetString(SR.Page_CallBackError));
}
else {
bool needsCallbackLoadScript = !String.IsNullOrEmpty(_requestValueCollection[callbackLoadScriptID]);
Response.Write(needsCallbackLoadScript ?
Util.QuoteJScriptString(HttpUtility.HtmlEncode(e.Message)) :
HttpUtility.HtmlEncode(e.Message));
}
}
return;
}
// TAP version of PrepareCallback.
// !! IMPORTANT !!
// If you change this method, also change PrepareCallback.
private async Task PrepareCallbackAsync(string callbackControlID) {
Response.Cache.SetNoStore();
try {
string param = _requestValueCollection[callbackParameterID];
_callbackControl = FindControl(callbackControlID) as ICallbackEventHandler;
if (_callbackControl != null) {
using (Context.SyncContext.AllowVoidAsyncOperationsBlock()) {
_callbackControl.RaiseCallbackEvent(param);
await GetWaitForPreviousStepCompletionAwaitable();
}
}
else {
throw new InvalidOperationException(SR.GetString(SR.Page_CallBackTargetInvalid, callbackControlID));
}
}
catch (Exception e) {
Response.Clear();
Response.Write('e');
if (Context.IsCustomErrorEnabled) {
Response.Write(SR.GetString(SR.Page_CallBackError));
}
else {
bool needsCallbackLoadScript = !String.IsNullOrEmpty(_requestValueCollection[callbackLoadScriptID]);
Response.Write(needsCallbackLoadScript ?
Util.QuoteJScriptString(HttpUtility.HtmlEncode(e.Message)) :
HttpUtility.HtmlEncode(e.Message));
}
}
return;
}
private void RenderCallback() {
bool needsCallbackLoadScript = !String.IsNullOrEmpty(_requestValueCollection[callbackLoadScriptID]);
try {
string index = null;
if (needsCallbackLoadScript) {
index = _requestValueCollection[callbackIndexID];
if (String.IsNullOrEmpty(index)) {
throw new HttpException(SR.GetString(SR.Page_CallBackInvalid));
}
// We validate the user string because we're injecting it into the response script.
// We don't need the integer, so we don't call Parse, we just need to check only expected
// characters are in the string (0 to 9)
for (int i = 0; i < index.Length; i++) {
char c = index[i];
if (c < '0' || c > '9') {
throw new HttpException(SR.GetString(SR.Page_CallBackInvalid));
}
}
Response.Write("<script>parent.__pendingCallbacks[");
Response.Write(index);
Response.Write("].xmlRequest.responseText=\"");
}
if (_callbackControl != null) {
string result = _callbackControl.GetCallbackResult();
if (EnableEventValidation) {
// Outputting the new value for the validation field under the length|value format.
string validation = ClientScript.GetEventValidationFieldValue();
Response.Write(validation.Length.ToString(CultureInfo.InvariantCulture));
Response.Write('|');
Response.Write(validation);
}
else {
Response.Write('s');
}
Response.Write(needsCallbackLoadScript ? Util.QuoteJScriptString(result) : result);
}
if (needsCallbackLoadScript) {
Response.Write("\";parent.__pendingCallbacks[");
Response.Write(index);
Response.Write("].xmlRequest.readyState=4;parent.WebForm_CallbackComplete();</script>");
}
}
catch (Exception e) {
Response.Clear();
Response.Write('e');
if (Context.IsCustomErrorEnabled) {
Response.Write(SR.GetString(SR.Page_CallBackError));
}
else {
Response.Write(needsCallbackLoadScript ?
Util.QuoteJScriptString(HttpUtility.HtmlEncode(e.Message)) :
HttpUtility.HtmlEncode(e.Message));
}
}
return;
}
private bool RenderDivAroundHiddenInputs(HtmlTextWriter writer) {
return writer.RenderDivAroundHiddenInputs && (!EnableLegacyRendering || (RenderingCompatibility >= VersionUtil.Framework40));
}
internal void SetForm(HtmlForm form) {
_form = form;
}
internal void SetPostFormRenderDelegate(RenderMethod renderMethod) {
_postFormRenderDelegate = renderMethod;
}
public HtmlForm Form { get { return _form; } }
/// <devdoc>
/// <para>If called, ViewState will be persisted (see ASURT 73020).</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void RegisterViewStateHandler() {
_needToPersistViewState = true;
}
private void SaveAllState() {
// Don't do anything if no one cares about the view state (see ASURT 73020)
// Note: If _needToPersistViewState is false, control state should also be ignored.
if (!_needToPersistViewState)
return;
Pair statePair = new Pair();
// Control state is saved as a dictionary of
// 1. A list of controls that require postback (stored under the page id)
// 2. A dictionary of controls and their control state
IDictionary controlStates = null;
if (_registeredControlsRequiringControlState != null &&
_registeredControlsRequiringControlState.Count > 0) {
#if OBJECTSTATEFORMATTER
controlStates = new HybridDictionary(_registeredControlsRequiringControlState.Count + 1);
#else
controlStates = new Hashtable(_registeredControlsRequiringControlState.Count + 1);
#endif
foreach (Control ctl in _registeredControlsRequiringControlState) {
object controlState = ctl.SaveControlStateInternal();
// Do not allow null control states to be added, and do not allow a control's state to be
// added more than once.
if (controlStates[ctl.UniqueID] == null && controlState != null) {
controlStates.Add(ctl.UniqueID, controlState);
}
}
}
if (_registeredControlsThatRequirePostBack != null && _registeredControlsThatRequirePostBack.Count > 0) {
if (controlStates == null) {
#if OBJECTSTATEFORMATTER
controlStates = new HybridDictionary();
#else
controlStates = new Hashtable();
#endif
}
controlStates.Add(PageRegisteredControlsThatRequirePostBackKey, _registeredControlsThatRequirePostBack);
}
// Only persist control state if it is nonempty.
if (controlStates != null && controlStates.Count > 0) {
statePair.First = controlStates;
}
// The state is saved as an array of objects:
// 1. The hash code string
// 2. The state of the entire control hierarchy
ViewStateMode inheritedMode = ViewStateMode;
if (inheritedMode == ViewStateMode.Inherit) {
inheritedMode = ViewStateMode.Enabled;
}
Pair allSavedViewState = new Pair(GetTypeHashCode().ToString(NumberFormatInfo.InvariantInfo), SaveViewStateRecursive(inheritedMode));
if (Context.TraceIsEnabled) {
int viewStateSize = 0;
if (allSavedViewState.Second is Pair) {
viewStateSize = EstimateStateSize(((Pair)allSavedViewState.Second).First);
} else if (allSavedViewState.Second is Triplet) {
viewStateSize = EstimateStateSize(((Triplet)allSavedViewState.Second).First);
}
Trace.AddControlStateSize(UniqueID, viewStateSize, controlStates == null? 0 : EstimateStateSize(controlStates[UniqueID]));
}
statePair.Second = allSavedViewState;
SavePageStateToPersistenceMedium(statePair);
}
/*
* Override this method to persist view state to something other
* than hidden fields (
*/
/// <devdoc>
/// <para>Saves any view state information for the page. Override
/// this method if you want to save the page view state in anything other than a hidden field.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected internal virtual void SavePageStateToPersistenceMedium(object state) {
PageStatePersister persister = PageStatePersister;
if (state is Pair) {
Pair pair = (Pair)state;
persister.ControlState = pair.First;
persister.ViewState = pair.Second;
}
else /* triplet, legacy case, see VSWhidbey 155185 */ {
persister.ViewState = state;
}
persister.Save();
}
/*
* Set the intrinsics in this page object
*/
private void SetIntrinsics(HttpContext context) {
SetIntrinsics(context, false /* allowAsync */);
}
private void SetIntrinsics(HttpContext context, bool allowAsync) {
_context = context;
_request = context.Request;
_response = context.Response;
_application = context.Application;
_cache = context.Cache;
if (!allowAsync && _context != null && _context.ApplicationInstance != null) {
// disable attempts to launch async operations from pages not marked as async=true
// the first non-async page [on the server.execute stack] disables async operations
// it is re-enabled back in HttpApplication after done executing handler
_context.SyncContext.Disable();
}
// Synchronize the ClientTarget
if (!String.IsNullOrEmpty(_clientTarget)) {
_request.ClientTarget = _clientTarget;
}
// DCR 85444: Support per device type encoding
HttpCapabilitiesBase caps = _request.Browser;
if(caps != null) {
// Dev10 440476: Page.SetIntrinsics method has a bug causing throwing NullReferenceException
// in certain circumstances. This edge case was regressed by the VSWhidbey fix below.
// VSWhidbey 109162: Set content type at the very beginning so it can be
// overwritten within the user code of the page if needed.
_response.ContentType = caps.PreferredRenderingMime;
string preferredResponseEncoding = caps.PreferredResponseEncoding;
string preferredRequestEncoding = caps.PreferredRequestEncoding;
if (!String.IsNullOrEmpty(preferredResponseEncoding)) {
_response.ContentEncoding = Encoding.GetEncoding(preferredResponseEncoding);
}
if(!String.IsNullOrEmpty(preferredRequestEncoding)) {
_request.ContentEncoding = Encoding.GetEncoding(preferredRequestEncoding);
}
}
// Hook up any automatic handler we may find (e.g. Page_Load)
HookUpAutomaticHandlers();
}
/// <devdoc>
/// Initializes the page's reference to the header control
/// </devdoc>
internal void SetHeader(HtmlHead header) {
_header = header;
if (!String.IsNullOrEmpty(_titleToBeSet)) {
if (_header == null) {
throw new InvalidOperationException(SR.GetString(SR.Page_Title_Requires_Head));
}
else {
Title = _titleToBeSet;
_titleToBeSet = null;
}
}
if (!String.IsNullOrEmpty(_descriptionToBeSet)) {
if (_header == null) {
throw new InvalidOperationException(SR.GetString(SR.Page_Description_Requires_Head));
}
else {
MetaDescription = _descriptionToBeSet;
_descriptionToBeSet = null;
}
}
if (!String.IsNullOrEmpty(_keywordsToBeSet)) {
if (_header == null) {
throw new InvalidOperationException(SR.GetString(SR.Page_Description_Requires_Head));
}
else {
MetaKeywords = _keywordsToBeSet;
_keywordsToBeSet = null;
}
}
}
/// Override to unload the previousPage. The previousPage is unloaded after
/// the current page since current page could depend on previousPage.
internal override void UnloadRecursive(bool dispose) {
base.UnloadRecursive(dispose);
if (_previousPage != null && _previousPage.IsCrossPagePostBack) {
_previousPage.UnloadRecursive(dispose);
}
}
// ASP Compat helpers
#if !FEATURE_PAL // FEATURE_PAL does not enable COM
private AspCompatApplicationStep _aspCompatStep;
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
protected IAsyncResult AspCompatBeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) {
SetIntrinsics(context);
_aspCompatStep = new AspCompatApplicationStep(context, new AspCompatCallback(ProcessRequest));
return _aspCompatStep.BeginAspCompatExecution(cb, extraData);
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
protected void AspCompatEndProcessRequest(IAsyncResult result) {
_aspCompatStep.EndAspCompatExecution(result);
}
#endif // !FEATURE_PAL
// Async page helpers
public void ExecuteRegisteredAsyncTasks() {
if (_legacyAsyncTaskManager == null) {
// no tasks registered
return;
}
if (_legacyAsyncTaskManager.TaskExecutionInProgress) {
// already executing - don't re-enter
return;
}
HttpAsyncResult ar = _legacyAsyncTaskManager.ExecuteTasks(null /*callback*/, null /*extraData*/);
if (ar.Error != null) {
// rethrow any errors running tasks synchronously
throw new HttpException(null, ar.Error);
}
}
private void CheckRemainingAsyncTasks(bool isThreadAbort) {
// this method is called at the end of page execution
// it throws if there are registered async tasks not executed yet
if (_legacyAsyncTaskManager != null) {
_legacyAsyncTaskManager.DisposeTimer();
if (isThreadAbort) {
_legacyAsyncTaskManager.CompleteAllTasksNow(true);
return;
}
if (!_legacyAsyncTaskManager.FailedToStartTasks && _legacyAsyncTaskManager.AnyTasksRemain) {
throw new HttpException(SR.GetString(SR.Registered_async_tasks_remain));
}
}
}
// Registers an asynchronous task with a page. Like other APIs on Page, this method is itself not thread-safe.
public void RegisterAsyncTask(PageAsyncTask task) {
if (task == null) {
throw new ArgumentNullException("task");
}
if (SynchronizationContextUtil.CurrentMode == SynchronizationContextMode.Legacy) {
if (_legacyAsyncTaskManager == null) {
_legacyAsyncTaskManager = new LegacyPageAsyncTaskManager(this);
}
// Need to convert the user-provided PageAsyncTask to a legacy-style task for consumption by the legacy task manager
LegacyPageAsyncTask legacyTask = new LegacyPageAsyncTask(task.BeginHandler, task.EndHandler, task.TimeoutHandler, task.State, task.ExecuteInParallel);
_legacyAsyncTaskManager.AddTask(legacyTask);
}
else {
// synchronous pages don't support async tasks
if (!(this is IHttpAsyncHandler)) {
throw new InvalidOperationException(SR.GetString(SR.Async_required));
}
if (_asyncTaskManager == null) {
_asyncTaskManager = new PageAsyncTaskManager();
}
// We need to detect whether this is TAP or APM and enqueue the appropriate concrete type
IPageAsyncTask asyncTask = (task.TaskHandler != null)
? (IPageAsyncTask)new PageAsyncTaskTap(task.TaskHandler)
: (IPageAsyncTask)new PageAsyncTaskApm(task.BeginHandler, task.EndHandler, task.State);
_asyncTaskManager.EnqueueTask(asyncTask);
}
}
class LegacyPageAsyncInfo {
private Page _page;
private bool _callerIsBlocking; // in case of blocking caller can't lock app instance on another thread (deadlock)
private HttpApplication _app;
private AspNetSynchronizationContextBase _syncContext;
private HttpAsyncResult _asyncResult;
private bool _asyncPointReached;
private int _handlerCount;
private ArrayList _beginHandlers;
private ArrayList _endHandlers;
private ArrayList _stateObjects;
private AsyncCallback _completionCallback;
private WaitCallback _callHandlersThreadpoolCallback;
private int _currentHandler;
private Exception _error;
private bool _completed;
internal LegacyPageAsyncInfo(Page page) {
_page = page;
_app = page.Context.ApplicationInstance;
_syncContext = page.Context.SyncContext;
_completionCallback = new AsyncCallback(this.OnAsyncHandlerCompletion);
_callHandlersThreadpoolCallback = new WaitCallback(this.CallHandlersFromThreadpoolThread);
}
internal HttpAsyncResult AsyncResult {
get { return _asyncResult; }
set { _asyncResult = value; }
}
internal bool AsyncPointReached {
get { return _asyncPointReached; }
set { _asyncPointReached = value; }
}
internal bool CallerIsBlocking {
get { return _callerIsBlocking; }
set { _callerIsBlocking = value; }
}
internal void AddHandler(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
if (_handlerCount == 0) {
_beginHandlers = new ArrayList();
_endHandlers = new ArrayList();
_stateObjects = new ArrayList();
}
_beginHandlers.Add(beginHandler);
_endHandlers.Add(endHandler);
_stateObjects.Add(state);
_handlerCount++;
}
internal void CallHandlers(bool onPageThread) {
try {
if (CallerIsBlocking || onPageThread) {
// locking app on another thread when the caller is blocking will lead to deadlocks, so don't lock here
// VSWhidbey 189344
CallHandlersPossiblyUnderLock(onPageThread);
} else {
lock (_app) {
CallHandlersPossiblyUnderLock(onPageThread);
}
}
}
catch (Exception e) {
_error = e;
_completed = true;
_asyncResult.Complete(onPageThread, null /*result*/, _error);
if (!onPageThread &&
e is ThreadAbortException &&
((ThreadAbortException)e).ExceptionState is HttpApplication.CancelModuleException) {
// don't leave this threadpool thread with CancelModuleException
// as thread state - it might lead to AppDomainUnloadedException
// later, when the current app domain is unloaded and there is
// an attempt to get thread state form another app domain on
// the same thread
ThreadResetAbortWithAssert();
}
}
}
private void CallHandlersPossiblyUnderLock(bool onPageThread) {
ThreadContext threadContext = null;
if (!onPageThread) {
threadContext = _app.OnThreadEnter();
}
try {
while (_currentHandler < _handlerCount && _error == null) {
try {
IAsyncResult ar = ((BeginEventHandler)_beginHandlers[_currentHandler])(_page, EventArgs.Empty, _completionCallback, _stateObjects[_currentHandler]);
if (ar == null) {
throw new InvalidOperationException(SR.GetString(SR.Async_null_asyncresult));
}
if (ar.CompletedSynchronously) {
try {
((EndEventHandler)_endHandlers[_currentHandler])(ar);
}
finally {
_currentHandler++;
}
continue;
}
// async completion
return;
}
catch (Exception e) {
if (onPageThread && _syncContext.PendingOperationsCount == 0) {
throw;
}
// Increment all of the appropriate error counters
PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_DURING_REQUEST);
PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_TOTAL);
// If it hasn't been handled, rememeber it
try {
if (!_page.HandleError(e))
_error = e;
}
catch (Exception e2) {
_error = e2;
}
}
}
// check if any async operations started
#if DBG
Debug.Trace("Async", "Page has PendingOperationsCount of " + _syncContext.PendingOperationsCount);
#endif
if (_syncContext.PendingCompletion(_callHandlersThreadpoolCallback)) {
return;
}
// get the error that happened in async completion delegates
if (_error == null && _syncContext.Error != null) {
try {
if (!_page.HandleError(_syncContext.Error)) {
_error = _syncContext.Error;
_syncContext.ClearError();
}
}
catch (Exception e) {
_error = e;
}
}
// finish up the page processing
try {
_page.Context.InvokeCancellableCallback(new WaitCallback(o => { _page.ProcessRequest(false /*includeStagesBeforeAsyncPoint*/, true /*includeStagesAfterAsyncPoint*/); }), null);
}
catch (Exception e) {
if (onPageThread)
throw;
_error = e;
}
// complete the async request (notify HttpAppplication)
if (threadContext != null) {
// call DisassociateFromCurrentThread before Complete, because complete
// might resume and finish up the pipeline inside the call
try {
threadContext.DisassociateFromCurrentThread();
}
finally {
threadContext = null;
}
}
_completed = true;
_asyncResult.Complete(onPageThread, null /*result*/, _error);
}
finally {
if (threadContext != null) {
threadContext.DisassociateFromCurrentThread();
}
}
}
private void OnAsyncHandlerCompletion(IAsyncResult ar) {
if (ar.CompletedSynchronously) // handled in CallHandlers()
return;
try {
((EndEventHandler)_endHandlers[_currentHandler])(ar);
}
catch (Exception e) {
_error = e;
}
if (_completed) {
// already completed (possibly due to timeout, don't continue)
return;
}
_currentHandler++;
if (Thread.CurrentThread.IsThreadPoolThread) {
// if on thread pool thread, use the current thread
CallHandlers(false);
}
else {
// if on a non-threadpool thread, requeue
ThreadPool.QueueUserWorkItem(_callHandlersThreadpoolCallback);
}
}
private void CallHandlersFromThreadpoolThread(Object data) {
Debug.Trace("Async", "Page -- CallHandlersFromThreadpoolThread");
CallHandlers(false);
}
internal void SetError(Exception error) {
_error = error;
}
}
private void AsyncPageProcessRequestBeforeAsyncPointCancellableCallback(Object state) {
ProcessRequest(true /*includeStagesBeforeAsyncPoint*/, false /*includeStagesAfterAsyncPoint*/);
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
protected IAsyncResult AsyncPageBeginProcessRequest(HttpContext context, AsyncCallback callback, Object extraData) {
// This method just dispatches to either the TAP or APM implementation, depending on the synchronization mode
if (SynchronizationContextUtil.CurrentMode == SynchronizationContextMode.Legacy) {
return LegacyAsyncPageBeginProcessRequest(context, callback, extraData);
}
else {
return TaskAsyncHelper.BeginTask(() => ProcessRequestAsync(context), callback, extraData);
}
}
internal CancellationTokenSource CreateCancellationTokenFromAsyncTimeout() {
TimeSpan timeout = AsyncTimeout;
// CancellationTokenSource can only create timers within a specific range (<= _maxAsyncTimeout)
return (timeout <= _maxAsyncTimeout)
? new CancellationTokenSource(timeout)
: new CancellationTokenSource();
}
// TAP
private async Task ProcessRequestAsync(HttpContext context) {
// we disallow async operations except during specific portions of the lifecycle
context.SyncContext.ProhibitVoidAsyncOperations();
SetIntrinsics(context, true /* allowAsync */);
if (_asyncTaskManager == null) {
// could be already created if AddOnPreRenderCompleteAsync called before ProcessRequest
_asyncTaskManager = new PageAsyncTaskManager();
}
try {
// process everything before the async point
// the AsyncPageProcessRequestBeforeAsyncPointCancellableCallback method has its own HandleError semantics and will not throw if the exception is handled
Task preWorkTask = null;
_context.InvokeCancellableCallback(_ => {
preWorkTask = ProcessRequestAsync(includeStagesBeforeAsyncPoint: true, includeStagesAfterAsyncPoint: false);
}, null);
await preWorkTask;
// perform the asynchronous work
try {
using (CancellationTokenSource cancellationTokenSource = CreateCancellationTokenFromAsyncTimeout()) {
CancellationToken cancellationToken = cancellationTokenSource.Token;
try {
await _asyncTaskManager.ExecuteTasksAsync(this, EventArgs.Empty, cancellationToken, _context.SyncContext, _context.ApplicationInstance);
}
finally {
// Homogenize any exceptions due to request timeout into a TimeoutException.
if (cancellationToken.IsCancellationRequested) {
throw new TimeoutException(SR.GetString(SR.Async_task_timed_out));
}
}
}
}
catch (Exception ex) {
// This catch block is copied from ProcessRequestMain
// Increment all of the appropriate error counters
PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_DURING_REQUEST);
PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_TOTAL);
// If it hasn't been handled, rethrow it
if (!HandleError(ex))
throw;
}
// process everything after the async point
Task postWorkTask = null;
_context.InvokeCancellableCallback(_ => {
postWorkTask = ProcessRequestAsync(includeStagesBeforeAsyncPoint: false, includeStagesAfterAsyncPoint: true);
}, null);
await postWorkTask;
}
finally {
// call Unload events
ProcessRequestCleanup();
}
}
private IAsyncResult LegacyAsyncPageBeginProcessRequest(HttpContext context, AsyncCallback callback, Object extraData) {
SetIntrinsics(context, true /* allowAsync */);
if (_legacyAsyncInfo == null) {
// could be already created if AddOnPreRenderCompleteAsync called before ProcessRequest
_legacyAsyncInfo = new LegacyPageAsyncInfo(this);
}
_legacyAsyncInfo.AsyncResult = new HttpAsyncResult(callback, extraData);
_legacyAsyncInfo.CallerIsBlocking = (callback == null);
// process request stages before async point
try {
_context.InvokeCancellableCallback(new WaitCallback(this.AsyncPageProcessRequestBeforeAsyncPointCancellableCallback), null);
}
catch (Exception e) {
if (_context.SyncContext.PendingOperationsCount == 0) {
// if there are no pending async operations it is ok to throw
throw;
}
// can't throw yet, have to wait for pending async operations to finish
Debug.Trace("Async", "Exception with async pending - saving the error");
_legacyAsyncInfo.SetError(e);
}
// register handler from async manager to run async tasks (if any tasks are registered)
// for blocking callers async tasks were already run
if (_legacyAsyncTaskManager != null && !_legacyAsyncInfo.CallerIsBlocking) {
_legacyAsyncTaskManager.RegisterHandlersForPagePreRenderCompleteAsync();
}
// mark async point
_legacyAsyncInfo.AsyncPointReached = true;
// disable async operations after this point
_context.SyncContext.Disable();
// call into async subscribers
_legacyAsyncInfo.CallHandlers(true /*onPageThread*/);
return _legacyAsyncInfo.AsyncResult;
}
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
protected void AsyncPageEndProcessRequest(IAsyncResult result) {
// This method just dispatches to either the TAP or APM implementation, depending on the synchronization mode
if (SynchronizationContextUtil.CurrentMode == SynchronizationContextMode.Legacy) {
LegacyAsyncPageEndProcessRequest(result);
}
else {
// EndTask() observes and throws any captured exceptions; also waits for asynchronous completion
TaskAsyncHelper.EndTask(result);
}
}
private void LegacyAsyncPageEndProcessRequest(IAsyncResult result) {
if (_legacyAsyncInfo == null)
return;
Debug.Assert(_legacyAsyncInfo.AsyncResult == result);
// End() observes and throws any captured exceptions
_legacyAsyncInfo.AsyncResult.End();
}
public void AddOnPreRenderCompleteAsync(BeginEventHandler beginHandler, EndEventHandler endHandler) {
AddOnPreRenderCompleteAsync(beginHandler, endHandler, null);
}
public void AddOnPreRenderCompleteAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, Object state) {
if (beginHandler == null) {
throw new ArgumentNullException("beginHandler");
}
if (endHandler == null) {
throw new ArgumentNullException("endHandler");
}
if (SynchronizationContextUtil.CurrentMode == SynchronizationContextMode.Normal) {
// If using the new synchronization patterns, go against the task manager directly
RegisterAsyncTask(new PageAsyncTask(beginHandler, endHandler, null, state));
return;
}
if (_legacyAsyncInfo == null) {
if (this is IHttpAsyncHandler) {
// could be called from ctor before process request
_legacyAsyncInfo = new LegacyPageAsyncInfo(this);
}
else {
// synchronous pages don't support add async handler
throw new InvalidOperationException(SR.GetString(SR.Async_required));
}
}
if (_legacyAsyncInfo.AsyncPointReached) {
throw new InvalidOperationException(SR.GetString(SR.Async_addhandler_too_late));
}
_legacyAsyncInfo.AddHandler(beginHandler, endHandler, state);
}
/// <devdoc>
/// <para>Instructs any validation controls included on the page to validate their
/// assigned information for the incoming page request.</para>
/// </devdoc>
public virtual void Validate() {
_validated = true;
if (_validators != null) {
for (int i = 0; i < Validators.Count; i++) {
Validators[i].Validate();
}
}
}
public virtual void Validate(string validationGroup) {
_validated = true;
if (_validators != null) {
ValidatorCollection validators = GetValidators(validationGroup);
// VSWhidbey 207823: When ValidationGroup is the default empty string,
// we should call the V1 method which could have been overridden so
// the overridden method on user page wouldn't be missed.
if (String.IsNullOrEmpty(validationGroup) &&
_validators.Count == validators.Count) {
Validate();
}
else {
for (int i = 0; i < validators.Count; i++) {
validators[i].Validate();
}
}
}
}
public ValidatorCollection GetValidators(string validationGroup) {
if (validationGroup == null) {
validationGroup = String.Empty;
}
ValidatorCollection validators = new ValidatorCollection();
if (_validators != null) {
for (int i = 0; i < Validators.Count; i++) {
BaseValidator baseValidator = Validators[i] as BaseValidator;
if (baseValidator != null) {
if (0 == String.Compare(baseValidator.ValidationGroup, validationGroup,
StringComparison.Ordinal)) {
validators.Add(baseValidator);
}
}
else if (validationGroup.Length == 0) {
validators.Add(Validators[i]);
}
}
}
return validators;
}
/// <devdoc>
/// <para>Throws an exception if it is runtime and we are not currently rendering the form runat=server tag.
/// Most controls that post back or that use client script require to be in this tag to function, so
/// they can call this during rendering. At design time this will do nothing.</para>
/// <para>Custom Control creators should call this during render if they render any sort of input tag, if they call
/// GetPostBackEventReference, or if they emit client script. A composite control does not need to make this
/// call.</para>
/// <para>This method should not be overridden unless creating an alternative page framework.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public virtual void VerifyRenderingInServerForm(Control control) {
// We only want to make this check if we are definitely at runtime
if (Context == null || DesignMode) {
return;
}
if (control == null) {
throw new ArgumentNullException("control");
}
if (!_inOnFormRender && !IsCallback) {
throw new HttpException(SR.GetString(SR.ControlRenderedOutsideServerForm, control.ClientID, control.GetType().Name));
}
}
public PageAdapter PageAdapter {
get {
if(_pageAdapter == null) {
ResolveAdapter();
_pageAdapter = (PageAdapter)AdapterInternal;
}
return _pageAdapter;
}
}
//
private String _relativeFilePath;
internal String RelativeFilePath {
get {
if (_relativeFilePath == null) {
String s = Context.Request.CurrentExecutionFilePath;
String filePath = Context.Request.FilePath;
if(filePath.Equals(s)) {
int slash = s.LastIndexOf('/');
if (slash >= 0) {
s = s.Substring(slash+1);
}
_relativeFilePath = s;
}
else {
_relativeFilePath = Server.UrlDecode(UrlPath.MakeRelative(filePath, s));
}
}
return _relativeFilePath;
}
}
private bool _designModeChecked = false;
private bool _designMode = false;
internal bool GetDesignModeInternal() {
if(!_designModeChecked) {
_designMode = (Site != null) ? Site.DesignMode : false;
_designModeChecked = true;
}
return _designMode;
}
// For use by controls to store information with same lifetime as the request, for example, all radio buttons can
// use this to store the dictionary of radio button groups. The key should be a type. For the example, the value associated with
// the key System.Web.UI.WebControls.WmlRadioButtonAdapter is a NameValueCollection of RadioButtonGroups.
private IDictionary _items;
[
Browsable(false)
]
public IDictionary Items {
get {
if (_items == null) {
_items = new HybridDictionary();
}
return _items;
}
}
// Simplified data binding context stack
private Stack _dataBindingContext;
/// <devdoc>
/// Creates a new context for databinding by pushing a new data item onto the databinding context stack.
/// </devdoc>
internal void PushDataBindingContext(object dataItem) {
if (_dataBindingContext == null) {
_dataBindingContext = new Stack();
}
_dataBindingContext.Push(dataItem);
}
/// <devdoc>
/// Exits a databinding context by removing the current data item from the databinding context stack.
/// </devdoc>
internal void PopDataBindingContext() {
Debug.Assert(_dataBindingContext != null);
Debug.Assert(_dataBindingContext.Count > 0);
_dataBindingContext.Pop();
}
/// <devdoc>
/// Gets the current data item from the top of the databinding context stack.
/// </devdoc>
public object GetDataItem() {
if ((_dataBindingContext == null) || (_dataBindingContext.Count == 0)) {
throw new InvalidOperationException(SR.GetString(SR.Page_MissingDataBindingContext));
}
return _dataBindingContext.Peek();
}
internal static bool IsSystemPostField(string field) {
return s_systemPostFields.Contains(field);
}
internal IScriptManager ScriptManager {
get {
return (IScriptManager)Items[typeof(IScriptManager)];
}
}
private void ValidateRawUrlIfRequired() {
// Only validate the RawUrl if we weren't asked to skip validation and the current validation mode says we should validate.
bool validationRequired = !SkipFormActionValidation && CalculateEffectiveValidateRequest();
if (validationRequired) {
// Simply touching the RawUrl property getter is sufficient to perform validation.
string unused = _request.RawUrl;
}
}
// Needed to support Validators in AJAX 1.0 (Windows OS Bugs 2015831)
#region Atlas ScriptManager Partial Rendering support
internal bool IsPartialRenderingSupported {
get {
if (!_pageFlags[isPartialRenderingSupportedSet]) {
Type scriptManagerType = ScriptManagerType;
if (scriptManagerType != null) {
object scriptManager = Page.Items[scriptManagerType];
if (scriptManager != null) {
PropertyInfo supportsPartialRenderingProperty = scriptManagerType.GetProperty("SupportsPartialRendering");
if (supportsPartialRenderingProperty != null) {
object supportsPartialRenderingValue = supportsPartialRenderingProperty.GetValue(scriptManager, null);
_pageFlags[isPartialRenderingSupported] = (bool)supportsPartialRenderingValue;
}
}
}
_pageFlags[isPartialRenderingSupportedSet] = true;
}
return _pageFlags[isPartialRenderingSupported];
}
}
internal Type ScriptManagerType {
get {
if (_scriptManagerType == null) {
_scriptManagerType = BuildManager.GetType("System.Web.UI.ScriptManager", false);
}
return _scriptManagerType;
}
set {
// Meant for unit testing
_scriptManagerType = value;
}
}
#endregion
#if DBG
// Temporary debugging method
/// <internalonly/>
/// <devdoc>
/// </devdoc>
public virtual void WalkViewState(object viewState, Control control, int indentLevel) {
if (viewState == null) {
return;
}
object [] viewStateArray = (object [])viewState;
object controlViewState = viewStateArray[0];
IDictionary childViewState = (IDictionary)viewStateArray[1];
string prefix = "";
for (int i=0; i < indentLevel; i++) {
prefix = prefix + " ";
}
if (controlViewState == null) {
System.Web.Util.Debug.Trace("tpeters", prefix + "ObjViewState: null");
}
else {
System.Web.Util.Debug.Trace("tpeters", prefix + "ObjViewState: " + controlViewState.ToString());
}
if (childViewState != null) {
for (IDictionaryEnumerator e = childViewState.GetEnumerator(); e.MoveNext();) {
int index = (int) e.Key;
object value = e.Value;
if (control == null) {
System.Web.Util.Debug.Trace("tpeters", prefix + "Control index: " + index.ToString());
WalkViewState(value, null, indentLevel + 1);
}
else {
string s = "None";
bool recurse = false;
if (control.HasControls()) {
if (index < control.Controls.Count) {
s = control.Controls[index].ToString();
recurse = true;
}
else {
s = "out of range";
}
}
System.Web.Util.Debug.Trace("tpeters", prefix + "Control index: " + index.ToString() + " control: " + s);
if (recurse) {
WalkViewState(value, control.Controls[index], indentLevel + 1);
}
}
}
}
}
#endif // DBG
}
// Used to define the list of valid values of the location attribute of the
// OutputCache directive.
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public enum OutputCacheLocation {
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
Any,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
Client,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
Downstream,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
Server,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
None,
ServerAndClient
}
internal enum SmartNavigationSupport {
NotDesiredOrSupported=0, // The Page does not ask for SmartNav, or the browser doesn't support it
Desired, // The Page asks for SmartNavigation, but we have not checked browser support
IE6OrNewer // SmartNavigation supported by IE6 or newer browsers
}
}
|