CPE_learningsite
This repository has no backups
This repository's network speed is throttled to 100KB/sec
Upgrade your account to fix these warnings, or use backups.vc for automated backups
d90493cf2f1f435b060f3ae01600f05f801f24a8
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 |
<#@ template language="C#" hostspecific="True" #> <#@ assembly name="EnvDTE" #> <#@ assembly name="System.Core.dll" #> <#@ assembly name="System.Data" #> <#@ assembly name="System.Xml" #> <#@ assembly name="System.Configuration" #> <#@ assembly name="System.Windows.Forms" #> <#@ import namespace="System.Collections.Generic" #> <#@ import namespace="System.Data" #> <#@ import namespace="System.Data.SqlClient" #> <#@ import namespace="System.Data.Common" #> <#@ import namespace="System.Diagnostics" #> <#@ import namespace="System.Globalization" #> <#@ import namespace="System.IO" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> <#@ import namespace="System.Text.RegularExpressions" #> <#@ import namespace="System.Configuration" #> <#@ import namespace="System.Windows.Forms" #> <#@ import namespace="Microsoft.VisualStudio.TextTemplating" #> <#+ /* This is code is based on the T4 template from the PetaPoco project which in turn is based on the subsonic project. ----------------------------------------------------------------------------------------- This template can read minimal schema information from the following databases: * SQL Server * SQL Server CE * MySQL * PostGreSQL * Oracle * Sqlite For connection and provider settings the template will look for the web.config or app.config file of the containing Visual Studio project. It will not however read DbProvider settings from this file. In order to work, the appropriate driver must be registered in the system machine.config file. If you're using Visual Studio 2010 the file you want is here: C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config After making changes to machine.config you will also need to restart Visual Studio. Here's a typical set of entries that might help if you're stuck: <system.data> <DbProviderFactories> <add name="Odbc Data Provider" invariant="System.Data.Odbc" description=".Net Framework Data Provider for Odbc" type="System.Data.Odbc.OdbcFactory, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> <add name="OleDb Data Provider" invariant="System.Data.OleDb" description=".Net Framework Data Provider for OleDb" type="System.Data.OleDb.OleDbFactory, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> <add name="OracleClient Data Provider" invariant="System.Data.OracleClient" description=".Net Framework Data Provider for Oracle" type="System.Data.OracleClient.OracleClientFactory, System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> <add name="SqlClient Data Provider" invariant="System.Data.SqlClient" description=".Net Framework Data Provider for SqlServer" type="System.Data.SqlClient.SqlClientFactory, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.3.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/> <add name="Microsoft SQL Server Compact Data Provider" invariant="System.Data.SqlServerCe.3.5" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=3.5.1.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/><add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/> <add name="Npgsql Data Provider" invariant="Npgsql" support="FF" description=".Net Framework Data Provider for Postgresql Server" type="Npgsql.NpgsqlFactory, Npgsql, Version=2.0.11.91, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7" /> </DbProviderFactories> </system.data> Also, the providers and their dependencies need to be installed to GAC. Eg; this is how I installed the drivers for PostgreSQL gacutil /i Npgsql.dll gacutil /i Mono.Security.dll ----------------------------------------------------------------------------------------- SubSonic - http://subsonicproject.com The contents of this file are subject to the New BSD License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.opensource.org/licenses/bsd-license.php Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. */ string ConnectionStringName = ""; string Namespace = ""; string ClassPrefix = ""; string ClassSuffix = ""; string SchemaName = null; bool IncludeViews = false; bool IncludeFunctions = false; public class Table { public List<Column> Columns; public List<TableIndex> Indices; public List<FKey> FKeys; public string Name; public string Schema; public bool IsView; public bool IsFunction; public string CleanName; public string ClassName; public string SequenceName; public bool Ignore; public string SQL; public Column PK { get { return this.Columns.SingleOrDefault(x=>x.IsPK); } } public Column GetColumn(string columnName) { return Columns.Single(x=>string.Compare(x.Name, columnName, true)==0); } public Column this[string columnName] { get { return GetColumn(columnName); } } public bool HasPK() { return ((PK != null) && (string.IsNullOrEmpty(PK.Name) != true)); } public TableIndex GetIndex(string indexName) { return Indices.Single(x=>string.Compare(x.Name, indexName, true)==0); } } public class Column { public string Name; public string PropertyName; public string PropertyType; public bool IsPK; public bool IsNullable; public bool IsAutoIncrement; public bool IsComputed; public bool Ignore; public int Size; public int Precision; public string DefaultValue; public string ProperPropertyType { get { if(IsNullable) { return PropertyType + CheckNullable(this); } return PropertyType; } } } public class Tables : List<Table> { public Tables() { } public Table GetTable(string tableName) { return this.Single(x=>string.Compare(x.Name, tableName, true)==0); } public Table this[string tableName] { get { return GetTable(tableName); } } } public class IndexColumn { public string Name; public bool IsAsc; } public class TableIndex { public string Name; public List<IndexColumn> IndexColumns; public bool IsUnique; public string SQL; } public class FKey { public string ToTable; public string FromColumn; public string ToColumn; } public class SP { public string Name; public string CleanName; public string ClassName; public string Schema; public string SchemaQualifiedName {get{return Schema+"."+Name;}} public List<SPParam> Parameters; public SP() { Parameters=new List<SPParam>(); } public string ArgList { get { StringBuilder sb=new StringBuilder(); int loopCount=1; foreach(var par in Parameters) { sb.AppendFormat("{0} {1}", par.SysType,par.CleanName); if(loopCount<Parameters.Count) sb.Append(","); loopCount++; } return sb.ToString(); } } } public enum SPParamDir { OutDirection, InDirection, InAndOutDirection } public class SPParam { public string Name; public string CleanName; public string SysType; public string NullableSysType; public string DbType; public SPParamDir Direction; } static Regex rxCleanUp = new Regex(@"[^\w\d_]", RegexOptions.Compiled); static string[] cs_keywords = { "abstract", "event", "new", "struct", "as", "explicit", "null", "switch", "base", "extern", "object", "this", "bool", "false", "operator", "throw", "break", "finally", "out", "true", "byte", "fixed", "override", "try", "case", "float", "params", "typeof", "catch", "for", "private", "uint", "char", "foreach", "protected", "ulong", "checked", "goto", "public", "unchecked", "class", "if", "readonly", "unsafe", "const", "implicit", "ref", "ushort", "continue", "in", "return", "using", "decimal", "int", "sbyte", "virtual", "default", "interface", "sealed", "volatile", "delegate", "internal", "short", "void", "do", "is", "sizeof", "while", "double", "lock", "stackalloc", "else", "long", "static", "enum", "namespace", "string" }; static Func<string, string> CleanUp = (str) => { str = rxCleanUp.Replace(str, "_"); if (char.IsDigit(str[0]) || cs_keywords.Contains(str)) str = "@" + str; return str; }; static string CheckNullable(Column col) { string result=""; if(col.IsNullable && col.PropertyType !="byte[]" && col.PropertyType !="string" && col.PropertyType !="Microsoft.SqlServer.Types.SqlGeography" && col.PropertyType !="Microsoft.SqlServer.Types.SqlGeometry" ) result="?"; return result; } string GetConnectionString(ref string connectionStringName, out string providerName) { var _CurrentProject = GetCurrentProject(); providerName=null; string result=""; ExeConfigurationFileMap configFile = new ExeConfigurationFileMap(); configFile.ExeConfigFilename = GetConfigPath(); if (string.IsNullOrEmpty(configFile.ExeConfigFilename)) throw new ArgumentNullException("The project does not contain App.config or Web.config file."); var config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None); var connSection=config.ConnectionStrings; //if the connectionString is empty - which is the defauls //look for count-1 - this is the last connection string //and takes into account AppServices and LocalSqlServer if(string.IsNullOrEmpty(connectionStringName)) { if(connSection.ConnectionStrings.Count>1) { connectionStringName = connSection.ConnectionStrings[connSection.ConnectionStrings.Count-1].Name; result=connSection.ConnectionStrings[connSection.ConnectionStrings.Count-1].ConnectionString; providerName=connSection.ConnectionStrings[connSection.ConnectionStrings.Count-1].ProviderName; } } else { try { result=connSection.ConnectionStrings[connectionStringName].ConnectionString; providerName=connSection.ConnectionStrings[connectionStringName].ProviderName; } catch { result="There is no connection string name called '"+connectionStringName+"'"; } } // if (String.IsNullOrEmpty(providerName)) // providerName="System.Data.SqlClient"; return result; } string _connectionString=""; string _providerName=""; void InitConnectionString() { if(String.IsNullOrEmpty(_connectionString)) { _connectionString=GetConnectionString(ref ConnectionStringName, out _providerName); if(_connectionString.Contains("|DataDirectory|")) { //have to replace it string dataFilePath=GetDataDirectory(); _connectionString=_connectionString.Replace("|DataDirectory|",dataFilePath); } } } public string ConnectionString { get { InitConnectionString(); return _connectionString; } } public string ProviderName { get { InitConnectionString(); return _providerName; } } public EnvDTE.Project GetCurrentProject() { IServiceProvider _ServiceProvider = (IServiceProvider)Host; if (_ServiceProvider == null) throw new Exception("Host property returned unexpected value (null)"); EnvDTE.DTE dte = (EnvDTE.DTE)_ServiceProvider.GetService(typeof(EnvDTE.DTE)); if (dte == null) throw new Exception("Unable to retrieve EnvDTE.DTE"); Array activeSolutionProjects = (Array)dte.ActiveSolutionProjects; if (activeSolutionProjects == null) throw new Exception("DTE.ActiveSolutionProjects returned null"); EnvDTE.Project dteProject = (EnvDTE.Project)activeSolutionProjects.GetValue(0); if (dteProject == null) throw new Exception("DTE.ActiveSolutionProjects[0] returned null"); return dteProject; } private string GetProjectPath() { EnvDTE.Project project = GetCurrentProject(); System.IO.FileInfo info = new System.IO.FileInfo(project.FullName); return info.Directory.FullName; } private string GetConfigPath() { EnvDTE.Project project = GetCurrentProject(); foreach (EnvDTE.ProjectItem item in project.ProjectItems) { // if it is the app.config file, then open it up if (item.Name.Equals("App.config",StringComparison.InvariantCultureIgnoreCase) || item.Name.Equals("Web.config",StringComparison.InvariantCultureIgnoreCase)) return GetProjectPath() + "\\" + item.Name; } return String.Empty; } public string GetDataDirectory() { EnvDTE.Project project=GetCurrentProject(); return System.IO.Path.GetDirectoryName(project.FileName)+"\\App_Data\\"; } static string zap_password(string connectionString) { var rx = new Regex("password=.*;", RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase); return rx.Replace(connectionString, "password=**zapped**;"); } public string GetColumnDefaultValue(Column col) { string sysType=string.Format("\"{0}\"",col.DefaultValue); switch (col.PropertyType.ToLower()) { case "long": case "int": case "double": case "decimal": case "bool": sysType= col.DefaultValue.ToString().Replace("'","").Replace("\"",""); break; case "guid": sysType= string.Format("\"{0}\"",col.DefaultValue); break; case "datetime": { if (col.DefaultValue.ToLower() == "current_time" || col.DefaultValue.ToLower() == "current_date"|| col.DefaultValue.ToLower() == "current_timestamp") sysType= "SystemMethods.CurrentDateTime"; else sysType= "\"" +col.DefaultValue+"\""; break; } } return sysType; } Tables LoadTables(bool makeSingular) { InitConnectionString(); WriteLine("// This file was automatically generated by the PetaPoco T4 Template"); WriteLine("// Do not make changes directly to this file - edit the template instead"); WriteLine("// "); WriteLine("// The following connection settings were used to generate this file"); WriteLine("// "); WriteLine("// Connection String Name: `{0}`", ConnectionStringName); WriteLine("// Provider: `{0}`", ProviderName); WriteLine("// Connection String: `{0}`", zap_password(ConnectionString)); WriteLine("// Schema: `{0}`", SchemaName); WriteLine("// Include Views: `{0}`", IncludeViews); WriteLine(""); DbProviderFactory _factory; try { _factory = DbProviderFactories.GetFactory(ProviderName); } catch (Exception x) { var error=x.Message.Replace("\r\n", "\n").Replace("\n", " "); Warning(string.Format("Failed to load provider `{0}` - {1}", ProviderName, error)); WriteLine(""); WriteLine("// -----------------------------------------------------------------------------------------"); WriteLine("// Failed to load provider `{0}` - {1}", ProviderName, error); WriteLine("// -----------------------------------------------------------------------------------------"); WriteLine(""); return new Tables(); } WriteLine("// Factory Name: `{0}`", _factory.GetType().Name); try { Tables result; using(var conn=_factory.CreateConnection()) { conn.ConnectionString=ConnectionString; conn.Open(); SchemaReader reader=null; if (_factory.GetType().Name == "MySqlClientFactory") { // MySql reader=new MySqlSchemaReader(); } else if (_factory.GetType().Name == "SqlCeProviderFactory") { // SQL CE reader=new SqlServerCeSchemaReader(); } else if (_factory.GetType().Name == "NpgsqlFactory") { // PostgreSQL reader=new PostGreSqlSchemaReader(); } else if (_factory.GetType().Name == "OracleClientFactory") { // Oracle reader=new OracleSchemaReader(); } else if (_factory.GetType().Name == "SQLiteFactory") { // Sqlite reader=new SqliteSchemaReader(); } else { // Assume SQL Server reader=new SqlServerSchemaReader(); } reader.outer=this; result=reader.ReadSchema(conn, _factory); // Remove unrequired tables/views for (int i=result.Count-1; i>=0; i--) { if (SchemaName!=null && string.Compare(result[i].Schema, SchemaName, true)!=0) { result.RemoveAt(i); continue; } if ((!IncludeViews && result[i].IsView) ||(!IncludeFunctions && result[i].IsFunction)) { result.RemoveAt(i); continue; } } } var rxClean = new Regex("^(Equals|GetHashCode|GetType|ToString|repo|Save|IsNew|Insert|Update|Delete|Exists|SingleOrDefault|Single|First|FirstOrDefault|Fetch|Page|Query)$"); foreach (var t in result) { if (!makeSingular) { t.ClassName = t.CleanName; } t.ClassName = ClassPrefix + t.ClassName + ClassSuffix; foreach (var c in t.Columns) { c.PropertyName = rxClean.Replace(c.PropertyName, "_$1"); // Make sure property name doesn't clash with class name if (c.PropertyName == t.ClassName) c.PropertyName = "_" + c.PropertyName; } } return result; } catch (Exception x) { var error=x.Message.Replace("\r\n", "\n").Replace("\n", " "); Warning(string.Format("Failed to read database schema - {0}", error)); WriteLine(""); WriteLine("// -----------------------------------------------------------------------------------------"); WriteLine("// Failed to read database schema - {0}", error); WriteLine("// -----------------------------------------------------------------------------------------"); WriteLine(""); return new Tables(); } } List<SP> SPsNotSupported(string providerName) { Warning("SP function creation is not supported for " + providerName); WriteLine(""); WriteLine("// -----------------------------------------------------------------------------------------"); WriteLine("// SP function creation is not supported for `{0}`", providerName); WriteLine("// -----------------------------------------------------------------------------------------"); return new List<SP>(); } List<SP> LoadSPs() { InitConnectionString(); WriteLine("// This file was automatically generated by the PetaPoco T4 Template"); WriteLine("// Do not make changes directly to this file - edit the template instead"); WriteLine("// "); WriteLine("// The following connection settings were used to generate this file"); WriteLine("// "); WriteLine("// Connection String Name: `{0}`", ConnectionStringName); WriteLine("// Provider: `{0}`", ProviderName); WriteLine("// Connection String: `{0}`", zap_password(ConnectionString)); WriteLine("// Schema: `{0}`", SchemaName); WriteLine("// Include Views: `{0}`", IncludeViews); WriteLine(""); DbProviderFactory _factory; try { _factory = DbProviderFactories.GetFactory(ProviderName); } catch (Exception x) { var error=x.Message.Replace("\r\n", "\n").Replace("\n", " "); Warning(string.Format("Failed to load provider `{0}` - {1}", ProviderName, error)); WriteLine(""); WriteLine("// -----------------------------------------------------------------------------------------"); WriteLine("// Failed to load provider `{0}` - {1}", ProviderName, error); WriteLine("// -----------------------------------------------------------------------------------------"); WriteLine(""); return new List<SP>(); } WriteLine("// Factory Name: `{0}`", _factory.GetType().Name); try { List<SP> result; using(var conn=_factory.CreateConnection()) { conn.ConnectionString=ConnectionString; conn.Open(); SchemaReader reader=null; if (_factory.GetType().Name == "MySqlClientFactory") { // MySql reader=new MySqlSchemaReader(); return SPsNotSupported(ProviderName); } else if (_factory.GetType().Name == "SqlCeProviderFactory") { // SQL CE reader=new SqlServerCeSchemaReader(); return SPsNotSupported(ProviderName); } else if (_factory.GetType().Name == "NpgsqlFactory") { // PostgreSQL reader=new PostGreSqlSchemaReader(); return SPsNotSupported(ProviderName); } else if (_factory.GetType().Name == "OracleClientFactory") { // Oracle reader=new OracleSchemaReader(); return SPsNotSupported(ProviderName); } else if (_factory.GetType().Name == "SQLiteFactory") { // Sqlite reader=new SqliteSchemaReader(); return SPsNotSupported(ProviderName); } else { // Assume SQL Server reader=new SqlServerSchemaReader(); } reader.outer=this; result=reader.ReadSPList(conn, _factory); // Remove unrequired procedures for (int i=result.Count-1; i>=0; i--) { if (SchemaName!=null && string.Compare(result[i].Schema, SchemaName, true)!=0) { result.RemoveAt(i); continue; } } } return result; } catch (Exception x) { var error=x.Message.Replace("\r\n", "\n").Replace("\n", " "); Warning(string.Format("Failed to read database schema - {0}", error)); WriteLine(""); WriteLine("// -----------------------------------------------------------------------------------------"); WriteLine("// Failed to read database schema - {0}", error); WriteLine("// -----------------------------------------------------------------------------------------"); WriteLine(""); return new List<SP>(); } } public bool IsTableNameInList(string tableName, Tables tbls) { if (tbls == null) return false; foreach(var tbItem in tbls) { if (String.Equals(tbItem.Name,tableName,StringComparison.InvariantCultureIgnoreCase)) { return true; } } return false; } public Table GetTableFromListByName(string tableName, Tables tbls) { if (tbls == null) return null; foreach(var tbItem in tbls) { if (String.Equals(tbItem.Name,tableName,StringComparison.InvariantCultureIgnoreCase)) { return tbItem; } } return null; } void SaveOutput(string outputFileName) { string templateDirectory = Path.GetDirectoryName(Host.TemplateFile); string outputFilePath = Path.Combine(templateDirectory, outputFileName); File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString()); this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length); } abstract class SchemaReader { public abstract Tables ReadSchema(DbConnection connection, DbProviderFactory factory); public abstract List<SP> ReadSPList(DbConnection connection, DbProviderFactory factory); public GeneratedTextTransformation outer; public void WriteLine(string o) { outer.WriteLine(o); } } static int GetDatatypePrecision(string type) { int startPos = type.IndexOf(","); if (startPos < 0) return -1; int endPos = type.IndexOf(")"); if (endPos < 0) return -1; string typePrecisionStr = type.Substring(startPos+1,endPos-startPos-1); int result = -1; if (int.TryParse(typePrecisionStr,out result)) return result; else return -1; } static int GetDatatypeSize(string type) { int startPos = type.IndexOf("("); if (startPos < 0) return -1; int endPos = type.IndexOf(","); if (endPos < 0) { endPos = type.IndexOf(")"); } string typeSizeStr = type.Substring(startPos+1,endPos-startPos-1); int result = -1; if (int.TryParse(typeSizeStr,out result)) return result; else return -1; } // Edit here to get a method to read the proc class SqlServerSchemaReader : SchemaReader { // SchemaReader.ReadSchema public override Tables ReadSchema(DbConnection connection, DbProviderFactory factory) { var result=new Tables(); _connection=connection; _factory=factory; var cmd=_factory.CreateCommand(); cmd.Connection=connection; cmd.CommandText=TABLE_SQL; //pull the tables in a reader using(cmd) { using (var rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Table tbl=new Table(); tbl.Name=rdr["TABLE_NAME"].ToString(); tbl.Schema=rdr["TABLE_SCHEMA"].ToString(); tbl.IsView=string.Compare(rdr["TABLE_TYPE"].ToString(), "View", true)==0; tbl.IsFunction=string.Compare(rdr["TABLE_TYPE"].ToString(), "TVF", true)==0; tbl.CleanName=CleanUp(tbl.Name); tbl.ClassName=Inflector.MakeSingular(tbl.CleanName); result.Add(tbl); } } } foreach (var tbl in result) { tbl.Columns=LoadColumns(tbl); // Mark the primary key string PrimaryKey=GetPK(tbl.Name); var pkColumn=tbl.Columns.SingleOrDefault(x=>x.Name.ToLower().Trim()==PrimaryKey.ToLower().Trim()); if(pkColumn!=null) { pkColumn.IsPK=true; } } return result; } public override List<SP> ReadSPList(DbConnection connection, DbProviderFactory factory) { var result=new List<SP>(); _connection=connection; _factory=factory; var cmd=_factory.CreateCommand(); cmd.Connection=connection; cmd.CommandText=SP_NAMES_SQL; //pull the tables in a reader using(cmd) { using (var rdr=cmd.ExecuteReader()) { while(rdr.Read()) { SP sp=new SP(); sp.Name=rdr["sp_name"].ToString(); sp.Schema = rdr["schema_name"].ToString(); sp.CleanName=CleanUp(sp.Name); sp.ClassName=Inflector.MakeSingular(sp.CleanName); result.Add(sp); } } } foreach (var sp in result) { sp.Parameters=LoadSPParams(sp); } return result; } DbConnection _connection; DbProviderFactory _factory; List<Column> LoadColumns(Table tbl) { using (var cmd=_factory.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=COLUMN_SQL; var p = cmd.CreateParameter(); p.ParameterName = "@tableName"; p.Value=tbl.Name; cmd.Parameters.Add(p); p = cmd.CreateParameter(); p.ParameterName = "@schemaName"; p.Value=tbl.Schema; cmd.Parameters.Add(p); var result=new List<Column>(); using (IDataReader rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Column col=new Column(); col.Name=rdr["ColumnName"].ToString(); col.PropertyName=CleanUp(col.Name); col.PropertyType=GetPropertyType(rdr["DataType"].ToString()); col.Size=GetDatatypeSize(rdr["DataType"].ToString()); col.Precision=GetDatatypePrecision(rdr["DataType"].ToString()); col.IsNullable=rdr["IsNullable"].ToString()=="YES"; col.IsAutoIncrement=((int)rdr["IsIdentity"])==1; col.IsComputed=((int)rdr["IsComputed"])==1; result.Add(col); } } return result; } } List<SPParam> LoadSPParams(SP sp) { using (var cmd=_factory.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=SP_PARAMETERS_SQL; var p = cmd.CreateParameter(); p.ParameterName = "@spname"; p.Value=sp.Name; cmd.Parameters.Add(p); var result=new List<SPParam>(); using (IDataReader rdr=cmd.ExecuteReader()) { while(rdr.Read()) { if (rdr["IS_RESULT"].ToString().ToUpper() == "YES") continue; SPParam param=new SPParam(); param.SysType=GetPropertyType(rdr["DATA_TYPE"].ToString()); param.NullableSysType=GetNullablePropertyType(rdr["DATA_TYPE"].ToString()); param.DbType=GetDbType(rdr["DATA_TYPE"].ToString()).ToString(); param.Name=rdr["PARAMETER_NAME"].ToString().Replace("@",""); param.CleanName=CleanUp(param.Name); if (rdr["PARAMETER_MODE"].ToString().ToUpper() == "OUT") param.Direction = SPParamDir.OutDirection; else if (rdr["PARAMETER_MODE"].ToString().ToUpper() == "IN") param.Direction = SPParamDir.InDirection; else param.Direction = SPParamDir.InAndOutDirection; result.Add(param); } } return result; } } string GetPK(string table){ string sql=@"SELECT c.name AS ColumnName FROM sys.indexes AS i INNER JOIN sys.index_columns AS ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id INNER JOIN sys.objects AS o ON i.object_id = o.object_id LEFT OUTER JOIN sys.columns AS c ON ic.object_id = c.object_id AND c.column_id = ic.column_id WHERE (i.is_primary_key = 1) AND (o.name = @tableName)"; using (var cmd=_factory.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=sql; var p = cmd.CreateParameter(); p.ParameterName = "@tableName"; p.Value=table; cmd.Parameters.Add(p); var result = ""; DbDataReader reader = cmd.ExecuteReader(); try { if (reader.Read()) { result = reader[0].ToString(); if (reader.Read()) { result = ""; } } } finally { // Always call Close when done reading. reader.Close(); } return result; } } string GetPropertyType(string sqlType) { string propertyType,dbType; GetPropertyAndDbType(sqlType,out propertyType,out dbType); return propertyType; } string GetNullablePropertyType(string sqlType) { string value = GetPropertyType(sqlType); if (value.ToUpper() != "STRING" && value.ToUpper() != "BYTE[]") return value + "?"; else return value; } string GetDbType(string sqlType) { string propertyType,dbType; GetPropertyAndDbType(sqlType,out propertyType,out dbType); return dbType; } void GetPropertyAndDbType(string sqlType, out string propertyType,out string dbType) { string sysType="string"; string sysDbType="DbType.String"; switch (sqlType) { case "varchar": sysType = "string"; sysDbType = "DbType.AnsiString"; break; case "bigint": sysType = "long"; sysDbType = "DbType.Int64"; break; case "smallint": sysType= "short"; sysDbType = "DbType.Int16"; break; case "int": sysType= "int"; sysDbType = "DbType.Int32"; break; case "uniqueidentifier": sysType= "Guid"; sysDbType = "DbType.Guid"; break; case "smalldatetime": case "datetime": case "datetime2": case "date": case "time": sysType= "DateTime"; sysDbType = "DbType.DateTime"; break; case "datetimeoffset": sysType = "DateTimeOffset"; sysDbType = "DbType.DateTimeOffset"; break; case "float": sysType="double"; sysDbType = "DbType.Double"; break; case "real": sysType="float"; sysDbType = "DbType.Double"; break; case "numeric": case "smallmoney": case "decimal": case "money": sysType= "decimal"; sysDbType = "DbType.Decimal"; break; case "tinyint": sysType = "byte"; sysDbType = "DbType.Byte"; break; case "bit": sysType= "bool"; sysDbType = "DbType.Boolean"; break; case "image": case "binary": case "varbinary": case "timestamp": sysType= "byte[]"; sysDbType = "DbType.Binary"; break; case "geography": sysType = "Microsoft.SqlServer.Types.SqlGeography"; sysDbType = "DbType."; break; case "geometry": sysType = "Microsoft.SqlServer.Types.SqlGeometry"; sysDbType = "DbType."; break; } propertyType = sysType; dbType = sysDbType; } string GetDBType(string sqlType) { string sysType="string"; switch (sqlType) { case "bigint": sysType = "long"; break; case "smallint": sysType= "short"; break; case "int": sysType= "int"; break; case "uniqueidentifier": sysType= "Guid"; break; case "smalldatetime": case "datetime": case "datetime2": case "date": case "time": sysType= "DateTime"; break; case "datetimeoffset": sysType = "DateTimeOffset"; break; case "float": sysType="double"; break; case "real": sysType="float"; break; case "numeric": case "smallmoney": case "decimal": case "money": sysType= "decimal"; break; case "tinyint": sysType = "byte"; break; case "bit": sysType= "bool"; break; case "image": case "binary": case "varbinary": case "timestamp": sysType= "byte[]"; break; case "geography": sysType = "Microsoft.SqlServer.Types.SqlGeography"; break; case "geometry": sysType = "Microsoft.SqlServer.Types.SqlGeometry"; break; } return sysType; } const string TABLE_SQL=@"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' OR TABLE_TYPE='VIEW' UNION SELECT SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME, 'TVF' FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE = 'FUNCTION' AND DATA_TYPE = 'TABLE'"; const string COLUMN_SQL=@"SELECT T.[Database] , T.Owner , T.TableName , T.ColumnName , T.OrdinalPosition , T.DefaultSetting , T.IsNullable , T.DataType , T.MaxLength , T.DatePrecision , T.IsIdentity , T.IsComputed FROM ( SELECT TABLE_CATALOG AS [Database], TABLE_SCHEMA AS Owner, TABLE_NAME AS TableName, COLUMN_NAME AS ColumnName, ORDINAL_POSITION AS OrdinalPosition, COLUMN_DEFAULT AS DefaultSetting, IS_NULLABLE AS IsNullable, DATA_TYPE AS DataType, CHARACTER_MAXIMUM_LENGTH AS MaxLength, DATETIME_PRECISION AS DatePrecision, COLUMNPROPERTY(object_id('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'), COLUMN_NAME, 'IsIdentity') AS IsIdentity, COLUMNPROPERTY(object_id('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'), COLUMN_NAME, 'IsComputed') as IsComputed FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=@tableName AND TABLE_SCHEMA=@schemaName --ORDER BY OrdinalPosition ASC UNION SELECT TABLE_CATALOG AS [Database], TABLE_SCHEMA AS Owner, TABLE_NAME AS TableName, COLUMN_NAME AS ColumnName, ORDINAL_POSITION AS OrdinalPosition, COLUMN_DEFAULT AS DefaultSetting, IS_NULLABLE AS IsNullable, DATA_TYPE AS DataType, CHARACTER_MAXIMUM_LENGTH AS MaxLength, DATETIME_PRECISION AS DatePrecision, COLUMNPROPERTY(object_id('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'), COLUMN_NAME, 'IsIdentity') AS IsIdentity, COLUMNPROPERTY(object_id('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'), COLUMN_NAME, 'IsComputed') as IsComputed FROM INFORMATION_SCHEMA.ROUTINE_COLUMNS WHERE TABLE_NAME=@tableName AND TABLE_SCHEMA=@schemaName ) T ORDER BY T.OrdinalPosition ASC"; const string SP_NAMES_SQL=@"SELECT o.name AS sp_name, s.name AS schema_name FROM sys.objects o INNER JOIN sys.schemas s ON o.schema_id = s.schema_id WHERE o.type = 'P' AND o.name NOT IN ( 'fn_diagramobjects', 'sp_alterdiagram', 'sp_creatediagram', 'sp_dropdiagram', 'sp_helpdiagramdefinition', 'sp_helpdiagrams', 'sp_renamediagram', 'sp_upgraddiagrams', 'sysdiagrams' )"; const string SP_PARAMETERS_SQL=@"SELECT * from information_schema.PARAMETERS where SPECIFIC_NAME = @spname order by ORDINAL_POSITION"; } class SqlServerCeSchemaReader : SchemaReader { // SchemaReader.ReadSchema public override Tables ReadSchema(DbConnection connection, DbProviderFactory factory) { var result=new Tables(); _connection=connection; _factory=factory; var cmd=_factory.CreateCommand(); cmd.Connection=connection; cmd.CommandText=TABLE_SQL; //pull the tables in a reader using(cmd) { using (var rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Table tbl=new Table(); tbl.Name=rdr["TABLE_NAME"].ToString(); tbl.CleanName=CleanUp(tbl.Name); tbl.ClassName=Inflector.MakeSingular(tbl.CleanName); tbl.Schema=null; tbl.IsView=false; result.Add(tbl); } } } foreach (var tbl in result) { tbl.Columns=LoadColumns(tbl); // Mark the primary key string PrimaryKey=GetPK(tbl.Name); var pkColumn=tbl.Columns.SingleOrDefault(x=>x.Name.ToLower().Trim()==PrimaryKey.ToLower().Trim()); if(pkColumn!=null) pkColumn.IsPK=true; } return result; } public override List<SP> ReadSPList(DbConnection connection, DbProviderFactory factory) { return new List<SP>(); } DbConnection _connection; DbProviderFactory _factory; List<Column> LoadColumns(Table tbl) { using (var cmd=_factory.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=COLUMN_SQL; var p = cmd.CreateParameter(); p.ParameterName = "@tableName"; p.Value=tbl.Name; cmd.Parameters.Add(p); var result=new List<Column>(); using (IDataReader rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Column col=new Column(); col.Name=rdr["ColumnName"].ToString(); col.PropertyName=CleanUp(col.Name); col.PropertyType=GetPropertyType(rdr["DataType"].ToString()); col.Size=GetDatatypeSize(rdr["DataType"].ToString()); col.Precision=GetDatatypePrecision(rdr["DataType"].ToString()); col.IsNullable=rdr["IsNullable"].ToString()=="YES"; col.IsAutoIncrement=rdr["AUTOINC_INCREMENT"]!=DBNull.Value; result.Add(col); } } return result; } } string GetPK(string table){ string sql=@"SELECT KCU.COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC ON KCU.CONSTRAINT_NAME=TC.CONSTRAINT_NAME WHERE TC.CONSTRAINT_TYPE='PRIMARY KEY' AND KCU.TABLE_NAME=@tableName"; using (var cmd=_factory.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=sql; var p = cmd.CreateParameter(); p.ParameterName = "@tableName"; p.Value=table; cmd.Parameters.Add(p); var result = ""; DbDataReader reader = cmd.ExecuteReader(); try { if (reader.Read()) { result = reader[0].ToString(); if (reader.Read()) { result = ""; } } } finally { // Always call Close when done reading. reader.Close(); } return result; } } string GetPropertyType(string sqlType) { string sysType="string"; switch (sqlType) { case "bigint": sysType = "long"; break; case "smallint": sysType= "short"; break; case "int": sysType= "int"; break; case "uniqueidentifier": sysType= "Guid"; break; case "smalldatetime": case "datetime": case "date": case "time": sysType= "DateTime"; break; case "float": sysType="double"; break; case "real": sysType="float"; break; case "numeric": case "smallmoney": case "decimal": case "money": sysType= "decimal"; break; case "tinyint": sysType = "byte"; break; case "bit": sysType= "bool"; break; case "image": case "binary": case "varbinary": case "timestamp": sysType= "byte[]"; break; } return sysType; } const string TABLE_SQL=@"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='TABLE'"; const string COLUMN_SQL=@"SELECT TABLE_CATALOG AS [Database], TABLE_SCHEMA AS Owner, TABLE_NAME AS TableName, COLUMN_NAME AS ColumnName, ORDINAL_POSITION AS OrdinalPosition, COLUMN_DEFAULT AS DefaultSetting, IS_NULLABLE AS IsNullable, DATA_TYPE AS DataType, AUTOINC_INCREMENT, CHARACTER_MAXIMUM_LENGTH AS MaxLength, DATETIME_PRECISION AS DatePrecision FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=@tableName ORDER BY OrdinalPosition ASC"; } class PostGreSqlSchemaReader : SchemaReader { // SchemaReader.ReadSchema public override Tables ReadSchema(DbConnection connection, DbProviderFactory factory) { var result=new Tables(); _connection=connection; _factory=factory; var cmd=_factory.CreateCommand(); cmd.Connection=connection; cmd.CommandText=TABLE_SQL; //pull the tables in a reader using(cmd) { using (var rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Table tbl=new Table(); tbl.Name=rdr["table_name"].ToString(); tbl.Schema=rdr["table_schema"].ToString(); tbl.IsView=string.Compare(rdr["table_type"].ToString(), "View", true)==0; tbl.CleanName=CleanUp(tbl.Name); tbl.ClassName=Inflector.MakeSingular(tbl.CleanName); result.Add(tbl); } } } foreach (var tbl in result) { tbl.Columns=LoadColumns(tbl); // Mark the primary key string PrimaryKey=GetPK(tbl.Name); var pkColumn=tbl.Columns.SingleOrDefault(x=>x.Name.ToLower().Trim()==PrimaryKey.ToLower().Trim()); if(pkColumn!=null) pkColumn.IsPK=true; } return result; } public override List<SP> ReadSPList(DbConnection connection, DbProviderFactory factory) { return new List<SP>(); } DbConnection _connection; DbProviderFactory _factory; List<Column> LoadColumns(Table tbl) { using (var cmd=_factory.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=COLUMN_SQL; var p = cmd.CreateParameter(); p.ParameterName = "@tableName"; p.Value=tbl.Name; cmd.Parameters.Add(p); var result=new List<Column>(); using (IDataReader rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Column col=new Column(); col.Name=rdr["column_name"].ToString(); col.PropertyName=CleanUp(col.Name); col.PropertyType=GetPropertyType(rdr["udt_name"].ToString()); col.Size=GetDatatypeSize(rdr["udt_name"].ToString()); col.Precision=GetDatatypePrecision(rdr["udt_name"].ToString()); col.IsNullable=rdr["is_nullable"].ToString()=="YES"; col.IsAutoIncrement = rdr["column_default"].ToString().StartsWith("nextval("); result.Add(col); } } return result; } } string GetPK(string table){ string sql=@"SELECT kcu.column_name FROM information_schema.key_column_usage kcu JOIN information_schema.table_constraints tc ON kcu.constraint_name=tc.constraint_name WHERE lower(tc.constraint_type)='primary key' AND kcu.table_name=@tablename"; using (var cmd=_factory.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=sql; var p = cmd.CreateParameter(); p.ParameterName = "@tableName"; p.Value=table; cmd.Parameters.Add(p); var result = ""; DbDataReader reader = cmd.ExecuteReader(); try { if (reader.Read()) { result = reader[0].ToString(); if (reader.Read()) { result = ""; } } } finally { // Always call Close when done reading. reader.Close(); } return result; } } string GetPropertyType(string sqlType) { switch (sqlType) { case "int8": case "serial8": return "long"; case "bool": return "bool"; case "bytea ": return "byte[]"; case "float8": return "double"; case "int4": case "serial4": return "int"; case "money ": return "decimal"; case "numeric": return "decimal"; case "float4": return "float"; case "int2": return "short"; case "time": case "timetz": case "timestamp": case "timestamptz": case "date": return "DateTime"; default: return "string"; } } const string TABLE_SQL=@" SELECT table_name, table_schema, table_type FROM information_schema.tables WHERE (table_type='BASE TABLE' OR table_type='VIEW') AND table_schema NOT IN ('pg_catalog', 'information_schema'); "; const string COLUMN_SQL=@" SELECT column_name, is_nullable, udt_name, column_default FROM information_schema.columns WHERE table_name=@tableName; "; } class MySqlSchemaReader : SchemaReader { // SchemaReader.ReadSchema public override Tables ReadSchema(DbConnection connection, DbProviderFactory factory) { var result=new Tables(); var cmd=factory.CreateCommand(); cmd.Connection=connection; cmd.CommandText=TABLE_SQL; //pull the tables in a reader using(cmd) { using (var rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Table tbl=new Table(); tbl.Name=rdr["TABLE_NAME"].ToString(); tbl.Schema=rdr["TABLE_SCHEMA"].ToString(); tbl.IsView=string.Compare(rdr["TABLE_TYPE"].ToString(), "View", true)==0; tbl.CleanName=CleanUp(tbl.Name); tbl.ClassName=Inflector.MakeSingular(tbl.CleanName); result.Add(tbl); } } } //this will return everything for the DB var schema = connection.GetSchema("COLUMNS"); //loop again - but this time pull by table name foreach (var item in result) { item.Columns=new List<Column>(); //pull the columns from the schema var columns = schema.Select("TABLE_NAME='" + item.Name + "'"); foreach (var row in columns) { Column col=new Column(); col.Name=row["COLUMN_NAME"].ToString(); col.PropertyName=CleanUp(col.Name); col.PropertyType=GetPropertyType(row); col.Size=GetDatatypeSize(row["DATA_TYPE"].ToString()); col.Precision=GetDatatypePrecision(row["DATA_TYPE"].ToString()); col.IsNullable=row["IS_NULLABLE"].ToString()=="YES"; col.IsPK=row["COLUMN_KEY"].ToString()=="PRI"; col.IsAutoIncrement=row["extra"].ToString().ToLower().IndexOf("auto_increment")>=0; item.Columns.Add(col); } } return result; } public override List<SP> ReadSPList(DbConnection connection, DbProviderFactory factory) { return new List<SP>(); } static string GetPropertyType(DataRow row) { bool bUnsigned = row["COLUMN_TYPE"].ToString().IndexOf("unsigned")>=0; string propType="string"; switch (row["DATA_TYPE"].ToString()) { case "bigint": propType= bUnsigned ? "ulong" : "long"; break; case "int": propType= bUnsigned ? "uint" : "int"; break; case "smallint": propType= bUnsigned ? "ushort" : "short"; break; case "guid": propType= "Guid"; break; case "smalldatetime": case "date": case "datetime": case "timestamp": propType= "DateTime"; break; case "float": propType="float"; break; case "double": propType="double"; break; case "numeric": case "smallmoney": case "decimal": case "money": propType= "decimal"; break; case "bit": case "bool": case "boolean": propType= "bool"; break; case "tinyint": propType = bUnsigned ? "byte" : "sbyte"; break; case "image": case "binary": case "blob": case "mediumblob": case "longblob": case "varbinary": propType= "byte[]"; break; } return propType; } const string TABLE_SQL=@" SELECT * FROM information_schema.tables WHERE (table_type='BASE TABLE' OR table_type='VIEW') "; } class OracleSchemaReader : SchemaReader { // SchemaReader.ReadSchema public override Tables ReadSchema(DbConnection connection, DbProviderFactory factory) { var result=new Tables(); _connection=connection; _factory=factory; var cmd=_factory.CreateCommand(); cmd.Connection=connection; cmd.CommandText=TABLE_SQL; cmd.GetType().GetProperty("BindByName").SetValue(cmd, true, null); //pull the tables in a reader using(cmd) { using (var rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Table tbl=new Table(); tbl.Name=rdr["TABLE_NAME"].ToString(); tbl.Schema = rdr["TABLE_SCHEMA"].ToString(); tbl.IsView=string.Compare(rdr["TABLE_TYPE"].ToString(), "View", true)==0; tbl.CleanName=CleanUp(tbl.Name); tbl.ClassName=Inflector.MakeSingular(tbl.CleanName); result.Add(tbl); } } } foreach (var tbl in result) { tbl.Columns=LoadColumns(tbl); // Mark the primary key string PrimaryKey=GetPK(tbl.Name); var pkColumn=tbl.Columns.SingleOrDefault(x=>x.Name.ToLower().Trim()==PrimaryKey.ToLower().Trim()); if(pkColumn!=null) pkColumn.IsPK=true; } return result; } public override List<SP> ReadSPList(DbConnection connection, DbProviderFactory factory) { return new List<SP>(); } DbConnection _connection; DbProviderFactory _factory; List<Column> LoadColumns(Table tbl) { using (var cmd=_factory.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=COLUMN_SQL; cmd.GetType().GetProperty("BindByName").SetValue(cmd, true, null); var p = cmd.CreateParameter(); p.ParameterName = ":tableName"; p.Value=tbl.Name; cmd.Parameters.Add(p); var result=new List<Column>(); using (IDataReader rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Column col=new Column(); col.Name=rdr["ColumnName"].ToString(); col.PropertyName=CleanUp(col.Name); col.PropertyType=GetPropertyType(rdr["DataType"].ToString(), (rdr["DataType"] == DBNull.Value ? null : rdr["DataType"].ToString())); col.Size=GetDatatypeSize(rdr["DataType"].ToString()); col.Precision=GetDatatypePrecision(rdr["DataType"].ToString()); col.IsNullable=rdr["IsNullable"].ToString()=="YES"; col.IsAutoIncrement=false; result.Add(col); } } return result; } } string GetPK(string table){ string sql=@"select column_name from USER_CONSTRAINTS uc inner join USER_CONS_COLUMNS ucc on uc.constraint_name = ucc.constraint_name where uc.constraint_type = 'P' and uc.table_name = upper(:tableName) and ucc.position = 1"; using (var cmd=_factory.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=sql; cmd.GetType().GetProperty("BindByName").SetValue(cmd, true, null); var p = cmd.CreateParameter(); p.ParameterName = ":tableName"; p.Value=table; cmd.Parameters.Add(p); var result = ""; DbDataReader reader = cmd.ExecuteReader(); try { if (reader.Read()) { result = reader[0].ToString(); if (reader.Read()) { result = ""; } } } finally { // Always call Close when done reading. reader.Close(); } return result; } } string GetPropertyType(string sqlType, string dataScale) { string sysType="string"; switch (sqlType.ToLower()) { case "bigint": sysType = "long"; break; case "smallint": sysType= "short"; break; case "int": sysType= "int"; break; case "uniqueidentifier": sysType= "Guid"; break; case "smalldatetime": case "datetime": case "date": sysType= "DateTime"; break; case "float": sysType="double"; break; case "real": case "numeric": case "smallmoney": case "decimal": case "money": case "number": sysType= "decimal"; break; case "tinyint": sysType = "byte"; break; case "bit": sysType= "bool"; break; case "image": case "binary": case "varbinary": case "timestamp": sysType= "byte[]"; break; } if (sqlType == "number" && dataScale == "0") return "long"; return sysType; } const string TABLE_SQL=@"select TABLE_NAME, 'Table' TABLE_TYPE, USER TABLE_SCHEMA from USER_TABLES union all select VIEW_NAME, 'View', USER from USER_VIEWS"; const string COLUMN_SQL=@"select table_name TableName, column_name ColumnName, data_type DataType, data_scale DataScale, nullable IsNullable from USER_TAB_COLS utc where table_name = :tableName order by column_id"; } class SqliteSchemaReader : SchemaReader { // SchemaReader.ReadSchema public override Tables ReadSchema(DbConnection connection, DbProviderFactory factory) { var result=new Tables(); _connection=connection; _factory=factory; var cmd=_factory.CreateCommand(); cmd.Connection=connection; cmd.CommandText=TABLE_SQL; //cmd.GetType().GetProperty("BindByName").SetValue(cmd, true, null); //pull the tables in a reader using(cmd) { using (var rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Table tbl=new Table(); tbl.Name=rdr["name"].ToString(); tbl.Schema = ""; tbl.IsView=string.Compare(rdr["type"].ToString(), "view", true)==0; tbl.CleanName=CleanUp(tbl.Name); tbl.ClassName=Inflector.MakeSingular(tbl.CleanName); tbl.SQL = rdr["sql"].ToString(); result.Add(tbl); } } } foreach (var tbl in result) { tbl.Columns=LoadColumns(tbl); tbl.Indices = LoadIndices(tbl.Name); tbl.FKeys = LoadFKeys(tbl.Name); } return result; } public override List<SP> ReadSPList(DbConnection connection, DbProviderFactory factory) { return new List<SP>(); } DbConnection _connection; DbProviderFactory _factory; List<Column> LoadColumns(Table tbl) { using (var cmd=_factory.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=string.Format(COLUMN_SQL,tbl.Name); var result=new List<Column>(); using (IDataReader rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Column col=new Column(); col.Name=rdr["name"].ToString(); col.PropertyName=CleanUp(col.Name); col.PropertyType=GetPropertyType(rdr["type"].ToString(), (rdr["type"] == DBNull.Value ? null : rdr["type"].ToString())); col.Size=GetDatatypeSize(rdr["type"].ToString()); col.Precision=GetDatatypePrecision(rdr["type"].ToString()); col.IsNullable=rdr["notnull"].ToString()=="0"; col.IsAutoIncrement=false; col.IsPK=rdr["pk"].ToString()!="0"; if (col.IsPK) col.IsAutoIncrement = tbl.SQL.ToUpper().Contains("AUTOINCREMENT"); else col.IsAutoIncrement = false; col.DefaultValue = rdr["dflt_value"] == DBNull.Value ? null : rdr["dflt_value"].ToString(); result.Add(col); } } return result; } } List<TableIndex> LoadIndices(string tableName) { var result=new List<TableIndex>(); using (var cmd1=_factory.CreateCommand()) { cmd1.Connection=_connection; cmd1.CommandText=string.Format(INDEX_SQL,tableName); using (IDataReader rdr1=cmd1.ExecuteReader()) { while(rdr1.Read()) { TableIndex indx=new TableIndex(); indx.Name=rdr1["name"].ToString(); indx.SQL=rdr1["sql"].ToString(); indx.IndexColumns = new List<IndexColumn>(); indx.IsUnique = indx.SQL.ToUpper().Contains("UNIQUE"); using (var cmd2=_factory.CreateCommand()) { cmd2.Connection=_connection; cmd2.CommandText=string.Format(INDEX_INFO_SQL,indx.Name); using (IDataReader rdr2=cmd2.ExecuteReader()) { while(rdr2.Read()) { IndexColumn col = new IndexColumn(); col.Name = rdr2["name"].ToString(); indx.IndexColumns.Add(col); } } } result.Add(indx); } } } return result; } List<FKey> LoadFKeys(string tblName) { using (var cmd=_factory.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=string.Format(FKEY_INFO_SQL,tblName); var result=new List<FKey>(); using (IDataReader rdr=cmd.ExecuteReader()) { while(rdr.Read()) { FKey key=new FKey(); key.ToTable=rdr["table"].ToString(); key.ToColumn=rdr["to"].ToString(); key.FromColumn=rdr["from"].ToString(); result.Add(key); } } return result; } } string GetPropertyType(string sqlType, string dataScale) { string sysType="string"; switch (sqlType.ToLower()) { case "integer": case "int": case "tinyint": case "smallint": case "mediumint": case "int2": case "int8": sysType= "long"; break; case "bigint": case "unsigned big int": sysType= "long"; break; case "uniqueidentifier": sysType= "Guid"; break; case "smalldatetime": case "datetime": case "date": sysType= "DateTime"; break; case "float": case "double precision": case "double": sysType="double"; break; case "real": case "numeric": case "smallmoney": case "decimal": case "money": case "number": sysType= "decimal"; break; case "bit": sysType= "bool"; break; case "image": case "binary": case "varbinary": case "timestamp": sysType= "byte[]"; break; } if (sqlType == "number" && dataScale == "0") return "long"; return sysType; } const string TABLE_SQL=@"SELECT name, type , sql FROM sqlite_master WHERE type IN ('table','view') and name not in ('sqlite_sequence') "; const string COLUMN_SQL=@"pragma table_info({0})"; const string INDEX_SQL=@"SELECT name , sql FROM sqlite_master WHERE type IN ('index') and lower(tbl_name) = lower('{0}')"; const string INDEX_INFO_SQL=@"pragma index_info({0})"; const string FKEY_INFO_SQL=@"pragma foreign_key_list({0})"; } /// <summary> /// Summary for the Inflector class /// </summary> public static class Inflector { private static readonly List<InflectorRule> _plurals = new List<InflectorRule>(); private static readonly List<InflectorRule> _singulars = new List<InflectorRule>(); private static readonly List<string> _uncountables = new List<string>(); /// <summary> /// Initializes the <see cref="Inflector"/> class. /// </summary> static Inflector() { AddPluralRule("$", "s"); AddPluralRule("s$", "s"); AddPluralRule("(ax|test)is$", "$1es"); AddPluralRule("(octop|vir)us$", "$1i"); AddPluralRule("(alias|status)$", "$1es"); AddPluralRule("(bu)s$", "$1ses"); AddPluralRule("(buffal|tomat)o$", "$1oes"); AddPluralRule("([ti])um$", "$1a"); AddPluralRule("sis$", "ses"); AddPluralRule("(?:([^f])fe|([lr])f)$", "$1$2ves"); AddPluralRule("(hive)$", "$1s"); AddPluralRule("([^aeiouy]|qu)y$", "$1ies"); AddPluralRule("(x|ch|ss|sh)$", "$1es"); AddPluralRule("(matr|vert|ind)ix|ex$", "$1ices"); AddPluralRule("([m|l])ouse$", "$1ice"); AddPluralRule("^(ox)$", "$1en"); AddPluralRule("(quiz)$", "$1zes"); AddSingularRule("s$", String.Empty); AddSingularRule("ss$", "ss"); AddSingularRule("(n)ews$", "$1ews"); AddSingularRule("([ti])a$", "$1um"); AddSingularRule("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis"); AddSingularRule("(^analy)ses$", "$1sis"); AddSingularRule("([^f])ves$", "$1fe"); AddSingularRule("(hive)s$", "$1"); AddSingularRule("(tive)s$", "$1"); AddSingularRule("([lr])ves$", "$1f"); AddSingularRule("([^aeiouy]|qu)ies$", "$1y"); AddSingularRule("(s)eries$", "$1eries"); AddSingularRule("(m)ovies$", "$1ovie"); AddSingularRule("(x|ch|ss|sh)es$", "$1"); AddSingularRule("([m|l])ice$", "$1ouse"); AddSingularRule("(bus)es$", "$1"); AddSingularRule("(o)es$", "$1"); AddSingularRule("(shoe)s$", "$1"); AddSingularRule("(cris|ax|test)es$", "$1is"); AddSingularRule("(octop|vir)i$", "$1us"); AddSingularRule("(alias|status)$", "$1"); AddSingularRule("(alias|status)es$", "$1"); AddSingularRule("^(ox)en", "$1"); AddSingularRule("(vert|ind)ices$", "$1ex"); AddSingularRule("(matr)ices$", "$1ix"); AddSingularRule("(quiz)zes$", "$1"); AddIrregularRule("person", "people"); AddIrregularRule("man", "men"); AddIrregularRule("child", "children"); AddIrregularRule("sex", "sexes"); AddIrregularRule("tax", "taxes"); AddIrregularRule("move", "moves"); AddUnknownCountRule("equipment"); AddUnknownCountRule("information"); AddUnknownCountRule("rice"); AddUnknownCountRule("money"); AddUnknownCountRule("species"); AddUnknownCountRule("series"); AddUnknownCountRule("fish"); AddUnknownCountRule("sheep"); } /// <summary> /// Adds the irregular rule. /// </summary> /// <param name="singular">The singular.</param> /// <param name="plural">The plural.</param> private static void AddIrregularRule(string singular, string plural) { AddPluralRule(String.Concat("(", singular[0], ")", singular.Substring(1), "$"), String.Concat("$1", plural.Substring(1))); AddSingularRule(String.Concat("(", plural[0], ")", plural.Substring(1), "$"), String.Concat("$1", singular.Substring(1))); } /// <summary> /// Adds the unknown count rule. /// </summary> /// <param name="word">The word.</param> private static void AddUnknownCountRule(string word) { _uncountables.Add(word.ToLower()); } /// <summary> /// Adds the plural rule. /// </summary> /// <param name="rule">The rule.</param> /// <param name="replacement">The replacement.</param> private static void AddPluralRule(string rule, string replacement) { _plurals.Add(new InflectorRule(rule, replacement)); } /// <summary> /// Adds the singular rule. /// </summary> /// <param name="rule">The rule.</param> /// <param name="replacement">The replacement.</param> private static void AddSingularRule(string rule, string replacement) { _singulars.Add(new InflectorRule(rule, replacement)); } /// <summary> /// Makes the plural. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public static string MakePlural(string word) { return ApplyRules(_plurals, word); } /// <summary> /// Makes the singular. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public static string MakeSingular(string word) { return ApplyRules(_singulars, word); } /// <summary> /// Applies the rules. /// </summary> /// <param name="rules">The rules.</param> /// <param name="word">The word.</param> /// <returns></returns> private static string ApplyRules(IList<InflectorRule> rules, string word) { string result = word; if (!_uncountables.Contains(word.ToLower())) { for (int i = rules.Count - 1; i >= 0; i--) { string currentPass = rules[i].Apply(word); if (currentPass != null) { result = currentPass; break; } } } return result; } /// <summary> /// Converts the string to title case. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public static string ToTitleCase(string word) { return Regex.Replace(ToHumanCase(AddUnderscores(word)), @"\b([a-z])", delegate(Match match) { return match.Captures[0].Value.ToUpper(); }); } /// <summary> /// Converts the string to human case. /// </summary> /// <param name="lowercaseAndUnderscoredWord">The lowercase and underscored word.</param> /// <returns></returns> public static string ToHumanCase(string lowercaseAndUnderscoredWord) { return MakeInitialCaps(Regex.Replace(lowercaseAndUnderscoredWord, @"_", " ")); } /// <summary> /// Adds the underscores. /// </summary> /// <param name="pascalCasedWord">The pascal cased word.</param> /// <returns></returns> public static string AddUnderscores(string pascalCasedWord) { return Regex.Replace(Regex.Replace(Regex.Replace(pascalCasedWord, @"([A-Z]+)([A-Z][a-z])", "$1_$2"), @"([a-z\d])([A-Z])", "$1_$2"), @"[-\s]", "_").ToLower(); } /// <summary> /// Makes the initial caps. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public static string MakeInitialCaps(string word) { return String.Concat(word.Substring(0, 1).ToUpper(), word.Substring(1).ToLower()); } /// <summary> /// Makes the initial lower case. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public static string MakeInitialLowerCase(string word) { return String.Concat(word.Substring(0, 1).ToLower(), word.Substring(1)); } /// <summary> /// Determine whether the passed string is numeric, by attempting to parse it to a double /// </summary> /// <param name="str">The string to evaluated for numeric conversion</param> /// <returns> /// <c>true</c> if the string can be converted to a number; otherwise, <c>false</c>. /// </returns> public static bool IsStringNumeric(string str) { double result; return (double.TryParse(str, NumberStyles.Float, NumberFormatInfo.CurrentInfo, out result)); } /// <summary> /// Adds the ordinal suffix. /// </summary> /// <param name="number">The number.</param> /// <returns></returns> public static string AddOrdinalSuffix(string number) { if (IsStringNumeric(number)) { int n = int.Parse(number); int nMod100 = n % 100; if (nMod100 >= 11 && nMod100 <= 13) return String.Concat(number, "th"); switch (n % 10) { case 1: return String.Concat(number, "st"); case 2: return String.Concat(number, "nd"); case 3: return String.Concat(number, "rd"); default: return String.Concat(number, "th"); } } return number; } /// <summary> /// Converts the underscores to dashes. /// </summary> /// <param name="underscoredWord">The underscored word.</param> /// <returns></returns> public static string ConvertUnderscoresToDashes(string underscoredWord) { return underscoredWord.Replace('_', '-'); } #region Nested type: InflectorRule /// <summary> /// Summary for the InflectorRule class /// </summary> private class InflectorRule { /// <summary> /// /// </summary> public readonly Regex regex; /// <summary> /// /// </summary> public readonly string replacement; /// <summary> /// Initializes a new instance of the <see cref="InflectorRule"/> class. /// </summary> /// <param name="regexPattern">The regex pattern.</param> /// <param name="replacementText">The replacement text.</param> public InflectorRule(string regexPattern, string replacementText) { regex = new Regex(regexPattern, RegexOptions.IgnoreCase); replacement = replacementText; } /// <summary> /// Applies the specified word. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public string Apply(string word) { if (!regex.IsMatch(word)) return null; string replace = regex.Replace(word, replacement); if (word == word.ToUpper()) replace = replace.ToUpper(); return replace; } } #endregion } // https://raw.github.com/damieng/DamienGKit // http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4-made-easy-revisited // Manager class records the various blocks so it can split them up class Manager { private class Block { public String Name; public int Start, Length; public bool IncludeInDefault; } private Block currentBlock; private List<Block> files = new List<Block>(); private Block footer = new Block(); private Block header = new Block(); private ITextTemplatingEngineHost host; private StringBuilder template; protected List<String> generatedFileNames = new List<String>(); public static Manager Create(ITextTemplatingEngineHost host, StringBuilder template) { return (host is IServiceProvider) ? new VSManager(host, template) : new Manager(host, template); } public void StartNewFile(String name) { if (name == null) throw new ArgumentNullException("name"); CurrentBlock = new Block { Name = name }; } public void StartFooter(bool includeInDefault = true) { CurrentBlock = footer; footer.IncludeInDefault = includeInDefault; } public void StartHeader(bool includeInDefault = true) { CurrentBlock = header; header.IncludeInDefault = includeInDefault; } public void EndBlock() { if (CurrentBlock == null) return; CurrentBlock.Length = template.Length - CurrentBlock.Start; if (CurrentBlock != header && CurrentBlock != footer) files.Add(CurrentBlock); currentBlock = null; } public virtual void Process(bool split, bool sync = true) { if (split) { EndBlock(); String headerText = template.ToString(header.Start, header.Length); String footerText = template.ToString(footer.Start, footer.Length); String outputPath = Path.GetDirectoryName(host.TemplateFile); files.Reverse(); if (!footer.IncludeInDefault) template.Remove(footer.Start, footer.Length); foreach(Block block in files) { String fileName = Path.Combine(outputPath, block.Name); String content = headerText + template.ToString(block.Start, block.Length) + footerText; generatedFileNames.Add(fileName); CreateFile(fileName, content); template.Remove(block.Start, block.Length); } if (!header.IncludeInDefault) template.Remove(header.Start, header.Length); } } protected virtual void CreateFile(String fileName, String content) { if (IsFileContentDifferent(fileName, content)) File.WriteAllText(fileName, content); } public virtual String GetCustomToolNamespace(String fileName) { return null; } public virtual String DefaultProjectNamespace { get { return null; } } protected bool IsFileContentDifferent(String fileName, String newContent) { return !(File.Exists(fileName) && File.ReadAllText(fileName) == newContent); } private Manager(ITextTemplatingEngineHost host, StringBuilder template) { this.host = host; this.template = template; } private Block CurrentBlock { get { return currentBlock; } set { if (CurrentBlock != null) EndBlock(); if (value != null) value.Start = template.Length; currentBlock = value; } } private class VSManager: Manager { private EnvDTE.ProjectItem templateProjectItem; private EnvDTE.DTE dte; private Action<String> checkOutAction; private Action<IEnumerable<String>> projectSyncAction; public override String DefaultProjectNamespace { get { return templateProjectItem.ContainingProject.Properties.Item("DefaultNamespace").Value.ToString(); } } public override String GetCustomToolNamespace(string fileName) { return dte.Solution.FindProjectItem(fileName).Properties.Item("CustomToolNamespace").Value.ToString(); } public override void Process(bool split, bool sync) { if (templateProjectItem.ProjectItems == null) return; base.Process(split, sync); if (sync) projectSyncAction.EndInvoke(projectSyncAction.BeginInvoke(generatedFileNames, null, null)); } protected override void CreateFile(String fileName, String content) { if (IsFileContentDifferent(fileName, content)) { CheckoutFileIfRequired(fileName); File.WriteAllText(fileName, content); } } internal VSManager(ITextTemplatingEngineHost host, StringBuilder template) : base(host, template) { var hostServiceProvider = (IServiceProvider) host; if (hostServiceProvider == null) throw new ArgumentNullException("Could not obtain IServiceProvider"); dte = (EnvDTE.DTE) hostServiceProvider.GetService(typeof(EnvDTE.DTE)); if (dte == null) throw new ArgumentNullException("Could not obtain DTE from host"); templateProjectItem = dte.Solution.FindProjectItem(host.TemplateFile); checkOutAction = (String fileName) => dte.SourceControl.CheckOutItem(fileName); projectSyncAction = (IEnumerable<String> keepFileNames) => ProjectSync(templateProjectItem, keepFileNames); } private static void ProjectSync(EnvDTE.ProjectItem templateProjectItem, IEnumerable<String> keepFileNames) { var keepFileNameSet = new HashSet<String>(keepFileNames); var projectFiles = new Dictionary<String, EnvDTE.ProjectItem>(); var originalFilePrefix = Path.GetFileNameWithoutExtension(templateProjectItem.get_FileNames(0)) + "."; foreach(EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems) projectFiles.Add(projectItem.get_FileNames(0), projectItem); // Remove unused items from the project foreach(var pair in projectFiles) if (!keepFileNames.Contains(pair.Key) && !(Path.GetFileNameWithoutExtension(pair.Key) + ".").StartsWith(originalFilePrefix)) pair.Value.Delete(); // Add missing files to the project foreach(String fileName in keepFileNameSet) if (!projectFiles.ContainsKey(fileName)) templateProjectItem.ProjectItems.AddFromFile(fileName); } private void CheckoutFileIfRequired(String fileName) { var sc = dte.SourceControl; if (sc != null && sc.IsItemUnderSCC(fileName) && !sc.IsItemCheckedOut(fileName)) checkOutAction.EndInvoke(checkOutAction.BeginInvoke(fileName, null, null)); } } } /* End of Manager.tt */ #> |
Commits for CPE_learningsite/CPE/CPE.App/CPE.App.Api/OrmLite.Core.ttinclude
Revision | Author | Commited | Message |
---|---|---|---|
4cd176 ... | v.shishlov | Fri 27 Aug, 2021 14:33:17 +0000 | initial commit |