File size: 335,128 Bytes
08c8a6d | 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 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 | .NET Framework
Notes for Professionals
.NET
Framework
Notes for Professionals
100+ pages
of professional hints and tricks
GoalKicker.com
Free Programming Books
Disclaimer
This is an unocial free book created for educational purposes and is
not aliated with ocial .NET Framework group(s) or company(s).
All trademarks and registered trademarks are
the property of their respective owners
Contents
About
...................................................................................................................................................................................
1
Chapter 1: Getting started with .NET Framework
........................................................................................
2
Section 1.1: Hello World in C#
Section 1.2: Hello World in F#
Section 1.3: Hello World in Visual Basic .NET
Section 1.4: Hello World in C++/CLI
Section 1.5: Hello World in IL
Section 1.6: Hello World in PowerShell
Section 1.7: Hello World in Nemerle
Section 1.8: Hello World in Python (IronPython)
Section 1.9: Hello World in Oxygene
Section 1.10: Hello World in Boo
........................................................................................................................................
.......................................................................................................................................
..............................................................................................................
..............................................................................................................................
.........................................................................................................................................
.........................................................................................................................
.............................................................................................................................
.........................................................................................................
4
............................................................................................................................
...................................................................................................................................
Chapter 2: Strings
.........................................................................................................................................................
5
Section 2.1: Count characters
Section 2.2: Count distinct characters
Section 2.3: Convert string to/from another encoding
Section 2.4: Comparing strings
Section 2.5: Count occurrences of a character
Section 2.6: Split string into fixed length blocks
Section 2.7: Object.ToString() virtual method
Section 2.8: Immutability of strings
.......................................................................................................................................
.........................................................................................................................
....................................................................................................................................
.............................................................................................
5
..........................................................................................................
.........................................................................................................
............................................................................................................
.............................................................................................................................
Chapter 3: DateTime parsing
.................................................................................................................................
9
Section 3.1: ParseExact
Section 3.2: TryParse
Section 3.3: TryParseExact
..................................................................................................................................................
9
..................................................................................................................................................
10
.........................................................................................................................................
12
Chapter 4: Dictionaries
............................................................................................................................................
13
..............................................................................
...........................................................................................................................
Section 4.1: Initializing a Dictionary with a Collection Initializer
Section 4.2: Adding to a Dictionary
Section 4.3: Getting a value from a dictionary
Section 4.4: Make a Dictionary<string, T> with Case-Insensivitve keys
Section 4.5: IEnumerable to Dictionary (≥ .NET 3.5)
Section 4.6: Enumerating a Dictionary
Section 4.7: ConcurrentDictionary<TKey, TValue> (from .NET 4.0)
Section 4.8: Dictionary to List
Section 4.9: Removing from a Dictionary
Section 4.10: ContainsKey(TKey)
Section 4.11: ConcurrentDictionary augmented with Lazy'1 reduces duplicated computation
.........................................................................................................
.................................................................
................................................................................................
.................................................................................................................
...............................................................................................................................
.....................................................................................................................................
......................................................................................................................
......................................................................
...........................
17
Chapter 5: Collections
..............................................................................................................................................
19
........................................................................................................................................................
......................................................................................................................
Section 5.1: Using collection initializers
Section 5.2: Stack
Section 5.3: Creating an initialized List with Custom Types
Section 5.4: Queue
.......................................................................................................................................................
22
....................................................................................
20
Chapter 6: ReadOnlyCollections
.........................................................................................................................
24
Section 6.1: Creating a ReadOnlyCollection
Section 6.2: Updating a ReadOnlyCollection
Section 6.3: Warning: Elements in a ReadOnlyCollection are not inherently read-only
..............................................................................................................
...........................................................................................................
......................................
24
2
3
3
3
3
4
4
4
4
5
5
6
6
6
7
8
13
13
13
14
14
14
15
16
16
17
19
19
24
24
Chapter 7: Stack and Heap
Section 7.1: Value types in use
Section 7.2: Reference types in use
...................................................................................................................................
...................................................................................................................................
...........................................................................................................................
26
Chapter 8: LINQ
...........................................................................................................................................................
28
Section 8.1: SelectMany (flat map)
Section 8.2: Where (filter)
Section 8.3: Any
Section 8.4: GroupJoin
Section 8.5: Except
Section 8.6: Zip
Section 8.7: Aggregate (fold)
Section 8.8: ToLookup
Section 8.9: Intersect
Section 8.10: Concat
Section 8.11: All
Section 8.12: Sum
Section 8.13: SequenceEqual
Section 8.14: Min
Section 8.15: Distinct
Section 8.16: Count
Section 8.17: Cast
Section 8.18: Range
Section 8.19: ThenBy
Section 8.20: Repeat
Section 8.21: Empty
Section 8.22: Select (map)
Section 8.23: OrderBy
Section 8.24: OrderByDescending
Section 8.25: Contains
Section 8.26: First (find)
Section 8.27: Single
Section 8.28: Last
Section 8.29: LastOrDefault
Section 8.30: SingleOrDefault
Section 8.31: FirstOrDefault
Section 8.32: Skip
Section 8.33: Take
Section 8.34: Reverse
Section 8.35: OfType
Section 8.36: Max
Section 8.37: Average
Section 8.38: GroupBy
Section 8.39: ToDictionary
Section 8.40: Union
Section 8.41: ToArray
Section 8.42: ToList
Section 8.43: ElementAt
Section 8.44: ElementAtOrDefault
Section 8.45: SkipWhile
Section 8.46: TakeWhile
............................................................................................................................
28
...........................................................................................................................................
...........................................................................................................................................................
................................................................................................................................................
......................................................................................................................................................
............................................................................................................................................................
.....................................................................................................................................
................................................................................................................................................
...................................................................................................................................................
....................................................................................................................................................
.............................................................................................................................................................
.........................................................................................................................................................
......................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................
......................................................................................................................................................
.........................................................................................................................................................
.....................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.....................................................................................................................................................
..........................................................................................................................................
.................................................................................................................................................
.............................................................................................................................
.................................................................................................................................................
..............................................................................................................................................
.....................................................................................................................................................
........................................................................................................................................................
.......................................................................................................................................
....................................................................................................................................
........................................................................................................................................
.........................................................................................................................................................
.......................................................................................................................................................
..................................................................................................................................................
...................................................................................................................................................
.........................................................................................................................................................
.................................................................................................................................................
.................................................................................................................................................
..........................................................................................................................................
......................................................................................................................................................
..................................................................................................................................................
.....................................................................................................................................................
..............................................................................................................................................
.............................................................................................................................
...............................................................................................................................................
..............................................................................................................................................
26
26
29
29
30
31
31
31
32
32
32
32
33
33
33
34
34
34
34
35
35
35
35
36
36
36
36
37
37
37
38
38
38
39
39
39
39
39
40
40
41
42
42
42
42
42
43
Section 8.47: DefaultIfEmpty
Section 8.48: Join
Section 8.49: Left Outer Join
......................................................................................................................................
43
........................................................................................................................................................
43
......................................................................................................................................
44
Chapter 9: ForEach
....................................................................................................................................................
46
Section 9.1: Extension method for IEnumerable
Section 9.2: Calling a method on an object in a list
.......................................................................................................
46
.................................................................................................
46
Chapter 10: Reflection
..............................................................................................................................................
47
...........................................................................................................................
Section 10.1: What is an Assembly?
Section 10.2: Compare two objects with reflection
Section 10.3: Creating Object and setting properties using reflection
Section 10.4: How to create an object of T using Reflection
Section 10.5: Getting an attribute of an enum with reflection (and caching it)
...................................................................
..................................................................................
....................................................
48
..................................................................................................
Chapter 11: Expression Trees
.................................................................................................................................
50
Section 11.1: building a predicate of form field == value
Section 11.2: Simple Expression Tree Generated by the C# Compiler
Section 11.3: Expression for retrieving a static field
Section 11.4: InvocationExpression Class
..........................................................................................
50
....................................................................
50
..................................................................................................
...................................................................................................................
Chapter 12: Custom Types
Section 12.1: Struct Definition
Section 12.2: Class Definition
Chapter 13: Code Contracts
......................................................................................................................................
......................................................................................................................................
......................................................................................................................................
Section 13.1: Contracts for Interfaces
Section 13.2: Installing and Enabling Code Contracts
Section 13.3: Preconditions
Section 13.4: Postconditions
...................................................................................................................................
56
........................................................................................................................
56
..............................................................................................
56
.........................................................................................................................................
........................................................................................................................................
Chapter 14: Settings
..................................................................................................................................................
60
Section 14.1: AppSettings from ConfigurationSettings in .NET 1.x
Section 14.2: Reading AppSettings from ConfigurationManager in .NET 2.0 and later
Section 14.3: Introduction to strongly-typed application and user settings support from Visual Studio
...........................................................................
.......................................
60
60
................................................................................................................................................................................
61
Section 14.4: Reading strongly-typed settings from custom section of configuration file
.................................
62
Chapter 15: Regular Expressions (System.Text.RegularExpressions)
..............................................
65
............................................................................................................
65
Section 15.1: Check if pattern matches input
Section 15.2: Remove non alphanumeric characters from string
Section 15.3: Passing Options
Section 15.4: Match into groups
Section 15.5: Find all matches
Section 15.6: Simple match and replace
.....................................................................................................................................
.................................................................................................................................
....................................................................................................................................
...................................................................................................................
..........................................................................
65
Chapter 16: File Input/Output
Section 16.1: C# File.Exists()
Section 16.2: VB WriteAllText
Section 16.3: VB StreamWriter
Section 16.4: C# StreamWriter
Section 16.5: C# WriteAllText()
...............................................................................................................................
67
.........................................................................................................................................
......................................................................................................................................
....................................................................................................................................
...................................................................................................................................
...................................................................................................................................
Chapter 17: System.IO
..............................................................................................................................................
69
Section 17.1: Reading a text file using StreamReader
Section 17.2: Serial Ports using System.IO.SerialPorts
Section 17.3: Reading/Writing Data Using System.IO.File
..............................................................................................
.............................................................................................
.......................................................................................
70
Chapter 18: System.IO.File class
..........................................................................................................................
72
47
47
48
48
51
51
54
54
54
58
59
65
65
65
66
67
67
67
67
68
69
69
Section 18.1: Delete a file
Section 18.2: Strip unwanted lines from a text file
Section 18.3: Convert text file encoding
Section 18.4: Enumerate files older than a specified amount
Section 18.5: Move a File from one location to another
.............................................................................................................................................
...................................................................................................
....................................................................................................................
72
73
73
.................................................................................
74
..........................................................................................
74
Chapter 19: Reading and writing Zip files
......................................................................................................
76
Section 19.1: Listing ZIP contents
Section 19.2: Extracting files from ZIP files
Section 19.3: Updating a ZIP file
................................................................................................................................
76
...............................................................................................................
76
.................................................................................................................................
76
Chapter 20: Managed Extensibility Framework
..........................................................................................
78
Section 20.1: Connecting (Basic)
Section 20.2: Exporting a Type (Basic)
Section 20.3: Importing (Basic)
................................................................................................................................
78
.....................................................................................................................
78
..................................................................................................................................
79
Chapter 21: SpeechRecognitionEngine class to recognize speech
....................................................
80
Section 21.1: Asynchronously recognizing speech based on a restricted set of phrases
Section 21.2: Asynchronously recognizing speech for free text dictation
.............................................................
80
....................................
80
Chapter 22: System.Runtime.Caching.MemoryCache (ObjectCache)
..............................................
81
Section 22.1: Adding Item to Cache (Set)
Section 22.2: System.Runtime.Caching.MemoryCache (ObjectCache)
..................................................................................................................
81
.................................................................
81
Chapter 23: System.Reflection.Emit namespace
.......................................................................................
83
Section 23.1: Creating an assembly dynamically
.....................................................................................................
83
Chapter 24: .NET Core
.............................................................................................................................................
86
Section 24.1: Basic Console App
.................................................................................................................................
86
Chapter 25: ADO.NET
................................................................................................................................................
87
Section 25.1: Best Practices - Executing Sql Statements
Section 25.2: Executing SQL statements as a command
Section 25.3: Using common interfaces to abstract away vendor specific classes
.........................................................................................
.......................................................................................
............................................
89
Chapter 26: Dependency Injection
.....................................................................................................................
90
Section 26.1: How Dependency Injection Makes Unit Testing Easier
Section 26.2: Dependency Injection - Simple example
Section 26.3: Why We Use Dependency Injection Containers (IoC Containers)
.....................................................................
...........................................................................................
..................................................
91
Chapter 27: Platform Invoke
Section 27.1: Marshaling structs
Section 27.2: Marshaling unions
Section 27.3: Calling a Win32 dll function
Section 27.4: Using Windows API
Section 27.5: Marshalling arrays
................................................................................................................................
.................................................................................................................................
................................................................................................................................
.................................................................................................................
96
...............................................................................................................................
................................................................................................................................
Chapter 28: NuGet packaging system
.............................................................................................................
98
Section 28.1: Uninstalling a package from one project in a solution
Section 28.2: Installing a specific version of a package
Section 28.3: Adding a package source feed (MyGet, Klondike, ect)
Section 28.4: Installing the NuGet Package Manager
Section 28.5: Managing Packages through the UI
Section 28.6: Managing Packages through the console
Section 28.7: Updating a package
Section 28.8: Uninstalling a package
Section 28.9: Uninstall a specific version of package
.....................................................................
.........................................................................................
....................................................................
98
.............................................................................................
..................................................................................................
.........................................................................................
............................................................................................................................
......................................................................................................................
...........................................................................................
87
88
90
90
94
94
95
97
97
98
98
98
99
99
99
100
100
Chapter 29: Globalization in ASP.NET MVC using Smart internationalization for ASP.NET
............................................................................................................................................................................................
101
Section 29.1: Basic configuration and setup
...........................................................................................................
101
Chapter 30: System.Net.Mail
Section 30.1: MailMessage
Section 30.2: Mail with Attachment
..............................................................................................................................
........................................................................................................................................
.........................................................................................................................
104
Chapter 31: Using Progress<T> and IProgress<T>
...................................................................................
105
Section 31.1: Simple Progress reporting
Section 31.2: Using IProgress<T>
Chapter 32: JSON Serialization
..................................................................................................................
105
.............................................................................................................................
.........................................................................................................................
Section 32.1: Deserialization using System.Web.Script.Serialization.JavaScriptSerializer
Section 32.2: Serialization using Json.NET
Section 32.3: Serialization-Deserialization using Newtonsoft.Json
Section 32.4: Deserialization using Json.NET
Section 32.5: Dynamic binding
Section 32.6: Serialization using Json.NET with JsonSerializerSettings
.........................................................................................................
......................................................................
................................................................................................................................
.............................................................................................................
..............................................................
.................................
107
Chapter 33: JSON in .NET with Newtonsoft.Json
Section 33.1: Deserialize an object from JSON text
Section 33.2: Serialize object into JSON
...............................................................................................
.................................................................................................................
.....................................................................................
110
Chapter 34: XmlSerializer
....................................................................................................................................
111
....................................................................................................................................
Section 34.1: Formatting: Custom DateTime format
Section 34.2: Serialize object
Section 34.3: Deserialize object
Section 34.4: Behaviour: Map array name to property (XmlArray)
Section 34.5: Behaviour: Map Element name to Property
Section 34.6: Eciently building multiple serializers with derived types specified dynamically
....................................................................
....................................................................................
...............................................................................................................................
.............................................................................................
......................
112
Chapter 35: VB Forms
............................................................................................................................................
115
Section 35.1: Hello World in VB.NET Forms
Section 35.2: For Beginners
Section 35.3: Forms Timer
Chapter 36: JIT compiler
......................................................................................................................................
........................................................................................................................................
.......................................................................................................................................
.............................................................................................................
115
Section 36.1: IL compilation sample
.........................................................................................................................
118
Chapter 37: CLR
.........................................................................................................................................................
121
Section 37.1: An introduction to Common Language Runtime
.............................................................................
121
Chapter 38: TPL Dataflow
....................................................................................................................................
122
Section 38.1: Asynchronous Producer Consumer With A Bounded BuerBlock
Section 38.2: Posting to an ActionBlock and waiting for completion
Section 38.3: Linking blocks to create a pipeline
Section 38.4: Synchronous Producer/Consumer with BuerBlock<T>
...................................................................................................
...............................................................
................................................
122
..................................................................
Chapter 39: Threading
...........................................................................................................................................
125
Section 39.1: Accessing form controls from other threads
Chapter 40: Process and Thread anity setting
...................................................................................
125
....................................................................................
Section 40.1: Get process anity mask
Section 40.2: Set process anity mask
..................................................................................................................
..................................................................................................................
127
Chapter 41: Parallel processing using .Net framework
........................................................................
129
Section 41.1: Parallel Extensions
...............................................................................................................................
129
Chapter 42: Task Parallel Library (TPL)
.......................................................................................................
130
Section 42.1: Basic producer-consumer loop (BlockingCollection)
Section 42.2: Parallel.Invoke
Section 42.3: Task: Returning a value
.....................................................................................................................................
.....................................................................................................................
......................................................................
130
103
103
105
107
107
108
108
108
109
110
110
111
111
111
111
112
115
115
118
122
122
123
127
127
130
131
..................................................................................................................................
..........................................................................................................................................
.......................................................................................................................................
....................................................................................................
....................................................................................
................................................................................................................
..............................................................................................
....................................................................................................................................
Section 42.4: Parallel.ForEach
Section 42.5: Parallel.For
Section 42.6: Task: basic instantiation and Wait
Section 42.7: Task.WhenAll
Section 42.8: Flowing execution context with AsyncLocal
Section 42.9: Parallel.ForEach in VB.NET
Section 42.10: Task: WaitAll and variable capturing
Section 42.11: Task: WaitAny
Section 42.12: Task: handling exceptions (using Wait)
Section 42.13: Task: handling exceptions (without using Wait)
Section 42.14: Task: cancelling using CancellationToken
Section 42.15: Task.WhenAny
..........................................................................................
............................................................................
134
.....................................................................................
...................................................................................................................................
Chapter 43: Task Parallel Library (TPL) API Overviews
.......................................................................
137
Section 43.1: Perform work in response to a button click and update the UI
.....................................................
137
Chapter 44: Synchronization Contexts
.........................................................................................................
138
Section 44.1: Execute code on the UI thread after performing background work
.............................................
138
Chapter 45: Memory management
................................................................................................................
139
Section 45.1: Use SafeHandle when wrapping unmanaged resources
Section 45.2: Unmanaged Resources
Chapter 46: Garbage Collection
.....................................................................................................................
.......................................................................................................................
...............................................................
139
Section 46.1: A basic example of (garbage) collection
Section 46.2: Live objects and dead objects - the basics
Section 46.3: Multiple dead objects
Section 46.4: Weak References
Section 46.5: Dispose() vs. finalizers
Section 46.6: Proper disposal and finalization of objects
.........................................................................................................................
...............................................................................................................................
.......................................................................................................................
.....................................................................................
144
.........................................................................................
.....................................................................................
141
Chapter 47: Exceptions
.........................................................................................................................................
146
...................................................................................
...........................................................................................................................
..................................................................................................................................
Section 47.1: Catching and rethrowing caught exceptions
Section 47.2: Using a finally block
Section 47.3: Exception Filters
Section 47.4: Rethrowing an exception within a catch block
Section 47.5: Throwing an exception from a dierent method while preserving its information
Section 47.6: Catching an exception
Chapter 48: System.Diagnostics
Section 48.1: Run shell commands
Section 48.2: Send Command to CMD and Receive Output
Section 48.3: Stopwatch
...........................................................................................................................................
..........................................................................................................................
.......................................................................................................................
......................................................................................................................
.................................................................................
................................................................................
....................
148
Chapter 49: Encryption / Cryptography
.....................................................................................................
153
Section 49.1: Encryption and Decryption using Cryptography (AES)
Section 49.2: RijndaelManaged
Section 49.3: Encrypt and decrypt data using AES (in C#)
Section 49.4: Create a Key from a Password / Random SALT (in C#)
...............................................................................................................................
..................................................................
..................................................................................
...............................................................
158
Chapter 50: Work with SHA1 in C#
...................................................................................................................
161
Section 50.1: #Generate SHA1 checksum of a file
Section 50.2: #Generate hash of a text
..................................................................................................
161
..................................................................................................................
161
Chapter 51: Unit testing
.........................................................................................................................................
162
Section 51.1: Adding MSTest unit testing project to an existing solution
Section 51.2: Creating a sample test method
.........................................................................................................
162
.............................................................
162
Chapter 52: Write to and read from StdErr stream
...............................................................................
163
131
131
132
132
132
133
133
134
134
135
136
139
141
141
142
142
143
146
147
147
148
149
150
150
150
152
153
154
155
Section 52.1: Write to standard error output using Console
Section 52.2: Read from standard error of child process
Chapter 53: Upload file and POST data to webserver
.................................................................................
....................................................................................
163
163
..........................................................................
164
Section 53.1: Upload file with WebRequest
.............................................................................................................
164
Chapter 54: Networking
.......................................................................................................................................
166
Section 54.1: Basic TCP chat (TcpListener, TcpClient, NetworkStream)
Section 54.2: Basic SNTP client (UdpClient)
...........................................................................................................
167
..............................................................
166
Chapter 55: HTTP servers
....................................................................................................................................
169
Section 55.1: Basic read-only HTTP file server (ASP.NET Core)
Section 55.2: Basic read-only HTTP file server (HttpListener)
...........................................................................
169
.............................................................................
170
Chapter 56: HTTP clients
......................................................................................................................................
173
Section 56.1: Reading GET response as string using System.Net.HttpClient
Section 56.2: Basic HTTP downloader using System.Net.Http.HttpClient
Section 56.3: Reading GET response as string using System.Net.HttpWebRequest
Section 56.4: Reading GET response as string using System.Net.WebClient
Section 56.5: Sending a POST request with a string payload using System.Net.HttpWebRequest
Section 56.6: Sending a POST request with a string payload using System.Net.WebClient
Section 56.7: Sending a POST request with a string payload using System.Net.HttpClient
.......................................................
...........................................................
.........................................
.....................................................
.............................
..............................
.................
174
Chapter 57: Serial Ports
........................................................................................................................................
176
Section 57.1: Basic operation
Section 57.2: List available port names
Section 57.3: Asynchronous read
Section 57.4: Synchronous text echo service
Section 57.5: Asynchronous message receiver
....................................................................................................................................
..................................................................................................................
............................................................................................................................
.........................................................................................................
......................................................................................................
177
Appendix A: Acronym Glossary
Section A.1: .Net Related Acronyms
.........................................................................................................................
180
........................................................................................................................
180
Credits
............................................................................................................................................................................
181
You may also like
......................................................................................................................................................
184
173
173
174
174
175
175
176
176
176
176
About
Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
https://goalkicker.com/DotNETFrameworkBook
This .NET Framework Notes for Professionals book is compiled from Stack Overflow
Documentation, the content is written by the beautiful people at Stack Overflow.
Text content is released under Creative Commons BY-SA, see credits at the end
of this book whom contributed to the various chapters. Images may be copyright
of their respective owners unless otherwise specified
This is an unofficial free book created for educational purposes and is not
affiliated with official .NET Framework group(s) or company(s) nor Stack
Overflow. All trademarks and registered trademarks are the property of their
respective company owners
The information presented in this book is not guaranteed to be correct nor
accurate, use at your own risk
Please send feedback and corrections to web@petercv.com
GoalKicker.com – .NET Framework Notes for Professionals
1
Chapter 1: Getting started with .NET
Framework
.NET
Version Release Date
1.0
2002-02-13
1.1
2.0
3.0
3.5
2003-04-24
2005-11-07
2006-11-06
2007-11-19
3.5 SP1 2008-08-11
4.0
4.5
4.5.1
4.5.2
4.6
4.6.1
4.6.2
4.7
2010-04-12
2012-08-15
2013-10-17
2014-05-05
2015-07-20
2015-11-17
2016-08-02
2017-04-05
4.7.1
2017-10-17
Compact Framework
Version Release Date
1.0
2000-01-01
2.0
3.5
3.7
3.9
2005-10-01
2007-11-19
2009-01-01
2013-06-01
Micro Framework
Version Release Date
4.2
2011-10-04
4.3
4.4
2012-12-04
2015-10-20
Section 1.1: Hello World in C#
using System;
class Program
{
// The Main() function is the first function to be executed in a program
static void Main()
{
// Write the string "Hello World to the standard out
Console.WriteLine("Hello World");
}
}
Console.WriteLine has several overloads. In this case, the string "Hello World" is the parameter, and it will output
the "Hello World" to the standard out stream during execution. Other overloads may call the .ToString of the
GoalKicker.com – .NET Framework Notes for Professionals
2
argument before writing to the stream. See the .NET Framework Documentation for more information.
Live Demo in Action at .NET Fiddle
Introduction to C#
Section 1.2: Hello World in F#
open System
[<EntryPoint>]
let main argv =
printfn "Hello World"
0
Live Demo in Action at .NET Fiddle
Introduction to F#
Section 1.3: Hello World in Visual Basic .NET
Imports System
Module Program
Public Sub Main()
Console.WriteLine("Hello World")
End Sub
End Module
Live Demo in Action at .NET Fiddle
Introduction to Visual Basic .NET
Section 1.4: Hello World in C++/CLI
using namespace System;
int main(array<String^>^ args)
{
Console::WriteLine("Hello World");
}
Section 1.5: Hello World in IL
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
.method public hidebysig static void Main() cil managed
{
.maxstack 8
IL_0000: nop
IL_0001: ldstr "Hello World"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
}
GoalKicker.com – .NET Framework Notes for Professionals
3
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
}
Section 1.6: Hello World in PowerShell
Write-Host "Hello World"
Introduction to PowerShell
Section 1.7: Hello World in Nemerle
System.Console.WriteLine("Hello World");
Section 1.8: Hello World in Python (IronPython)
print "Hello World"
import clr
from System import Console
Console.WriteLine("Hello World")
Section 1.9: Hello World in Oxygene
namespace HelloWorld;
interface
type
App = class
public
class method Main(args: array of String);
end;
implementation
class method App.Main(args: array of String);
begin
Console.WriteLine('Hello World');
end;
end.
Section 1.10: Hello World in Boo
print "Hello World"
GoalKicker.com – .NET Framework Notes for Professionals
4
Chapter 2: Strings
Section 2.1: Count characters
If you need to count characters then, for the reasons explained in Remarks section, you can't simply use Length
property because it's the length of the array of System.Char which are not characters but code-units (not Unicode
code-points nor graphemes). Correct code is then:
int length = text.EnumerateCharacters().Count();
A small optimization may rewrite EnumerateCharacters() extension method specifically for this purpose:
public static class StringExtensions
{
public static int CountCharacters(this string text)
{
if (String.IsNullOrEmpty(text))
return 0;
int count = 0;
var enumerator = StringInfo.GetTextElementEnumerator(text);
while (enumerator.MoveNext())
++count;
return count;
}
}
Section 2.2: Count distinct characters
If you need to count distinct characters then, for the reasons explained in Remarks section, you can't simply use
Length property because it's the length of the array of System.Char which are not characters but code-units (not
Unicode code-points nor graphemes). If, for example, you simply write text.Distinct().Count() you will get
incorrect results, correct code:
int distinctCharactersCount = text.EnumerateCharacters().Count();
One step further is to count occurrences of each character, if performance aren't an issue you may simply do it
like this (in this example regardless of case):
var frequencies = text.EnumerateCharacters()
.GroupBy(x => x, StringComparer.CurrentCultureIgnoreCase)
.Select(x => new { Character = x.Key, Count = x.Count() };
Section 2.3: Convert string to/from another encoding
.NET strings contain System.Char (UTF-16 code-units). If you want to save (or manage) text with another encoding
you have to work with an array of System.Byte.
Conversions are performed by classes derived from System.Text.Encoder and System.Text.Decoder which,
together, can convert to/from another encoding (from a byte X encoded array byte[] to an UTF-16 encoded
System.String and vice-versa).
Because the encoder/decoder usually works very close to each other they're grouped together in a class derived
GoalKicker.com – .NET Framework Notes for Professionals
5
from System.Text.Encoding, derived classes offer conversions to/from popular encodings (UTF-8, UTF-16 and so
on).
Examples:
Convert a string to UTF-8
byte[] data = Encoding.UTF8.GetBytes("This is my text");
Convert UTF-8 data to a string
var text = Encoding.UTF8.GetString(data);
Change encoding of an existing text file
This code will read content of an UTF-8 encoded text file and save it back encoded as UTF-16. Note that this code is
not optimal if file is big because it will read all its content into memory:
var content = File.ReadAllText(path, Encoding.UTF8);
File.WriteAllText(content, Encoding.UTF16);
Section 2.4: Comparing strings
Despite String is a reference type == operator compares string values rather than references.
As you may know string is just an array of characters. But if you think that strings equality check and comparison
is made character by character, you are mistaken. This operation is culture specific (see Remarks below): some
character sequences can be treated as equal depending on the culture.
Think twice before short circuiting equality check by comparing Length properties of two strings!
Use overloads of String.Equals method which accept additional StringComparison enumeration value, if you
need to change default behavior.
Section 2.5: Count occurrences of a character
Because of the reasons explained in Remarks section you can't simply do this (unless you want to count occurrences
of a specific code-unit):
int count = text.Count(x => x == ch);
You need a more complex function:
public static int CountOccurrencesOf(this string text, string character)
{
return text.EnumerateCharacters()
.Count(x => String.Equals(x, character, StringComparer.CurrentCulture));
}
Note that string comparison (in contrast to character comparison which is culture invariant) must always be
performed according to rules to a specific culture.
Section 2.6: Split string into fixed length blocks
We cannot break a string into arbitrary points (because a System.Char may not be valid alone because it's a
combining character or part of a surrogate) then code must take that into account (note that with length I mean the
GoalKicker.com – .NET Framework Notes for Professionals
6
number of graphemes not the number of code-units):
public static IEnumerable<string> Split(this string value, int desiredLength)
{
var characters = StringInfo.GetTextElementEnumerator(value);
while (characters.MoveNext())
yield return String.Concat(Take(characters, desiredLength));
}
private static IEnumerable<string> Take(TextElementEnumerator enumerator, int count)
{
for (int i = 0; i < count; ++i)
{
yield return (string)enumerator.Current;
if (!enumerator.MoveNext())
yield break;
}
}
Section 2.7: Object.ToString() virtual method
Everything in .NET is an object, hence every type has ToString() method defined in Object class which can be
overridden. Default implementation of this method just returns the name of the type:
public class Foo
{
}
var foo = new Foo();
Console.WriteLine(foo); // outputs Foo
ToString() is implicitly called when concatinating value with a string:
public class Foo
{
public override string ToString()
{
return "I am Foo";
}
}
var foo = new Foo();
Console.WriteLine("I am bar and "+foo);// outputs I am bar and I am Foo
The result of this method is also extensively used by debugging tools. If, for some reason, you do not want to
override this method, but want to customize how debugger shows the value of your type, use DebuggerDisplay
Attribute (MSDN):
// [DebuggerDisplay("Person = FN {FirstName}, LN {LastName}")]
[DebuggerDisplay("Person = FN {"+nameof(Person.FirstName)+"}, LN {"+nameof(Person.LastName)+"}")]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set;}
// ...
}
GoalKicker.com – .NET Framework Notes for Professionals
7
Section 2.8: Immutability of strings
Strings are immutable. You just cannot change existing string. Any operation on the string crates a new instance of
the string having new value. It means that if you need to replace a single character in a very long string, memory will
be allocated for a new value.
string veryLongString = ...
// memory is allocated
string newString = veryLongString.Remove(0,1); // removes first character of the string.
If you need to perform many operations with string value, use StringBuilder class which is designed for efficient
strings manipulation:
var sb = new StringBuilder(someInitialString);
foreach(var str in manyManyStrings)
{
sb.Append(str);
}
var finalString = sb.ToString();
GoalKicker.com – .NET Framework Notes for Professionals
8
Chapter 3: DateTime parsing
Section 3.1: ParseExact
var dateString = "2015-11-24";
var date = DateTime.ParseExact(dateString, "yyyy-MM-dd", null);
Console.WriteLine(date);
11/24/2015 12:00:00 AM
Note that passing CultureInfo.CurrentCulture as the third parameter is identical to passing null. Or, you can
pass a specific culture.
Format Strings
Input string can be in any format that matches the format string
var date = DateTime.ParseExact("24|201511", "dd|yyyyMM", null);
Console.WriteLine(date);
11/24/2015 12:00:00 AM
Any characters that are not format specifiers are treated as literals
var date = DateTime.ParseExact("2015|11|24", "yyyy|MM|dd", null);
Console.WriteLine(date);
11/24/2015 12:00:00 AM
Case matters for format specifiers
var date = DateTime.ParseExact("2015-01-24 11:11:30", "yyyy-mm-dd hh:MM:ss", null);
Console.WriteLine(date);
11/24/2015 11:01:30 AM
Note that the month and minute values were parsed into the wrong destinations.
Single-character format strings must be one of the standard formats
var date = DateTime.ParseExact("11/24/2015", "d", new CultureInfo("en-US"));
var date = DateTime.ParseExact("2015-11-24T10:15:45", "s", null);
var date = DateTime.ParseExact("2015-11-24 10:15:45Z", "u", null);
Exceptions
ArgumentNullException
GoalKicker.com – .NET Framework Notes for Professionals
9
var date = DateTime.ParseExact(null, "yyyy-MM-dd", null);
var date = DateTime.ParseExact("2015-11-24", null, null);
FormatException
var date = DateTime.ParseExact("", "yyyy-MM-dd", null);
var date = DateTime.ParseExact("2015-11-24", "", null);
var date = DateTime.ParseExact("2015-0C-24", "yyyy-MM-dd", null);
var date = DateTime.ParseExact("2015-11-24", "yyyy-QQ-dd", null);
// Single-character format strings must be one of the standard formats
var date = DateTime.ParseExact("2015-11-24", "q", null);
// Format strings must match the input exactly* (see next section)
var date = DateTime.ParseExact("2015-11-24", "d", null); // Expects 11/24/2015 or 24/11/2015 for
most cultures
Handling multiple possible formats
var date = DateTime.ParseExact("2015-11-24T10:15:45",
new [] { "s", "t", "u", "yyyy-MM-dd" }, // Will succeed as long as input matches one of these
CultureInfo.CurrentCulture, DateTimeStyles.None);
Handling culture differences
var dateString = "10/11/2015";
var date = DateTime.ParseExact(dateString, "d", new CultureInfo("en-US"));
Console.WriteLine("Day: {0}; Month: {1}", date.Day, date.Month);
Day: 11; Month: 10
date = DateTime.ParseExact(dateString, "d", new CultureInfo("en-GB"));
Console.WriteLine("Day: {0}; Month: {1}", date.Day, date.Month);
Day: 10; Month: 11
Section 3.2: TryParse
This method accepts a string as input, attempts to parse it into a DateTime, and returns a Boolean result indicating
success or failure. If the call succeeds, the variable passed as the out parameter is populated with the parsed result.
If the parse fails, the variable passed as the out parameter is set to the default value, DateTime.MinValue.
TryParse(string, out DateTime)
DateTime parsedValue;
if (DateTime.TryParse("monkey", out parsedValue))
{
Console.WriteLine("Apparently, 'monkey' is a date/time value. Who knew?");
}
This method attempts to parse the input string based on the system regional settings and known formats such as
GoalKicker.com – .NET Framework Notes for Professionals
10
ISO 8601 and other common formats.
DateTime.TryParse("11/24/2015 14:28:42", out parsedValue); // true
DateTime.TryParse("2015-11-24 14:28:42", out parsedValue); // true
DateTime.TryParse("2015-11-24T14:28:42", out parsedValue); // true
DateTime.TryParse("Sat, 24 Nov 2015 14:28:42", out parsedValue); // true
Since this method does not accept culture info, it uses the system locale. This can lead to unexpected results.
// System set to en-US culture
bool result = DateTime.TryParse("24/11/2015", out parsedValue);
Console.WriteLine(result);
False
// System set to en-GB culture
bool result = DateTime.TryParse("11/24/2015", out parsedValue);
Console.WriteLine(result);
False
// System set to en-GB culture
bool result = DateTime.TryParse("10/11/2015", out parsedValue);
Console.WriteLine(result);
True
Note that if you are in the US, you might be surprised that the parsed result is November 10, not October 11.
TryParse(string, IFormatProvider, DateTimeStyles, out DateTime)
if (DateTime.TryParse(" monkey ", new CultureInfo("en-GB"),
DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite, out parsedValue)
{
Console.WriteLine("Apparently, ' monkey ' is a date/time value. Who knew?");
}
Unlike its sibling method, this overload allows a specific culture and style(s) to be specified. Passing null for the
IFormatProvider parameter uses the system culture.
Exceptions
Note that it is possible for this method to throw an exception under certain conditions. These relate to the
parameters introduced for this overload: IFormatProvider and DateTimeStyles.
NotSupportedException: IFormatProvider specifies a neutral culture
ArgumentException: DateTimeStyles is not a valid option, or contains incompatible flags such as
AssumeLocal and AssumeUniversal.
GoalKicker.com – .NET Framework Notes for Professionals
11
Section 3.3: TryParseExact
This method behaves as a combination of TryParse and ParseExact: It allows custom format(s) to be specified, and
returns a Boolean result indicating success or failure rather than throwing an exception if the parse fails.
TryParseExact(string, string, IFormatProvider, DateTimeStyles, out DateTime)
This overload attempts to parse the input string against a specific format. The input string must match that format
in order to be parsed.
DateTime.TryParseExact("11242015", "MMddyyyy", null, DateTimeStyles.None, out parsedValue); // true
TryParseExact(string, string[], IFormatProvider, DateTimeStyles, out DateTime)
This overload attempts to parse the input string against an array of formats. The input string must match at least
one format in order to be parsed.
DateTime.TryParseExact("11242015", new [] { "yyyy-MM-dd", "MMddyyyy" }, null, DateTimeStyles.None,
out parsedValue); // true
GoalKicker.com – .NET Framework Notes for Professionals
12
Chapter 4: Dictionaries
Section 4.1: Initializing a Dictionary with a Collection Initializer
// Translates to `dict.Add(1, "First")` etc.
var dict = new Dictionary<int, string>()
{
{ 1, "First" },
{ 2, "Second" },
{ 3, "Third" }
};
// Translates to `dict[1] = "First"` etc.
// Works in C# 6.0.
var dict = new Dictionary<int, string>()
{
[1] = "First",
[2] = "Second",
[3] = "Third"
};
Section 4.2: Adding to a Dictionary
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "First");
dict.Add(2, "Second");
// To safely add items (check to ensure item does not already exist - would throw)
if(!dict.ContainsKey(3))
{
dict.Add(3, "Third");
}
Alternatively they can be added/set via the an indexer. (An indexer internally looks like a property, having a get and
set, but takes a parameter of any type which is specified between the brackets) :
Dictionary<int, string> dict = new Dictionary<int, string>();
dict[1] = "First";
dict[2] = "Second";
dict[3] = "Third";
Unlike the Add method which throws an exception, if a key is already contained in the dictionary, the indexer just
replaces the existing value.
For thread-safe dictionary use ConcurrentDictionary<TKey, TValue>:
var dict = new ConcurrentDictionary<int, string>();
dict.AddOrUpdate(1, "First", (oldKey, oldValue) => "First");
Section 4.3: Getting a value from a dictionary
Given this setup code:
var dict = new Dictionary<int, string>()
{
{ 1, "First" },
GoalKicker.com – .NET Framework Notes for Professionals
13
{ 2, "Second" },
{ 3, "Third" }
};
You may want to read the value for the entry with key 1. If key doesn't exist getting a value will throw
KeyNotFoundException, so you may want to first check for that with ContainsKey:
if (dict.ContainsKey(1))
Console.WriteLine(dict[1]);
This has one disadvantage: you will search through your dictionary twice (once to check for existence and one to
read the value). For a large dictionary this can impact performance. Fortunately both operations can be performed
together:
string value;
if (dict.TryGetValue(1, out value))
Console.WriteLine(value);
Section 4.4: Make a Dictionary<string, T> with Case-
Insensivitve keys
var MyDict = new Dictionary<string,T>(StringComparison.InvariantCultureIgnoreCase)
Section 4.5: IEnumerable to Dictionary (≥ .NET 3.5)
Create a Dictionary<TKey, TValue> from an IEnumerable<T>:
using System;
using System.Collections.Generic;
using System.Linq;
public class Fruits
{
public int Id { get; set; }
public string Name { get; set; }
}
var fruits = new[]
{
new Fruits { Id = 8 , Name = "Apple" },
new Fruits { Id = 3 , Name = "Banana" },
new Fruits { Id = 7 , Name = "Mango" },
};
// Dictionary<int, string> key value
var dictionary = fruits.ToDictionary(x => x.Id, x => x.Name);
Section 4.6: Enumerating a Dictionary
You can enumerate through a Dictionary in one of 3 ways:
Using KeyValue pairs
GoalKicker.com – .NET Framework Notes for Professionals
14
Dictionary<int, string> dict = new Dictionary<int, string>();
foreach(KeyValuePair<int, string> kvp in dict)
{
Console.WriteLine("Key : " + kvp.Key.ToString() + ", Value : " + kvp.Value);
}
Using Keys
Dictionary<int, string> dict = new Dictionary<int, string>();
foreach(int key in dict.Keys)
{
Console.WriteLine("Key : " + key.ToString() + ", Value : " + dict[key]);
}
Using Values
Dictionary<int, string> dict = new Dictionary<int, string>();
foreach(string s in dict.Values)
{
Console.WriteLine("Value : " + s);
}
Section 4.7: ConcurrentDictionary<TKey, TValue> (from .NET
4.0)
Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads
concurrently.
Creating an instance
Creating an instance works pretty much the same way as with Dictionary<TKey, TValue>, e.g.:
var dict = new ConcurrentDictionary<int, string>();
Adding or Updating
You might be surprised, that there is no Add method, but instead there is AddOrUpdate with 2 overloads:
(1) AddOrUpdate(TKey key, TValue, Func<TKey, TValue, TValue> addValue) - Adds a key/value pair if the key does
not already exist, or updates a key/value pair by using the specified function if the key already exists.
(2) AddOrUpdate(TKey key, Func<TKey, TValue> addValue, Func<TKey, TValue, TValue> updateValueFactory)
- Uses the specified functions to add a key/value pair to the if the key does not already exist, or to update a key/value pair
if the key already exists.
Adding or updating a value, no matter what was the value if it was already present for given key (1):
string addedValue = dict.AddOrUpdate(1, "First", (updateKey, valueOld) => "First");
Adding or updating a value, but now altering the value in update, based on the previous value (1):
string addedValue2 = dict.AddOrUpdate(1, "First", (updateKey, valueOld) => $"{valueOld} Updated");
GoalKicker.com – .NET Framework Notes for Professionals
15
Using the overload (2) we can also add new value using a factory:
string addedValue3 = dict.AddOrUpdate(1, (key) => key == 1 ? "First" : "Not First", (updateKey,
valueOld) => $"{valueOld} Updated");
Getting value
Getting a value is the same as with the Dictionary<TKey,TValue>:
string value = null;
bool success = dict.TryGetValue(1, out value);
Getting or Adding a value
There are two mehod overloads, that will get or add a value in a thread-safe manner.
Get value with key 2, or add value "Second" if the key is not present:
string theValue = dict.GetOrAdd(2, "Second");
Using a factory for adding a value, if value is not present:
string theValue2 = dict.GetOrAdd(2, (key) => key == 2 ? "Second" : "Not Second." );
Section 4.8: Dictionary to List
Creating a list of KeyValuePair:
Dictionary<int, int> dictionary = new Dictionary<int, int>();
List<KeyValuePair<int, int>> list = new List<KeyValuePair<int, int>>();
list.AddRange(dictionary);
Creating a list of keys:
Dictionary<int, int> dictionary = new Dictionary<int, int>();
List<int> list = new List<int>();
list.AddRange(dictionary.Keys);
Creating a list of values:
Dictionary<int, int> dictionary = new Dictionary<int, int>();
List<int> list = new List<int>();
list.AddRange(dictionary.Values);
Section 4.9: Removing from a Dictionary
Given this setup code:
var dict = new Dictionary<int, string>()
{
{ 1, "First" },
{ 2, "Second" },
{ 3, "Third" }
};
GoalKicker.com – .NET Framework Notes for Professionals
16
Use the Remove method to remove a key and its associated value.
bool wasRemoved = dict.Remove(2);
Executing this code removes the key 2 and it's value from the dictionary. Remove returns a boolean value indicating
whether the specified key was found and removed from the dictionary. If the key does not exist in the dictionary,
nothing is removed from the dictionary, and false is returned (no exception is thrown).
It's incorrect to try and remove a key by setting the value for the key to null.
dict[2] = null; // WRONG WAY TO REMOVE!
This will not remove the key. It will just replace the previous value with a value of null.
To remove all keys and values from a dictionary, use the Clear method.
dict.Clear();
After executing Clear the dictionary's Count will be 0, but the internal capacity remains unchanged.
Section 4.10: ContainsKey(TKey)
To check if a Dictionary has an specifique key, you can call the method ContainsKey(TKey) and provide the key of
TKey type. The method returns a bool value when the key exists on the dictionary. For sample:
var dictionary = new Dictionary<string, Customer>()
{
{"F1", new Customer() { FirstName = "Felipe", ... } },
{"C2", new Customer() { FirstName = "Carl", ... } },
{"J7", new Customer() { FirstName = "John", ... } },
{"M5", new Customer() { FirstName = "Mary", ... } },
};
And check if a C2 exists on the Dictionary:
if (dictionary.ContainsKey("C2"))
{
// exists
}
The ContainsKey method is available on the generic version Dictionary<TKey, TValue>.
Section 4.11: ConcurrentDictionary augmented with Lazy'1
reduces duplicated computation
Problem
ConcurrentDictionary shines when it comes to instantly returning of existing keys from cache, mostly lock free, and
contending on a granular level. But what if the object creation is really expensive, outweighing the cost of context
switching, and some cache misses occur?
If the same key is requested from multiple threads, one of the objects resulting from colliding operations will be
eventually added to the collection, and the others will be thrown away, wasting the CPU resource to create the
object and memory resource to store the object temporarily. Other resources could be wasted as well. This is really
bad.
GoalKicker.com – .NET Framework Notes for Professionals
17
Solution
We can combine ConcurrentDictionary<TKey, TValue> with Lazy<TValue>. The idea is that ConcurrentDictionary
GetOrAdd method can only return the value which was actually added to the collection. The loosing Lazy objects
could be wasted in this case too, but that's not much problem, as the Lazy object itself is relatively unexpensive. The
Value property of the losing Lazy is never requested, because we are smart to only request the Value property of
the one actually added to the collection - the one returned from the GetOrAdd method:
public static class ConcurrentDictionaryExtensions
{
public static TValue GetOrCreateLazy<TKey, TValue>(
this ConcurrentDictionary<TKey, Lazy<TValue>> d,
TKey key,
Func<TKey, TValue> factory)
{
return
d.GetOrAdd(
key,
key1 =>
new Lazy<TValue>(() => factory(key1),
LazyThreadSafetyMode.ExecutionAndPublication)).Value;
}
}
Caching of XmlSerializer objects can be particularly expensive, and there is a lot of contention at the application
startup too. And there is more to this: if those are custom serializers, there will be a memory leak too for the rest of
the process lifecycle. The only benefit of the ConcurrentDictionary in this case is that for the rest of the process
lifecycle there will be no locks, but application startup and memory usage would be inacceptable. This is a job for
our ConcurrentDictionary, augmented with Lazy:
private ConcurrentDictionary<Type, Lazy<XmlSerializer>> _serializers =
new ConcurrentDictionary<Type, Lazy<XmlSerializer>>();
public XmlSerializer GetSerialier(Type t)
{
return _serializers.GetOrCreateLazy(t, BuildSerializer);
}
private XmlSerializer BuildSerializer(Type t)
{
throw new NotImplementedException("and this is a homework");
}
GoalKicker.com – .NET Framework Notes for Professionals
18
Chapter 5: Collections
Section 5.1: Using collection initializers
Some collection types can be initialized at the declaration time. For example, the following statement creates and
initializes the numbers with some integers:
List<int> numbers = new List<int>(){10, 9, 8, 7, 7, 6, 5, 10, 4, 3, 2, 1};
Internally, the C# compiler actually converts this initialization to a series of calls to the Add method. Consequently,
you can use this syntax only for collections that actually support the Add method.
The Stack<T> and Queue<T> classes do not support it.
For complex collections such as the Dictionary<TKey, TValue> class, that take key/value pairs, you can specify
each key/value pair as an anonymous type in the initializer list.
Dictionary<int, string> employee = new Dictionary<int, string>()
{{44, "John"}, {45, "Bob"}, {47, "James"}, {48, "Franklin"}};
The first item in each pair is the key, and the second is the value.
Section 5.2: Stack
There is a collection in .Net used to manage values in a Stack that uses the LIFO (last-in first-out) concept. The
basics of stacks is the method Push(T item) which is used to add elements in the stack and Pop() which is used to
get the last element added and remove it from the stack. The generic version can be used like the following code
for a queue of strings.
First, add the namespace:
using System.Collections.Generic;
and use it:
Stack<string> stack = new Stack<string>();
stack.Push("John");
stack.Push("Paul");
stack.Push("George");
stack.Push("Ringo");
string value;
value = stack.Pop(); // return Ringo
value = stack.Pop(); // return George
value = stack.Pop(); // return Paul
value = stack.Pop(); // return John
There is a non generic version of the type, which works with objects.
The namespace is:
using System.Collections;
GoalKicker.com – .NET Framework Notes for Professionals
19
And a code sample of non generic stack:
Stack stack = new Stack();
stack.Push("Hello World"); // string
stack.Push(5); // int
stack.Push(1d); // double
stack.Push(true); // bool
stack.Push(new Product()); // Product object
object value;
value = stack.Pop(); // return Product (Product type)
value = stack.Pop(); // return true (bool)
value = stack.Pop(); // return 1d (double)
value = stack.Pop(); // return 5 (int)
value = stack.Pop(); // return Hello World (string)
There is also a method called Peek() which returns the last element added but without removing it from the Stack.
Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
var lastValueAdded = stack.Peek(); // 20
It is possible to iterate on the elements on the stack and it will respect the order of the stack (LIFO).
Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
stack.Push(30);
stack.Push(40);
stack.Push(50);
foreach (int element in stack)
{
Console.WriteLine(element);
}
The output (without removing):
50
40
30
20
10
Section 5.3: Creating an initialized List with Custom Types
public class Model
{
public string Name { get; set; }
public bool? Selected { get; set; }
}
Here we have a Class with no constructor with two properties: Name and a nullable boolean property Selected. If we
wanted to initialize a List<Model>, there are a few different ways to execute this.
GoalKicker.com – .NET Framework Notes for Professionals
20
var SelectedEmployees = new List<Model>
{
new Model() {Name = "Item1", Selected = true},
new Model() {Name = "Item2", Selected = false},
new Model() {Name = "Item3", Selected = false},
new Model() {Name = "Item4"}
};
Here, we are creating several new instances of our Model class, and initializing them with data. What if we added a
constructor?
public class Model
{
public Model(string name, bool? selected = false)
{
Name = name;
selected = Selected;
}
public string Name { get; set; }
public bool? Selected { get; set; }
}
This allows us to initialize our List a little differently.
var SelectedEmployees = new List<Model>
{
new Model("Mark", true),
new Model("Alexis"),
new Model("")
};
What about a Class where one of the properties is a class itself?
public class Model
{
public string Name { get; set; }
public bool? Selected { get; set; }
}
public class ExtendedModel : Model
{
public ExtendedModel()
{
BaseModel = new Model();
}
public Model BaseModel { get; set; }
public DateTime BirthDate { get; set; }
}
Notice we reverted the constructor on the Model class to simplify the example a little bit.
var SelectedWithBirthDate = new List<ExtendedModel>
{
new ExtendedModel()
{
BaseModel = new Model { Name = "Mark", Selected = true},
BirthDate = new DateTime(2015, 11, 23)
GoalKicker.com – .NET Framework Notes for Professionals
21
},
new ExtendedModel()
{
BaseModel = new Model { Name = "Random"},
BirthDate = new DateTime(2015, 11, 23)
}
};
Note that we can interchange our List<ExtendedModel> with Collection<ExtendedModel>, ExtendedModel[],
object[], or even simply [].
Section 5.4: Queue
There is a collection in .Net used to manage values in a Queue that uses the FIFO (first-in first-out) concept. The
basics of queues is the method Enqueue(T item) which is used to add elements in the queue and Dequeue() which
is used to get the first element and remove it from the queue. The generic version can be used like the following
code for a queue of strings.
First, add the namespace:
using System.Collections.Generic;
and use it:
Queue<string> queue = new Queue<string>();
queue.Enqueue("John");
queue.Enqueue("Paul");
queue.Enqueue("George");
queue.Enqueue("Ringo");
string dequeueValue;
dequeueValue = queue.Dequeue(); // return John
dequeueValue = queue.Dequeue(); // return Paul
dequeueValue = queue.Dequeue(); // return George
dequeueValue = queue.Dequeue(); // return Ringo
There is a non generic version of the type, which works with objects.
The namespace is:
using System.Collections;
Adn a code sample fo non generic queue:
Queue queue = new Queue();
queue.Enqueue("Hello World"); // string
queue.Enqueue(5); // int
queue.Enqueue(1d); // double
queue.Enqueue(true); // bool
queue.Enqueue(new Product()); // Product object
object dequeueValue;
dequeueValue = queue.Dequeue(); // return Hello World (string)
dequeueValue = queue.Dequeue(); // return 5 (int)
dequeueValue = queue.Dequeue(); // return 1d (double)
dequeueValue = queue.Dequeue(); // return true (bool)
dequeueValue = queue.Dequeue(); // return Product (Product type)
GoalKicker.com – .NET Framework Notes for Professionals
22
There is also a method called Peek() which returns the object at the beginning of the queue without removing it the
elements.
Queue<int> queue = new Queue<int>();
queue.Enqueue(10);
queue.Enqueue(20);
queue.Enqueue(30);
queue.Enqueue(40);
queue.Enqueue(50);
foreach (int element in queue)
{
Console.WriteLine(i);
}
The output (without removing):
10
20
30
40
50
GoalKicker.com – .NET Framework Notes for Professionals
23
Chapter 6: ReadOnlyCollections
Section 6.1: Creating a ReadOnlyCollection
Using the Constructor
A ReadOnlyCollection is created by passing an existing IList object into the constructor:
var groceryList = new List<string> { "Apple", "Banana" };
var readOnlyGroceryList = new ReadOnlyCollection<string>(groceryList);
Using LINQ
Additionaly, LINQ provides an AsReadOnly() extension method for IList objects:
var readOnlyVersion = groceryList.AsReadOnly();
Note
Typically, you want to maintain the source collection privately and allow public access to the ReadOnlyCollection.
While you could create a ReadOnlyCollection from an in-line list, you would be unable to modify the collection
after you created it.
var readOnlyGroceryList = new List<string> {"Apple", "Banana"}.AsReadOnly();
// Great, but you will not be able to update the grocery list because
// you do not have a reference to the source list anymore!
If you find yourself doing this, you may want to consider using another data structure, such as an
ImmutableCollection.
Section 6.2: Updating a ReadOnlyCollection
A ReadOnlyCollection cannot be edited directly. Instead, the source collection is updated and the
ReadOnlyCollection will reflect these changes. This is the key feature of the ReadOnlyCollection.
var groceryList = new List<string> { "Apple", "Banana" };
var readOnlyGroceryList = new ReadOnlyCollection<string>(groceryList);
var itemCount = readOnlyGroceryList.Count; // There are currently 2 items
//readOnlyGroceryList.Add("Candy"); // Compiler Error - Items cannot be added to a
ReadOnlyCollection object
groceryList.Add("Vitamins"); // ..but they can be added to the original collection
itemCount = readOnlyGroceryList.Count; // Now there are 3 items
var lastItem = readOnlyGroceryList.Last(); // The last item on the read only list is now "Vitamins"
View Demo
Section 6.3: Warning: Elements in a ReadOnlyCollection are
not inherently read-only
If the source collection is of a type that is not immutable, elements accessed through a ReadOnlyCollection can be
GoalKicker.com – .NET Framework Notes for Professionals
24
modified.
public class Item
{
public string Name { get; set; }
public decimal Price { get; set; }
}
public static void FillOrder()
{
// An order is generated
var order = new List<Item>
{
new Item { Name = "Apple", Price = 0.50m },
new Item { Name = "Banana", Price = 0.75m },
new Item { Name = "Vitamins", Price = 5.50m }
};
// The current sub total is $6.75
var subTotal = order.Sum(item => item.Price);
// Let the customer preview their order
var customerPreview = new ReadOnlyCollection<Item>(order);
// The customer can't add or remove items, but they can change
// the price of an item, even though it is a ReadOnlyCollection
customerPreview.Last().Price = 0.25m;
// The sub total is now only $1.50!
subTotal = order.Sum(item => item.Price);
}
View Demo
GoalKicker.com – .NET Framework Notes for Professionals
25
Chapter 7: Stack and Heap
Section 7.1: Value types in use
Value types simply contain a value.
All value types are derived from the System.ValueType class, and this includes most of the built in types.
When creating a new value type, the an area of memory called the stack is used.
The stack will grow accordingly, by the size the declared type. So for example, an int will always be allocated 32 bits
of memory on the stack. When the value type is no longer in scope, the space on the stack will be deallocated.
The code below demonstrates a value type being assigned to a new variable. A struct is being used as a convenient
way to create a custom value type (the System.ValueType class cannot be otherwise extended).
The important thing to understand is that when assigning a value type, the value itself copied to the new variable,
meaning we have two distinct instances of the object, that cannot affect each other.
struct PersonAsValueType
{
public string Name;
}
class Program
{
static void Main()
{
PersonAsValueType personA;
personA.Name = "Bob";
var personB = personA;
personA.Name = "Linda";
Console.WriteLine( // Outputs 'False' - because
object.ReferenceEquals( // personA and personB are referencing
personA, // different areas of memory
personB));
Console.WriteLine(personA.Name); // Outputs 'Linda'
Console.WriteLine(personB.Name); // Outputs 'Bob'
}
}
Section 7.2: Reference types in use
Reference types are comprised of both a reference to a memory area, and a value stored within that area.
This is analogous to pointers in C/C++.
All reference types are stored on what is known as the heap.
The heap is simply a managed area of memory where objects are stored. When a new object is instantiated, a part
of the heap will be allocated for use by that object, and a reference to that location of the heap will be returned. The
heap is managed and maintained by the garbage collector, and does not allow for manual intervention.
In addition to the memory space required for the instance itself, additional space is required to store the reference
GoalKicker.com – .NET Framework Notes for Professionals
26
itself, along with additional temporary information required by the .NET CLR.
The code below demonstrates a reference type being assigned to a new variable. In this instance, we are using a
class, all classes are reference types (even if static).
When a reference type is assigned to another variable, it is the reference to the object that is copied over, not the
value itself. This is an important distinction between value types and reference types.
The implications of this are that we now have two references to the same object.
Any changes to the values within that object will be reflected by both variables.
class PersonAsReferenceType
{
public string Name;
}
class Program
{
static void Main()
{
PersonAsReferenceType personA;
personA = new PersonAsReferenceType { Name = "Bob" };
var personB = personA;
personA.Name = "Linda";
Console.WriteLine( // Outputs 'True' - because
object.ReferenceEquals( // personA and personB are referencing
personA, // the *same* memory location
personB));
Console.WriteLine(personA.Name); // Outputs 'Linda'
Console.WriteLine(personB.Name); // Outputs 'Linda'
}
GoalKicker.com – .NET Framework Notes for Professionals
27
Chapter 8: LINQ
LINQ (Language Integrated Query) is an expression that retrieves data from a data source. LINQ simplifies this
situation by offering a consistent model for working with data across various kinds of data sources and formats. In
a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform
data in XML documents, SQL databases, ADO.NET Datasets, .NET collections, and any other format for which a
provider is available. LINQ can be used in C# and VB.
Section 8.1: SelectMany (flat map)
Enumerable.Select returns an output element for every input element. Whereas Enumerable.SelectMany
produces a variable number of output elements for each input element. This means that the output sequence may
contain more or fewer elements than were in the input sequence.
Lambda expressions passed to Enumerable.Select must return a single item. Lambda expressions passed to
Enumerable.SelectMany must produce a child sequence. This child sequence may contain a varying number of
elements for each element in the input sequence.
Example
class Invoice
{
public int Id { get; set; }
}
class Customer
{
public Invoice[] Invoices {get;set;}
}
var customers = new[] {
new Customer {
Invoices = new[] {
new Invoice {Id=1},
new Invoice {Id=2},
}
},
new Customer {
Invoices = new[] {
new Invoice {Id=3},
new Invoice {Id=4},
}
},
new Customer {
Invoices = new[] {
new Invoice {Id=5},
new Invoice {Id=6},
}
}
};
var allInvoicesFromAllCustomers = customers.SelectMany(c => c.Invoices);
Console.WriteLine(
string.Join(",", allInvoicesFromAllCustomers.Select(i => i.Id).ToArray()));
Output:
GoalKicker.com – .NET Framework Notes for Professionals
28
1,2,3,4,5,6
View Demo
Enumerable.SelectMany can also be achieved with a syntax-based query using two consecutive from clauses:
var allInvoicesFromAllCustomers
= from customer in customers
from invoice in customer.Invoices
select invoice;
Section 8.2: Where (filter)
This method returns an IEnumerable with all the elements that meets the lambda expression
Example
var personNames = new[]
{
"Foo", "Bar", "Fizz", "Buzz"
};
var namesStartingWithF = personNames.Where(p => p.StartsWith("F"));
Console.WriteLine(string.Join(",", namesStartingWithF));
Output:
Foo,Fizz
View Demo
Section 8.3: Any
Returns true if the collection has any elements that meets the condition in the lambda expression:
var numbers = new[] {1,2,3,4,5};
var isNotEmpty = numbers.Any();
Console.WriteLine(isNotEmpty); //True
var anyNumberIsOne = numbers.Any(n => n == 1);
Console.WriteLine(anyNumberIsOne); //True
var anyNumberIsSix = numbers.Any(n => n == 6);
Console.WriteLine(anyNumberIsSix); //False
var anyNumberIsOdd = numbers.Any(n => (n & 1) == 1);
Console.WriteLine(anyNumberIsOdd); //True
var anyNumberIsNegative = numbers.Any(n => n < 0);
Console.WriteLine(anyNumberIsNegative); //False
GoalKicker.com – .NET Framework Notes for Professionals
29
Section 8.4: GroupJoin
class Developer
{
public int Id { get; set; }
public string Name { get; set; }
}
class Project
{
public int DeveloperId { get; set; }
public string Name { get; set; }
}
var developers = new[] {
new Developer {
Id = 1,
Name = "Foobuzz"
},
new Developer {
Id = 2,
Name = "Barfizz"
}
};
var projects = new[] {
new Project {
DeveloperId = 1,
Name = "Hello World 3D"
},
new Project {
DeveloperId = 1,
Name = "Super Fizzbuzz Maker"
},
new Project {
DeveloperId = 2,
Name = "Citizen Kane - The action game"
},
new Project {
DeveloperId = 2,
Name = "Pro Pong 2016"
}
};
var grouped = developers.GroupJoin(
inner: projects,
outerKeySelector: dev => dev.Id,
innerKeySelector: proj => proj.DeveloperId,
resultSelector:
(dev, projs) => new {
DeveloperName = dev.Name,
ProjectNames = projs.Select(p => p.Name).ToArray()});
foreach(var item in grouped)
{
Console.WriteLine(
"{0}'s projects: {1}",
item.DeveloperName,
string.Join(", ", item.ProjectNames));
}
GoalKicker.com – .NET Framework Notes for Professionals
30
//Foobuzz's projects: Hello World 3D, Super Fizzbuzz Maker
//Barfizz's projects: Citizen Kane - The action game, Pro Pong 2016
Section 8.5: Except
var numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evenNumbersBetweenSixAndFourteen = new[] { 6, 8, 10, 12 };
var result = numbers.Except(evenNumbersBetweenSixAndFourteen);
Console.WriteLine(string.Join(",", result));
//1, 2, 3, 4, 5, 7, 9
Section 8.6: Zip
.NET Version ≥ 4.0
var tens = new[] {10,20,30,40,50};
var units = new[] {1,2,3,4,5};
var sums = tens.Zip(units, (first, second) => first + second);
Console.WriteLine(string.Join(",", sums));
//11,22,33,44,55
Section 8.7: Aggregate (fold)
Generating a new object in each step:
var elements = new[] {1,2,3,4,5};
var commaSeparatedElements = elements.Aggregate(
seed: "",
func: (aggregate, element) => $"{aggregate}{element},");
Console.WriteLine(commaSeparatedElements); //1,2,3,4,5,
Using the same object in all steps:
var commaSeparatedElements2 = elements.Aggregate(
seed: new StringBuilder(),
func: (seed, element) => seed.Append($"{element},"));
Console.WriteLine(commaSeparatedElements2.ToString()); //1,2,3,4,5,
Using a result selector:
var commaSeparatedElements3 = elements.Aggregate(
seed: new StringBuilder(),
func: (seed, element) => seed.Append($"{element},"),
resultSelector: (seed) => seed.ToString());
Console.WriteLine(commaSeparatedElements3); //1,2,3,4,5,
If a seed is omitted, the first element becomes the seed:
GoalKicker.com – .NET Framework Notes for Professionals
31
var seedAndElements = elements.Select(n=>n.ToString());
var commaSeparatedElements4 = seedAndElements.Aggregate(
func: (aggregate, element) => $"{aggregate}{element},");
Console.WriteLine(commaSeparatedElements4); //12,3,4,5,
Section 8.8: ToLookup
var persons = new[] {
new { Name="Fizz", Job="Developer"},
new { Name="Buzz", Job="Developer"},
new { Name="Foo", Job="Astronaut"},
new { Name="Bar", Job="Astronaut"},
};
var groupedByJob = persons.ToLookup(p => p.Job);
foreach(var theGroup in groupedByJob)
{
Console.WriteLine(
"{0} are {1}s",
string.Join(",", theGroup.Select(g => g.Name).ToArray()),
theGroup.Key);
}
//Fizz,Buzz are Developers
//Foo,Bar are Astronauts
Section 8.9: Intersect
var numbers1to10 = new[] {1,2,3,4,5,6,7,8,9,10};
var numbers5to15 = new[] {5,6,7,8,9,10,11,12,13,14,15};
var numbers5to10 = numbers1to10.Intersect(numbers5to15);
Console.WriteLine(string.Join(",", numbers5to10));
//5,6,7,8,9,10
Section 8.10: Concat
var numbers1to5 = new[] {1, 2, 3, 4, 5};
var numbers4to8 = new[] {4, 5, 6, 7, 8};
var numbers1to8 = numbers1to5.Concat(numbers4to8);
Console.WriteLine(string.Join(",", numbers1to8));
//1,2,3,4,5,4,5,6,7,8
Note that duplicates are kept in the result. If this is undesirable, use Union instead.
Section 8.11: All
var numbers = new[] {1,2,3,4,5};
var allNumbersAreOdd = numbers.All(n => (n & 1) == 1);
GoalKicker.com – .NET Framework Notes for Professionals
32
Console.WriteLine(allNumbersAreOdd); //False
var allNumbersArePositive = numbers.All(n => n > 0);
Console.WriteLine(allNumbersArePositive); //True
Note that the All method functions by checking for the first element to evaluate as false according to the
predicate. Therefore, the method will return true for any predicate in the case that the set is empty:
var numbers = new int[0];
var allNumbersArePositive = numbers.All(n => n > 0);
Console.WriteLine(allNumbersArePositive); //True
Section 8.12: Sum
var numbers = new[] {1,2,3,4};
var sumOfAllNumbers = numbers.Sum();
Console.WriteLine(sumOfAllNumbers); //10
var cities = new[] {
new {Population = 1000},
new {Population = 2500},
new {Population = 4000}
};
var totalPopulation = cities.Sum(c => c.Population);
Console.WriteLine(totalPopulation); //7500
Section 8.13: SequenceEqual
var numbers = new[] {1,2,3,4,5};
var sameNumbers = new[] {1,2,3,4,5};
var sameNumbersInDifferentOrder = new[] {5,1,4,2,3};
var equalIfSameOrder = numbers.SequenceEqual(sameNumbers);
Console.WriteLine(equalIfSameOrder); //True
var equalIfDifferentOrder = numbers.SequenceEqual(sameNumbersInDifferentOrder);
Console.WriteLine(equalIfDifferentOrder); //False
Section 8.14: Min
var numbers = new[] {1,2,3,4};
var minNumber = numbers.Min();
Console.WriteLine(minNumber); //1
var cities = new[] {
new {Population = 1000},
new {Population = 2500},
new {Population = 4000}
};
var minPopulation = cities.Min(c => c.Population);
Console.WriteLine(minPopulation); //1000
GoalKicker.com – .NET Framework Notes for Professionals
33
Section 8.15: Distinct
var numbers = new[] {1, 1, 2, 2, 3, 3, 4, 4, 5, 5};
var distinctNumbers = numbers.Distinct();
Console.WriteLine(string.Join(",", distinctNumbers));
//1,2,3,4,5
Section 8.16: Count
IEnumerable<int> numbers = new[] {1,2,3,4,5,6,7,8,9,10};
var numbersCount = numbers.Count();
Console.WriteLine(numbersCount); //10
var evenNumbersCount = numbers.Count(n => (n & 1) == 0);
Console.WriteLine(evenNumbersCount); //5
Section 8.17: Cast
Cast is different from the other methods of Enumerable in that it is an extension method for IEnumerable, not for
IEnumerable<T>. Thus it can be used to convert instances of the former into instances of the later.
This does not compile since ArrayList does not implement IEnumerable<T>:
var numbers = new ArrayList() {1,2,3,4,5};
Console.WriteLine(numbers.First());
This works as expected:
var numbers = new ArrayList() {1,2,3,4,5};
Console.WriteLine(numbers.Cast<int>().First()); //1
Cast does not perform conversion casts. The following compiles but throws InvalidCastException at runtime:
var numbers = new int[] {1,2,3,4,5};
decimal[] numbersAsDecimal = numbers.Cast<decimal>().ToArray();
The proper way to perform a converting cast to a collection is as follows:
var numbers= new int[] {1,2,3,4,5};
decimal[] numbersAsDecimal = numbers.Select(n => (decimal)n).ToArray();
Section 8.18: Range
The two parameters to Range are the first number and the count of elements to produce (not the last number).
// prints 1,2,3,4,5,6,7,8,9,10
Console.WriteLine(string.Join(",", Enumerable.Range(1, 10)));
// prints 10,11,12,13,14
Console.WriteLine(string.Join(",", Enumerable.Range(10, 5)));
GoalKicker.com – .NET Framework Notes for Professionals
34
Section 8.19: ThenBy
ThenBy can only be used after a OrderBy clause allowing to order using multiple criteria
var persons = new[]
{
new {Id = 1, Name = "Foo", Order = 1},
new {Id = 1, Name = "FooTwo", Order = 2},
new {Id = 2, Name = "Bar", Order = 2},
new {Id = 2, Name = "BarTwo", Order = 1},
new {Id = 3, Name = "Fizz", Order = 2},
new {Id = 3, Name = "FizzTwo", Order = 1},
};
var personsSortedByName = persons.OrderBy(p => p.Id).ThenBy(p => p.Order);
Console.WriteLine(string.Join(",", personsSortedByName.Select(p => p.Name)));
//This will display :
//Foo,FooTwo,BarTwo,Bar,FizzTwo,Fizz
Section 8.20: Repeat
Enumerable.Repeat generates a sequence of a repeated value. In this example it generates "Hello" 4 times.
var repeats = Enumerable.Repeat("Hello", 4);
foreach (var item in repeats)
{
Console.WriteLine(item);
}
/* output:
Hello
Hello
Hello
Hello
*/
Section 8.21: Empty
To create an empty IEnumerable of int:
IEnumerable<int> emptyList = Enumerable.Empty<int>();
This empty IEnumerable is cached for each Type T, so that:
Enumerable.Empty<decimal>() == Enumerable.Empty<decimal>(); // This is True
Enumerable.Empty<int>() == Enumerable.Empty<decimal>(); // This is False
Section 8.22: Select (map)
var persons = new[]
{
new {Id = 1, Name = "Foo"},
new {Id = 2, Name = "Bar"},
new {Id = 3, Name = "Fizz"},
new {Id = 4, Name = "Buzz"}
GoalKicker.com – .NET Framework Notes for Professionals
35
};
var names = persons.Select(p => p.Name);
Console.WriteLine(string.Join(",", names.ToArray()));
//Foo,Bar,Fizz,Buzz
This type of function is usually called map in functional programming languages.
Section 8.23: OrderBy
var persons = new[]
{
new {Id = 1, Name = "Foo"},
new {Id = 2, Name = "Bar"},
new {Id = 3, Name = "Fizz"},
new {Id = 4, Name = "Buzz"}
};
var personsSortedByName = persons.OrderBy(p => p.Name);
Console.WriteLine(string.Join(",", personsSortedByName.Select(p => p.Id).ToArray()));
//2,4,3,1
Section 8.24: OrderByDescending
var persons = new[]
{
new {Id = 1, Name = "Foo"},
new {Id = 2, Name = "Bar"},
new {Id = 3, Name = "Fizz"},
new {Id = 4, Name = "Buzz"}
};
var personsSortedByNameDescending = persons.OrderByDescending(p => p.Name);
Console.WriteLine(string.Join(",", personsSortedByNameDescending.Select(p => p.Id).ToArray()));
//1,3,4,2
Section 8.25: Contains
var numbers = new[] {1,2,3,4,5};
Console.WriteLine(numbers.Contains(3)); //True
Console.WriteLine(numbers.Contains(34)); //False
Section 8.26: First (find)
var numbers = new[] {1,2,3,4,5};
var firstNumber = numbers.First();
Console.WriteLine(firstNumber); //1
var firstEvenNumber = numbers.First(n => (n & 1) == 0);
Console.WriteLine(firstEvenNumber); //2
GoalKicker.com – .NET Framework Notes for Professionals
36
The following throws InvalidOperationException with message "Sequence contains no matching element":
var firstNegativeNumber = numbers.First(n => n < 0);
Section 8.27: Single
var oneNumber = new[] {5};
var theOnlyNumber = oneNumber.Single();
Console.WriteLine(theOnlyNumber); //5
var numbers = new[] {1,2,3,4,5};
var theOnlyNumberSmallerThanTwo = numbers.Single(n => n < 2);
Console.WriteLine(theOnlyNumberSmallerThanTwo); //1
The following throws InvalidOperationException since there is more than one element in the sequence:
var theOnlyNumberInNumbers = numbers.Single();
var theOnlyNegativeNumber = numbers.Single(n => n < 0);
Section 8.28: Last
var numbers = new[] {1,2,3,4,5};
var lastNumber = numbers.Last();
Console.WriteLine(lastNumber); //5
var lastEvenNumber = numbers.Last(n => (n & 1) == 0);
Console.WriteLine(lastEvenNumber); //4
The following throws InvalidOperationException:
var lastNegativeNumber = numbers.Last(n => n < 0);
Section 8.29: LastOrDefault
var numbers = new[] {1,2,3,4,5};
var lastNumber = numbers.LastOrDefault();
Console.WriteLine(lastNumber); //5
var lastEvenNumber = numbers.LastOrDefault(n => (n & 1) == 0);
Console.WriteLine(lastEvenNumber); //4
var lastNegativeNumber = numbers.LastOrDefault(n => n < 0);
Console.WriteLine(lastNegativeNumber); //0
var words = new[] { "one", "two", "three", "four", "five" };
var lastWord = words.LastOrDefault();
Console.WriteLine(lastWord); // five
var lastLongWord = words.LastOrDefault(w => w.Length > 4);
Console.WriteLine(lastLongWord); // three
var lastMissingWord = words.LastOrDefault(w => w.Length > 5);
GoalKicker.com – .NET Framework Notes for Professionals
37
Console.WriteLine(lastMissingWord); // null
Section 8.30: SingleOrDefault
var oneNumber = new[] {5};
var theOnlyNumber = oneNumber.SingleOrDefault();
Console.WriteLine(theOnlyNumber); //5
var numbers = new[] {1,2,3,4,5};
var theOnlyNumberSmallerThanTwo = numbers.SingleOrDefault(n => n < 2);
Console.WriteLine(theOnlyNumberSmallerThanTwo); //1
var theOnlyNegativeNumber = numbers.SingleOrDefault(n => n < 0);
Console.WriteLine(theOnlyNegativeNumber); //0
The following throws InvalidOperationException:
var theOnlyNumberInNumbers = numbers.SingleOrDefault();
Section 8.31: FirstOrDefault
var numbers = new[] {1,2,3,4,5};
var firstNumber = numbers.FirstOrDefault();
Console.WriteLine(firstNumber); //1
var firstEvenNumber = numbers.FirstOrDefault(n => (n & 1) == 0);
Console.WriteLine(firstEvenNumber); //2
var firstNegativeNumber = numbers.FirstOrDefault(n => n < 0);
Console.WriteLine(firstNegativeNumber); //0
var words = new[] { "one", "two", "three", "four", "five" };
var firstWord = words.FirstOrDefault();
Console.WriteLine(firstWord); // one
var firstLongWord = words.FirstOrDefault(w => w.Length > 3);
Console.WriteLine(firstLongWord); // three
var firstMissingWord = words.FirstOrDefault(w => w.Length > 5);
Console.WriteLine(firstMissingWord); // null
Section 8.32: Skip
Skip will enumerate the first N items without returning them. Once item number N+1 is reached, Skip starts
returning every enumerated item:
var numbers = new[] {1,2,3,4,5};
var allNumbersExceptFirstTwo = numbers.Skip(2);
Console.WriteLine(string.Join(",", allNumbersExceptFirstTwo.ToArray()));
//3,4,5
GoalKicker.com – .NET Framework Notes for Professionals
38
Section 8.33: Take
This method takes the first n elements from an enumerable.
var numbers = new[] {1,2,3,4,5};
var threeFirstNumbers = numbers.Take(3);
Console.WriteLine(string.Join(",", threeFirstNumbers.ToArray()));
//1,2,3
Section 8.34: Reverse
var numbers = new[] {1,2,3,4,5};
var reversed = numbers.Reverse();
Console.WriteLine(string.Join(",", reversed.ToArray()));
//5,4,3,2,1
Section 8.35: OfType
var mixed = new object[] {1,"Foo",2,"Bar",3,"Fizz",4,"Buzz"};
var numbers = mixed.OfType<int>();
Console.WriteLine(string.Join(",", numbers.ToArray()));
//1,2,3,4
Section 8.36: Max
var numbers = new[] {1,2,3,4};
var maxNumber = numbers.Max();
Console.WriteLine(maxNumber); //4
var cities = new[] {
new {Population = 1000},
new {Population = 2500},
new {Population = 4000}
};
var maxPopulation = cities.Max(c => c.Population);
Console.WriteLine(maxPopulation); //4000
Section 8.37: Average
var numbers = new[] {1,2,3,4};
var averageNumber = numbers.Average();
Console.WriteLine(averageNumber);
// 2,5
This method calculates the average of enumerable of numbers.
var cities = new[] {
GoalKicker.com – .NET Framework Notes for Professionals
39
new {Population = 1000},
new {Population = 2000},
new {Population = 4000}
};
var averagePopulation = cities.Average(c => c.Population);
Console.WriteLine(averagePopulation);
// 2333,33
This method calculates the average of enumerable using delegated function.
Section 8.38: GroupBy
var persons = new[] {
new { Name="Fizz", Job="Developer"},
new { Name="Buzz", Job="Developer"},
new { Name="Foo", Job="Astronaut"},
new { Name="Bar", Job="Astronaut"},
};
var groupedByJob = persons.GroupBy(p => p.Job);
foreach(var theGroup in groupedByJob)
{
Console.WriteLine(
"{0} are {1}s",
string.Join(",", theGroup.Select(g => g.Name).ToArray()),
theGroup.Key);
}
//Fizz,Buzz are Developers
//Foo,Bar are Astronauts
Group invoices by country, generating a new object with the number of record, total paid, and average paid
var a = db.Invoices.GroupBy(i => i.Country)
.Select(g => new { Country = g.Key,
Count = g.Count(),
Total = g.Sum(i => i.Paid),
Average = g.Average(i => i.Paid) });
If we want only the totals, no group
var a = db.Invoices.GroupBy(i => 1)
.Select(g => new { Count = g.Count(),
Total = g.Sum(i => i.Paid),
Average = g.Average(i => i.Paid) });
If we need several counts
var a = db.Invoices.GroupBy(g => 1)
.Select(g => new { High = g.Count(i => i.Paid >= 1000),
Low = g.Count(i => i.Paid < 1000),
Sum = g.Sum(i => i.Paid) });
Section 8.39: ToDictionary
Returns a new dictionary from the source IEnumerable using the provided keySelector function to determine keys.
GoalKicker.com – .NET Framework Notes for Professionals
40
Will throw an ArgumentException if keySelector is not injective(returns a unique value for each member of the
source collection.) There are overloads which allow one to specify the value to be stored as well as the key.
var persons = new[] {
new { Name="Fizz", Id=1},
new { Name="Buzz", Id=2},
new { Name="Foo", Id=3},
new { Name="Bar", Id=4},
};
Specifying just a key selector function will create a Dictionary<TKey,TVal> with TKey the return Type of the key
selector, TVal the original object Type, and the original object as the stored value.
var personsById = persons.ToDictionary(p => p.Id);
// personsById is a Dictionary<int,object>
Console.WriteLine(personsById[1].Name); //Fizz
Console.WriteLine(personsById[2].Name); //Buzz
Specifying a value selector function as well will create a Dictionary<TKey,TVal> with TKey still the return type of
the key selector, but TVal now the return type of the value selector function, and the returned value as the stored
value.
var namesById = persons.ToDictionary(p => p.Id, p => p.Name);
//namesById is a Dictionary<int,string>
Console.WriteLine(namesById[3]); //Foo
Console.WriteLine(namesById[4]); //Bar
As stated above, the keys returned by the key selector must be unique. The following will throw an exception.
var persons = new[] {
new { Name="Fizz", Id=1},
new { Name="Buzz", Id=2},
new { Name="Foo", Id=3},
new { Name="Bar", Id=4},
new { Name="Oops", Id=4}
};
var willThrowException = persons.ToDictionary(p => p.Id)
If a unique key can not be given for the source collection, consider using ToLookup instead. On the surface,
ToLookup behaves similarly to ToDictionary, however, in the resulting Lookup each key is paired with a collection of
values with matching keys.
Section 8.40: Union
var numbers1to5 = new[] {1,2,3,4,5};
var numbers4to8 = new[] {4,5,6,7,8};
var numbers1to8 = numbers1to5.Union(numbers4to8);
Console.WriteLine(string.Join(",", numbers1to8));
//1,2,3,4,5,6,7,8
Note that duplicates are removed from the result. If this is undesirable, use Concat instead.
GoalKicker.com – .NET Framework Notes for Professionals
41
Section 8.41: ToArray
var numbers = new[] {1,2,3,4,5,6,7,8,9,10};
var someNumbers = numbers.Where(n => n < 6);
Console.WriteLine(someNumbers.GetType().Name);
//WhereArrayIterator`1
var someNumbersArray = someNumbers.ToArray();
Console.WriteLine(someNumbersArray.GetType().Name);
//Int32[]
Section 8.42: ToList
var numbers = new[] {1,2,3,4,5,6,7,8,9,10};
var someNumbers = numbers.Where(n => n < 6);
Console.WriteLine(someNumbers.GetType().Name);
//WhereArrayIterator`1
var someNumbersList = someNumbers.ToList();
Console.WriteLine(
someNumbersList.GetType().Name + " - " +
someNumbersList.GetType().GetGenericArguments()[0].Name);
//List`1 - Int32
Section 8.43: ElementAt
var names = new[] {"Foo","Bar","Fizz","Buzz"};
var thirdName = names.ElementAt(2);
Console.WriteLine(thirdName); //Fizz
//The following throws ArgumentOutOfRangeException
var minusOnethName = names.ElementAt(-1);
var fifthName = names.ElementAt(4);
Section 8.44: ElementAtOrDefault
var names = new[] {"Foo","Bar","Fizz","Buzz"};
var thirdName = names.ElementAtOrDefault(2);
Console.WriteLine(thirdName); //Fizz
var minusOnethName = names.ElementAtOrDefault(-1);
Console.WriteLine(minusOnethName); //null
var fifthName = names.ElementAtOrDefault(4);
Console.WriteLine(fifthName); //null
Section 8.45: SkipWhile
var numbers = new[] {2,4,6,8,1,3,5,7};
GoalKicker.com – .NET Framework Notes for Professionals
42
var oddNumbers = numbers.SkipWhile(n => (n & 1) == 0);
Console.WriteLine(string.Join(",", oddNumbers.ToArray()));
//1,3,5,7
Section 8.46: TakeWhile
var numbers = new[] {2,4,6,1,3,5,7,8};
var evenNumbers = numbers.TakeWhile(n => (n & 1) == 0);
Console.WriteLine(string.Join(",", evenNumbers.ToArray()));
//2,4,6
Section 8.47: DefaultIfEmpty
var numbers = new[] {2,4,6,8,1,3,5,7};
var numbersOrDefault = numbers.DefaultIfEmpty();
Console.WriteLine(numbers.SequenceEqual(numbersOrDefault)); //True
var noNumbers = new int[0];
var noNumbersOrDefault = noNumbers.DefaultIfEmpty();
Console.WriteLine(noNumbersOrDefault.Count()); //1
Console.WriteLine(noNumbersOrDefault.Single()); //0
var noNumbersOrExplicitDefault = noNumbers.DefaultIfEmpty(34);
Console.WriteLine(noNumbersOrExplicitDefault.Count()); //1
Console.WriteLine(noNumbersOrExplicitDefault.Single()); //34
Section 8.48: Join
class Developer
{
public int Id { get; set; }
public string Name { get; set; }
}
class Project
{
public int DeveloperId { get; set; }
public string Name { get; set; }
}
var developers = new[] {
new Developer {
Id = 1,
Name = "Foobuzz"
},
new Developer {
Id = 2,
Name = "Barfizz"
}
};
var projects = new[] {
GoalKicker.com – .NET Framework Notes for Professionals
43
new Project {
DeveloperId = 1,
Name = "Hello World 3D"
},
new Project {
DeveloperId = 1,
Name = "Super Fizzbuzz Maker"
},
new Project {
DeveloperId = 2,
Name = "Citizen Kane - The action game"
},
new Project {
DeveloperId = 2,
Name = "Pro Pong 2016"
}
};
var denormalized = developers.Join(
inner: projects,
outerKeySelector: dev => dev.Id,
innerKeySelector: proj => proj.DeveloperId,
resultSelector:
(dev, proj) => new {
ProjectName = proj.Name,
DeveloperName = dev.Name});
foreach(var item in denormalized)
{
Console.WriteLine("{0} by {1}", item.ProjectName, item.DeveloperName);
}
//Hello World 3D by Foobuzz
//Super Fizzbuzz Maker by Foobuzz
//Citizen Kane - The action game by Barfizz
//Pro Pong 2016 by Barfizz
Section 8.49: Left Outer Join
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Pet
{
public string Name { get; set; }
public Person Owner { get; set; }
}
public static void Main(string[] args)
{
var magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
var terry = new Person { FirstName = "Terry", LastName = "Adams" };
var barley = new Pet { Name = "Barley", Owner = terry };
var people = new[] { magnus, terry };
var pets = new[] { barley };
GoalKicker.com – .NET Framework Notes for Professionals
44
var query =
from person in people
join pet in pets on person equals pet.Owner into gj
from subpet in gj.DefaultIfEmpty()
select new
{
person.FirstName,
PetName = subpet?.Name ?? "-" // Use - if he has no pet
};
foreach (var p in query)
Console.WriteLine($"{p.FirstName}: {p.PetName}");
}
GoalKicker.com – .NET Framework Notes for Professionals
45
Chapter 9: ForEach
Section 9.1: Extension method for IEnumerable
ForEach() is defined on the List<T> class, but not on IQueryable<T> or IEnumerable<T>. You have two choices in
those cases:
ToList first
The enumeration (or query) will be evaluated, copying the results into a new list or calling the database. The
method is then called on each item.
IEnumerable<Customer> customers = new List<Customer>();
customers.ToList().ForEach(c => c.SendEmail());
This method has obvious memory usage overhead, as an intermediate list is created.
Extension method
Write an extension method:
public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
foreach(T item in enumeration)
{
action(item);
}
}
Use:
IEnumerable<Customer> customers = new List<Customer>();
customers.ForEach(c => c.SendEmail());
Caution: The Framework's LINQ methods have been designed with the intention of being pure, which means they
do not produce side effects. The ForEach method's only purpose is to produce side effects, and deviates from the
other methods in this aspect. You may consider just using a plain foreach loop instead.
Section 9.2: Calling a method on an object in a list
public class Customer {
public void SendEmail()
{
// Sending email code here
}
}
List<Customer> customers = new List<Customer>();
customers.Add(new Customer());
customers.Add(new Customer());
customers.ForEach(c => c.SendEmail());
GoalKicker.com – .NET Framework Notes for Professionals
46
Chapter 10: Reflection
Section 10.1: What is an Assembly?
Assemblies are the building block of any Common Language Runtime (CLR) application. Every type you define,
together with its methods, properties and their bytecode, is compiled and packaged inside an Assembly.
using System.Reflection;
Assembly assembly = this.GetType().Assembly;
Assemblies are self-documenting: they do not only contain types, methods and their IL code, but also the Metadata
necessary to inspect and consume them, both at compile and runtime:
Assembly assembly = Assembly.GetExecutingAssembly();
foreach (var type in assembly.GetTypes())
{
Console.WriteLine(type.FullName);
}
Assemblies have names which describes their full, unique identity:
Console.WriteLine(typeof(int).Assembly.FullName);
// Will print: "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
If this name includes a PublicKeyToken, it is called a strong name. Strong-naming an assembly is the process of
creating a signature by using the private key that corresponds to the public key distributed with the assembly. This
signature is added to the Assembly manifest, which contains the names and hashes of all the files that make up the
assembly, and its PublicKeyToken becomes part of the name. Assemblies that have the same strong name should
be identical; strong names are used in versioning and to prevent assembly conflicts.
Section 10.2: Compare two objects with reflection
public class Equatable
{
public string field1;
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
var type = obj.GetType();
if (GetType() != type)
return false;
var fields = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
foreach (var field in fields)
if (field.GetValue(this) != field.GetValue(obj))
return false;
return true;
}
GoalKicker.com – .NET Framework Notes for Professionals
47
public override int GetHashCode()
{
var accumulator = 0;
var fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
foreach (var field in fields)
accumulator = unchecked ((accumulator * 937) ^ field.GetValue(this).GetHashCode());
return accumulator;
}
}
Note: this example do a field based comparasion (ignore static fields and properties) for simplicity
Section 10.3: Creating Object and setting properties using
reflection
Lets say we have a class Classy that has property Propertua
public class Classy
{
public string Propertua {get; set;}
}
to set Propertua using reflection:
var typeOfClassy = typeof (Classy);
var classy = new Classy();
var prop = typeOfClassy.GetProperty("Propertua");
prop.SetValue(classy, "Value");
Section 10.4: How to create an object of T using Reflection
Using the default constructor
T variable = Activator.CreateInstance(typeof(T));
Using parameterized constructor
T variable = Activator.CreateInstance(typeof(T), arg1, arg2);
Section 10.5: Getting an attribute of an enum with reflection
(and caching it)
Attributes can be useful for denoting metadata on enums. Getting the value of this can be slow, so it is important to
cache results.
private static Dictionary<object, object> attributeCache = new Dictionary<object, object>();
public static T GetAttribute<T, V>(this V value)
where T : Attribute
where V : struct
{
object temp;
// Try to get the value from the static cache.
GoalKicker.com – .NET Framework Notes for Professionals
48
if (attributeCache.TryGetValue(value, out temp))
{
return (T) temp;
}
else
{
// Get the type of the struct passed in.
Type type = value.GetType();
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the custom attributes of the type desired found on the struct.
T[] attribs = (T[])fieldInfo.GetCustomAttributes(typeof(T), false);
// Return the first if there was a match.
var result = attribs.Length > 0 ? attribs[0] : null;
// Cache the result so future checks won't need reflection.
attributeCache.Add(value, result);
return result;
}
}
GoalKicker.com – .NET Framework Notes for Professionals
49
Chapter 11: Expression Trees
Section 11.1: building a predicate of form field == value
To build up an expression like _ => _.Field == "VALUE" at runtime.
Given a predicate _ => _.Field and a string value "VALUE", create an expression that tests whether or not the
predicate is true.
The expression is suitable for:
IQueryable<T>, IEnumerable<T> to test the predicate.
entity framework or Linq to SQL to create a Where clause that tests the predicate.
This method will build an appropriate Equal expression that tests whether or not Field equals "VALUE".
public static Expression<Func<T, bool>> BuildEqualPredicate<T>(
Expression<Func<T, string>> memberAccessor,
string term)
{
var toString = Expression.Convert(Expression.Constant(term), typeof(string));
Expression expression = Expression.Equal(memberAccessor.Body, toString);
var predicate = Expression.Lambda<Func<T, bool>>(
expression,
memberAccessor.Parameters);
return predicate;
}
The predicate can be used by including the predicate in a Where extension method.
var predicate = PredicateExtensions.BuildEqualPredicate<Entity>(
_ => _.Field,
"VALUE");
var results = context.Entity.Where(predicate).ToList();
Section 11.2: Simple Expression Tree Generated by the C#
Compiler
Consider the following C# code
Expression<Func<int, int>> expression = a => a + 1;
Because the C# compiler sees that the lambda expression is assigned to an Expression type rather than a delegate
type it generates an expression tree roughly equivalent to this code
ParameterExpression parameterA = Expression.Parameter(typeof(int), "a");
var expression = (Expression<Func<int, int>>)Expression.Lambda(
Expression.Add(
parameterA,
Expression.Constant(1)),
parameterA);
The root of the tree is the lambda expression which contains a body and a list of parameters. The lambda has 1
parameter called "a". The body is a single expression of CLR type BinaryExpression and NodeType of Add. This
expression represents addition. It has two subexpressions denoted as Left and Right. Left is the
GoalKicker.com – .NET Framework Notes for Professionals
50
ParameterExpression for the parameter "a" and Right is a ConstantExpression with the value 1.
The simplest usage of this expression is printing it:
Console.WriteLine(expression); //prints a => (a + 1)
Which prints the equivalent C# code.
The expression tree can be compiled into a C# delegate and executed by the CLR
Func<int, int> lambda = expression.Compile();
Console.WriteLine(lambda(2)); //prints 3
Usually expressions are translated to other languages like SQL, but can be also used to invoke private, protected
and internal members of public or non-public types as alternative to Reflection.
Section 11.3: Expression for retrieving a static field
Having example type like this:
public TestClass
{
public static string StaticPublicField = "StaticPublicFieldValue";
}
We can retrieve value of StaticPublicField:
var fieldExpr = Expression.Field(null, typeof(TestClass), "StaticPublicField");
var labmda = Expression.Lambda<Func<string>>(fieldExpr);
It can be then i.e. compiled into a delegate for retrieving field value.
Func<string> retriever = lambda.Compile();
var fieldValue = retriever();
//fieldValue result is StaticPublicFieldValue
Section 11.4: InvocationExpression Class
InvocationExpression class allows invocation of other lambda expressions that are parts of the same Expression
tree.
You create them with static Expression.Invoke method.
Problem We want to get on the items which have "car" in their description. We need to check it for null before
searching for a string inside but we don't want it to be called excessively, as the computation could be expensive.
using System;
using System.Linq;
using System.Linq.Expressions;
public class Program
{
public static void Main()
{
var elements = new[] {
GoalKicker.com – .NET Framework Notes for Professionals
51
new Element { Description = "car" },
new Element { Description = "cargo" },
new Element { Description = "wheel" },
new Element { Description = null },
new Element { Description = "Madagascar" },
};
var elementIsInterestingExpression = CreateSearchPredicate(
searchTerm: "car",
whereToSearch: (Element e) => e.Description);
Console.WriteLine(elementIsInterestingExpression.ToString());
var elementIsInteresting = elementIsInterestingExpression.Compile();
var interestingElements = elements.Where(elementIsInteresting);
foreach (var e in interestingElements)
{
Console.WriteLine(e.Description);
}
var countExpensiveComputations = 0;
Action incCount = () => countExpensiveComputations++;
elements
.Where(
CreateSearchPredicate(
"car",
(Element e) => ExpensivelyComputed(
e, incCount
)
).Compile()
)
.Count();
Console.WriteLine("Property extractor is called {0} times.", countExpensiveComputations);
}
private class Element
{
public string Description { get; set; }
}
private static string ExpensivelyComputed(Element source, Action count)
{
count();
return source.Description;
}
private static Expression<Func<T, bool>> CreateSearchPredicate<T>(
string searchTerm,
Expression<Func<T, string>> whereToSearch)
{
var extracted = Expression.Parameter(typeof(string), "extracted");
Expression<Func<string, bool>> coalesceNullCheckWithSearch =
Expression.Lambda<Func<string, bool>>(
Expression.AndAlso(
Expression.Not(
Expression.Call(typeof(string), "IsNullOrEmpty", null, extracted)
),
Expression.Call(extracted, "Contains", null, Expression.Constant(searchTerm))
),
extracted);
GoalKicker.com – .NET Framework Notes for Professionals
52
var elementParameter = Expression.Parameter(typeof(T), "element");
return Expression.Lambda<Func<T, bool>>(
Expression.Invoke(
coalesceNullCheckWithSearch,
Expression.Invoke(whereToSearch, elementParameter)
),
elementParameter
);
}
}
Output
element => Invoke(extracted => (Not(IsNullOrEmpty(extracted)) AndAlso extracted.Contains("car")),
Invoke(e => e.Description, element))
car
cargo
Madagascar
Predicate is called 5 times.
First thing to note is how the actual propery access, wrapped in an Invoke:
Invoke(e => e.Description, element)
, and this is the only part that touches e.Description, and in place of it, extracted parameter of type string is
passed to the next one:
(Not(IsNullOrEmpty(extracted)) AndAlso extracted.Contains("car"))
Another important thing to note here is AndAlso. It computes only the left part, if the first part returns 'false'. It's a
common mistake to use the bitwise operator 'And' instead of it, which always computes both parts, and would fail
with a NullReferenceException in this example.
GoalKicker.com – .NET Framework Notes for Professionals
53
Chapter 12: Custom Types
Section 12.1: Struct Definition
Structs inherit from System.ValueType, are value types, and live on the stack. When value types are passed
as a parameter, they are passed by value.
Struct MyStruct
{
public int x;
public int y;
}
Passed by value means that the value of the parameter is copied for the method, and any changes made to the
parameter in the method are not reflected outside of the method. For instance, consider the following code, which
calls a method named AddNumbers, passing in the variables a and b, which are of type int, which is a Value type.
int a = 5;
int b = 6;
AddNumbers(a,b);
public AddNumbers(int x, int y)
{
int z = x + y; // z becomes 11
x = x + 5; // now we changed x to be 10
z = x + y; // now z becomes 16
}
Even though we added 5 to x inside the method, the value of a remains unchanged, because it's a Value type, and
that means x was a copy of a's value, but not actually a.
Remember, Value types live on the stack, and are passed by value.
Section 12.2: Class Definition
Classes inherit from System.Object, are reference types, and live on the heap. When reference types are
passed as a parameter, they are passed by reference.
public Class MyClass
{
public int a;
public int b;
}
Passed by reference means that a reference to the parameter is passed to the method, and any changes to the
parameter will be reflected outside of the method when it returns, because the reference is to the exact same object
in memory. Let's use the same example as before, but we'll "wrap" the ints in a class first.
MyClass instanceOfMyClass = new MyClass();
instanceOfMyClass.a = 5;
instanceOfMyClass.b = 6;
AddNumbers(instanceOfMyClass);
public AddNumbers(MyClass sample)
{
GoalKicker.com – .NET Framework Notes for Professionals
54
int z = sample.a + sample.b; // z becomes 11
sample.a = sample.a + 5; // now we changed a to be 10
z = sample.a + sample.b; // now z becomes 16
}
This time, when we changed sample.a to 10, the value of instanceOfMyClass.a also changes, because it was passed
by reference. Passed by reference means that a reference (also sometimes called a pointer) to the object was passed
into the method, instead of a copy of the object itself.
Remember, Reference types live on the heap, and are passed by reference.
GoalKicker.com – .NET Framework Notes for Professionals
55
Chapter 13: Code Contracts
Section 13.1: Contracts for Interfaces
Using Code Contracts it is possible to apply a contract to an interface. This is done by declaring an abstract class
that implments the interfaces. The interface should be tagged with the ContractClassAttribute and the contract
definition (the abstract class) should be tagged with the ContractClassForAttribute
C# Example...
[ContractClass(typeof(MyInterfaceContract))]
public interface IMyInterface
{
string DoWork(string input);
}
//Never inherit from this contract defintion class
[ContractClassFor(typeof(IMyInterface))]
internal abstract class MyInterfaceContract : IMyInterface
{
private MyInterfaceContract() { }
public string DoWork(string input)
{
Contract.Requires(!string.IsNullOrEmpty(input));
Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
throw new NotSupportedException();
}
}
public class MyInterfaceImplmentation : IMyInterface
{
public string DoWork(string input)
{
return input;
}
}
Static Analysis Result...
Section 13.2: Installing and Enabling Code Contracts
While System.Diagnostics.Contracts is included within the .Net Framework. To use Code Contracts you must
install the Visual Studio extensions.
Under Extensions and Updates search for Code Contracts then install the Code Contracts Tools
GoalKicker.com – .NET Framework Notes for Professionals
56
After the tools are installed you must enable Code Contracts within your Project solution. At the minimum you
probably want to enable the Static Checking (check after build). If you are implementing a library that will be used
by other solutions you may want to consider also enabling Runtime Checking.
GoalKicker.com – .NET Framework Notes for Professionals
57
Section 13.3: Preconditions
Preconditions allows methods to provide minimum required values for input parameters
Example...
void DoWork(string input)
{
Contract.Requires(!string.IsNullOrEmpty(input));
//do work
}
GoalKicker.com – .NET Framework Notes for Professionals
58
Static Analysis Result...
Section 13.4: Postconditions
Postconditions ensure that the returned results from a method will match the provided definition. This provides the
caller with a definition of the expected result. Postconditions may allowed for simplied implmentations as some
possible outcomes can be provided by the static analyizer.
Example...
string GetValue()
{
Contract.Ensures(Contract.Result<string>() != null);
return null;
}
Static Analyis Result...
GoalKicker.com – .NET Framework Notes for Professionals
59
Chapter 14: Settings
Section 14.1: AppSettings from ConfigurationSettings in .NET
1.x
Deprecated usage
The ConfigurationSettings class was the original way to retrieve settings for an assembly in .NET 1.0 and 1.1. It has
been superseded by the ConfigurationManager class and the WebConfigurationManager class.
If you have two keys with the same name in the appSettings section of the configuration file, the last one is used.
app.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="keyName" value="anything, as a string"/>
<add key="keyNames" value="123"/>
<add key="keyNames" value="234"/>
</appSettings>
</configuration>
Program.cs
using System;
using System.Configuration;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
string keyValue = ConfigurationSettings.AppSettings["keyName"];
Debug.Assert("anything, as a string".Equals(keyValue));
string twoKeys = ConfigurationSettings.AppSettings["keyNames"];
Debug.Assert("234".Equals(twoKeys));
Console.ReadKey();
}
}
}
Section 14.2: Reading AppSettings from
ConfigurationManager in .NET 2.0 and later
The ConfigurationManager class supports the AppSettings property, which allows you to continue reading settings
from the appSettings section of a configuration file the same way as .NET 1.x supported.
app.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
GoalKicker.com – .NET Framework Notes for Professionals
60
<appSettings>
<add key="keyName" value="anything, as a string"/>
<add key="keyNames" value="123"/>
<add key="keyNames" value="234"/>
</appSettings>
</configuration>
Program.cs
using System;
using System.Configuration;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
string keyValue = ConfigurationManager.AppSettings["keyName"];
Debug.Assert("anything, as a string".Equals(keyValue));
var twoKeys = ConfigurationManager.AppSettings["keyNames"];
Debug.Assert("234".Equals(twoKeys));
Console.ReadKey();
}
}
}
Section 14.3: Introduction to strongly-typed application and
user settings support from Visual Studio
Visual Studio helps manage user and application settings. Using this approach has these benefits over using the
appSettings section of the configuration file.
1.
Settings can be made strongly typed. Any type which can be serialized can be used for a settings value.
2.
Application settings can be easily separated from user settings. Application settings are stored in a single
configuration file: web.config for Web sites and Web applications, and app.config, renamed as
assembly.exe.config, where assembly is the name of the executable. User settings (not used by Web projects)
are stored in a user.config file in the user's Application Data folder (which varies with the operating system
version).
3.
Application settings from class libraries can be combined into a single configuration file without risk of name
collisions, since each class library can have its own custom settings section.
In most project types, the Project Properties Designer has a Settings tab which is the starting point for creating
custom application and user settings. Initially, the Settings tab will be blank, with a single link to create a default
settings file. Clicking the link results in these changes:
1.
If a configuration file (app.config or web.config) does not exist for the project, one will be created.
2.
The Settings tab will be replaced with a grid control which enables you to create, edit, and delete individual
settings entries.
3.
In Solution Explorer, a Settings.settings item is added under the Properties special folder. Opening this
GoalKicker.com – .NET Framework Notes for Professionals
61
item will open the Settings tab.
4.
A new file with a new partial class is added under the Properties folder in the project folder. This new file is
named Settings.Designer.__ (.cs, .vb, etc.), and the class is named Settings. The class is code-generated,
so it should not be edited, but the class is a partial class, so you can extend the class by putting additional
members in a separate file. Furthermore, the class is implemented using the Singleton Pattern, exposing the
singleton instance with the property named Default.
As you add each new entry to the Settings tab, Visual Studio does these two things:
1.
Saves the setting in the configuration file, in a custom configuration section designed to be managed by the
Settings class.
2.
Creates a new member in the Settings class to read, write, and present the setting in the specific type
selected from the Settings tab.
Section 14.4: Reading strongly-typed settings from custom
section of configuration file
Starting from a new Settings class and custom configuration section:
Add an application setting named ExampleTimeout, using the time System.Timespan, and set the value to 1 minute:
Save the Project Properties, which saves the Settings tab entries, as well as re-generates the custom Settings class
and updates the project configuration file.
Use the setting from code (C#):
Program.cs
GoalKicker.com – .NET Framework Notes for Professionals
62
using System;
using System.Diagnostics;
using ConsoleApplication1.Properties;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
TimeSpan exampleTimeout = Settings.Default.ExampleTimeout;
Debug.Assert(TimeSpan.FromMinutes(1).Equals(exampleTimeout));
Console.ReadKey();
}
}
}
Under the covers
Look in the project configuration file to see how the application setting entry has been created:
app.config (Visual Studio updates this automatically)
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup,
System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="ConsoleApplication1.Properties.Settings"
type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<appSettings />
<applicationSettings>
<ConsoleApplication1.Properties.Settings>
<setting name="ExampleTimeout" serializeAs="String">
<value>00:01:00</value>
</setting>
</ConsoleApplication1.Properties.Settings>
</applicationSettings>
</configuration>
Notice that the appSettings section is not used. The applicationSettings section contains a custom namespace-
qualified section that has a setting element for each entry. The type of the value is not stored in the configuration
file; it is only known by the Settings class.
Look in the Settings class to see how it uses the ConfigurationManager class to read this custom section.
Settings.designer.cs (for C# projects)
...
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("00:01:00")]
public global::System.TimeSpan ExampleTimeout {
get {
return ((global::System.TimeSpan)(this["ExampleTimeout"]));
GoalKicker.com – .NET Framework Notes for Professionals
63
}
}
...
Notice that a DefaultSettingValueAttribute was created to stored the value entered in the Settings tab of the
Project Properties Designer. If the entry is missing from the configuration file, this default value is used instead.
GoalKicker.com – .NET Framework Notes for Professionals
64
Chapter 15: Regular Expressions
(System.Text.RegularExpressions)
Section 15.1: Check if pattern matches input
public bool Check()
{
string input = "Hello World!";
string pattern = @"H.ll. W.rld!";
// true
return Regex.IsMatch(input, pattern);
}
Section 15.2: Remove non alphanumeric characters from
string
public string Remove()
{
string input = "Hello./!";
return Regex.Replace(input, "[^a-zA-Z0-9]", "");
}
Section 15.3: Passing Options
public bool Check()
{
string input = "Hello World!";
string pattern = @"H.ll. W.rld!";
// true
return Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
}
Section 15.4: Match into groups
public string Check()
{
string input = "Hello World!";
string pattern = @"H.ll. (?<Subject>W.rld)!";
Match match = Regex.Match(input, pattern);
// World
return match.Groups["Subject"].Value;
}
Section 15.5: Find all matches
Using
using System.Text.RegularExpressions;
Code
GoalKicker.com – .NET Framework Notes for Professionals
65
static void Main(string[] args)
{
string input = "Carrot Banana Apple Cherry Clementine Grape";
// Find words that start with uppercase 'C'
string pattern = @"\bC\w*\b";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match m in matches)
Console.WriteLine(m.Value);
}
Output
Carrot
Cherry
Clementine
Section 15.6: Simple match and replace
public string Check()
{
string input = "Hello World!";
string pattern = @"W.rld";
// Hello Stack Overflow!
return Regex.Replace(input, pattern, "Stack Overflow");
}
GoalKicker.com – .NET Framework Notes for Professionals
66
Chapter 16: File Input/Output
Parameter
string path Path of the file to check. (relative or fully qualified)
Details
Section 16.1: C# File.Exists()
using System;
using System.IO;
public class Program
{
public static void Main()
{
string filePath = "somePath";
if(File.Exists(filePath))
{
Console.WriteLine("Exists");
}
else
{
Console.WriteLine("Does not exist");
}
}
}
Can also be used in a ternary operator.
Console.WriteLine(File.Exists(pathToFile) ? "Exists" : "Does not exist");
Section 16.2: VB WriteAllText
Imports System.IO
Dim filename As String = "c:\path\to\file.txt"
File.WriteAllText(filename, "Text to write" & vbCrLf)
Section 16.3: VB StreamWriter
Dim filename As String = "c:\path\to\file.txt"
If System.IO.File.Exists(filename) Then
Dim writer As New System.IO.StreamWriter(filename)
writer.Write("Text to write" & vbCrLf) 'Add a newline
writer.close()
End If
Section 16.4: C# StreamWriter
using System.Text;
using System.IO;
string filename = "c:\path\to\file.txt";
//'using' structure allows for proper disposal of stream.
using (StreamWriter writer = new StreamWriter(filename"))
GoalKicker.com – .NET Framework Notes for Professionals
67
{
writer.WriteLine("Text to Write\n");
}
Section 16.5: C# WriteAllText()
using System.IO;
using System.Text;
string filename = "c:\path\to\file.txt";
File.writeAllText(filename, "Text to write\n");
GoalKicker.com – .NET Framework Notes for Professionals
68
Chapter 17: System.IO
Section 17.1: Reading a text file using StreamReader
string fullOrRelativePath = "testfile.txt";
string fileData;
using (var reader = new StreamReader(fullOrRelativePath))
{
fileData = reader.ReadToEnd();
}
Note that this StreamReader constructor overload does some auto encoding detection, which may or may not
conform to the actual encoding used in the file.
Please note that there are some convenience methods that read all text from file available on the System.IO.File
class, namely File.ReadAllText(path) and File.ReadAllLines(path).
Section 17.2: Serial Ports using System.IO.SerialPorts
Iterating over connected serial ports
using System.IO.Ports;
string[] ports = SerialPort.GetPortNames();
for (int i = 0; i < ports.Length; i++)
{
Console.WriteLine(ports[i]);
}
Instantiating a System.IO.SerialPort object
using System.IO.Ports;
SerialPort port = new SerialPort();
SerialPort port = new SerialPort("COM 1"); ;
SerialPort port = new SerialPort("COM 1", 9600);
NOTE: Those are just three of the seven overloads of the constructor for the SerialPort type.
Reading/Writing data over the SerialPort
The simplest way is to use the SerialPort.Read and SerialPort.Write methods. However you can also retrieve a
System.IO.Stream object which you can use to stream data over the SerialPort. To do this, use
SerialPort.BaseStream.
Reading
int length = port.BytesToRead;
//Note that you can swap out a byte-array for a char-array if you prefer.
byte[] buffer = new byte[length];
port.Read(buffer, 0, length);
You can also read all data available:
string curData = port.ReadExisting();
GoalKicker.com – .NET Framework Notes for Professionals
69
Or simply read to the first newline encountered in the incoming data:
string line = port.ReadLine();
Writing
The easiest way to write data over the SerialPort is:
port.Write("here is some text to be sent over the serial port.");
However you can also send data over like this when needed:
//Note that you can swap out the byte-array with a char-array if you so choose.
byte[] data = new byte[1] { 255 };
port.Write(data, 0, data.Length);
Section 17.3: Reading/Writing Data Using System.IO.File
First, let's see three different ways of extracting data from a file.
string fileText = File.ReadAllText(file);
string[] fileLines = File.ReadAllLines(file);
byte[] fileBytes = File.ReadAllBytes(file);
On the first line, we read all the data in the file as a string.
On the second line, we read the data in the file into a string-array. Each line in the file becomes an element in
the array.
On the third we read the bytes from the file.
Next, let's see three different methods of appending data to a file. If the file you specify doesn't exist, each method
will automatically create the file before attempting to append the data to it.
File.AppendAllText(file, "Here is some data that is\nappended to the file.");
File.AppendAllLines(file, new string[2] { "Here is some data that is", "appended to the file." });
using (StreamWriter stream = File.AppendText(file))
{
stream.WriteLine("Here is some data that is");
stream.Write("appended to the file.");
}
On the first line we simply add a string to the end of the specified file.
On the second line we add each element of the array onto a new line in the file.
Finally on the third line we use File.AppendText to open up a streamwriter which will append whatever data
is written to it.
And lastly, let's see three different methods of writing data to a file. The difference between appending and writing
being that writing over-writes the data in the file while appending adds to the data in the file. If the file you specify
doesn't exist, each method will automatically create the file before attempting to write the data to it.
File.WriteAllText(file, "here is some data\nin this file.");
File.WriteAllLines(file, new string[2] { "here is some data", "in this file" });
File.WriteAllBytes(file, new byte[2] { 0, 255 });
The first line writes a string to the file.
The second line writes each string in the array on it's own line in the file.
GoalKicker.com – .NET Framework Notes for Professionals
70
And the third line allows you to write a byte array to the file.
GoalKicker.com – .NET Framework Notes for Professionals
71
Chapter 18: System.IO.File class
Parameter
source
The file that is to be moved to another location.
Details
destination
The directory in which you would like to move source to (this variable should also contain the name
(and file extension) of the file.
Section 18.1: Delete a file
To delete a file (if you have required permissions) is as simple as:
File.Delete(path);
However many things may go wrong:
You do not have required permissions (UnauthorizedAccessException is thrown).
File may be in use by someone else (IOException is thrown).
File cannot be deleted because of low level error or media is read-only (IOException is thrown).
File does not exist anymore (IOException is thrown).
Note that last point (file does not exist) is usually circumvented with a code snippet like this:
if (File.Exists(path))
File.Delete(path);
However it's not an atomic operation and file may be delete by someone else between the call to File.Exists()
and before File.Delete(). Right approach to handle I/O operation requires exception handling (assuming an
alternative course of actions may be taken when operation fails):
if (File.Exists(path))
{
try
{
File.Delete(path);
}
catch (IOException exception)
{
if (!File.Exists(path))
return; // Someone else deleted this file
// Something went wrong...
}
catch (UnauthorizedAccessException exception)
{
// I do not have required permissions
}
}
Note that this I/O errors sometimes are transitory (file in use, for example) and if a network connection is involved
then it may automatically recover without any action from our side. It's then common to retry an I/O operation few
times with a small delay between each attempt:
public static void Delete(string path)
{
if (!File.Exists(path))
GoalKicker.com – .NET Framework Notes for Professionals
72
return;
for (int i=1; ; ++i)
{
try
{
File.Delete(path);
return;
}
catch (IOException e)
{
if (!File.Exists(path))
return;
if (i == NumberOfAttempts)
throw;
Thread.Sleep(DelayBetweenEachAttempt);
}
// You may handle UnauthorizedAccessException but this issue
// will probably won't be fixed in few seconds...
}
}
private const int NumberOfAttempts = 3;
private const int DelayBetweenEachAttempt = 1000; // ms
Note: in Windows environment file will not be really deleted when you call this function, if someone else open the
file using FileShare.Delete then file can be deleted but it will effectively happen only when owner will close the
file.
Section 18.2: Strip unwanted lines from a text file
To change a text file is not easy because its content must be moved around. For small files easiest method is to
read its content in memory and then write back modified text.
In this example we read all lines from a file and drop all blank lines then we write back to original path:
File.WriteAllLines(path,
File.ReadAllLines(path).Where(x => !String.IsNullOrWhiteSpace(x)));
If file is too big to load it in memory and output path is different from input path:
File.WriteAllLines(outputPath,
File.ReadLines(inputPath).Where(x => !String.IsNullOrWhiteSpace(x)));
Section 18.3: Convert text file encoding
Text is saved encoded (see also Strings topic) then sometimes you may need to change its encoding, this example
assumes (for simplicity) that file is not too big and it can be entirely read in memory:
public static void ConvertEncoding(string path, Encoding from, Encoding to)
{
File.WriteAllText(path, File.ReadAllText(path, from), to);
}
GoalKicker.com – .NET Framework Notes for Professionals
73
When performing conversions do not forget that file may contain BOM (Byte Order Mark), to better understand
how it's managed refer to Encoding.UTF8.GetString doesn't take into account the Preamble/BOM.
Section 18.4: Enumerate files older than a specified amount
This snippet is an helper function to enumerate all files older than a specified age, it's useful - for example - when
you have to delete old log files or old cached data.
static IEnumerable<string> EnumerateAllFilesOlderThan(
TimeSpan maximumAge,
string path,
string searchPattern = "*.*",
SearchOption options = SearchOption.TopDirectoryOnly)
{
DateTime oldestWriteTime = DateTime.Now - maximumAge;
return Directory.EnumerateFiles(path, searchPattern, options)
.Where(x => Directory.GetLastWriteTime(x) < oldestWriteTime);
}
Used like this:
var oldFiles = EnumerateAllFilesOlderThan(TimeSpan.FromDays(7), @"c:\log", "*.log");
Few things to note:
Search is performed using Directory.EnumerateFiles() instead of Directory.GetFiles(). Enumeration is
alive then you won't need to wait until all file system entries have been fetched.
We're checking for last write time but you may use creation time or last access time (for example to delete
unused cached files, note that access time may be disabled).
Granularity isn't uniform for all those properties (write time, access time, creation time), check MSDN for
details about this.
Section 18.5: Move a File from one location to another
File.Move
In order to move a file from one location to another, one simple line of code can achieve this:
File.Move(@"C:\TemporaryFile.txt", @"C:\TemporaryFiles\TemporaryFile.txt");
However, there are many things that could go wrong with this simple operation. For instance, what if the user
running your program does not have a Drive that is labelled 'C'? What if they did - but they decided to rename it to
'B', or 'M'?
What if the Source file (the file in which you would like to move) has been moved without your knowing - or what if
it simply doesn't exist.
This can be circumvented by first checking to see whether the source file does exist:
string source = @"C:\TemporaryFile.txt", destination = @"C:\TemporaryFiles\TemporaryFile.txt";
if(File.Exists("C:\TemporaryFile.txt"))
{
File.Move(source, destination);
}
This will ensure that at that very moment, the file does exist, and can be moved to another location. There may be
GoalKicker.com – .NET Framework Notes for Professionals
74
times where a simple call to File.Exists won't be enough. If it isn't, check again, convey to the user that the
operation failed - or handle the exception.
A FileNotFoundException is not the only exception you are likely to encounter.
See below for possible exceptions:
Exception Type
Description
IOException
The file already exists or the source file could not be found.
ArgumentNullException
The value of the Source and/or Destination parameters is null.
ArgumentException
The value of the Source and/or Destination parameters are empty, or contain
invalid characters.
UnauthorizedAccessException You do not have the required permissions in order to perform this action.
PathTooLongException
The Source, Destination or specified path(s) exceed the maximum length. On
Windows, a Path's length must be less than 248 characters, while File names must
be less than 260 characters.
DirectoryNotFoundException The specified directory could not be found.
NotSupportedException
The Source or Destination paths or file names are in an invalid format.
GoalKicker.com – .NET Framework Notes for Professionals
75
Chapter 19: Reading and writing Zip files
The ZipFile class lives in the System.IO.Compression namespace. It can be used to read from, and write to Zip
files.
Section 19.1: Listing ZIP contents
This snippet will list all the filenames of a zip archive. The filenames are relative to the zip root.
using (FileStream fs = new FileStream("archive.zip", FileMode.Open))
using (ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Read))
{
for (int i = 0; i < archive.Entries.Count; i++)
{
Console.WriteLine($"{i}: {archive.Entries[i]}");
}
}
Section 19.2: Extracting files from ZIP files
Extracting all the files into a directory is very easy:
using (FileStream fs = new FileStream("archive.zip", FileMode.Open))
using (ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Read))
{
archive.ExtractToDirectory(AppDomain.CurrentDomain.BaseDirectory);
}
When the file already exists, a System.IO.IOException will be thrown.
Extracting specific files:
using (FileStream fs = new FileStream("archive.zip", FileMode.Open))
using (ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Read))
{
// Get a root entry file
archive.GetEntry("test.txt").ExtractToFile("test_extracted_getentries.txt", true);
// Enter a path if you want to extract files from a subdirectory
archive.GetEntry("sub/subtest.txt").ExtractToFile("test_sub.txt", true);
// You can also use the Entries property to find files
archive.Entries.FirstOrDefault(f => f.Name ==
"test.txt")?.ExtractToFile("test_extracted_linq.txt", true);
// This will throw a System.ArgumentNullException because the file cannot be found
archive.GetEntry("nonexistingfile.txt").ExtractToFile("fail.txt", true);
}
Any of these methods will produce the same result.
Section 19.3: Updating a ZIP file
To update a ZIP file, the file has to be opened with ZipArchiveMode.Update instead.
using (FileStream fs = new FileStream("archive.zip", FileMode.Open))
GoalKicker.com – .NET Framework Notes for Professionals
76
using (ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Update))
{
// Add file to root
archive.CreateEntryFromFile("test.txt", "test.txt");
// Add file to subfolder
archive.CreateEntryFromFile("test.txt", "symbols/test.txt");
}
There is also the option to write directly to a file within the archive:
var entry = archive.CreateEntry("createentry.txt");
using(var writer = new StreamWriter(entry.Open()))
{
writer.WriteLine("Test line");
}
GoalKicker.com – .NET Framework Notes for Professionals
77
Chapter 20: Managed Extensibility
Framework
Section 20.1: Connecting (Basic)
See the other (Basic) examples above.
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
namespace Demo
{
public static class Program
{
public static void Main()
{
using (var catalog = new ApplicationCatalog())
using (var exportProvider = new CatalogExportProvider(catalog))
using (var container = new CompositionContainer(exportProvider))
{
exportProvider.SourceProvider = container;
UserWriter writer = new UserWriter();
// at this point, writer's userProvider field is null
container.ComposeParts(writer);
// now, it should be non-null (or an exception will be thrown).
writer.PrintAllUsers();
}
}
}
}
As long as something in the application's assembly search path has [Export(typeof(IUserProvider))],
UserWriter's corresponding import will be satisfied and the users will be printed.
Other types of catalogs (e.g., DirectoryCatalog) can be used instead of (or in addition to) ApplicationCatalog, to
look in other places for exports that satisfy the imports.
Section 20.2: Exporting a Type (Basic)
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
namespace Demo
{
[Export(typeof(IUserProvider))]
public sealed class UserProvider : IUserProvider
{
public ReadOnlyCollection<User> GetAllUsers()
{
return new List<User>
{
new User(0, "admin"),
new User(1, "Dennis"),
GoalKicker.com – .NET Framework Notes for Professionals
78
new User(2, "Samantha"),
}.AsReadOnly();
}
}
}
This could be defined virtually anywhere; all that matters is that the application knows where to look for it (via the
ComposablePartCatalogs it creates).
Section 20.3: Importing (Basic)
using System;
using System.ComponentModel.Composition;
namespace Demo
{
public sealed class UserWriter
{
[Import(typeof(IUserProvider))]
private IUserProvider userProvider;
public void PrintAllUsers()
{
foreach (User user in this.userProvider.GetAllUsers())
{
Console.WriteLine(user);
}
}
}
}
This is a type that has a dependency on an IUserProvider, which could be defined anywhere. Like the previous
example, all that matters is that the application knows where to look for the matching export (via the
ComposablePartCatalogs it creates).
GoalKicker.com – .NET Framework Notes for Professionals
79
Chapter 21: SpeechRecognitionEngine class
to recognize speech
LoadGrammar: Parameters
grammar
Details
The grammar to load. For example, a DictationGrammar object to allow free
text dictation.
RecognizeAsync: Parameters
Details
mode
The RecognizeMode for the current recognition: Single for just one
recognition, Multiple to allow multiple.
GrammarBuilder.Append: Parameters Details
choices
Appends some choices to the grammar builder. This means that, when the
user inputs speech, the recognizer can follow different "branches" from a
grammar.
Choices constructor: Parameters
Details
choices
An array of choices for the grammar builder. See GrammarBuilder.Append.
Grammar constructor: Parameter
Details
builder
The GrammarBuilder to construct a Grammar from.
Section 21.1: Asynchronously recognizing speech based on a
restricted set of phrases
SpeechRecognitionEngine recognitionEngine = new SpeechRecognitionEngine();
GrammarBuilder builder = new GrammarBuilder();
builder.Append(new Choices("I am", "You are", "He is", "She is", "We are", "They are"));
builder.Append(new Choices("friendly", "unfriendly"));
recognitionEngine.LoadGrammar(new Grammar(builder));
recognitionEngine.SpeechRecognized += delegate(object sender, SpeechRecognizedEventArgs e)
{
Console.WriteLine("You said: {0}", e.Result.Text);
};
recognitionEngine.SetInputToDefaultAudioDevice();
recognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
Section 21.2: Asynchronously recognizing speech for free text
dictation
using System.Speech.Recognition;
// ...
SpeechRecognitionEngine recognitionEngine = new SpeechRecognitionEngine();
recognitionEngine.LoadGrammar(new DictationGrammar());
recognitionEngine.SpeechRecognized += delegate(object sender, SpeechRecognizedEventArgs e)
{
Console.WriteLine("You said: {0}", e.Result.Text);
};
recognitionEngine.SetInputToDefaultAudioDevice();
recognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
GoalKicker.com – .NET Framework Notes for Professionals
80
Chapter 22:
System.Runtime.Caching.MemoryCache
(ObjectCache)
Section 22.1: Adding Item to Cache (Set)
Set function inserts a cache entry into the cache by using a CacheItem instance to supply the key and value for the
cache entry.
This function Overrides ObjectCache.Set(CacheItem, CacheItemPolicy)
private static bool SetToCache()
{
string key = "Cache_Key";
string value = "Cache_Value";
//Get a reference to the default MemoryCache instance.
var cacheContainer = MemoryCache.Default;
var policy = new CacheItemPolicy()
{
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(DEFAULT_CACHE_EXPIRATION_MINUTES)
};
var itemToCache = new CacheItem(key, value); //Value is of type object.
cacheContainer.Set(itemToCache, policy);
}
Section 22.2: System.Runtime.Caching.MemoryCache
(ObjectCache)
This function gets existing item form cache, and if the item don't exist in cache, it will fetch item based on the
valueFetchFactory function.
public static TValue GetExistingOrAdd<TValue>(string key, double minutesForExpiration,
Func<TValue> valueFetchFactory)
{
try
{
//The Lazy class provides Lazy initialization which will evaluate
//the valueFetchFactory only if item is not in the cache.
var newValue = new Lazy<TValue>(valueFetchFactory);
//Setup the cache policy if item will be saved back to cache.
CacheItemPolicy policy = new CacheItemPolicy()
{
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutesForExpiration)
};
//returns existing item form cache or add the new value if it does not exist.
var cachedItem = _cacheContainer.AddOrGetExisting(key, newValue, policy) as
Lazy<TValue>;
return (cachedItem ?? newValue).Value;
}
catch (Exception excep)
{
GoalKicker.com – .NET Framework Notes for Professionals
81
return default(TValue);
}
}
GoalKicker.com – .NET Framework Notes for Professionals
82
Chapter 23: System.Reflection.Emit
namespace
Section 23.1: Creating an assembly dynamically
using System;
using System.Reflection;
using System.Reflection.Emit;
class DemoAssemblyBuilder
{
public static void Main()
{
// An assembly consists of one or more modules, each of which
// contains zero or more types. This code creates a single-module
// assembly, the most common case. The module contains one type,
// named "MyDynamicType", that has a private field, a property
// that gets and sets the private field, constructors that
// initialize the private field, and a method that multiplies
// a user-supplied number by the private field value and returns
// the result. In C# the type might look like this:
/*
public class MyDynamicType
{
private int m_number;
public MyDynamicType() : this(42) {}
public MyDynamicType(int initNumber)
{
m_number = initNumber;
}
public int Number
{
get { return m_number; }
set { m_number = value; }
}
public int MyMethod(int multiplier)
{
return m_number * multiplier;
}
}
*/
AssemblyName aName = new AssemblyName("DynamicAssemblyExample");
AssemblyBuilder ab =
AppDomain.CurrentDomain.DefineDynamicAssembly(
aName,
AssemblyBuilderAccess.RunAndSave);
// For a single-module assembly, the module name is usually
// the assembly name plus an extension.
ModuleBuilder mb =
ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");
TypeBuilder tb = mb.DefineType(
"MyDynamicType",
TypeAttributes.Public);
GoalKicker.com – .NET Framework Notes for Professionals
83
// Add a private field of type int (Int32).
FieldBuilder fbNumber = tb.DefineField(
"m_number",
typeof(int),
FieldAttributes.Private);
// Next, we make a simple sealed method.
MethodBuilder mbMyMethod = tb.DefineMethod(
"MyMethod",
MethodAttributes.Public,
typeof(int),
new[] { typeof(int) });
ILGenerator il = mbMyMethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // Load this - always the first argument of any instance method
il.Emit(OpCodes.Ldfld, fbNumber);
il.Emit(OpCodes.Ldarg_1); // Load the integer argument
il.Emit(OpCodes.Mul); // Multiply the two numbers with no overflow checking
il.Emit(OpCodes.Ret); // Return
// Next, we build the property. This involves building the property itself, as well as the
// getter and setter methods.
PropertyBuilder pbNumber = tb.DefineProperty(
"Number", // Name
PropertyAttributes.None,
typeof(int), // Type of the property
new Type[0]); // Types of indices, if any
MethodBuilder mbSetNumber = tb.DefineMethod(
"set_Number", // Name - setters are set_Property by convention
// Setter is a special method and we don't want it to appear to callers from C#
MethodAttributes.PrivateScope | MethodAttributes.HideBySig | MethodAttributes.Public |
MethodAttributes.SpecialName,
typeof(void), // Setters don't return a value
new[] { typeof(int) }); // We have a single argument of type System.Int32
// To generate the body of the method, we'll need an IL generator
il = mbSetNumber.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // Load this
il.Emit(OpCodes.Ldarg_1); // Load the new value
il.Emit(OpCodes.Stfld, fbNumber); // Save the new value to this.m_number
il.Emit(OpCodes.Ret); // Return
// Finally, link the method to the setter of our property
pbNumber.SetSetMethod(mbSetNumber);
MethodBuilder mbGetNumber = tb.DefineMethod(
"get_Number",
MethodAttributes.PrivateScope | MethodAttributes.HideBySig | MethodAttributes.Public |
MethodAttributes.SpecialName,
typeof(int),
new Type[0]);
il = mbGetNumber.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // Load this
il.Emit(OpCodes.Ldfld, fbNumber); // Load the value of this.m_number
il.Emit(OpCodes.Ret); // Return the value
pbNumber.SetGetMethod(mbGetNumber);
// Finally, we add the two constructors.
// Constructor needs to call the constructor of the parent class, or another constructor in
GoalKicker.com – .NET Framework Notes for Professionals
84
the same class
ConstructorBuilder intConstructor = tb.DefineConstructor(
MethodAttributes.Public, CallingConventions.Standard | CallingConventions.HasThis,
new[] { typeof(int) });
il = intConstructor.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // this
il.Emit(OpCodes.Call, typeof(object).GetConstructor(new Type[0])); // call parent's
constructor
il.Emit(OpCodes.Ldarg_0); // this
il.Emit(OpCodes.Ldarg_1); // our int argument
il.Emit(OpCodes.Stfld, fbNumber); // store argument in this.m_number
il.Emit(OpCodes.Ret);
var parameterlessConstructor = tb.DefineConstructor(
MethodAttributes.Public, CallingConventions.Standard | CallingConventions.HasThis, new
Type[0]);
il = parameterlessConstructor.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // this
il.Emit(OpCodes.Ldc_I4_S, (byte)42); // load 42 as an integer constant
il.Emit(OpCodes.Call, intConstructor); // call this(42)
il.Emit(OpCodes.Ret);
// And make sure the type is created
Type ourType = tb.CreateType();
// The types from the assembly can be used directly using reflection, or we can save the
assembly to use as a reference
object ourInstance = Activator.CreateInstance(ourType);
Console.WriteLine(ourType.GetProperty("Number").GetValue(ourInstance)); // 42
// Save the assembly for use elsewhere. This is very useful for debugging - you can use e.g.
ILSpy to look at the equivalent IL/C# code.
ab.Save(@"DynamicAssemblyExample.dll");
// Using newly created type
var myDynamicType = tb.CreateType();
var myDynamicTypeInstance = Activator.CreateInstance(myDynamicType);
Console.WriteLine(myDynamicTypeInstance.GetType()); // MyDynamicType
var numberField = myDynamicType.GetField("m_number", BindingFlags.NonPublic |
BindingFlags.Instance);
numberField.SetValue (myDynamicTypeInstance, 10);
Console.WriteLine(numberField.GetValue(myDynamicTypeInstance)); // 10
}
}
GoalKicker.com – .NET Framework Notes for Professionals
85
Chapter 24: .NET Core
.NET Core is a general purpose development platform maintained by Microsoft and the .NET community on GitHub.
It is cross-platform, supporting Windows, macOS and Linux, and can be used in device, cloud, and embedded/IoT
scenarios.
When you think of .NET Core the following should come to mind (flexible deployment, cross-platform, command-
line tools, open source).
Another great thing is that even if it's open source Microsoft is actively supporting it.
Section 24.1: Basic Console App
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("\nWhat is your name? ");
var name = Console.ReadLine();
var date = DateTime.Now;
Console.WriteLine("\nHello, {0}, on {1:d} at {1:t}", name, date);
Console.Write("\nPress any key to exit...");
Console.ReadKey(true);
}
}
GoalKicker.com – .NET Framework Notes for Professionals
86
Chapter 25: ADO.NET
ADO(ActiveX Data Objects).Net is a tool provided by Microsoft which provides access to data sources such as SQL
Server, Oracle, and XML through its components. .Net front-end applications can retrieve, create, and manipulate
data, once they are connected to a data source through ADO.Net with appropriate privileges.
ADO.Net provides a connection-less architecture. It is a secure approach to interact with a database, since, the
connection doesn't have to be maintained during the entire session.
Section 25.1: Best Practices - Executing Sql Statements
public void SaveNewEmployee(Employee newEmployee)
{
// best practice - wrap all database connections in a using block so they are always closed &
disposed even in the event of an Exception
// best practice - retrieve the connection string by name from the app.config or web.config
(depending on the application type) (note, this requires an assembly reference to
System.configuration)
using(SqlConnection con = new
SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionName"].Conne
ctionString))
{
// best practice - use column names in your INSERT statement so you are not dependent on the
sql schema column order
// best practice - always use parameters to avoid sql injection attacks and errors if
malformed text is used like including a single quote which is the sql equivalent of escaping or
starting a string (varchar/nvarchar)
// best practice - give your parameters meaningful names just like you do variables in your
code
using(SqlCommand sc = new SqlCommand("INSERT INTO employee (FirstName, LastName,
DateOfBirth /*etc*/) VALUES (@firstName, @lastName, @dateOfBirth /*etc*/)", con))
{
// best practice - always specify the database data type of the column you are using
// best practice - check for valid values in your code and/or use a database constraint,
if inserting NULL then use System.DbNull.Value
sc.Parameters.Add(new SqlParameter("@firstName", SqlDbType.VarChar, 200){Value =
newEmployee.FirstName ?? (object) System.DBNull.Value});
sc.Parameters.Add(new SqlParameter("@lastName", SqlDbType.VarChar, 200){Value =
newEmployee.LastName ?? (object) System.DBNull.Value});
// best practice - always use the correct types when specifying your parameters, Value
is assigned to a DateTime instance and not a string representation of a Date
sc.Parameters.Add(new SqlParameter("@dateOfBirth", SqlDbType.Date){ Value =
newEmployee.DateOfBirth });
// best practice - open your connection as late as possible unless you need to verify
that the database connection is valid and won't fail and the proceeding code execution takes a long
time (not the case here)
con.Open();
sc.ExecuteNonQuery();
}
// the end of the using block will close and dispose the SqlConnection
// best practice - end the using block as soon as possible to release the database connection
}
}
// supporting class used as parameter for example
public class Employee
GoalKicker.com – .NET Framework Notes for Professionals
87
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
Best practice for working with ADO.NET
Rule of thumb is to open connection for minimal time. Close the connection explicitly once your procedure
execution is over this will return the connection object back to connection pool. Default connection pool max
size = 100. As connection pooling enhances the performance of physical connection to SQL
Server.Connection Pooling in SQL Server
Wrap all database connections in a using block so they are always closed & disposed even in the event of an
Exception. See using Statement (C# Reference) for more information on using statements
Retrieve the connection strings by name from the app.config or web.config (depending on the application
type)
This requires an assembly reference to System.configuration
See Connection Strings and Configuration Files for additional information on how to structure your
configuration file
Always use parameters for incoming values to
Avoid sql injection attacks
Avoid errors if malformed text is used like including a single quote which is the sql equivalent of
escaping or starting a string (varchar/nvarchar)
Letting the database provider reuse query plans (not supported by all database providers) which
increases efficiency
When working with parameters
Sql parameters type and size mismatch is a common cause of insert/ updated/ select failure
Give your Sql parameters meaningful names just like you do variables in your code
Specify the database data type of the column you are using, this ensures the wrong parameter types is
not used which could lead to unexpected results
Validate your incoming parameters before you pass them into the command (as the saying goes,
"garbage in, garbage out"). Validate incoming values as early as possible in the stack
Use the correct types when assigning your parameter values, example: do not assign the string value
of a DateTime, instead assign an actual DateTime instance to the value of the parameter
Specify the size of string-type parameters. This is because SQL Server can re-use execution plans if the
parameters match in type and size. Use -1 for MAX
Do not use the method AddWithValue, the main reason is it is very easy to forget to specify the
parameter type or the precision/scale when needed. For additional information see Can we stop using
AddWithValue already?
When using database connections
Open the connection as late as possible and close it as soon as possible. This is a general guideline
when working with any external resource
Never share database connection instances (example: having a singleton host a shared instance of
type SqlConnection). Have your code always create a new database connection instance when needed
and then have the calling code dispose of it and "throw it away" when it is done. The reason for this is
Most database providers have some sort of connection pooling so creating new managed
connections is cheap
It eliminates any future errors if the code starts working with multiple threads
Section 25.2: Executing SQL statements as a command
// Uses Windows authentication. Replace the Trusted_Connection parameter with
GoalKicker.com – .NET Framework Notes for Professionals
88
// User Id=...;Password=...; to use SQL Server authentication instead. You may
// want to find the appropriate connection string for your server.
string connectionString =
@"Server=myServer\myInstance;Database=myDataBase;Trusted_Connection=True;"
string sql = "INSERT INTO myTable (myDateTimeField, myIntField) " +
"VALUES (@someDateTime, @someInt);";
// Most ADO.NET objects are disposable and, thus, require the using keyword.
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql, connection))
{
// Use parameters instead of string concatenation to add user-supplied
// values to avoid SQL injection and formatting issues. Explicitly supply datatype.
// System.Data.SqlDbType is an enumeration. See Note1
command.Parameters.Add("@someDateTime", SqlDbType.DateTime).Value = myDateTimeVariable;
command.Parameters.Add("@someInt", SqlDbType.Int).Value = myInt32Variable;
// Execute the SQL statement. Use ExecuteScalar and ExecuteReader instead
// for query that return results (or see the more specific examples, once
// those have been added).
connection.Open();
command.ExecuteNonQuery();
}
Note 1: Please see SqlDbType Enumeration for the MSFT SQL Server-specific variation.
Note 2: Please see MySqlDbType Enumeration for the MySQL-specific variation.
Section 25.3: Using common interfaces to abstract away
vendor specific classes
var providerName = "System.Data.SqlClient"; //Oracle.ManagedDataAccess.Client, IBM.Data.DB2
var connectionString = "{your-connection-string}";
//you will probably get the above two values in the ConnectionStringSettings object from .config file
var factory = DbProviderFactories.GetFactory(providerName);
using(var connection = factory.CreateConnection()) { //IDbConnection
connection.ConnectionString = connectionString;
connection.Open();
using(var command = connection.CreateCommand()) { //IDbCommand
command.CommandText = "{query}";
using(var reader = command.ExecuteReader()) { //IDataReader
while(reader.Read()) {
...
}
}
}
}
GoalKicker.com – .NET Framework Notes for Professionals
89
Chapter 26: Dependency Injection
Section 26.1: How Dependency Injection Makes Unit Testing
Easier
This builds on the previous example of the Greeter class which has two dependencies, IGreetingProvider and
IGreetingWriter.
The actual implementation of IGreetingProvider might retrieve a string from an API call or a database. The
implementation of IGreetingWriter might display the greeting in the console. But because Greeter has its
dependencies injected into its constructor, it's easy to write a unit test that injects mocked versions of those
interfaces. In real life we might use a framework like Moq, but in this case I'll write those mocked implementations.
public class TestGreetingProvider : IGreetingProvider
{
public const string TestGreeting = "Hello!";
public string GetGreeting()
{
return TestGreeting;
}
}
public class TestGreetingWriter : List<string>, IGreetingWriter
{
public void WriteGreeting(string greeting)
{
Add(greeting);
}
}
[TestClass]
public class GreeterTests
{
[TestMethod]
public void Greeter_WritesGreeting()
{
var greetingProvider = new TestGreetingProvider();
var greetingWriter = new TestGreetingWriter();
var greeter = new Greeter(greetingProvider, greetingWriter);
greeter.Greet();
Assert.AreEqual(greetingWriter[0], TestGreetingProvider.TestGreeting);
}
}
The behavior of IGreetingProvider and IGreetingWriter are not relevant to this test. We want to test that
Greeter gets a greeting and writes it. The design of Greeter (using dependency injection) allows us to inject mocked
dependencies without any complicated moving parts. All we're testing is that Greeter interacts with those
dependencies as we expect it to.
Section 26.2: Dependency Injection - Simple example
This class is called Greeter. Its responsibility is to output a greeting. It has two dependencies. It needs something
that will give it the greeting to output, and then it needs a way to output that greeting. Those dependencies are
both described as interfaces, IGreetingProvider and IGreetingWriter. In this example, those two dependencies
are "injected" into Greeter. (Further explanation following the example.)
GoalKicker.com – .NET Framework Notes for Professionals
90
public class Greeter
{
private readonly IGreetingProvider _greetingProvider;
private readonly IGreetingWriter _greetingWriter;
public Greeter(IGreetingProvider greetingProvider, IGreetingWriter greetingWriter)
{
_greetingProvider = greetingProvider;
_greetingWriter = greetingWriter;
}
public void Greet()
{
var greeting = _greetingProvider.GetGreeting();
_greetingWriter.WriteGreeting(greeting);
}
}
public interface IGreetingProvider
{
string GetGreeting();
}
public interface IGreetingWriter
{
void WriteGreeting(string greeting);
}
The Greeting class depends on both IGreetingProvider and IGreetingWriter, but it is not responsible for
creating instances of either. Instead it requires them in its constructor. Whatever creates an instance of Greeting
must provide those two dependencies. We can call that "injecting" the dependencies.
Because dependencies are provided to the class in its constructor, this is also called "constructor injection."
A few common conventions:
The constructor saves the dependencies as private fields. As soon as the class is instantiated, those
dependencies are available to all other non-static methods of the class.
The private fields are readonly. Once they are set in the constructor they cannot be changed. This indicates
that those fields should not (and cannot) be modified outside of the constructor. That further ensures that
those dependencies will be available for the lifetime of the class.
The dependencies are interfaces. This is not strictly necessary, but is common because it makes it easier to
substitute one implementation of the dependency with another. It also allows providing a mocked version of
the interface for unit testing purposes.
Section 26.3: Why We Use Dependency Injection Containers
(IoC Containers)
Dependency injection means writing classes so that they do not control their dependencies - instead, their
dependencies are provided to them ("injected.")
This is not the same thing as using a dependency injection framework (often called a "DI container", "IoC container",
or just "container") like Castle Windsor, Autofac, SimpleInjector, Ninject, Unity, or others.
A container just makes dependency injection easier. For example, suppose you write a number of classes that rely
on dependency injection. One class depends on several interfaces, the classes that implement those interfaces
depend on other interfaces, and so on. Some depend on specific values. And just for fun, some of those classes
GoalKicker.com – .NET Framework Notes for Professionals
91
implement IDisposable and need to be disposed.
Each individual class is well-written and easy to test. But now there's a different problem: Creating an instance of a
class has become much more complicated. Suppose we're creating an instance of a CustomerService class. It has
dependencies and its dependencies have dependencies. Constructing an instance might look something like this:
public CustomerData GetCustomerData(string customerNumber)
{
var customerApiEndpoint = ConfigurationManager.AppSettings["customerApi:customerApiEndpoint"];
var logFilePath = ConfigurationManager.AppSettings["logwriter:logFilePath"];
var authConnectionString =
ConfigurationManager.ConnectionStrings["authorization"].ConnectionString;
using(var logWriter = new LogWriter(logFilePath ))
{
using(var customerApiClient = new CustomerApiClient(customerApiEndpoint))
{
var customerService = new CustomerService(
new SqlAuthorizationRepository(authorizationConnectionString, logWriter),
new CustomerDataRepository(customerApiClient, logWriter),
logWriter
);
// All this just to create an instance of CustomerService!
return customerService.GetCustomerData(string customerNumber);
}
}
}
You might wonder, why not put the whole giant construction in a separate function that just returns
CustomerService? One reason is that because the dependencies for each class are injected into it, a class isn't
responsible for knowing whether those dependencies are IDisposable or disposing them. It just uses them. So if a
we had a GetCustomerService() function that returned a fully-constructed CustomerService, that class might
contain a number of disposable resources and no way to access or dispose them.
And aside from disposing IDisposable, who wants to call a series of nested constructors like that, ever? That's a
short example. It could get much, much worse. Again, that doesn't mean that we wrote the classes the wrong way.
The classes might be individually perfect. The challenge is composing them together.
A dependency injection container simplifies that. It allows us to specify which class or value should be used to fulfill
each dependency. This slightly oversimplified example uses Castle Windsor:
var container = new WindsorContainer()
container.Register(
Component.For<CustomerService>(),
Component.For<ILogWriter, LogWriter>()
.DependsOn(Dependency.OnAppSettingsValue("logFilePath", "logWriter:logFilePath")),
Component.For<IAuthorizationRepository, SqlAuthorizationRepository>()
.DependsOn(Dependency.OnValue(connectionString,
ConfigurationManager.ConnectionStrings["authorization"].ConnectionString)),
Component.For<ICustomerDataProvider, CustomerApiClient>()
.DependsOn(Dependency.OnAppSettingsValue("apiEndpoint",
"customerApi:customerApiEndpoint"))
);
We call this "registering dependencies" or "configuring the container." Translated, this tells our WindsorContainer:
If a class requires ILogWriter, create an instance of LogWriter. LogWriter requires a file path. Use this value
from AppSettings.
GoalKicker.com – .NET Framework Notes for Professionals
92
If a class requires IAuthorizationRepository, create an instance of SqlAuthorizationRepository. It
requires a connection string. Use this value from the ConnectionStrings section.
If a class requires ICustomerDataProvider, create a CustomerApiClient and provide the string it needs from
AppSettings.
When we request a dependency from the container we call that "resolving" a dependency. It's bad practice to do
that directly using the container, but that's a different story. For demonstration purposes, we could now do this:
var customerService = container.Resolve<CustomerService>();
var data = customerService.GetCustomerData(customerNumber);
container.Release(customerService);
The container knows that CustomerService depends on IAuthorizationRepository and ICustomerDataProvider.
It knows what classes it needs to create to fulfill those requirements. Those classes, in turn, have more
dependencies, and the container knows how to fulfill those. It will create every class it needs to until it can return an
instance of CustomerService.
If it gets to a point where a class requires a dependency that we haven't registered, like IDoesSomethingElse, then
when we try to resolve CustomerService it will throw a clear exception telling us that we haven't registered
anything to fulfill that requirement.
Each DI framework behaves a little differently, but typically they give us some control over how certain classes are
instantiated. For example, do we want it to create one instance of LogWriter and provide it to every class that
depends on ILogWriter, or do we want it to create a new one every time? Most containers have a way to specify
that.
What about classes that implement IDisposable? That's why we call container.Release(customerService); at the
end. Most containers (including Windsor) will step back through all of the dependencies created and Dispose the
ones that need disposing. If CustomerService is IDisposable it will dispose that too.
Registering dependencies as seen above might just look like more code to write. But when we have lots of classes
with lots of dependencies then it really pays off. And if we had to write those same classes without using
dependency injection then that same application with lots of classes would become difficult to maintain and test.
This scratches the surface of why we use dependency injection containers. How we configure our application to use
one (and use it correctly) is not just one topic - it's a number of topics, as the instructions and examples vary from
one container to the next.
GoalKicker.com – .NET Framework Notes for Professionals
93
Chapter 27: Platform Invoke
Section 27.1: Marshaling structs
Simple struct
C++ signature:
typedef struct _PERSON
{
int age;
char name[32];
} PERSON, *LP_PERSON;
void GetSpouse(PERSON person, LP_PERSON spouse);
C# definition
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct PERSON
{
public int age;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string name;
}
[DllImport("family.dll", CharSet = CharSet.Auto)]
public static extern bool GetSpouse(PERSON person, ref PERSON spouse);
Struct with unknown size array fields. Passing in
C++ signature
typedef struct
{
int length;
int *data;
} VECTOR;
void SetVector(VECTOR &vector);
When passed from managed to unmanaged code, this
The data array should be defined as IntPtr and memory should be explicitly allocated with
Marshal.AllocHGlobal() (and freed with Marshal.FreeHGlobal() afterwords):
[StructLayout(LayoutKind.Sequential)]
public struct VECTOR : IDisposable
{
int length;
IntPtr dataBuf;
public int[] data
{
set
{
FreeDataBuf();
GoalKicker.com – .NET Framework Notes for Professionals
94
if (value != null && value.Length > 0)
{
dataBuf = Marshal.AllocHGlobal(value.Length * Marshal.SizeOf(value[0]));
Marshal.Copy(value, 0, dataBuf, value.Length);
length = value.Length;
}
}
}
void FreeDataBuf()
{
if (dataBuf != IntPtr.Zero)
{
Marshal.FreeHGlobal(dataBuf);
dataBuf = IntPtr.Zero;
}
}
public void Dispose()
{
FreeDataBuf();
}
}
[DllImport("vectors.dll")]
public static extern void SetVector([In]ref VECTOR vector);
Struct with unknown size array fields. Receiving
C++ signature:
typedef struct
{
char *name;
} USER;
bool GetCurrentUser(USER *user);
When such data is passed out of unmanaged code and memory is allocated by the unmanaged functions, the
managed caller should receive it into an IntPrt variable and convert the buffer to a managed array. In case of
strings there is a convenient Marshal.PtrToStringAnsi() method:
[StructLayout(LayoutKind.Sequential)]
public struct USER
{
IntPtr nameBuffer;
public string name { get { return Marshal.PtrToStringAnsi(nameBuffer); } }
}
[DllImport("users.dll")]
public static extern bool GetCurrentUser(out USER user);
Section 27.2: Marshaling unions
Value-type fields only
C++ declaration
typedef union
{
char c;
GoalKicker.com – .NET Framework Notes for Professionals
95
int i;
} CharOrInt;
C# declaration
[StructLayout(LayoutKind.Explicit)]
public struct CharOrInt
{
[FieldOffset(0)]
public byte c;
[FieldOffset(0)]
public int i;
}
Mixing value-type and reference fields
Overlapping a reference value with a value type one is not allowed so you cannot simply use the FieldOffset(0)
text; FieldOffset(0) i; will not compile for
typedef union
{
char text[128];
int i;
} TextOrInt;
and generally you would have to employ custom marshaling. However, in particular cases like this simpler technics
may be used:
[StructLayout(LayoutKind.Sequential)]
public struct TextOrInt
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
public byte[] text;
public int i { get { return BitConverter.ToInt32(text, 0); } }
}
Section 27.3: Calling a Win32 dll function
using System.Runtime.InteropServices;
class PInvokeExample
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern uint MessageBox(IntPtr hWnd, String text, String caption, int options);
public static void test()
{
MessageBox(IntPtr.Zero, "Hello!", "Message", 0);
}
}
Declare a function as static extern stting DllImportAttribute with its Value property set to .dll name. Don't
forget to use System.Runtime.InteropServices namespace. Then call it as an regular static method.
The Platform Invocation Services will take care of loading the .dll and finding the desired finction. The P/Invoke in
most simple cases will also marshal parameters and return value to and from the .dll (i.e. convert from .NET
datatypes to Win32 ones and vice versa).
GoalKicker.com – .NET Framework Notes for Professionals
96
Section 27.4: Using Windows API
Use pinvoke.net.
Before declaring an extern Windows API function in your code, consider looking for it on pinvoke.net. They most
likely already have a suitable declaration with all supporting types and good examples.
Section 27.5: Marshalling arrays
Arrays of simple type
[DllImport("Example.dll")]
static extern void SetArray(
[MarshalAs(UnmanagedType.LPArray, SizeConst = 128)]
byte[] data);
Arrays of string
[DllImport("Example.dll")]
static extern void SetStrArray(string[] textLines);
GoalKicker.com – .NET Framework Notes for Professionals
97
Chapter 28: NuGet packaging system
Section 28.1: Uninstalling a package from one project in a
solution
PM> Uninstall-Package -ProjectName MyProjectB EntityFramework
Section 28.2: Installing a specific version of a package
PM> Install-Package EntityFramework -Version 6.1.2
Section 28.3: Adding a package source feed (MyGet, Klondike,
ect)
nuget sources add -name feedname -source http://sourcefeedurl
Section 28.4: Installing the NuGet Package Manager
In order to be able to manage your projects' packages, you need the NuGet Package Manager. This is a Visual
Studio Extension, explained in the official docs: Installing and Updating NuGet Client.
Starting with Visual Studio 2012, NuGet is included in every edition, and can be used from: Tools -> NuGet Package
Manager -> Package Manager Console.
You do so through the Tools menu of Visual Studio, clicking Extensions and Updates:
This installs both the GUI:
Available through clicking "Manage NuGet Packages..." on a project or its References folder
And the Package Manager Console:
GoalKicker.com – .NET Framework Notes for Professionals
98
Tools -> NuGet Package Manager -> Package Manager Console.
Section 28.5: Managing Packages through the UI
When you right-click a project (or its References folder), you can click the "Manage NuGet Packages..." option. This
shows the Package Manager Dialog.
Section 28.6: Managing Packages through the console
Click the menus Tools -> NuGet Package Manager -> Package Manager Console to show the console in your IDE.
Official documentation here.
Here you can issue, amongst others, install-package commands which installs the entered package into the
currently selected "Default project":
Install-Package Elmah
You can also provide the project to install the package to, overriding the selected project in the "Default project"
dropdown:
Install-Package Elmah -ProjectName MyFirstWebsite
Section 28.7: Updating a package
To update a package use the following command:
PM> Update-Package EntityFramework
GoalKicker.com – .NET Framework Notes for Professionals
99
where EntityFramework is the name of the package to be updated. Note that update will run for all projects, and so
is different from Install-Package EntityFramework which would install to "Default project" only.
You can also specify a single project explicitly:
PM> Update-Package EntityFramework -ProjectName MyFirstWebsite
Section 28.8: Uninstalling a package
PM> Uninstall-Package EntityFramework
Section 28.9: Uninstall a specific version of package
PM> uninstall-Package EntityFramework -Version 6.1.2
GoalKicker.com – .NET Framework Notes for Professionals
100
Chapter 29: Globalization in ASP.NET MVC
using Smart internationalization for
ASP.NET
Section 29.1: Basic configuration and setup
1.
2.
Add the I18N nuget package to your MVC project.
In web.config, add the i18n.LocalizingModule to your <httpModules> or <modules> section.
<!-- IIS 6 -->
<httpModules>
<add name="i18n.LocalizingModule" type="i18n.LocalizingModule, i18n" />
</httpModules>
<!-- IIS 7 -->
<system.webServer>
<modules>
<add name="i18n.LocalizingModule" type="i18n.LocalizingModule, i18n" />
</modules>
</system.webServer>
3.
Add a folder named "locale" to the root of your site. Create a subfolder for each culture you wish to support.
For example, /locale/fr/.
4.
5.
In each culture-specific folder, create a text file named messages.po.
For testing purposes, enter the following lines of text in your messages.po file:
#: Translation test
msgid "Hello, world!"
msgstr "Bonjour le monde!"
6.
Add a controller to your project which returns some text to translate.
using System.Web.Mvc;
namespace I18nDemo.Controllers
{
public class DefaultController : Controller
{
public ActionResult Index()
{
// Text inside [[[triple brackets]]] must precisely match
// the msgid in your .po file.
return Content("[[[Hello, world!]]]");
}
}
}
7.
Run your MVC application and browse to the route corresponding to your controller action, such as
http://localhost:[yourportnumber]/default.
Observe that the URL is changed to reflect your default culture, such as
http://localhost:[yourportnumber]/en/default.
8.
Replace /en/ in the URL with /fr/ (or whatever culture you've selected.) The page should now display the
translated version of your text.
9.
Change your browser's language setting to prefer your alternate culture and browse to /default again.
Observe that the URL is changed to reflect your alternate culture and the translated text appears.
GoalKicker.com – .NET Framework Notes for Professionals
101
10.
In web.config, add handlers so that users cannot browse to your locale folder.
<!-- IIS 6 -->
<system.web>
<httpHandlers>
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
</system.web>
<!-- IIS 7 -->
<system.webServer>
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode"
type="System.Web.HttpNotFoundHandler"/>
</handlers>
</system.webServer>
GoalKicker.com – .NET Framework Notes for Professionals
102
Chapter 30: System.Net.Mail
Section 30.1: MailMessage
Here is the example of creating of mail message with attachments. After creating we send this message with the
help of SmtpClient class. Default 25 port is used here.
public class clsMail
{
private static bool SendMail(string mailfrom, List<string>replytos, List<string> mailtos,
List<string> mailccs, List<string> mailbccs, string body, string subject, List<string> Attachment)
{
try
{
using(MailMessage MyMail = new MailMessage())
{
MyMail.From = new MailAddress(mailfrom);
foreach (string mailto in mailtos)
MyMail.To.Add(mailto);
if (replytos != null && replytos.Any())
{
foreach (string replyto in replytos)
MyMail.ReplyToList.Add(replyto);
}
if (mailccs != null && mailccs.Any())
{
foreach (string mailcc in mailccs)
MyMail.CC.Add(mailcc);
}
if (mailbccs != null && mailbccs.Any())
{
foreach (string mailbcc in mailbccs)
MyMail.Bcc.Add(mailbcc);
}
MyMail.Subject = subject;
MyMail.IsBodyHtml = true;
MyMail.Body = body;
MyMail.Priority = MailPriority.Normal;
if (Attachment != null && Attachment.Any())
{
System.Net.Mail.Attachment attachment;
foreach (var item in Attachment)
{
attachment = new System.Net.Mail.Attachment(item);
MyMail.Attachments.Add(attachment);
}
}
SmtpClient smtpMailObj = new SmtpClient();
smtpMailObj.Host = "your host";
smtpMailObj.Port = 25;
smtpMailObj.Credentials = new System.Net.NetworkCredential("uid", "pwd");
smtpMailObj.Send(MyMail);
return true;
GoalKicker.com – .NET Framework Notes for Professionals
103
}
}
catch
{
return false;
}
}
}
Section 30.2: Mail with Attachment
MailMessage represents mail message which can be sent further using SmtpClient class. Several attachments (files)
can be added to mail message.
using System.Net.Mail;
using(MailMessage myMail = new MailMessage())
{
Attachment attachment = new Attachment(path);
myMail.Attachments.Add(attachment);
// further processing to send the mail message
}
GoalKicker.com – .NET Framework Notes for Professionals
104
Chapter 31: Using Progress<T> and
IProgress<T>
Section 31.1: Simple Progress reporting
IProgress<T> can be used to report progress of some procedure to another procedure. This example shows how
you can create a basic method that reports its progress.
void Main()
{
IProgress<int> p = new Progress<int>(progress =>
{
Console.WriteLine("Running Step: {0}", progress);
});
LongJob(p);
}
public void LongJob(IProgress<int> progress)
{
var max = 10;
for (int i = 0; i < max; i++)
{
progress.Report(i);
}
}
Output:
Running Step: 0
Running Step: 3
Running Step: 4
Running Step: 5
Running Step: 6
Running Step: 7
Running Step: 8
Running Step: 9
Running Step: 2
Running Step: 1
Note that when you this code runs, you may see numbers be output out of order. This is because the
IProgress<T>.Report() method is run asynchronously, and is therefore not as suitable for situations where the
progress must be reported in order.
Section 31.2: Using IProgress<T>
It's important to note that the System.Progress<T> class does not have the Report() method available on it. This
method was implemented explicitly from the IProgress<T> interface, and therefore must be called on a
Progress<T> when it's cast to an IProgress<T>.
var p1 = new Progress<int>();
p1.Report(1); //compiler error, Progress does not contain method 'Report'
IProgress<int> p2 = new Progress<int>();
p2.Report(2); //works
GoalKicker.com – .NET Framework Notes for Professionals
105
var p3 = new Progress<int>();
((IProgress<int>)p3).Report(3); //works
GoalKicker.com – .NET Framework Notes for Professionals
106
Chapter 32: JSON Serialization
Section 32.1: Deserialization using
System.Web.Script.Serialization.JavaScriptSerializer
The JavaScriptSerializer.Deserialize<T>(input) method attempts to deserialize a string of valid JSON into an
object of the specified type <T>, using the default mappings natively supported by JavaScriptSerializer.
using System.Collections;
using System.Web.Script.Serialization;
// ...
string rawJSON = "{\"Name\":\"Fibonacci Sequence\",\"Numbers\":[0, 1, 1, 2, 3, 5, 8, 13]}";
JavaScriptSerializer JSS = new JavaScriptSerializer();
Dictionary<string, object> parsedObj = JSS.Deserialize<Dictionary<string, object>>(rawJSON);
string name = parsedObj["Name"].toString();
ArrayList numbers = (ArrayList)parsedObj["Numbers"]
Note: The JavaScriptSerializer object was introduced in .NET version 3.5
Section 32.2: Serialization using Json.NET
[JsonObject("person")]
public class Person
{
[JsonProperty("name")]
public string PersonName { get; set; }
[JsonProperty("age")]
public int PersonAge { get; set; }
[JsonIgnore]
public string Address { get; set; }
}
Person person = new Person { PersonName = "Andrius", PersonAge = 99, Address = "Some address" };
string rawJson = JsonConvert.SerializeObject(person);
Console.WriteLine(rawJson); // {"name":"Andrius","age":99}
Notice how properties (and classes) can be decorated with attributes to change their appearance in resulting json
string or to remove them from json string at all (JsonIgnore).
More information about Json.NET serialization attributes can be found here.
In C#, public identifiers are written in PascalCase by convention. In JSON, the convention is to use camelCase for all
names. You can use a contract resolver to convert between the two.
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
[JsonIgnore]
GoalKicker.com – .NET Framework Notes for Professionals
107
public string Address { get; set; }
}
public void ToJson() {
Person person = new Person { Name = "Andrius", Age = 99, Address = "Some address" };
var resolver = new CamelCasePropertyNamesContractResolver();
var settings = new JsonSerializerSettings { ContractResolver = resolver };
string json = JsonConvert.SerializeObject(person, settings);
Console.WriteLine(json); // {"name":"Andrius","age":99}
}
Section 32.3: Serialization-Deserialization using
Newtonsoft.Json
Unlike the other helpers, this one uses static class helpers to serialize and deserialize, hence it is a little bit easier
than the others to use.
using Newtonsoft.Json;
var rawJSON = "{\"Name\":\"Fibonacci Sequence\",\"Numbers\":[0, 1, 1, 2, 3, 5, 8, 13]}";
var fibo = JsonConvert.DeserializeObject<Dictionary<string, object>>(rawJSON);
var rawJSON2 = JsonConvert.SerializeObject(fibo);
Section 32.4: Deserialization using Json.NET
internal class Sequence{
public string Name;
public List<int> Numbers;
}
// ...
string rawJSON = "{\"Name\":\"Fibonacci Sequence\",\"Numbers\":[0, 1, 1, 2, 3, 5, 8, 13]}";
Sequence sequence = JsonConvert.DeserializeObject<Sequence>(rawJSON);
For more information, refer to the Json.NET official site.
Note: Json.NET supports .NET version 2 and higher.
Section 32.5: Dynamic binding
Newtonsoft's Json.NET allows you to bind json dynamically (using ExpandoObject / Dynamic objects) without the
need to create the type explicitly.
Serialization
dynamic jsonObject = new ExpandoObject();
jsonObject.Title = "Merchent of Venice";
jsonObject.Author = "William Shakespeare";
Console.WriteLine(JsonConvert.SerializeObject(jsonObject));
De-serialization
var rawJson = "{\"Name\":\"Fibonacci Sequence\",\"Numbers\":[0, 1, 1, 2, 3, 5, 8, 13]}";
dynamic parsedJson = JObject.Parse(rawJson);
GoalKicker.com – .NET Framework Notes for Professionals
108
Console.WriteLine("Name: " + parsedJson.Name);
Console.WriteLine("Name: " + parsedJson.Numbers.Length);
Notice that the keys in the rawJson object have been turned into member variables in the dynamic object.
This is useful in cases where an application can accept/ produce varying formats of JSON. It is however suggested to
use an extra level of validation for the Json string or to the dynamic object generated as a result of serialization/ de-
serialization.
Section 32.6: Serialization using Json.NET with
JsonSerializerSettings
This serializer has some nice features that the default .net json serializer doesn't have, like Null value handling, you
just need to create the JsonSerializerSettings :
public static string Serialize(T obj)
{
string result = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { NullValueHandling
= NullValueHandling.Ignore});
return result;
}
Another serious serializer issue in .net is the self referencing loop. In the case of a student that is enrolled in a
course, its instance has a course property and a course has a collection of students that means a List<Student>
which will create a reference loop. You can handle this with JsonSerializerSettings :
public static string Serialize(T obj)
{
string result = JsonConvert.SerializeObject(obj, new JsonSerializerSettings {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
return result;
}
You can put various serializations option like this:
public static string Serialize(T obj)
{
string result = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { NullValueHandling
= NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
return result;
}
GoalKicker.com – .NET Framework Notes for Professionals
109
Chapter 33: JSON in .NET with
Newtonsoft.Json
The NuGet package Newtonsoft.Json has become the defacto standard for using and manipulating JSON formatted
text and objects in .NET. It is a robust tool that is fast, and easy to use.
Section 33.1: Deserialize an object from JSON text
var json = "{\"Name\":\"Joe Smith\",\"Age\":21}";
var person = JsonConvert.DeserializeObject<Person>(json);
This yields a Person object with Name "Joe Smith" and Age 21.
Section 33.2: Serialize object into JSON
using Newtonsoft.Json;
var obj = new Person
{
Name = "Joe Smith",
Age = 21
};
var serializedJson = JsonConvert.SerializeObject(obj);
This results in this JSON: {"Name":"Joe Smith","Age":21}
GoalKicker.com – .NET Framework Notes for Professionals
110
Chapter 34: XmlSerializer
Section 34.1: Formatting: Custom DateTime format
public class Dog
{
private const string _birthStringFormat = "yyyy-MM-dd";
[XmlIgnore]
public DateTime Birth {get; set;}
[XmlElement(ElementName="Birth")]
public string BirthString
{
get { return Birth.ToString(_birthStringFormat); }
set { Birth = DateTime.ParseExact(value, _birthStringFormat, CultureInfo.InvariantCulture);
}
}
}
Section 34.2: Serialize object
public void SerializeFoo(string fileName, Foo foo)
{
var serializer = new XmlSerializer(typeof(Foo));
using (var stream = File.Open(fileName, FileMode.Create))
{
serializer.Serialize(stream, foo);
}
}
Section 34.3: Deserialize object
public Foo DeserializeFoo(string fileName)
{
var serializer = new XmlSerializer(typeof(Foo));
using (var stream = File.OpenRead(fileName))
{
return (Foo)serializer.Deserialize(stream);
}
}
Section 34.4: Behaviour: Map array name to property
(XmlArray)
<Store>
<Articles>
<Product/>
<Product/>
</Articles>
</Store>
public class Store
{
[XmlArray("Articles")]
GoalKicker.com – .NET Framework Notes for Professionals
111
public List<Product> Products {get; set; }
}
Section 34.5: Behaviour: Map Element name to Property
<Foo>
<Dog/>
</Foo>
public class Foo
{
// Using XmlElement
[XmlElement(Name="Dog")]
public Animal Cat { get; set; }
}
Section 34.6: Eciently building multiple serializers with
derived types specified dynamically
Where we came from
Sometimes we can't provide all of the required metadata needed for the XmlSerializer framework in attribute.
Suppose we have a base class of serialized objects, and some of the derived classes are unknown to the base class.
We can't place an attribute for all of the classes which are not know at the design time of the base type. We could
have another team developing some of the derived classes.
What can we do
We can use new XmlSerializer(type, knownTypes), but that would be a O(N^2) operation for N serializers, at least
to discover all of the types supplied in arguments:
// Beware of the N^2 in terms of the number of types.
var allSerializers = allTypes.Select(t => new XmlSerializer(t, allTypes));
var serializerDictionary = Enumerable.Range(0, allTypes.Length)
.ToDictionary (i => allTypes[i], i => allSerializers[i])
In this example, the the Base type is not aware of it's derived types, which is normal in OOP.
Doing it efficiently
Luckily, there is a method which addresses this particular problem - supplying known types for multiple serializers
efficiently:
System.Xml.Serialization.XmlSerializer.FromTypes Method (Type[])
The FromTypes method allows you to efficiently create an array of XmlSerializer objects for processing an
array of Type objects.
var allSerializers = XmlSerializer.FromTypes(allTypes);
var serializerDictionary = Enumerable.Range(0, allTypes.Length)
.ToDictionary(i => allTypes[i], i => allSerializers[i]);
Here is a complete code sample:
GoalKicker.com – .NET Framework Notes for Professionals
112
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Linq;
using System.Linq;
public class Program
{
public class Container
{
public Base Base { get; set; }
}
public class Base
{
public int JustSomePropInBase { get; set; }
}
public class Derived : Base
{
public int JustSomePropInDerived { get; set; }
}
public void Main()
{
var sampleObject = new Container { Base = new Derived() };
var allTypes = new[] { typeof(Container), typeof(Base), typeof(Derived) };
Console.WriteLine("Trying to serialize without a derived class metadata:");
SetupSerializers(allTypes.Except(new[] { typeof(Derived) }).ToArray());
try
{
Serialize(sampleObject);
}
catch (InvalidOperationException e)
{
Console.WriteLine();
Console.WriteLine("This error was anticipated,");
Console.WriteLine("we have not supplied a derived class.");
Console.WriteLine(e);
}
Console.WriteLine("Now trying to serialize with all of the type information:");
SetupSerializers(allTypes);
Serialize(sampleObject);
Console.WriteLine();
Console.WriteLine("Slides down well this time!");
}
static void Serialize<T>(T o)
{
serializerDictionary[typeof(T)].Serialize(Console.Out, o);
}
private static Dictionary<Type, XmlSerializer> serializerDictionary;
static void SetupSerializers(Type[] allTypes)
{
var allSerializers = XmlSerializer.FromTypes(allTypes);
serializerDictionary = Enumerable.Range(0, allTypes.Length)
.ToDictionary(i => allTypes[i], i => allSerializers[i]);
}
GoalKicker.com – .NET Framework Notes for Professionals
113
}
Output:
Trying to serialize without a derived class metadata:
<?xml version="1.0" encoding="utf-16"?>
System.InvalidOperationException: The type Program+Derived was not expected. Use the XmlInclude
or SoapInclude attribute to specify types that are not known statically.
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write2_Base(String n,
String ns, Base o, Boolean isNullable, Boolean needType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write3_Container(String
n, String ns, Container o, Boolean isNullable, Boolean needType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write4_Container(Object
o)
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o,
XmlSerializerNamespaces namespaces, String encodingStyle, String id)
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o,
XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o,
XmlSerializerNamespaces namespaces, String encodingStyle)
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o,
XmlSerializerNamespaces namespaces)
at Program.Serialize[T](T o)
at Program.Main()
Now trying to serialize with all of the type information:
<?xml version="1.0" encoding="utf-16"?>
0
0
Slides down well this time!
What's in the output
This error message recommends what we tried to avoid (or what we can not do in some scenarios) - referencing
derived types from base class:
Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
This is how we get our derived class in the XML:
<Base xsi:type="Derived">
Base corresponds to the property type declared in the Container type, and Derived being the type of the instance
actually supplied.
Here is a working example fiddle
GoalKicker.com – .NET Framework Notes for Professionals
114
Chapter 35: VB Forms
Section 35.1: Hello World in VB.NET Forms
To show a message box when the form has been shown:
Public Class Form1
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
MessageBox.Show("Hello, World!")
End Sub
End Class
To show a message box before the form has been shown:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MessageBox.Show("Hello, World!")
End Sub
End Class
Load() will be called first, and only once, when the form first loads. Show() will be called every time the user
launches the form. Activate() will be called every time the user makes the form active.
Load() will execute before Show() is called, but be warned: calling msgBox() in show can cause that msgBox() to
execute before Load() is finished. It is generally a bad idea to depend on event ordering between Load(),
Show(), and similar.
Section 35.2: For Beginners
Some things all beginners should know / do that will help them have a good start with VB .Net:
Set the following Options:
'can be permanently set
' Tools / Options / Projects and Soluntions / VB Defaults
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
End Class
Use &, not + for string concatenation. Strings should be studied in some detail as they are widely used.
Spend some time understanding Value and Reference Types.
Never use Application.DoEvents. Pay attention to the 'Caution'. When you reach a point where this seems like
something you must use, ask.
The documentation is your friend.
Section 35.3: Forms Timer
The Windows.Forms.Timer component can be used to provide the user information that is not time critical. Create
a form with one button, one label, and a Timer component.
GoalKicker.com – .NET Framework Notes for Professionals
115
For example it could be used to show the user the time of day periodically.
'can be permanently set
' Tools / Options / Projects and Soluntions / VB Defaults
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
Timer1.Interval = 60 * 1000 'one minute intervals
'start timer
Timer1.Start()
Label1.Text = DateTime.Now.ToLongTimeString
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.Text = DateTime.Now.ToLongTimeString
End Sub
End Class
But this timer is not suited for timing. An example would be using it for a countdown. In this example we will
simulate a countdown to three minutes. This may very well be one of the most boringly important examples here.
'can be permanently set
' Tools / Options / Projects and Soluntions / VB Defaults
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
ctSecs = 0 'clear count
Timer1.Interval = 1000 'one second in ms.
'start timers
stpw.Reset()
stpw.Start()
Timer1.Start()
End Sub
Dim stpw As New Stopwatch
Dim ctSecs As Integer
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
ctSecs += 1
If ctSecs = 180 Then 'about 2.5 seconds off on my PC!
'stop timing
stpw.Stop()
Timer1.Stop()
'show actual elapsed time
'Is it near 180?
Label1.Text = stpw.Elapsed.TotalSeconds.ToString("n1")
End If
End Sub
End Class
GoalKicker.com – .NET Framework Notes for Professionals
116
After button1 is clicked, about three minutes pass and label1 shows the results. Does label1 show 180? Probably
not. On my machine it showed 182.5!
The reason for the discrepancy is in the documentation, "The Windows Forms Timer component is single-threaded,
and is limited to an accuracy of 55 milliseconds." This is why it shouldn't be used for timing.
By using the timer and stopwatch a little differently we can obtain better results.
'can be permanently set
' Tools / Options / Projects and Soluntions / VB Defaults
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
Timer1.Interval = 100 'one tenth of a second in ms.
'start timers
stpw.Reset()
stpw.Start()
Timer1.Start()
End Sub
Dim stpw As New Stopwatch
Dim threeMinutes As TimeSpan = TimeSpan.FromMinutes(3)
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If stpw.Elapsed >= threeMinutes Then '0.1 off on my PC!
'stop timing
stpw.Stop()
Timer1.Stop()
'show actual elapsed time
'how close?
Label1.Text = stpw.Elapsed.TotalSeconds.ToString("n1")
End If
End Sub
End Class
There are other timers that can be used as needed. This search should help in that regard.
GoalKicker.com – .NET Framework Notes for Professionals
117
Chapter 36: JIT compiler
JIT compilation, or just-in-time compilation, is an alternative approach to interpretation of code or ahead-of-time
compilation. JIT compilation is used in the .NET framework. The CLR code (C#, F#, Visual Basic, etc.) is first compiled
into something called Interpreted Language, or IL. This is lower level code that is closer to machine code, but is not
platform specific. Rather, at runtime, this code is compiled into machine code for the relevant system.
Section 36.1: IL compilation sample
Simple Hello World Application:
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
}
}
}
Equivalent IL Code (which will be JIT compiled)
// Microsoft (R) .NET Framework IL Disassembler. Version 4.6.1055.0
// Copyright (c) Microsoft Corporation. All rights reserved.
// Metadata version: v4.0.30319
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly HelloWorld
{
.custom instance void
[mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00
08 00 00 00 00 00 )
.custom instance void
[mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00
54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx
63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows.
// --- The following custom attribute is added automatically, do not uncomment -------
// .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype
[mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 07 01 00 00 00 00 )
.custom instance void [mscorlib]System.Reflection.AssemblyTitleAttribute::.ctor(string) = ( 01 00
0A 48 65 6C 6C 6F 57 6F 72 6C 64 00 00 ) // ...HelloWorld..
.custom instance void [mscorlib]System.Reflection.AssemblyDescriptionAttribute::.ctor(string) = (
01 00 00 00 00 )
.custom instance void [mscorlib]System.Reflection.AssemblyConfigurationAttribute::.ctor(string) =
( 01 00 00 00 00 )
.custom instance void [mscorlib]System.Reflection.AssemblyCompanyAttribute::.ctor(string) = ( 01
00 00 00 00 )
GoalKicker.com – .NET Framework Notes for Professionals
118
.custom instance void [mscorlib]System.Reflection.AssemblyProductAttribute::.ctor(string) = ( 01
00 0A 48 65 6C 6C 6F 57 6F 72 6C 64 00 00 ) // ...HelloWorld..
.custom instance void [mscorlib]System.Reflection.AssemblyCopyrightAttribute::.ctor(string) = ( 01
00 12 43 6F 70 79 72 69 67 68 74 20 C2 A9 20 // ...Copyright ..
20 32 30 31 37 00 00 ) // 2017..
.custom instance void [mscorlib]System.Reflection.AssemblyTrademarkAttribute::.ctor(string) = ( 01
00 00 00 00 )
.custom instance void [mscorlib]System.Runtime.InteropServices.ComVisibleAttribute::.ctor(bool) =
( 01 00 00 00 00 )
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01
00 24 33 30 38 62 33 64 38 36 2D 34 31 37 32 // ..$308b3d86-4172
2D 34 30 32 32 2D 61 66 63 63 2D 33 66 38 65 33 // -4022-afcc-3f8e3
32 33 33 63 35 62 30 00 00 ) // 233c5b0..
.custom instance void [mscorlib]System.Reflection.AssemblyFileVersionAttribute::.ctor(string) = (
01 00 07 31 2E 30 2E 30 2E 30 00 00 ) // ...1.0.0.0..
.custom instance void [mscorlib]System.Runtime.Versioning.TargetFrameworkAttribute::.ctor(string)
= ( 01 00 1C 2E 4E 45 54 46 72 61 6D 65 77 6F 72 6B // ....NETFramework
2C 56 65 72 73 69 6F 6E 3D 76 34 2E 35 2E 32 01 // ,Version=v4.5.2.
00 54 0E 14 46 72 61 6D 65 77 6F 72 6B 44 69 73 // .T..FrameworkDis
70 6C 61 79 4E 61 6D 65 14 2E 4E 45 54 20 46 72 // playName..NET Fr
61 6D 65 77 6F 72 6B 20 34 2E 35 2E 32 ) // amework 4.5.2
.hash algorithm 0x00008004
.ver 1:0:0:0
}
.module HelloWorld.exe
// MVID: {2A7E1D59-1272-4B47-85F6-D7E1ED057831}
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003 // WINDOWS_CUI
.corflags 0x00020003 // ILONLY 32BITPREFERRED
// Image base: 0x0000021C70230000
// =============== CLASS MEMBERS DECLARATION ===================
.class private auto ansi beforefieldinit HelloWorld.Program
extends [mscorlib]System.Object
{
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 13 (0xd)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "Hello World"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
} // end of method Program::Main
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method Program::.ctor
} // end of class HelloWorld.Program
GoalKicker.com – .NET Framework Notes for Professionals
119
Generated with MS ILDASM tool (IL disassembler)
GoalKicker.com – .NET Framework Notes for Professionals
120
Chapter 37: CLR
Section 37.1: An introduction to Common Language Runtime
The Common Language Runtime (CLR) is a virtual machine environment and part of the .NET Framework. It
contains:
A portable bytecode language called Common Intermediate Language (abbreviated CIL, or IL)
A Just-In-Time compiler that generates machine code
A tracing garbage collector that provides automatic memory management
Support for lightweight sub-processes called AppDomains
Security mechanisms through the concepts of verifiable code and trust levels
Code that runs in the CLR is referred to as managed code to distinguish it from code running outside the CLR
(usually native code) which is referred to as unmanaged code. There are various mechanisms that facilitate
interoperability between managed and unmanaged code.
GoalKicker.com – .NET Framework Notes for Professionals
121
Chapter 38: TPL Dataflow
Section 38.1: Asynchronous Producer Consumer With A
Bounded BuerBlock
var bufferBlock = new BufferBlock<int>(new DataflowBlockOptions
{
BoundedCapacity = 1000
});
var cancellationToken = new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token;
var producerTask = Task.Run(async () =>
{
var random = new Random();
while (!cancellationToken.IsCancellationRequested)
{
var value = random.Next();
await bufferBlock.SendAsync(value, cancellationToken);
}
});
var consumerTask = Task.Run(async () =>
{
while (await bufferBlock.OutputAvailableAsync())
{
var value = bufferBlock.Receive();
Console.WriteLine(value);
}
});
await Task.WhenAll(producerTask, consumerTask);
Section 38.2: Posting to an ActionBlock and waiting for
completion
// Create a block with an asynchronous action
var block = new ActionBlock<string>(async hostName =>
{
IPAddress[] ipAddresses = await Dns.GetHostAddressesAsync(hostName);
Console.WriteLine(ipAddresses[0]);
});
block.Post("google.com"); // Post items to the block's InputQueue for processing
block.Post("reddit.com");
block.Post("stackoverflow.com");
block.Complete(); // Tell the block to complete and stop accepting new items
await block.Completion; // Asynchronously wait until all items completed processingu
Section 38.3: Linking blocks to create a pipeline
var httpClient = new HttpClient();
// Create a block the accepts a uri and returns its contents as a string
var downloaderBlock = new TransformBlock<string, string>(
GoalKicker.com – .NET Framework Notes for Professionals
122
async uri => await httpClient.GetStringAsync(uri));
// Create a block that accepts the content and prints it to the console
var printerBlock = new ActionBlock<string>(
contents => Console.WriteLine(contents));
// Make the downloaderBlock complete the printerBlock when its completed.
var dataflowLinkOptions = new DataflowLinkOptions {PropagateCompletion = true};
// Link the block to create a pipeline
downloaderBlock.LinkTo(printerBlock, dataflowLinkOptions);
// Post urls to the first block which will pass their contents to the second one.
downloaderBlock.Post("http://youtube.com");
downloaderBlock.Post("http://github.com");
downloaderBlock.Post("http://twitter.com");
downloaderBlock.Complete(); // Completion will propagate to printerBlock
await printerBlock.Completion; // Only need to wait for the last block in the pipeline
Section 38.4: Synchronous Producer/Consumer with
BuerBlock<T>
public class Producer
{
private static Random random = new Random((int)DateTime.UtcNow.Ticks);
//produce the value that will be posted to buffer block
public double Produce ( )
{
var value = random.NextDouble();
Console.WriteLine($"Producing value: {value}");
return value;
}
}
public class Consumer
{
//consume the value that will be received from buffer block
public void Consume (double value) => Console.WriteLine($"Consuming value: {value}");
}
class Program
{
private static BufferBlock<double> buffer = new BufferBlock<double>();
static void Main (string[] args)
{
//start a task that will every 1 second post a value from the producer to buffer block
var producerTask = Task.Run(async () =>
{
var producer = new Producer();
while(true)
{
buffer.Post(producer.Produce());
await Task.Delay(1000);
}
});
//start a task that will recieve values from bufferblock and consume it
var consumerTask = Task.Run(() =>
{
var consumer = new Consumer();
while(true)
GoalKicker.com – .NET Framework Notes for Professionals
123
{
consumer.Consume(buffer.Receive());
}
});
Task.WaitAll(new[] { producerTask, consumerTask });
}
}
GoalKicker.com – .NET Framework Notes for Professionals
124
Chapter 39: Threading
Section 39.1: Accessing form controls from other threads
If you want to change an attribute of a control such as a textbox or label from another thread than the GUI thread
that created the control, you will have to invoke it or else you might get an error message stating:
"Cross-thread operation not valid: Control 'control_name' accessed from a thread other than the thread it
was created on."
Using this example code on a system.windows.forms form will cast an exception with that message:
private void button4_Click(object sender, EventArgs e)
{
Thread thread = new Thread(updatetextbox);
thread.Start();
}
private void updatetextbox()
{
textBox1.Text = "updated"; // Throws exception
}
Instead when you want to change a textbox's text from within a thread that doesn't own it use Control.Invoke or
Control.BeginInvoke. You can also use Control.InvokeRequired to check if invoking the control is necessary.
private void updatetextbox()
{
if (textBox1.InvokeRequired)
textBox1.BeginInvoke((Action)(() => textBox1.Text = "updated"));
else
textBox1.Text = "updated";
}
If you need to do this often, you can write an extension for invokeable objects to reduce the amount of code
necessary to make this check:
public static class Extensions
{
public static void BeginInvokeIfRequired(this ISynchronizeInvoke obj, Action action)
{
if (obj.InvokeRequired)
obj.BeginInvoke(action, new object[0]);
else
action();
}
}
And updating the textbox from any thread becomes a bit simpler:
private void updatetextbox()
{
textBox1.BeginInvokeIfRequired(() => textBox1.Text = "updated");
}
GoalKicker.com – .NET Framework Notes for Professionals
125
Be aware that Control.BeginInvoke as used in this example is asynchronous, meaning that code coming after a call
to Control.BeginInvoke can be run immedeately after, whether or not the passed delegate has been executed yet.
If you need to be sure that textBox1 is updated before continuing, use Control.Invoke instead, which will block the
calling thread until your delegate has been executed. Do note that this approach can slow your code down
significantly if you make many invoke calls and note that it will deadlock your application if your GUI thread is
waiting for the calling thread to complete or release a held resource.
GoalKicker.com – .NET Framework Notes for Professionals
126
Chapter 40: Process and Thread anity
setting
Parameter
affinity
Details
integer that describes the set of processors on which the process is allowed to run. For example, on a 8
processor system if you want your process to be executed only on processors 3 and 4 than you choose
affinity like this : 00001100 which equals 12
Section 40.1: Get process anity mask
public static int GetProcessAffinityMask(string processName = null)
{
Process myProcess = GetProcessByName(ref processName);
int processorAffinity = (int)myProcess.ProcessorAffinity;
Console.WriteLine("Process {0} Affinity Mask is : {1}", processName,
FormatAffinity(processorAffinity));
return processorAffinity;
}
public static Process GetProcessByName(ref string processName)
{
Process myProcess;
if (string.IsNullOrEmpty(processName))
{
myProcess = Process.GetCurrentProcess();
processName = myProcess.ProcessName;
}
else
{
Process[] processList = Process.GetProcessesByName(processName);
myProcess = processList[0];
}
return myProcess;
}
private static string FormatAffinity(int affinity)
{
return Convert.ToString(affinity, 2).PadLeft(Environment.ProcessorCount, '0');
}
}
Example of usage :
private static void Main(string[] args)
{
GetProcessAffinityMask();
Console.ReadKey();
}
// Output:
// Process Test.vshost Affinity Mask is : 11111111
Section 40.2: Set process anity mask
public static void SetProcessAffinityMask(int affinity, string processName = null)
GoalKicker.com – .NET Framework Notes for Professionals
127
{
Process myProcess = GetProcessByName(ref processName);
Console.WriteLine("Process {0} Old Affinity Mask is : {1}", processName,
FormatAffinity((int)myProcess.ProcessorAffinity));
myProcess.ProcessorAffinity = new IntPtr(affinity);
Console.WriteLine("Process {0} New Affinity Mask is : {1}", processName,
FormatAffinity((int)myProcess.ProcessorAffinity));
}
Example of usage :
private static void Main(string[] args)
{
int newAffinity = Convert.ToInt32("10101010", 2);
SetProcessAffinityMask(newAffinity);
Console.ReadKey();
}
// Output :
// Process Test.vshost Old Affinity Mask is : 11111111
// Process Test.vshost New Affinity Mask is : 10101010
GoalKicker.com – .NET Framework Notes for Professionals
128
Chapter 41: Parallel processing using .Net
framework
This Topic is about Multi core programming using Task Parallel Library with .NET framework. The task parallel
library allows you to write code which is human readable and adjusts itself with the number of Cores available. So
you can be sure that your software would auto-upgrade itself with the upgrading environment.
Section 41.1: Parallel Extensions
Parallel extensions have been introduced along with the Task Parallel Library to achieve data Parallelism. Data
parallelism refers to scenarios in which the same operation is performed concurrently (that is, in parallel) on
elements in a source collection or array. The .NET provides new constructs to achieve data parallelism by using
Parallel.For and Parallel.Foreach constructs.
//Sequential version
foreach (var item in sourcecollection){
Process(item);
}
// Parallel equivalent
Parallel.foreach(sourcecollection, item => Process(item));
The above mentioned Parallel.ForEach construct utilizes the multiple cores and thus enhances the performance in
the same fashion.
GoalKicker.com – .NET Framework Notes for Professionals
129
Chapter 42: Task Parallel Library (TPL)
Section 42.1: Basic producer-consumer loop
(BlockingCollection)
var collection = new BlockingCollection<int>(5);
var random = new Random();
var producerTask = Task.Run(() => {
for(int item=1; item<=10; item++)
{
collection.Add(item);
Console.WriteLine("Produced: " + item);
Thread.Sleep(random.Next(10,1000));
}
collection.CompleteAdding();
Console.WriteLine("Producer completed!");
});
It is worth noting that if you do not call collection.CompleteAdding();, you are able to keep adding to the
collection even if your consumer task is running. Just call collection.CompleteAdding(); when you are sure there
are no more additions. This functionality can be used to make a Multiple Producer to a Single Consumer pattern
where you have multiple sources feeding items into the BlockingCollection and a single consumer pulling items out
and doing something with them. If your BlockingCollection is empty before you call complete adding, the
Enumerable from collection.GetConsumingEnumerable() will block until a new item is added to the collection or
BlockingCollection.CompleteAdding(); is called and the queue is empty.
var consumerTask = Task.Run(() => {
foreach(var item in collection.GetConsumingEnumerable())
{
Console.WriteLine("Consumed: " + item);
Thread.Sleep(random.Next(10,1000));
}
Console.WriteLine("Consumer completed!");
});
Task.WaitAll(producerTask, consumerTask);
Console.WriteLine("Everything completed!");
Section 42.2: Parallel.Invoke
var actions = Enumerable.Range(1, 10).Select(n => new Action(() =>
{
Console.WriteLine("I'm task " + n);
if((n & 1) == 0)
throw new Exception("Exception from task " + n);
})).ToArray();
try
{
Parallel.Invoke(actions);
}
catch(AggregateException ex)
{
foreach(var inner in ex.InnerExceptions)
Console.WriteLine("Task failed: " + inner.Message);
GoalKicker.com – .NET Framework Notes for Professionals
130
}
Section 42.3: Task: Returning a value
Task that return a value has return type of Task< TResult > where TResult is the type of value that needs to be
returned. You can query the outcome of a Task by its Result property.
Task<int> t = Task.Run(() =>
{
int sum = 0;
for(int i = 0; i < 500; i++)
sum += i;
return sum;
});
Console.WriteLine(t.Result); // Outuput 124750
If the Task execute asynchronously than awaiting the Task returns it's result.
public async Task DoSomeWork()
{
WebClient client = new WebClient();
// Because the task is awaited, result of the task is assigned to response
string response = await client.DownloadStringTaskAsync("http://somedomain.com");
}
Section 42.4: Parallel.ForEach
This example uses Parallel.ForEach to calculate the sum of the numbers between 1 and 10000 by using multiple
threads. To achieve thread-safety, Interlocked.Add is used to sum the numbers.
using System.Threading;
int Foo()
{
int total = 0;
var numbers = Enumerable.Range(1, 10000).ToList();
Parallel.ForEach(numbers,
() => 0, // initial value,
(num, state, localSum) => num + localSum,
localSum => Interlocked.Add(ref total, localSum));
return total; // total = 50005000
}
Section 42.5: Parallel.For
This example uses Parallel.For to calculate the sum of the numbers between 1 and 10000 by using multiple
threads. To achieve thread-safety, Interlocked.Add is used to sum the numbers.
using System.Threading;
int Foo()
{
int total = 0;
Parallel.For(1, 10001,
GoalKicker.com – .NET Framework Notes for Professionals
131
() => 0, // initial value,
(num, state, localSum) => num + localSum,
localSum => Interlocked.Add(ref total, localSum));
return total; // total = 50005000
}
Section 42.6: Task: basic instantiation and Wait
A task can be created by directly instantiating the Task class...
var task = new Task(() =>
{
Console.WriteLine("Task code starting...");
Thread.Sleep(2000);
Console.WriteLine("...task code ending!");
});
Console.WriteLine("Starting task...");
task.Start();
task.Wait();
Console.WriteLine("Task completed!");
...or by using the static Task.Run method:
Console.WriteLine("Starting task...");
var task = Task.Run(() =>
{
Console.WriteLine("Task code starting...");
Thread.Sleep(2000);
Console.WriteLine("...task code ending!");
});
task.Wait();
Console.WriteLine("Task completed!");
Note that only in the first case it is necessary to explicitly invoke Start.
Section 42.7: Task.WhenAll
var random = new Random();
IEnumerable<Task<int>> tasks = Enumerable.Range(1, 5).Select(n => Task.Run(() =>
{
Console.WriteLine("I'm task " + n);
return n;
}));
Task<int[]> task = Task.WhenAll(tasks);
int[] results = await task;
Console.WriteLine(string.Join(",", results.Select(n => n.ToString())));
// Output: 1,2,3,4,5
Section 42.8: Flowing execution context with AsyncLocal
When you need to pass some data from the parent task to its children tasks, so it logically flows with the execution,
use AsyncLocal class:
void Main()
{
GoalKicker.com – .NET Framework Notes for Professionals
132
AsyncLocal<string> user = new AsyncLocal<string>();
user.Value = "initial user";
// this does not affect other tasks - values are local relative to the branches of execution flow
Task.Run(() => user.Value = "user from another task");
var task1 = Task.Run(() =>
{
Console.WriteLine(user.Value); // outputs "initial user"
Task.Run(() =>
{
// outputs "initial user" - value has flown from main method to this task without being
changed
Console.WriteLine(user.Value);
}).Wait();
user.Value = "user from task1";
Task.Run(() =>
{
// outputs "user from task1" - value has flown from main method to task1
// than value was changed and flown to this task.
Console.WriteLine(user.Value);
}).Wait();
});
task1.Wait();
// outputs "initial user" - changes do not propagate back upstream the execution flow
Console.WriteLine(user.Value);
}
Note: As can be seen from the example above AsynLocal.Value has copy on read semantic, but if you flow some
reference type and change its properties you will affect other tasks. Hence, best practice with AsyncLocal is to use
value types or immutable types.
Section 42.9: Parallel.ForEach in VB.NET
For Each row As DataRow In FooDataTable.Rows
Me.RowsToProcess.Add(row)
Next
Dim myOptions As ParallelOptions = New ParallelOptions()
myOptions.MaxDegreeOfParallelism = environment.processorcount
Parallel.ForEach(RowsToProcess, myOptions, Sub(currentRow, state)
ProcessRowParallel(currentRow, state)
End Sub)
Section 42.10: Task: WaitAll and variable capturing
var tasks = Enumerable.Range(1, 5).Select(n => new Task<int>(() =>
{
Console.WriteLine("I'm task " + n);
return n;
})).ToArray();
foreach(var task in tasks) task.Start();
Task.WaitAll(tasks);
GoalKicker.com – .NET Framework Notes for Professionals
133
foreach(var task in tasks)
Console.WriteLine(task.Result);
Section 42.11: Task: WaitAny
var allTasks = Enumerable.Range(1, 5).Select(n => new Task<int>(() => n)).ToArray();
var pendingTasks = allTasks.ToArray();
foreach(var task in allTasks) task.Start();
while(pendingTasks.Length > 0)
{
var finishedTask = pendingTasks[Task.WaitAny(pendingTasks)];
Console.WriteLine("Task {0} finished", finishedTask.Result);
pendingTasks = pendingTasks.Except(new[] {finishedTask}).ToArray();
}
Task.WaitAll(allTasks);
Note: The final WaitAll is necessary becasue WaitAny does not cause exceptions to be observed.
Section 42.12: Task: handling exceptions (using Wait)
var task1 = Task.Run(() =>
{
Console.WriteLine("Task 1 code starting...");
throw new Exception("Oh no, exception from task 1!!");
});
var task2 = Task.Run(() =>
{
Console.WriteLine("Task 2 code starting...");
throw new Exception("Oh no, exception from task 2!!");
});
Console.WriteLine("Starting tasks...");
try
{
Task.WaitAll(task1, task2);
}
catch(AggregateException ex)
{
Console.WriteLine("Task(s) failed!");
foreach(var inner in ex.InnerExceptions)
Console.WriteLine(inner.Message);
}
Console.WriteLine("Task 1 status is: " + task1.Status); //Faulted
Console.WriteLine("Task 2 status is: " + task2.Status); //Faulted
Section 42.13: Task: handling exceptions (without using Wait)
var task1 = Task.Run(() =>
{
Console.WriteLine("Task 1 code starting...");
throw new Exception("Oh no, exception from task 1!!");
});
var task2 = Task.Run(() =>
GoalKicker.com – .NET Framework Notes for Professionals
134
{
Console.WriteLine("Task 2 code starting...");
throw new Exception("Oh no, exception from task 2!!");
});
var tasks = new[] {task1, task2};
Console.WriteLine("Starting tasks...");
while(tasks.All(task => !task.IsCompleted));
foreach(var task in tasks)
{
if(task.IsFaulted)
Console.WriteLine("Task failed: " +
task.Exception.InnerExceptions.First().Message);
}
Console.WriteLine("Task 1 status is: " + task1.Status); //Faulted
Console.WriteLine("Task 2 status is: " + task2.Status); //Faulted
Section 42.14: Task: cancelling using CancellationToken
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
var task = new Task((state) =>
{
int i = 1;
var myCancellationToken = (CancellationToken)state;
while(true)
{
Console.Write("{0} ", i++);
Thread.Sleep(1000);
myCancellationToken.ThrowIfCancellationRequested();
}
},
cancellationToken: cancellationToken,
state: cancellationToken);
Console.WriteLine("Counting to infinity. Press any key to cancel!");
task.Start();
Console.ReadKey();
cancellationTokenSource.Cancel();
try
{
task.Wait();
}
catch(AggregateException ex)
{
ex.Handle(inner => inner is OperationCanceledException);
}
Console.WriteLine($"{Environment.NewLine}You have cancelled! Task status is: {task.Status}");
//Canceled
As an alternative to ThrowIfCancellationRequested, the cancellation request can be detected with
IsCancellationRequested and a OperationCanceledException can be thrown manually:
//New task delegate
GoalKicker.com – .NET Framework Notes for Professionals
135
int i = 1;
var myCancellationToken = (CancellationToken)state;
while(!myCancellationToken.IsCancellationRequested)
{
Console.Write("{0} ", i++);
Thread.Sleep(1000);
}
Console.WriteLine($"{Environment.NewLine}Ouch, I have been cancelled!!");
throw new OperationCanceledException(myCancellationToken);
Note how the cancellation token is passed to the task constructor in the cancellationToken parameter. This is
needed so that the task transitions to the Canceled state, not to the Faulted state, when
ThrowIfCancellationRequested is invoked. Also, for the same reason, the cancellation token is explicitly supplied
in the constructor of OperationCanceledException in the second case.
Section 42.15: Task.WhenAny
var random = new Random();
IEnumerable<Task<int>> tasks = Enumerable.Range(1, 5).Select(n => Task.Run(async() =>
{
Console.WriteLine("I'm task " + n);
await Task.Delay(random.Next(10,1000));
return n;
}));
Task<Task<int>> whenAnyTask = Task.WhenAny(tasks);
Task<int> completedTask = await whenAnyTask;
Console.WriteLine("The winner is: task " + await completedTask);
await Task.WhenAll(tasks);
Console.WriteLine("All tasks finished!");
GoalKicker.com – .NET Framework Notes for Professionals
136
Chapter 43: Task Parallel Library (TPL) API
Overviews
Section 43.1: Perform work in response to a button click and
update the UI
This example demonstrates how you can respond to a button click by performing some work on a worker thread
and then update the user interface to indicate completion
void MyButton_OnClick(object sender, EventArgs args)
{
Task.Run(() => // Schedule work using the thread pool
{
System.Threading.Thread.Sleep(5000); // Sleep for 5 seconds to simulate work.
})
.ContinueWith(p => // this continuation contains the 'update' code to run on the UI thread
{
this.TextBlock_ResultText.Text = "The work completed at " + DateTime.Now.ToString()
},
TaskScheduler.FromCurrentSynchronizationContext()); // make sure the update is run on the UI
thread.
}
GoalKicker.com – .NET Framework Notes for Professionals
137
Chapter 44: Synchronization Contexts
Section 44.1: Execute code on the UI thread after performing
background work
This example shows how to update a UI component from a background thread by using a SynchronizationContext
void Button_Click(object sender, EventArgs args)
{
SynchronizationContext context = SynchronizationContext.Current;
Task.Run(() =>
{
for(int i = 0; i < 10; i++)
{
Thread.Sleep(500); //simulate work being done
context.Post(ShowProgress, "Work complete on item " + i);
}
}
}
void UpdateCallback(object state)
{
// UI can be safely updated as this method is only called from the UI thread
this.MyTextBox.Text = state as string;
}
In this example, if you tried to directly update MyTextBox.Text inside the for loop, you would get a threading error.
By posting the UpdateCallback action to the SynchronizationContext, the text box is updated on the same thread
as the rest of the UI.
In practice, progress updates should be performed using an instance of System.IProgress<T>. The default
implementation System.Progress<T> automatically captures the synchronisation context it is created on.
GoalKicker.com – .NET Framework Notes for Professionals
138
Chapter 45: Memory management
Section 45.1: Use SafeHandle when wrapping unmanaged
resources
When writing wrappers for unmanaged resources, you should subclass SafeHandle rather than trying to implement
IDisposable and a finalizer yourself. Your SafeHandle subclass should be as small and simple as possible to
minimize the chance of a handle leak. This likely means that your SafeHandle implementation would an internal
implementation detail of a class which wraps it to provide a usable API. This class ensures that, even if a program
leaks your SafeHandle instance, your unmanaged handle is released.
using System.Runtime.InteropServices;
class MyHandle : SafeHandle
{
public override bool IsInvalid => handle == IntPtr.Zero;
public MyHandle() : base(IntPtr.Zero, true)
{ }
public MyHandle(int length) : this()
{
SetHandle(Marshal.AllocHGlobal(length));
}
protected override bool ReleaseHandle()
{
Marshal.FreeHGlobal(handle);
return true;
}
}
Disclaimer: This example is an attempt to show how to guard a managed resource with SafeHandle which
implements IDisposable for you and configures finalizers appropriately. It is very contrived and likely pointless to
allocate a chunk of memory in this manner.
Section 45.2: Unmanaged Resources
When we talk about the GC and the "heap", we're really talking about what's called the managed heap. Objects on
the managed heap can access resources not on the managed heap, for example, when writing to or reading from a
file. Unexpected behavior can occur when, a file is opened for reading and then an exception occurs, preventing the
file handle from closing as it normally would. For this reason, .NET requires that unmanaged resources implement
the IDisposable interface. This interface has a single method called Dispose with no parameters:
public interface IDisposable
{
Dispose();
}
When handling unmanaged resources, you should make sure that they are properly disposed. You can do this by
explicitly calling Dispose() in a finally block, or with a using statement.
StreamReader sr;
string textFromFile;
string filename = "SomeFile.txt";
try
GoalKicker.com – .NET Framework Notes for Professionals
139
{
sr = new StreamReader(filename);
textFromFile = sr.ReadToEnd();
}
finally
{
if (sr != null) sr.Dispose();
}
or
string textFromFile;
string filename = "SomeFile.txt";
using (StreamReader sr = new Streamreader(filename))
{
textFromFile = sr.ReadToEnd();
}
The latter is the preferred method, and is automatically expanded to the former during compilation.
GoalKicker.com – .NET Framework Notes for Professionals
140
Chapter 46: Garbage Collection
In .Net, objects created with new() are allocated on the managed heap. These objects are never explicitly finalized
by the program that uses them; instead, this process is controlled by the .Net Garbage Collector.
Some of the examples below are "lab cases" to show the Garbage Collector at work and some significant details of
its behavior, while other focus on how to prepare classes for proper handling by the Garbage Collector.
Section 46.1: A basic example of (garbage) collection
Given the following class:
public class FinalizableObject
{
public FinalizableObject()
{
Console.WriteLine("Instance initialized");
}
~FinalizableObject()
{
Console.WriteLine("Instance finalized");
}
}
A program that creates an instance, even without using it:
new FinalizableObject(); // Object instantiated, ready to be used
Produces the following output:
<namespace>.FinalizableObject initialized
If nothing else happens, the object is not finalized until the program ends (which frees all objects on the managed
heap, finalizing these in the process).
It is possible to force the Garbage Collector to run at a given point, as follows:
new FinalizableObject(); // Object instantiated, ready to be used
GC.Collect();
Which produces the following result:
<namespace>.FinalizableObject initialized
<namespace>.FinalizableObject finalized
This time, as soon as the Garbage Collector was invoked, the unused (aka "dead") object was finalized and freed
from the managed heap.
Section 46.2: Live objects and dead objects - the basics
Rule of thumb: when garbage collection occurs, "live objects" are those still in use, while "dead objects" are those
no longer used (any variable or field referencing them, if any, has gone out of scope before the collection occurs).
GoalKicker.com – .NET Framework Notes for Professionals
141
In the following example (for convenience, FinalizableObject1 and FinalizableObject2 are subclasses of
FinalizableObject from the example above and thus inherit the initialization / finalization message behavior):
var obj1 = new FinalizableObject1(); // Finalizable1 instance allocated here
var obj2 = new FinalizableObject2(); // Finalizable2 instance allocated here
obj1 = null; // No more references to the Finalizable1 instance
GC.Collect();
The output will be:
<namespace>.FinalizableObject1 initialized
<namespace>.FinalizableObject2 initialized
<namespace>.FinalizableObject1 finalized
At the time when the Garbage Collector is invoked, FinalizableObject1 is a dead object and gets finalized, while
FinalizableObject2 is a live object and it is kept on the managed heap.
Section 46.3: Multiple dead objects
What if two (or several) otherwise dead objects reference one another? This is shown in the example below,
supposing that OtherObject is a public property of FinalizableObject:
var obj1 = new FinalizableObject1();
var obj2 = new FinalizableObject2();
obj1.OtherObject = obj2;
obj2.OtherObject = obj1;
obj1 = null; // Program no longer references Finalizable1 instance
obj2 = null; // Program no longer references Finalizable2 instance
// But the two objects still reference each other
GC.Collect();
This produces the following output:
<namespace>.FinalizedObject1 initialized
<namespace>.FinalizedObject2 initialized
<namespace>.FinalizedObject1 finalized
<namespace>.FinalizedObject2 finalized
The two objects are finalized and freed from the managed heap despite referencing each other (because no other
reference exists to any of them from an actually live object).
Section 46.4: Weak References
Weak references are... references, to other objects (aka "targets"), but "weak" as they do not prevent those objects
from being garbage-collected. In other words, weak references do not count when the Garbage Collector evaluates
objects as "live" or "dead".
The following code:
var weak = new WeakReference<FinalizableObject>(new FinalizableObject());
GC.Collect();
Produces the output:
<namespace>.FinalizableObject initialized
GoalKicker.com – .NET Framework Notes for Professionals
142
<namespace>.FinalizableObject finalized
The object is freed from the managed heap despite being referenced by the WeakReference variable (still in scope
when the Garbage collector was invoked).
Consequence #1: at any time, it is unsafe to assume whether a WeakReference target is still allocated on the
managed heap or not.
Consequence #2: whenever a program needs to access the target of a Weakreference, code should be provided for
both cases, of the target being still allocated or not. The method to access the target is TryGetTarget:
var target = new object(); // Any object will do as target
var weak = new WeakReference<object>(target); // Create weak reference
target = null; // Drop strong reference to the target
// ... Many things may happen in-between
// Check whether the target is still available
if(weak.TryGetTarget(out target))
{
// Use re-initialized target variable
// To do whatever the target is needed for
}
else
{
// Do something when there is no more target object
// The target variable value should not be used here
}
The generic version of WeakReference is available since .Net 4.5. All framework versions provide a non-generic,
untyped version that is built in the same way and checked as follows:
var target = new object(); // Any object will do as target
var weak = new WeakReference(target); // Create weak reference
target = null; // Drop strong reference to the target
// ... Many things may happen in-between
// Check whether the target is still available
if (weak.IsAlive)
{
target = weak.Target;
// Use re-initialized target variable
// To do whatever the target is needed for
}
else
{
// Do something when there is no more target object
// The target variable value should not be used here
}
Section 46.5: Dispose() vs. finalizers
Implement Dispose() method (and declare the containing class as IDisposable) as a means to ensure any memory-
heavy resources are freed as soon as the object is no longer used. The "catch" is that there is no strong guarantee
the the Dispose() method would ever be invoked (unlike finalizers that always get invoked at the end of the life of
the object).
GoalKicker.com – .NET Framework Notes for Professionals
143
One scenario is a program calling Dispose() on objects it explicitly creates:
private void SomeFunction()
{
// Initialize an object that uses heavy external resources
var disposableObject = new ClassThatImplementsIDisposable();
// ... Use that object
// Dispose as soon as no longer used
disposableObject.Dispose();
// ... Do other stuff
// The disposableObject variable gets out of scope here
// The object will be finalized later on (no guarantee when)
// But it no longer holds to the heavy external resource after it was disposed
}
Another scenario is declaring a class to be instantiated by the framework. In this case the new class usually inherits
a base class, for instance in MVC one creates a controller class as a subclass of System.Web.Mvc.ControllerBase.
When the base class implements IDisposable interface, this is a good hint that Dispose() would be invoked properly
by the framework - but again there is no strong guarantee.
Thus Dispose() is not a substitute for a finalizer; instead, the two should be used for different purposes:
A finalizer eventually frees resources to avoid memory leaks that would occur otherwise
Dispose() frees resources (possibly the same ones) as soon as these are no longer needed, to ease pressure
on overall memory allocation.
Section 46.6: Proper disposal and finalization of objects
As Dispose() and finalizers are aimed to different purposes, a class managing external memory-heavy resources
should implement both of them. The consequence is writing the class so that it handles well two possible scenarios:
When only the finalizer is invoked
When Dispose() is invoked first and later the finalizer is invoked as well
One solution is writing the cleanup code in such a way that running it once or twice would produce the same result
as running it only once. Feasibility depends on the nature of the cleanup, for instance:
Closing an already closed database connection would probably have no effect so it works
Updating some "usage count" is dangerous and would produce a wrong result when called twice instead of
once.
A safer solution is ensuring by design that the cleanup code is called once and only once whatever the external
context. This can be achieved the "classic way" using a dedicated flag:
public class DisposableFinalizable1: IDisposable
{
private bool disposed = false;
~DisposableFinalizable1() { Cleanup(); }
public void Dispose() { Cleanup(); }
private void Cleanup()
GoalKicker.com – .NET Framework Notes for Professionals
144
{
if(!disposed)
{
// Actual code to release resources gets here, then
disposed = true;
}
}
}
Alternately, the Garbage Collector provides a specific method SuppressFinalize() that allows skipping the finalizer
after Dispose has been invoked:
public class DisposableFinalizable2 : IDisposable
{
~DisposableFinalizable2() { Cleanup(); }
public void Dispose()
{
Cleanup();
GC.SuppressFinalize(this);
}
private void Cleanup()
{
// Actual code to release resources gets here
}
}
GoalKicker.com – .NET Framework Notes for Professionals
145
Chapter 47: Exceptions
Section 47.1: Catching and rethrowing caught exceptions
When you want to catch an exception and do something, but you can't continue execution of the current block of
code because of the exception, you may want to rethrow the exception to the next exception handler in the call
stack. There are good ways and bad ways to do this.
private static void AskTheUltimateQuestion()
{
try
{
var x = 42;
var y = x / (x - x); // will throw a DivideByZeroException
// IMPORTANT NOTE: the error in following string format IS intentional
// and exists to throw an exception to the FormatException catch, below
Console.WriteLine("The secret to life, the universe, and everything is {1}", y);
}
catch (DivideByZeroException)
{
// we do not need a reference to the exception
Console.WriteLine("Dividing by zero would destroy the universe.");
// do this to preserve the stack trace:
throw;
}
catch (FormatException ex)
{
// only do this if you need to change the type of the Exception to be thrown
// and wrap the inner Exception
// remember that the stack trace of the outer Exception will point to the
// next line
// you'll need to examine the InnerException property to get the stack trace
// to the line that actually started the problem
throw new InvalidOperationException("Watch your format string indexes.", ex);
}
catch (Exception ex)
{
Console.WriteLine("Something else horrible happened. The exception: " + ex.Message);
// do not do this, because the stack trace will be changed to point to
// this location instead of the location where the exception
// was originally thrown:
throw ex;
}
}
static void Main()
{
try
{
AskTheUltimateQuestion();
}
catch
{
// choose this kind of catch if you don't need any information about
GoalKicker.com – .NET Framework Notes for Professionals
146
// the exception that was caught
// this block "eats" all exceptions instead of rethrowing them
}
}
You can filter by exception type and even by exception properties (new in C# 6.0, a bit longer available in VB.NET
(citation needed)):
Documentation/C#/new features
Section 47.2: Using a finally block
The finally { ... } block of a try-finally or try-catch-finally will always execute, regardless of whether an
exception occurred or not (except when a StackOverflowException has been thrown or call has been made to
Environment.FailFast()).
It can be utilized to free or clean up resources acquired in the try { ... } block safely.
Console.Write("Please enter a filename: ");
string filename = Console.ReadLine();
Stream fileStream = null;
try
{
fileStream = File.Open(filename);
}
catch (FileNotFoundException)
{
Console.WriteLine("File '{0}' could not be found.", filename);
}
finally
{
if (fileStream != null)
{
fileStream.Dispose();
}
}
Section 47.3: Exception Filters
Since C# 6.0 exceptions can be filtered using the when operator.
This is similar to using a simple if but does not unwind the stack if the condition inside the when is not met.
Example
try
{
// ...
}
catch (Exception e) when (e.InnerException != null) // Any condition can go in here.
{
// ...
}
The same info can be found in the C# 6.0 Features here: Exception filters
GoalKicker.com – .NET Framework Notes for Professionals
147
Section 47.4: Rethrowing an exception within a catch block
Within a catch block the throw keyword can be used on its own, without specifying an exception value, to rethrow
the exception which was just caught. Rethrowing an exception allows the original exception to continue up the
exception handling chain, preserving its call stack or associated data:
try {...}
catch (Exception ex) {
// Note: the ex variable is *not* used
throw;
}
A common anti-pattern is to instead throw ex, which has the effect of limiting the next exception handler's view of
the stack trace:
try {...}
catch (Exception ex) {
// Note: the ex variable is thrown
// future stack traces of the exception will not see prior calls
throw ex;
}
In general using throw ex isn't desirable, as future exception handlers which inspect the stack trace will only be
able to see calls as far back as throw ex. By omitting the ex variable, and using the throw keyword alone the
original exception will "bubble-up".
Section 47.5: Throwing an exception from a dierent method
while preserving its information
Occasionally you'd want to catch an exception and throw it from a different thread or method while preserving the
original exception stack. This can be done with ExceptionDispatchInfo:
using System.Runtime.ExceptionServices;
void Main()
{
ExceptionDispatchInfo capturedException = null;
try
{
throw new Exception();
}
catch (Exception ex)
{
capturedException = ExceptionDispatchInfo.Capture(ex);
}
Foo(capturedException);
}
void Foo(ExceptionDispatchInfo exceptionDispatchInfo)
{
// Do stuff
if (capturedException != null)
{
// Exception stack trace will show it was thrown from Main() and not from Foo()
exceptionDispatchInfo.Throw();
}
GoalKicker.com – .NET Framework Notes for Professionals
148
}
Section 47.6: Catching an exception
Code can and should throw exceptions in exceptional circumstances. Examples of this include:
Attempting to read past the end of a stream
Not having necessary permissions to access a file
Attempting to perform an invalid operation, such as dividing by zero
A timeout occurring when downloading a file from the internet
The caller can handle these exceptions by "catching" them, and should only do so when:
It can actually resolve the exceptional circumstance or recover appropriately, or;
It can provide additional context to the exception that would be useful if the exception needs to be re-thrown
(re-thrown exceptions are caught by exception handlers further up the call stack)
It should be noted that choosing not to catch an exception is perfectly valid if the intention is for it to be handled at
a higher level.
Catching an exception is done by wrapping the potentially-throwing code in a try { ... } block as follows, and
catching the exceptions it's able to handle in a catch (ExceptionType) { ... } block:
Console.Write("Please enter a filename: ");
string filename = Console.ReadLine();
Stream fileStream;
try
{
fileStream = File.Open(filename);
}
catch (FileNotFoundException)
{
Console.WriteLine("File '{0}' could not be found.", filename);
}
GoalKicker.com – .NET Framework Notes for Professionals
149
Chapter 48: System.Diagnostics
Section 48.1: Run shell commands
string strCmdText = "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);
This is to hide the cmd window.
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
process.StartInfo = startInfo;
process.Start();
Section 48.2: Send Command to CMD and Receive Output
This method allows a command to be sent to Cmd.exe, and returns the standard output (including standard error) as
a string:
private static string SendCommand(string command)
{
var cmdOut = string.Empty;
var startInfo = new ProcessStartInfo("cmd", command)
{
WorkingDirectory = @"C:\Windows\System32", // Directory to make the call from
WindowStyle = ProcessWindowStyle.Hidden, // Hide the window
UseShellExecute = false, // Do not use the OS shell to start the process
CreateNoWindow = true, // Start the process in a new window
RedirectStandardOutput = true, // This is required to get STDOUT
RedirectStandardError = true // This is required to get STDERR
};
var p = new Process {StartInfo = startInfo};
p.Start();
p.OutputDataReceived += (x, y) => cmdOut += y.Data;
p.ErrorDataReceived += (x, y) => cmdOut += y.Data;
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
return cmdOut;
}
Usage
var servername = "SVR-01.domain.co.za";
var currentUsers = SendCommand($"/C QUERY USER /SERVER:{servername}")
Output
string currentUsers = "USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME Joe.Bloggs ica-cgp#0 2
GoalKicker.com – .NET Framework Notes for Professionals
150
Active 24692+13:29 25/07/2016 07:50 Jim.McFlannegan ica-cgp#1 3 Active . 25/07/2016 08:33
Andy.McAnderson ica-cgp#2 4 Active . 25/07/2016 08:54 John.Smith ica-cgp#4 5 Active 14 25/07/2016
08:57 Bob.Bobbington ica-cgp#5 6 Active 24692+13:29 25/07/2016 09:05 Tim.Tom ica-cgp#6 7 Active .
25/07/2016 09:08 Bob.Joges ica-cgp#7 8 Active 24692+13:29 25/07/2016 09:13"
On some occasions, access to the server in question may be restricted to certain users. If you have the login
credentials for this user, then it is possible to send queries with this method:
private static string SendCommand(string command)
{
var cmdOut = string.Empty;
var startInfo = new ProcessStartInfo("cmd", command)
{
WorkingDirectory = @"C:\Windows\System32",
WindowStyle = ProcessWindowStyle.Hidden, // This does not actually work in conjunction
with "runas" - the console window will still appear!
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
Verb = "runas",
Domain = "doman1.co.za",
UserName = "administrator",
Password = GetPassword()
};
var p = new Process {StartInfo = startInfo};
p.Start();
p.OutputDataReceived += (x, y) => cmdOut += y.Data;
p.ErrorDataReceived += (x, y) => cmdOut += y.Data;
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
return cmdOut;
}
Getting the password:
static SecureString GetPassword()
{
var plainText = "password123";
var ss = new SecureString();
foreach (char c in plainText)
{
ss.AppendChar(c);
}
return ss;
}
Notes
Both of the above methods will return a concatenation of STDOUT and STDERR, as OutputDataReceived and
ErrorDataReceived are both appending to the same variable - cmdOut.
GoalKicker.com – .NET Framework Notes for Professionals
151
Section 48.3: Stopwatch
This example shows how Stopwatch can be used to benchmark a block of code.
using System;
using System.Diagnostics;
public class Benchmark : IDisposable
{
private Stopwatch sw;
public Benchmark()
{
sw = Stopwatch.StartNew();
}
public void Dispose()
{
sw.Stop();
Console.WriteLine(sw.Elapsed);
}
}
public class Program
{
public static void Main()
{
using (var bench = new Benchmark())
{
Console.WriteLine("Hello World");
}
}
}
GoalKicker.com – .NET Framework Notes for Professionals
152
Chapter 49: Encryption / Cryptography
Section 49.1: Encryption and Decryption using Cryptography
(AES)
Decryption Code
public static string Decrypt(string cipherText)
{
if (cipherText == null)
return null;
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(CryptKey, new byte[] { 0x49, 0x76,
0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(),
CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
Encryption Code
public static string Encrypt(string cipherText)
{
if (cipherText == null)
return null;
byte[] clearBytes = Encoding.Unicode.GetBytes(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(CryptKey, new byte[] { 0x49, 0x76,
0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(),
CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
GoalKicker.com – .NET Framework Notes for Professionals
153
cipherText = Convert.ToBase64String(ms.ToArray());
}
}
return cipherText;
}
Usage
var textToEncrypt = "TestEncrypt";
var encrypted = Encrypt(textToEncrypt);
var decrypted = Decrypt(encrypted);
Section 49.2: RijndaelManaged
Required Namespace: System.Security.Cryptography
private class Encryption {
private const string SecretKey = "topSecretKeyusedforEncryptions";
private const string SecretIv = "secretVectorHere";
public string Encrypt(string data) {
return string.IsNullOrEmpty(data) ? data :
Convert.ToBase64String(this.EncryptStringToBytesAes(data, this.GetCryptographyKey(),
this.GetCryptographyIv()));
}
public string Decrypt(string data) {
return string.IsNullOrEmpty(data) ? data :
this.DecryptStringFromBytesAes(Convert.FromBase64String(data), this.GetCryptographyKey(),
this.GetCryptographyIv());
}
private byte[] GetCryptographyKey() {
return Encoding.ASCII.GetBytes(SecretKey.Replace('e', '!'));
}
private byte[] GetCryptographyIv() {
return Encoding.ASCII.GetBytes(SecretIv.Replace('r', '!'));
}
private byte[] EncryptStringToBytesAes(string plainText, byte[] key, byte[] iv) {
MemoryStream encrypt;
RijndaelManaged aesAlg = null;
try {
aesAlg = new RijndaelManaged {
Key = key,
IV = iv
};
var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
encrypt = new MemoryStream();
using (var csEncrypt = new CryptoStream(encrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt)) {
swEncrypt.Write(plainText);
}
}
GoalKicker.com – .NET Framework Notes for Professionals
154
} finally {
aesAlg?.Clear();
}
return encrypt.ToArray();
}
private string DecryptStringFromBytesAes(byte[] cipherText, byte[] key, byte[] iv) {
RijndaelManaged aesAlg = null;
string plaintext;
try {
aesAlg = new RijndaelManaged {
Key = key,
IV = iv
};
var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (var msDecrypt = new MemoryStream(cipherText)) {
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor,
CryptoStreamMode.Read)) {
using (var srDecrypt = new StreamReader(csDecrypt))
plaintext = srDecrypt.ReadToEnd();
}
}
} finally {
aesAlg?.Clear();
}
return plaintext;
}
}
Usage
var textToEncrypt = "hello World";
var encrypted = new Encryption().Encrypt(textToEncrypt); //-> zBmW+FUxOvdbpOGm9Ss/vQ==
var decrypted = new Encryption().Decrypt(encrypted); //-> hello World
Note:
Rijndael is the predecessor of the standard symmetric cryptographic algorithm AES.
Section 49.3: Encrypt and decrypt data using AES (in C#)
using System;
using System.IO;
using System.Security.Cryptography;
namespace Aes_Example
{
class AesExample
{
public static void Main()
{
try
{
string original = "Here is some data to encrypt!";
// Create a new instance of the Aes class.
// This generates a new key and initialization vector (IV).
using (Aes myAes = Aes.Create())
GoalKicker.com – .NET Framework Notes for Professionals
155
{
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes_Aes(original,
myAes.Key,
myAes.IV);
// Decrypt the bytes to a string.
string roundtrip = DecryptStringFromBytes_Aes(encrypted,
myAes.Key,
myAes.IV);
//Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Round Trip: {0}", roundtrip);
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
}
static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
// Create an Aes object with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key,
aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt,
encryptor,
CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
GoalKicker.com – .NET Framework Notes for Professionals
156
// Return the encrypted bytes from the memory stream.
return encrypted;
}
static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
// Declare the string used to hold the decrypted text.
string plaintext = null;
// Create an Aes object with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key,
aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt,
decryptor,
CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
}
This example is from MSDN.
It is a console demo application, showing how to encrypt a string by using the standard AES encryption, and how to
decrypt it afterwards.
(AES = Advanced Encryption Standard, a specification for the encryption of electronic data established by the U.S.
National Institute of Standards and Technology (NIST) in 2001 which is still the de-facto standard for symmetric
encryption)
Notes:
GoalKicker.com – .NET Framework Notes for Professionals
157
In a real encryption scenario, you need to choose a proper cipher mode (can be assigned to the Mode
property by selecting a value from the CipherMode enumeration). Never use the CipherMode.ECB (electronic
codebook mode), since this procuces a weak cypher stream
To create a good (and not a weak) Key, either use a cryptographic random generator or use the example
above (Create a Key from a Password). The recommended KeySize is 256 bit. Supported key sizes are
available via the LegalKeySizes property.
To initialize the initialization vector IV, you can use a SALT as shown in the example above (Random SALT)
Supported block sizes are available via the SupportedBlockSizes property, the block size can be assigned via
the BlockSize property
Usage: see Main() method.
Section 49.4: Create a Key from a Password / Random SALT
(in C#)
using System;
using System.Security.Cryptography;
using System.Text;
public class PasswordDerivedBytesExample
{
public static void Main(String[] args)
{
// Get a password from the user.
Console.WriteLine("Enter a password to produce a key:");
byte[] pwd = Encoding.Unicode.GetBytes(Console.ReadLine());
byte[] salt = CreateRandomSalt(7);
// Create a TripleDESCryptoServiceProvider object.
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
try
{
Console.WriteLine("Creating a key with PasswordDeriveBytes...");
// Create a PasswordDeriveBytes object and then create
// a TripleDES key from the password and salt.
PasswordDeriveBytes pdb = new PasswordDeriveBytes(pwd, salt);
// Create the key and set it to the Key property
// of the TripleDESCryptoServiceProvider object.
tdes.Key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV);
Console.WriteLine("Operation complete.");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
// Clear the buffers
ClearBytes(pwd);
ClearBytes(salt);
GoalKicker.com – .NET Framework Notes for Professionals
158
// Clear the key.
tdes.Clear();
}
Console.ReadLine();
}
#region Helper methods
/// <summary>
/// Generates a random salt value of the specified length.
/// </summary>
public static byte[] CreateRandomSalt(int length)
{
// Create a buffer
byte[] randBytes;
if (length >= 1)
{
randBytes = new byte[length];
}
else
{
randBytes = new byte[1];
}
// Create a new RNGCryptoServiceProvider.
RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();
// Fill the buffer with random bytes.
rand.GetBytes(randBytes);
// return the bytes.
return randBytes;
}
/// <summary>
/// Clear the bytes in a buffer so they can't later be read from memory.
/// </summary>
public static void ClearBytes(byte[] buffer)
{
// Check arguments.
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
// Set each byte in the buffer to 0.
for (int x = 0; x < buffer.Length; x++)
{
buffer[x] = 0;
}
}
#endregion
}
This example is taken from MSDN.
It is a console demo, and it shows how to create a secure key based on a user-defined password, and how to create
a random SALT based on the cryptographic random generator.
GoalKicker.com – .NET Framework Notes for Professionals
159
Notes:
The built-in function PasswordDeriveBytes uses the standard PBKDF1 algorithm to generate a key from the
password. Per default, it uses 100 iterations to generate the key to slow down brute force attacks. The SALT
generated randomly further strenghens the key.
The function CryptDeriveKey converts the key generated by PasswordDeriveBytes into a key compatible
with the specified encryption algorithm (here "TripleDES") by using the specified hash algorithm (here
"SHA1"). The keysize in this example is 192 bytes, and the initialization vector IV is taken from the triple-DES
crypto provider
Usually, this mechanism is used to protect a stronger random generated key by a password, which encrypts
large amount of data. You can also use it to provide multiple passwords of different users to give access to
the same data (being protected by a different random key).
Unfortunately, CryptDeriveKey does currently not support AES. See here.
NOTE: As a workaround, you can create a random AES key for encryption of the data to be protected with
AES and store the AES key in a TripleDES-Container which uses the key generated by CryptDeriveKey. But
that limits the security to TripleDES, does not take advantage of the larger keysizes of AES and creates a
dependency to TripleDES.
Usage: See Main() method.
GoalKicker.com – .NET Framework Notes for Professionals
160
Chapter 50: Work with SHA1 in C#
in this project you see how to work with SHA1 cryptographic hash function. for example get hash from string and
how to crack SHA1 hash.
source compelete on github: https://github.com/mahdiabasi/SHA1Tool
Section 50.1: #Generate SHA1 checksum of a file
first you add System.Security.Cryptography namespace to your project
public string GetSha1Hash(string filePath)
{
using (FileStream fs = File.OpenRead(filePath))
{
SHA1 sha = new SHA1Managed();
return BitConverter.ToString(sha.ComputeHash(fs));
}
}
Section 50.2: #Generate hash of a text
public static string TextToHash(string text)
{
var sh = SHA1.Create();
var hash = new StringBuilder();
byte[] bytes = Encoding.UTF8.GetBytes(text);
byte[] b = sh.ComputeHash(bytes);
foreach (byte a in b)
{
var h = a.ToString("x2");
hash.Append(h);
}
return hash.ToString();
}
GoalKicker.com – .NET Framework Notes for Professionals
161
Chapter 51: Unit testing
Section 51.1: Adding MSTest unit testing project to an existing
solution
Right click on the solution, Add new project
From the Test section, select an Unit Test Project
Pick a name for the assembly - if you are testing project Foo, the name can be Foo.Tests
Add a reference to the tested project in the unit test project references
Section 51.2: Creating a sample test method
MSTest (the default testing framework) requires you to have your test classes decorated by a [TestClass] attribute,
and the test methods with a [TestMethod] attribute, and to be public.
[TestClass]
public class FizzBuzzFixture
{
[TestMethod]
public void Test1()
{
//arrange
var solver = new FizzBuzzSolver();
//act
var result = solver.FizzBuzz(1);
//assert
Assert.AreEqual("1",result);
}
}
GoalKicker.com – .NET Framework Notes for Professionals
162
Chapter 52: Write to and read from StdErr
stream
Section 52.1: Write to standard error output using Console
var sourceFileName = "NonExistingFile";
try
{
System.IO.File.Copy(sourceFileName, "DestinationFile");
}
catch (Exception e)
{
var stdErr = Console.Error;
stdErr.WriteLine($"Failed to copy '{sourceFileName}': {e.Message}");
}
Section 52.2: Read from standard error of child process
var errors = new System.Text.StringBuilder();
var process = new Process
{
StartInfo = new ProcessStartInfo
{
RedirectStandardError = true,
FileName = "xcopy.exe",
Arguments = "\"NonExistingFile\" \"DestinationFile\"",
UseShellExecute = false
},
};
process.ErrorDataReceived += (s, e) => errors.AppendLine(e.Data);
process.Start();
process.BeginErrorReadLine();
process.WaitForExit();
if (errors.Length > 0) // something went wrong
System.Console.Error.WriteLine($"Child process error: \r\n {errors}");
GoalKicker.com – .NET Framework Notes for Professionals
163
Chapter 53: Upload file and POST data to
webserver
Section 53.1: Upload file with WebRequest
To send a file and form data in single request, content should have multipart/form-data type.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
public async Task<string> UploadFile(string url, string filename,
Dictionary<string, object> postData)
{
var request = WebRequest.CreateHttp(url);
var boundary = $"{Guid.NewGuid():N}"; // boundary will separate each parameter
request.ContentType = $"multipart/form-data; {nameof(boundary)}={boundary}";
request.Method = "POST";
using (var requestStream = request.GetRequestStream())
using (var writer = new StreamWriter(requestStream))
{
foreach (var data in postData)
await writer.WriteAsync( // put all POST data into request
$"\r\n--{boundary}\r\nContent-Disposition: " +
$"form-data; name=\"{data.Key}\"\r\n\r\n{data.Value}");
await writer.WriteAsync( // file header
$"\r\n--{boundary}\r\nContent-Disposition: " +
$"form-data; name=\"File\"; filename=\"{Path.GetFileName(filename)}\"\r\n" +
"Content-Type: application/octet-stream\r\n\r\n");
await writer.FlushAsync();
using (var fileStream = File.OpenRead(filename))
await fileStream.CopyToAsync(requestStream);
await writer.WriteAsync($"\r\n--{boundary}--\r\n");
}
using (var response = (HttpWebResponse) await request.GetResponseAsync())
using (var responseStream = response.GetResponseStream())
{
if (responseStream == null)
return string.Empty;
using (var reader = new StreamReader(responseStream))
return await reader.ReadToEndAsync();
}
}
Usage:
var response = await uploader.UploadFile("< YOUR URL >", "< PATH TO YOUR FILE >",
new Dictionary<string, object>
{
{"Comment", "test"},
{"Modified", DateTime.Now }
GoalKicker.com – .NET Framework Notes for Professionals
164
});
GoalKicker.com – .NET Framework Notes for Professionals
165
Chapter 54: Networking
Section 54.1: Basic TCP chat (TcpListener, TcpClient,
NetworkStream)
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
class TcpChat
{
static void Main(string[] args)
{
if(args.Length == 0)
{
Console.WriteLine("Basic TCP chat");
Console.WriteLine();
Console.WriteLine("Usage:");
Console.WriteLine("tcpchat server <port>");
Console.WriteLine("tcpchat client <url> <port>");
return;
}
try
{
Run(args);
}
catch(IOException)
{
Console.WriteLine("--- Connection lost");
}
catch(SocketException ex)
{
Console.WriteLine("--- Can't connect: " + ex.Message);
}
}
static void Run(string[] args)
{
TcpClient client;
NetworkStream stream;
byte[] buffer = new byte[256];
var encoding = Encoding.ASCII;
if(args[0].StartsWith("s", StringComparison.InvariantCultureIgnoreCase))
{
var port = int.Parse(args[1]);
var listener = new TcpListener(IPAddress.Any, port);
listener.Start();
Console.WriteLine("--- Waiting for a connection...");
client = listener.AcceptTcpClient();
}
else
{
var hostName = args[1];
var port = int.Parse(args[2]);
client = new TcpClient();
client.Connect(hostName, port);
GoalKicker.com – .NET Framework Notes for Professionals
166
}
stream = client.GetStream();
Console.WriteLine("--- Connected. Start typing! (exit with Ctrl-C)");
while(true)
{
if(Console.KeyAvailable)
{
var lineToSend = Console.ReadLine();
var bytesToSend = encoding.GetBytes(lineToSend + "\r\n");
stream.Write(bytesToSend, 0, bytesToSend.Length);
stream.Flush();
}
if (stream.DataAvailable)
{
var receivedBytesCount = stream.Read(buffer, 0, buffer.Length);
var receivedString = encoding.GetString(buffer, 0, receivedBytesCount);
Console.Write(receivedString);
}
}
}
}
Section 54.2: Basic SNTP client (UdpClient)
See RFC 2030 for details on the SNTP protocol.
using System;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Sockets;
class SntpClient
{
const int SntpPort = 123;
static DateTime BaseDate = new DateTime(1900, 1, 1);
static void Main(string[] args)
{
if(args.Length == 0) {
Console.WriteLine("Simple SNTP client");
Console.WriteLine();
Console.WriteLine("Usage: sntpclient <sntp server url> [<local timezone>]");
Console.WriteLine();
Console.WriteLine("<local timezone>: a number between -12 and 12 as hours from UTC");
Console.WriteLine("(append .5 for an extra half an hour)");
return;
}
double localTimeZoneInHours = 0;
if(args.Length > 1)
localTimeZoneInHours = double.Parse(args[1], CultureInfo.InvariantCulture);
var udpClient = new UdpClient();
udpClient.Client.ReceiveTimeout = 5000;
var sntpRequest = new byte[48];
sntpRequest[0] = 0x23; //LI=0 (no warning), VN=4, Mode=3 (client)
GoalKicker.com – .NET Framework Notes for Professionals
167
udpClient.Send(
dgram: sntpRequest,
bytes: sntpRequest.Length,
hostname: args[0],
port: SntpPort);
byte[] sntpResponse;
try
{
IPEndPoint remoteEndpoint = null;
sntpResponse = udpClient.Receive(ref remoteEndpoint);
}
catch(SocketException)
{
Console.WriteLine("*** No response received from the server");
return;
}
uint numberOfSeconds;
if(BitConverter.IsLittleEndian)
numberOfSeconds = BitConverter.ToUInt32(
sntpResponse.Skip(40).Take(4).Reverse().ToArray()
,0);
else
numberOfSeconds = BitConverter.ToUInt32(sntpResponse, 40);
var date = BaseDate.AddSeconds(numberOfSeconds).AddHours(localTimeZoneInHours);
Console.WriteLine(
$"Current date in server: {date:yyyy-MM-dd HH:mm:ss}
UTC{localTimeZoneInHours:+0.#;-0.#;.}");
}
}
GoalKicker.com – .NET Framework Notes for Professionals
168
Chapter 55: HTTP servers
Section 55.1: Basic read-only HTTP file server (ASP.NET Core)
1 - Create an empty folder, it will contain the files created in the next steps.
2 - Create a file named project.json with the following content (adjust the port number and rootDirectory as
appropriate):
{
"dependencies": {
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final"
},
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:60000"
},
"frameworks": {
"dnxcore50": { }
},
"fileServer": {
"rootDirectory": "c:\\users\\username\\Documents"
}
}
3 - Create a file named Startup.cs with the following code:
using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.FileProviders;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.StaticFiles;
using Microsoft.Extensions.Configuration;
public class Startup
{
public void Configure(IApplicationBuilder app)
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("project.json");
var config = builder.Build();
var rootDirectory = config["fileServer:rootDirectory"];
Console.WriteLine("File server root directory: " + rootDirectory);
var fileProvider = new PhysicalFileProvider(rootDirectory);
var options = new StaticFileOptions();
options.ServeUnknownFileTypes = true;
options.FileProvider = fileProvider;
options.OnPrepareResponse = context =>
{
context.Context.Response.ContentType = "application/octet-stream";
context.Context.Response.Headers.Add(
"Content-Disposition",
$"Attachment; filename=\"{context.File.Name}\"");
};
GoalKicker.com – .NET Framework Notes for Professionals
169
app.UseStaticFiles(options);
}
}
4 - Open a command prompt, navigate to the folder and execute:
dnvm use 1.0.0-rc1-final -r coreclr -p
dnu restore
Note: These commands need to be run only once. Use dnvm list to check the actual number of the latest installed
version of the core CLR.
5 - Start the server with: dnx web. Files can now be requested at http://localhost:60000/path/to/file.ext.
For simplicity, filenames are assumed to be all ASCII (for the filename part in the Content-Disposition header) and
file access errors are not handled.
Section 55.2: Basic read-only HTTP file server (HttpListener)
Notes:
This example must be run in administrative mode.
Only one simultaneous client is supported.
For simplicity, filenames are assumed to be all ASCII (for the filename part in the Content-Disposition header) and file
access errors are not handled.
using System;
using System.IO;
using System.Net;
class HttpFileServer
{
private static HttpListenerResponse response;
private static HttpListener listener;
private static string baseFilesystemPath;
static void Main(string[] args)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine(
"*** HttpListener requires at least Windows XP SP2 or Windows Server 2003.");
return;
}
if(args.Length < 2)
{
Console.WriteLine("Basic read-only HTTP file server");
Console.WriteLine();
Console.WriteLine("Usage: httpfileserver <base filesystem path> <port>");
Console.WriteLine("Request format: http://url:port/path/to/file.ext");
return;
}
baseFilesystemPath = Path.GetFullPath(args[0]);
var port = int.Parse(args[1]);
GoalKicker.com – .NET Framework Notes for Professionals
170
listener = new HttpListener();
listener.Prefixes.Add("http://*:" + port + "/");
listener.Start();
Console.WriteLine("--- Server stated, base path is: " + baseFilesystemPath);
Console.WriteLine("--- Listening, exit with Ctrl-C");
try
{
ServerLoop();
}
catch(Exception ex)
{
Console.WriteLine(ex);
if(response != null)
{
SendErrorResponse(500, "Internal server error");
}
}
}
static void ServerLoop()
{
while(true)
{
var context = listener.GetContext();
var request = context.Request;
response = context.Response;
var fileName = request.RawUrl.Substring(1);
Console.WriteLine(
"--- Got {0} request for: {1}",
request.HttpMethod, fileName);
if (request.HttpMethod.ToUpper() != "GET")
{
SendErrorResponse(405, "Method must be GET");
continue;
}
var fullFilePath = Path.Combine(baseFilesystemPath, fileName);
if(!File.Exists(fullFilePath))
{
SendErrorResponse(404, "File not found");
continue;
}
Console.Write(" Sending file...");
using (var fileStream = File.OpenRead(fullFilePath))
{
response.ContentType = "application/octet-stream";
response.ContentLength64 = (new FileInfo(fullFilePath)).Length;
response.AddHeader(
"Content-Disposition",
"Attachment; filename=\"" + Path.GetFileName(fullFilePath) + "\"");
fileStream.CopyTo(response.OutputStream);
}
response.OutputStream.Close();
response = null;
Console.WriteLine(" Ok!");
}
}
GoalKicker.com – .NET Framework Notes for Professionals
171
static void SendErrorResponse(int statusCode, string statusResponse)
{
response.ContentLength64 = 0;
response.StatusCode = statusCode;
response.StatusDescription = statusResponse;
response.OutputStream.Close();
Console.WriteLine("*** Sent error: {0} {1}", statusCode, statusResponse);
}
}
GoalKicker.com – .NET Framework Notes for Professionals
172
Chapter 56: HTTP clients
Section 56.1: Reading GET response as string using
System.Net.HttpClient
HttpClient is available through NuGet: Microsoft HTTP Client Libraries.
string requestUri = "http://www.example.com";
string responseData;
using (var client = new HttpClient())
{
using(var response = client.GetAsync(requestUri).Result)
{
response.EnsureSuccessStatusCode();
responseData = response.Content.ReadAsStringAsync().Result;
}
}
Section 56.2: Basic HTTP downloader using
System.Net.Http.HttpClient
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
class HttpGet
{
private static async Task DownloadAsync(string fromUrl, string toFile)
{
using (var fileStream = File.OpenWrite(toFile))
{
using (var httpClient = new HttpClient())
{
Console.WriteLine("Connecting...");
using (var networkStream = await httpClient.GetStreamAsync(fromUrl))
{
Console.WriteLine("Downloading...");
await networkStream.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
}
}
}
static void Main(string[] args)
{
try
{
Run(args).Wait();
}
catch (Exception ex)
{
if (ex is AggregateException)
ex = ((AggregateException)ex).Flatten().InnerExceptions.First();
GoalKicker.com – .NET Framework Notes for Professionals
173
Console.WriteLine("--- Error: " +
(ex.InnerException?.Message ?? ex.Message));
}
}
static async Task Run(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Basic HTTP downloader");
Console.WriteLine();
Console.WriteLine("Usage: httpget <url>[<:port>] <file>");
return;
}
await DownloadAsync(fromUrl: args[0], toFile: args[1]);
Console.WriteLine("Done!");
}
}
Section 56.3: Reading GET response as string using
System.Net.HttpWebRequest
string requestUri = "http://www.example.com";
string responseData;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(parameters.Uri);
WebResponse response = request.GetResponse();
using (StreamReader responseReader = new StreamReader(response.GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
Section 56.4: Reading GET response as string using
System.Net.WebClient
string requestUri = "http://www.example.com";
string responseData;
using (var client = new WebClient())
{
responseData = client.DownloadString(requestUri);
}
Section 56.5: Sending a POST request with a string payload
using System.Net.HttpWebRequest
string requestUri = "http://www.example.com";
string requestBodyString = "Request body string.";
string contentType = "text/plain";
string requestMethod = "POST";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri)
{
Method = requestMethod,
ContentType = contentType,
};
GoalKicker.com – .NET Framework Notes for Professionals
174
byte[] bytes = Encoding.UTF8.GetBytes(requestBodyString);
Stream stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Section 56.6: Sending a POST request with a string payload
using System.Net.WebClient
string requestUri = "http://www.example.com";
string requestBodyString = "Request body string.";
string contentType = "text/plain";
string requestMethod = "POST";
byte[] responseBody;
byte[] requestBodyBytes = Encoding.UTF8.GetBytes(requestBodyString);
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = contentType;
responseBody = client.UploadData(requestUri, requestMethod, requestBodyBytes);
}
Section 56.7: Sending a POST request with a string payload
using System.Net.HttpClient
HttpClient is available through NuGet: Microsoft HTTP Client Libraries.
string requestUri = "http://www.example.com";
string requestBodyString = "Request body string.";
string contentType = "text/plain";
string requestMethod = "POST";
var request = new HttpRequestMessage
{
RequestUri = requestUri,
Method = requestMethod,
};
byte[] requestBodyBytes = Encoding.UTF8.GetBytes(requestBodyString);
request.Content = new ByteArrayContent(requestBodyBytes);
request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
HttpResponseMessage result = client.SendAsync(request).Result;
result.EnsureSuccessStatusCode();
GoalKicker.com – .NET Framework Notes for Professionals
175
Chapter 57: Serial Ports
Section 57.1: Basic operation
var serialPort = new SerialPort("COM1", 9600, Parity.Even, 8, StopBits.One);
serialPort.Open();
serialPort.WriteLine("Test data");
string response = serialPort.ReadLine();
Console.WriteLine(response);
serialPort.Close();
Section 57.2: List available port names
string[] portNames = SerialPort.GetPortNames();
Section 57.3: Asynchronous read
void SetupAsyncRead(SerialPort serialPort)
{
serialPort.DataReceived += (sender, e) => {
byte[] buffer = new byte[4096];
switch (e.EventType)
{
case SerialData.Chars:
var port = (SerialPort)sender;
int bytesToRead = port.BytesToRead;
if (bytesToRead > buffer.Length)
Array.Resize(ref buffer, bytesToRead);
int bytesRead = port.Read(buffer, 0, bytesToRead);
// Process the read buffer here
// ...
break;
case SerialData.Eof:
// Terminate the service here
// ...
break;
}
};
Section 57.4: Synchronous text echo service
using System.IO.Ports;
namespace TextEchoService
{
class Program
{
static void Main(string[] args)
{
var serialPort = new SerialPort("COM1", 9600, Parity.Even, 8, StopBits.One);
serialPort.Open();
string message = "";
while (message != "quit")
{
message = serialPort.ReadLine();
serialPort.WriteLine(message);
}
GoalKicker.com – .NET Framework Notes for Professionals
176
serialPort.Close();
}
}
}
Section 57.5: Asynchronous message receiver
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text;
using System.Threading;
namespace AsyncReceiver
{
class Program
{
const byte STX = 0x02;
const byte ETX = 0x03;
const byte ACK = 0x06;
const byte NAK = 0x15;
static ManualResetEvent terminateService = new ManualResetEvent(false);
static readonly object eventLock = new object();
static List<byte> unprocessedBuffer = null;
static void Main(string[] args)
{
try
{
var serialPort = new SerialPort("COM11", 9600, Parity.Even, 8, StopBits.One);
serialPort.DataReceived += DataReceivedHandler;
serialPort.ErrorReceived += ErrorReceivedHandler;
serialPort.Open();
terminateService.WaitOne();
serialPort.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception occurred: {0}", e.Message);
}
Console.ReadKey();
}
static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
lock (eventLock)
{
byte[] buffer = new byte[4096];
switch (e.EventType)
{
case SerialData.Chars:
var port = (SerialPort)sender;
int bytesToRead = port.BytesToRead;
if (bytesToRead > buffer.Length)
Array.Resize(ref buffer, bytesToRead);
int bytesRead = port.Read(buffer, 0, bytesToRead);
ProcessBuffer(buffer, bytesRead);
break;
case SerialData.Eof:
terminateService.Set();
break;
GoalKicker.com – .NET Framework Notes for Professionals
177
}
}
}
static void ErrorReceivedHandler(object sender, SerialErrorReceivedEventArgs e)
{
lock (eventLock)
if (e.EventType == SerialError.TXFull)
{
Console.WriteLine("Error: TXFull. Can't handle this!");
terminateService.Set();
}
else
{
Console.WriteLine("Error: {0}. Resetting everything", e.EventType);
var port = (SerialPort)sender;
port.DiscardInBuffer();
port.DiscardOutBuffer();
unprocessedBuffer = null;
port.Write(new byte[] { NAK }, 0, 1);
}
}
static void ProcessBuffer(byte[] buffer, int length)
{
List<byte> message = unprocessedBuffer;
for (int i = 0; i < length; i++)
if (buffer[i] == ETX)
{
if (message != null)
{
Console.WriteLine("MessageReceived: {0}",
Encoding.ASCII.GetString(message.ToArray()));
message = null;
}
}
else if (buffer[i] == STX)
message = null;
else if (message != null)
message.Add(buffer[i]);
unprocessedBuffer = message;
}
}
}
This program waits for messages enclosed in STX and ETX bytes and outputs the text coming between them.
Everything else is discarded. On write buffer overflow it stops. On other errors it reset input and output buffers and
waits for further messages.
The code illustrates:
Asynchronous serial port reading (see SerialPort.DataReceived usage).
Serial port error processing (see SerialPort.ErrorReceived usage).
Non-text message-based protocol implementation.
Partial message reading.
The SerialPort.DataReceived event may happen earlier than entire message (up to ETX) comes. The
entire message may also not be available in the input buffer (SerialPort.Read(..., ..., port.BytesToRead)
reads only a part of the message). In this case we stash the received part (unprocessedBuffer) and
carry on waiting for further data.
Dealing with several messages coming in one go.
GoalKicker.com – .NET Framework Notes for Professionals
178
The SerialPort.DataReceived event may happen only after several messages have been sent by the
other end.
GoalKicker.com – .NET Framework Notes for Professionals
179
Appendix A: Acronym Glossary
Section A.1: .Net Related Acronyms
Please note that some terms like JIT and GC are generic enough to apply to many programming language
environments and runtimes.
CLR: Common Language Runtime
IL: Intermediate Language
EE: Execution Engine
JIT: Just-in-time compiler
GC: Garbage Collector
OOM: Out of memory
STA: Single-threaded apartment
MTA: Multi-threaded apartment
GoalKicker.com – .NET Framework Notes for Professionals
180
Credits
Thank you greatly to all the people from Stack Overflow Documentation who helped provide this content,
more changes can be sent to web@petercv.com for new content to be published or updated
Adi Lester
Adil Mammadov
Adriano Repetti
Akshay Anand
Alan McBee
ale10ander
Aleks Andreev
Alexander Mandt
Alexander V.
Alfred Myers
Aman Sharma
Andrew Jens
Andrew Morton
Andrey Shchekin
Andrius
Anik Saha
Aphelion
Arvin Baccay
Arxae
Ashtonian
Athari
avat
Axarydax
BananaSft
Bassie
Behzad
Benjamin Hodgson
binki
Bjørn
Bradley Grainger
Bruno Garcia
BrunoLM
Carlos Muñoz
CodeCaster
Daniel A. White
Darrel Lee
Dave R.
dbasnett
delete me
demonplus
Denuath
DLeh
Dmitry Egorov
DoNot
Dr Rob Lang
Drew
DrewJordan
Chapters 42 and 47
Chapter 8
Chapters 1, 2, 4 and 18
Chapter 25
Chapters 12, 14 and 47
Chapters 16 and 35
Chapters 10, 52 and 53
Chapter 49
Chapter 8
Chapter 47
Chapters 5 and 42
Chapter 1
Chapter 25
Chapter 28
Chapter 32
Chapter 28
Chapter 34
Chapter 47
Chapter 19
Chapter 28
Chapter 1
Chapter 46
Chapter 51
Chapter 47
Chapter 48
Chapter 39
Chapter 8
Chapter 45
Chapters 4 and 10
Chapter 8
Chapter 8
Chapter 15
Chapter 8
Chapters 8, 17, 28, 47 and 56
Chapters 1 and 25
Chapter 4
Chapter 47
Chapter 35
Chapter 18
Chapters 30 and 49
Chapter 15
Chapters 31 and 33
Chapters 27 and 57
Chapter 8
Chapter 9
Chapter 25
Chapters 12 and 45
GoalKicker.com – .NET Framework Notes for Professionals
181
Eduardo Molteni
Ehsan Sajjad
Eric
Felipe Oriani
Filip Frącz
Fredou
Gajendra
GalacticCowboy
George Polevoy
Guanxi
Gusdor
Haney
harriyott
hatchet
Heinzi
Hogan
Hywel Rees
i3arnon
Ian
Igor
Ingenioushax
Jacobr365
Jagadisha B S
JamyRyals
jbtule
Jigar
Jim
jnovo
Joe Amenta
John
Kevin Montrose
Konamiman
Krikor Ailanjian
Kritner
lokusking
Lorenzo Dematté
Luaan
Lucas Trzesniewski
M22an
Mafii
mahdi abasi
MarcinJuraszek
Mark C.
Matas Vaitkevicius
Mathias Müller
Matt
Matt dc
matteeyah
Matthew Whited
McKay
Mellow
Mihail Stancescu
Mr.Mindor
Chapter 8
Chapter 8
Chapter 32
Chapters 4 and 5
Chapter 17
Chapter 48
Chapter 37
Chapters 3 and 8
Chapters 4, 11 and 34
Chapter 22
Chapters 43 and 44
Chapter 8
Chapter 5
Chapter 4
Chapter 25
Chapter 4
Chapter 7
Chapter 38
Chapter 4
Chapter 25
Chapter 16
Chapters 38, 42 and 43
Chapter 49
Chapter 42
Chapter 8
Chapter 10
Chapter 11
Chapter 8
Chapters 8 and 20
Chapter 3
Chapter 1
Chapters 8, 42, 54, 55 and 56
Chapter 36
Chapter 47
Chapter 49
Chapter 10
Chapter 23
Chapter 9
Chapter 32
Chapter 47
Chapter 50
Chapters 1 and 8
Chapter 5
Chapters 10 and 28
Chapter 42
Chapter 49
Chapter 15
Chapter 1
Chapter 13
Chapter 8
Chapter 39
Chapter 24
Chapter 8
GoalKicker.com – .NET Framework Notes for Professionals
182
MSE
n.podbielski
Nate Barbettini
Nikola.Lukovic
NikolayKondratyev
Ogglas
Ondřej Štorc
Ozair Kafray
Pavel Mayorov
Pavel Voronin
PedroSouki
ProgramFOX
Ringil
Rion Williams
Robert Columbia
RoyalPotato
Ruben Steins
Salvador Rubio Martinez
Sammi
Scott Hannen
SeeuD1
Sergio Domínguez
Sidewinder94
smdrager
starbeamrainbowlabs
Steve
Steven Doggart
Stilgar
Tanveer Badar
tehDorf
the berserker
Theodoros
Chatzigiannakis
Thomas Bledsoe
Thriggle
toddmo
Tolga Evcimen
Tomáš Hübelbauer
user2321864
vicky
wangengzheng
Yahfoufi
ʇolɐǝz ǝɥʇ qoq
Chapter 40
Chapter 11
Chapter 8
Chapter 38
Chapter 23
Chapter 48
Chapter 48
Chapter 28
Chapter 42
Chapters 2 and 42
Chapter 32
Chapter 21
Chapter 4
Chapter 1
Chapter 4
Chapter 17
Chapter 8
Chapter 8
Chapter 8
Chapters 26 and 29
Chapter 1
Chapter 8
Chapter 8
Chapter 10
Chapters 37 and 47
Chapter 30
Chapter 1
Chapter 11
Chapter 58
Chapters 6 and 15
Chapter 4
Chapter 37
Chapter 42
Chapter 32
Chapter 23
Chapter 32
Chapter 4
Chapter 25
Chapter 30
Chapter 11
Chapter 41
Chapter 1
GoalKicker.com – .NET Framework Notes for Professionals
183
You may also like
|