nhydrate /trunk/Source/nHydrate.Generator/SqlSchemaToModel.cs

Language C# Lines 1987
MD5 Hash 1308f602434d19ebd77e68af9a43fdd9 Estimated Cost $37,860 (why?)
Repository https://nhydrate.svn.codeplex.com/svn View Raw File
   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
#region Copyright (c) 2006-2012 nHydrate.org, All Rights Reserved
//--------------------------------------------------------------------- *
//                          NHYDRATE.ORG                                *
//             Copyright (c) 2006-2012 All Rights reserved              *
//                                                                      *
//                                                                      *
//This file and its contents are protected by United States and         *
//International copyright laws.  Unauthorized reproduction and/or       *
//distribution of all or any portion of the code contained herein       *
//is strictly prohibited and will result in severe civil and criminal   *
//penalties.  Any violations of this copyright will be prosecuted       *
//to the fullest extent possible under law.                             *
//                                                                      *
//THE SOURCE CODE CONTAINED HEREIN AND IN RELATED FILES IS PROVIDED     *
//TO THE REGISTERED DEVELOPER FOR THE PURPOSES OF EDUCATION AND         *
//TROUBLESHOOTING. UNDER NO CIRCUMSTANCES MAY ANY PORTION OF THE SOURCE *
//CODE BE DISTRIBUTED, DISCLOSED OR OTHERWISE MADE AVAILABLE TO ANY     *
//THIRD PARTY WITHOUT THE EXPRESS WRITTEN CONSENT OF THE NHYDRATE GROUP *
//                                                                      *
//UNDER NO CIRCUMSTANCES MAY THE SOURCE CODE BE USED IN WHOLE OR IN     *
//PART, AS THE BASIS FOR CREATING A PRODUCT THAT PROVIDES THE SAME, OR  *
//SUBSTANTIALLY THE SAME, FUNCTIONALITY AS THIS PRODUCT                 *
//                                                                      *
//THE REGISTERED DEVELOPER ACKNOWLEDGES THAT THIS SOURCE CODE           *
//CONTAINS VALUABLE AND PROPRIETARY TRADE SECRETS OF NHYDRATE,          *
//THE REGISTERED DEVELOPER AGREES TO EXPEND EVERY EFFORT TO             *
//INSURE ITS CONFIDENTIALITY.                                           *
//                                                                      *
//THE END USER LICENSE AGREEMENT (EULA) ACCOMPANYING THE PRODUCT        *
//PERMITS THE REGISTERED DEVELOPER TO REDISTRIBUTE THE PRODUCT IN       *
//EXECUTABLE FORM ONLY IN SUPPORT OF APPLICATIONS WRITTEN USING         *
//THE PRODUCT.  IT DOES NOT PROVIDE ANY RIGHTS REGARDING THE            *
//SOURCE CODE CONTAINED HEREIN.                                         *
//                                                                      *
//THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE.              *
//--------------------------------------------------------------------- *
#endregion

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
using nHydrate.Generator.Common;
using nHydrate.Generator.Common.Logging;
using nHydrate.Generator.Common.Util;
using nHydrate.Generator.Models;

namespace nHydrate.Generator
{
	internal enum SqlNativeTypes
	{
		image = 34,
		text = 35,
		uniqueidentifier = 36,
		date = 40,
		time = 41,
		datetime2 = 42,
		datetimeoffset = 43,
		tinyint = 48,
		smallint = 52,
		@int = 56,
		smalldatetime = 58,
		real = 59,
		money = 60,
		datetime = 61,
		@float = 62,
		sql_variant = 98,
		ntext = 99,
		bit = 104,
		@decimal = 106,
		numeric = 108,
		smallmoney = 122,
		bigint = 127,
		varbinary = 165,
		varchar = 167,
		binary = 173,
		@char = 175,
		timestamp = 189,
		nvarchar = 231,
		sysname = 231,
		nchar = 239,
		hierarchyid = 240,
		geometry = 240,
		geography = 240,
		xml = 241,
	}

	internal static class SqlSchemaToModel
	{
		#region Class Members

		//private string _connectString;
		//private bool _assumeInheritance = true;

		#endregion

		#region Constructors

		//public SqlSchemaToModel(string connectString, bool assumeInheritance)
		//{
		//  this._connectString = connectString;
		//  _assumeInheritance = assumeInheritance;
		//}

		#endregion

		//#region Events

		//public event EventHandler<ProgressEventArgs> Progress;

		//protected virtual void OnProgress(ProgressEventArgs e)
		//{
		//  if (this.Progress != null)
		//    this.Progress(this, e);
		//}

		//#endregion

		///// <summary>
		///// Load a database schema
		///// </summary>
		///// <param name="project">The project object to load from database</param>
		//public bool GetProjectFromSqlSchema(nHydrateGeneratorProject project)
		//{
		//  return this.GetProjectFromSqlSchema(project, true);
		//}

		public static void SetupNewProject(nHydrateGeneratorProject project, string connectionString)
		{
			var root = project.RootController.Object as ModelRoot;
			var companyName = GetCompanyName(connectionString);
			var projectName = GetProjectName(connectionString);
			var databaseName = GetDatabaseName(connectionString);
			var databaseCollation = GetDatabaseCollation(connectionString);

			if (!string.IsNullOrEmpty(companyName))
				root.CompanyName = companyName;
			if (!string.IsNullOrEmpty(projectName))
				root.ProjectName = projectName;
			if (!string.IsNullOrEmpty(databaseName))
				root.Database.DatabaseName = databaseName;
			root.Version = "0.0.0.0";
			root.SQLServerType = GetSQLVersion(connectionString);

			root.Database.Columns.Clear();
			root.Database.Relations.Clear();
			root.Database.Tables.Clear();
		}

		/// <summary>
		/// Load a database schema
		/// </summary>
		/// <param name="project">The project object to load from database</param>
		/// <param name="refreshModel">Determines whether to load all model controllers and other UI components</param>
		public static bool GetProjectFromSqlSchema(nHydrateGeneratorProject project, string connectionString, bool refreshModel, bool assumeInheritance)
		{
			try
			{
				if (!IsValidConnectionString(connectionString))
				{
					//this.OnProgress(new ProgressEventArgs() { PercentDone = 100 });
					GenerationHelper.ShowError("The SQL Server engine could not be found.");
					return false;
				}

				if (!IsSupportedSQLVersion(connectionString))
				{
					//this.OnProgress(new ProgressEventArgs() { PercentDone = 100 });
					GenerationHelper.ShowError("The current version of SQL is not supported.");
					return false;
				}

				var root = project.RootController.Object as ModelRoot;
				SetupNewProject(project, connectionString);
				var databaseCollation = GetDatabaseCollation(connectionString);

				//var root = project.RootController.Object as ModelRoot;
				//var companyName = GetCompanyName(connectionString);
				//var projectName = GetProjectName(connectionString);
				//var databaseName = GetDatabaseName(connectionString);
				//var databaseCollation = GetDatabaseCollation(connectionString);
				
				//if (!string.IsNullOrEmpty(companyName))
				//  root.CompanyName = companyName;
				//if (!string.IsNullOrEmpty(projectName))
				//  root.ProjectName = projectName;
				//if (!string.IsNullOrEmpty(databaseName))
				//  root.Database.DatabaseName = databaseName;
				//root.Version = "0.0.0.0";
				//root.SQLServerType = GetSQLVersion(connectionString);

				//root.Database.Columns.Clear();
				//root.Database.Relations.Clear();
				//root.Database.Tables.Clear();

				//Progress
				//this.OnProgress(new ProgressEventArgs() { PercentDone = 0, Text = "Loading..." });

				var tableCount = GetTableCount(connectionString);
				var tableIndex = 1;

				#region Tables

				var tableReader = (SqlDataReader)DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, GetSqlDatabaseTables());
				while (tableReader.Read())
				{
					var startTime1 = DateTime.Now;

					var currentTable = root.Database.Tables.Add(tableReader["name"].ToString());
					currentTable.DBSchema = tableReader["schema"].ToString();

					////Progress
					//this.OnProgress(new ProgressEventArgs()
					//{
					//  PercentDone = (int)(tableIndex * 100.0 / tableCount),
					//  Text = currentTable.Name
					//});

					if (!ValidationHelper.ValidDatabaseIdenitifer(currentTable.Name))
					{
						currentTable.CodeFacade = ValidationHelper.MakeDatabaseIdentifier(currentTable.Name);
					}

					//If single field table with identity then mark it immutable
					if ((currentTable.Columns.Count == 1) && (currentTable.GetColumns().First().Identity == IdentityTypeConstants.Database))
					{
						currentTable.Immutable = true;
					}

					//Default to false when importing
					currentTable.AllowCreateAudit = false;
					currentTable.AllowModifiedAudit = false;
					currentTable.AllowTimestamp = false;

					#region Table Attributes
					if (CanUseExtendedProperty(connectionString))
					{
						var tableAttributeReader = (SqlDataReader)DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, "SELECT name, value FROM  ::fn_listextendedproperty (default,'user', 'dbo', 'table', '" + currentTable.Name + "', default, default)");
						while (tableAttributeReader.Read())
						{
							var attribName = string.Empty;
							attribName = tableAttributeReader["name"].ToString();
							if (attribName.ToLower().Equals("ms_description"))
							{
								currentTable.Description = tableAttributeReader["value"].ToString();
							}
							else if (attribName.ToLower().Equals("generated"))
							{
								currentTable.Generated = bool.Parse(tableAttributeReader["value"].ToString());
							}
							else if (attribName.ToLower().Equals("associative"))
							{
								currentTable.AssociativeTable = bool.Parse(tableAttributeReader["value"].ToString());
							}
							else if (attribName.ToLower().Equals("hasHistory"))
							{
								currentTable.HasHistory = bool.Parse(tableAttributeReader["value"].ToString());
							}
							System.Windows.Forms.Application.DoEvents();
						}
						tableAttributeReader.Close();
					}
					#endregion

					//System.Windows.Forms.Application.DoEvents();

					var endTime1 = DateTime.Now;
					//System.Diagnostics.Debug.WriteLine("Table '" + currentTable.Name + "': " + endTime1.Subtract(startTime1).TotalMilliseconds.ToString("###,###,###"));

					if (currentTable.Name == "sysdiagrams" ||
						currentTable.Name == "__nhydrateschema")
					{
						root.Database.Tables.Remove(currentTable);
					}
					tableIndex++;

				}
				tableReader.Close();

				#region Columns

					var startTime2 = DateTime.Now;
					var columnReader = (SqlDataReader)DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, GetSqlColumnsForTable());
					while (columnReader.Read())
					{
						var columnName = columnReader["columnName"].ToString();
						var tableName = columnReader["tableName"].ToString();

						var currentTable = root.Database.Tables.FirstOrDefault(x => x.Name == tableName);
						if (currentTable != null)
						{
							if (StringHelper.Match(columnName, ((ModelRoot)project.RootController.Object).Database.CreatedByColumnName) ||
								StringHelper.Match(columnName, ((ModelRoot)project.RootController.Object).Database.CreatedDateColumnName))
							{
								currentTable.AllowCreateAudit = true;
							}
							else if (StringHelper.Match(columnName, ((ModelRoot)project.RootController.Object).Database.ModifiedByColumnName) ||
								StringHelper.Match(columnName, ((ModelRoot)project.RootController.Object).Database.ModifiedDateColumnName) ||
								StringHelper.Match(columnName, "updated_by") || StringHelper.Match(columnName, "updated_date"))
							{
								currentTable.AllowModifiedAudit = true;
							}
							else if (StringHelper.Match(columnName, ((ModelRoot)project.RootController.Object).Database.TimestampColumnName))
							{
								currentTable.AllowTimestamp = true;
							}
							else
							{
								var currentColumn = root.Database.Columns.Add(columnName);

								if (!ValidationHelper.ValidDatabaseIdenitifer(currentColumn.Name))
								{
									currentColumn.CodeFacade = ValidationHelper.MakeDatabaseIdentifier(currentColumn.Name);
								}

								currentColumn.ParentTableRef = currentTable.CreateRef();
								currentColumn.AllowNull = bool.Parse(columnReader["allowNull"].ToString());
								if (bool.Parse(columnReader["isIdentity"].ToString()))
									currentColumn.Identity = IdentityTypeConstants.Database;
								else
									currentColumn.Identity = IdentityTypeConstants.None;

								if (columnReader["isPrimaryKey"] != System.DBNull.Value)
									currentColumn.PrimaryKey = true;

								//currentColumn.PrimaryKey = bool.Parse(columnReader["isPrimaryKey"].ToString());
								try
								{
									//string columnTypename = columnReader["datatype"].ToString();
									//if (StringHelper.Match(columnTypename, "numeric", true))
									//  currentColumn.DataType = SqlDbType.Decimal;
									//else
									//  currentColumn.DataType = (SqlDbType)Enum.Parse(typeof(SqlDbType), columnTypename, true);
									currentColumn.DataType = DatabaseHelper.GetSQLDataType((SqlNativeTypes)int.Parse(columnReader["xtype"].ToString()));
								}
								catch { }

								var defaultvalue = columnReader["defaultValue"].ToString();
								SetupDefault(currentColumn, defaultvalue);

								currentColumn.Length = (int)columnReader["length"];

								//Decimals are a little different
								if (currentColumn.DataType == SqlDbType.Decimal)
								{
									currentColumn.Length = (byte)columnReader["precision"];
									currentColumn.Scale = (int)columnReader["scale"];
								}

								if (columnReader["collation"] != System.DBNull.Value)
								{
									if (databaseCollation != (string)columnReader["collation"])
										currentColumn.Collate = (string)columnReader["collation"];
								}

								currentTable.Columns.Add(currentColumn.CreateRef());
							} //Create New Column
						}
					}
					columnReader.Close();
					var endTime2 = DateTime.Now;
					//System.Diagnostics.Debug.WriteLine("Table '" + currentTable.Name + "' Load Columns: " + endTime2.Subtract(startTime2).TotalMilliseconds.ToString("###,###,###"));

					if (CanUseExtendedProperty(connectionString))
					{
						foreach (Table table in root.Database.Tables)
						{
							foreach (var column in table.GetColumns())
							{
								var startTime3 = DateTime.Now;
								var columnAttributeReader = DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, "SELECT name, value FROM  ::fn_listextendedproperty (default,'user', 'dbo', 'table', '" + table.Name + "', 'column', '" + column.Name + "')");
								while (columnAttributeReader.Read())
								{
									var attribName = string.Empty;
									attribName = columnAttributeReader["name"].ToString();
									if (attribName.ToLower().Equals("ms_description"))
									{
										column.Description = columnAttributeReader["value"].ToString();
									}
								}
								columnAttributeReader.Close();
								var endTime3 = DateTime.Now;
								//System.Diagnostics.Debug.WriteLine("Time 3: " + endTime3.Subtract(startTime3).TotalMilliseconds.ToString("###,###,###"));
							}
						}
					}

				#endregion

				#region Columns Extra Info

				columnReader = (SqlDataReader)DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, GetSqlColumnInfoAuxForTable());
				while (columnReader.Read())
				{
					var columnName = columnReader["columnname"].ToString();
					var tableName = columnReader["tablename"].ToString();
					var currentTable = root.Database.Tables.First(x => x.Name == tableName);

					var currentColumn = root.Database.Columns[columnName];
					if (currentColumn != null)
					{
						currentColumn.ComputedColumn = true;
						currentColumn.Formula = columnReader["definition"].ToString();
					}
				}
				columnReader.Close();

				#endregion

				#region Indexes

				var indexReader = (SqlDataReader)DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, GetSqlIndexesForTable());
				while (indexReader.Read())
				{
					var indexName = indexReader["indexname"].ToString();
					var columnName = indexReader["columnname"].ToString();
					var tableName = indexReader["tableName"].ToString();
					var currentTable = root.Database.Tables.FirstOrDefault(x => x.Name == tableName);
					if (currentTable != null)
					{
						var pk = bool.Parse(indexReader["is_primary_key"].ToString());
						var column = currentTable.GetColumns().FirstOrDefault(x => x.Name == columnName);
						if (column != null && !pk)
							column.IsIndexed = true;
					}
				}

				#endregion

				#endregion

				#region Relations

				var startTimeRelation = DateTime.Now;
				LoadRelations(project, assumeInheritance, connectionString);
				var endTimeRelation = DateTime.Now;
				//System.Diagnostics.Debug.WriteLine("Load Relations: " + endTimeRelation.Subtract(startTimeRelation).TotalMilliseconds.ToString("###,###,###"));

				#endregion

				#region Views

				var startTimeV = DateTime.Now;
				LoadViews(project, connectionString);
				var endTimeV = DateTime.Now;
				//System.Diagnostics.Debug.WriteLine("Load Views: " + endTimeV.Subtract(startTimeV).TotalMilliseconds.ToString("###,###,###"));

				#endregion

				#region Stored Procedures

				var startTimeSP = DateTime.Now;
				LoadStoredProcedures(project, connectionString);
				var endTimeSP = DateTime.Now;
				//System.Diagnostics.Debug.WriteLine("Load Stored Procedures: " + endTimeSP.Subtract(startTimeSP).TotalMilliseconds.ToString("###,###,###"));

				#endregion

				//Refresh the tree
				if (refreshModel)
				{
					//project.RootController.Node.RefreshDeep();
					//Thread t = new Thread(new ThreadStart(project.RootController.Node.RefreshDeep));
					//t.Start();
				}

				//Progress
				//this.OnProgress(new ProgressEventArgs() { PercentDone = 100, Text = "Complete" });
				return true;
			}
			catch (Exception ex)
			{
				throw;
			}
			finally
			{
				//Progress
				//this.OnProgress(new ProgressEventArgs() { PercentDone = 100, Text = "Complete" });
			}
		}

		public static IEnumerable<string> GetTableListFromDatabase(string connectionString)
		{
			var retval = new List<string>();
			var tableReader = (SqlDataReader)DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, GetSqlDatabaseTables());
			while (tableReader.Read())
			{
				retval.Add(tableReader["name"].ToString());
			}
			tableReader.Close();
			return retval;
		}

		public static IEnumerable<Column> GetTableDefinitionFromDatabase(string connectionString, string tableName, ModelRoot root)
		{
			try
			{
				var retval = new List<Column>();

				//Columns
				var connection = DatabaseHelper.GetConnection(connectionString);
				var columnReader = (SqlDataReader)DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, GetSqlColumnsForTable(tableName));
				while (columnReader.Read())
				{
					var columnName = columnReader["columnName"].ToString();
					if (StringHelper.Match(columnName, root.Database.CreatedByColumnName) || StringHelper.Match(columnName, root.Database.CreatedDateColumnName))
					{
						//Do Nothing
					}
					else if (StringHelper.Match(columnName, root.Database.ModifiedByColumnName) || StringHelper.Match(columnName, root.Database.ModifiedDateColumnName) ||
						StringHelper.Match(columnName, "updated_by") || StringHelper.Match(columnName, "updated_date"))
					{
						//Do Nothing
					}
					else if (StringHelper.Match(columnName, root.Database.TimestampColumnName))
					{
						//Do Nothing
					}
					else
					{
						var currentColumn = new Column(root);
						currentColumn.Name = columnName;

						if (!ValidationHelper.ValidDatabaseIdenitifer(currentColumn.Name))
						{
							currentColumn.CodeFacade = ValidationHelper.MakeDatabaseIdentifier(currentColumn.Name);
						}

						//currentColumn.ParentTableRef = currentTable.CreateRef();
						currentColumn.AllowNull = bool.Parse(columnReader["allowNull"].ToString());
						if (bool.Parse(columnReader["isIdentity"].ToString()))
							currentColumn.Identity = IdentityTypeConstants.Database;
						else
							currentColumn.Identity = IdentityTypeConstants.None;

						if (columnReader["isPrimaryKey"] != System.DBNull.Value)
							currentColumn.PrimaryKey = true;

						//currentColumn.PrimaryKey = bool.Parse(columnReader["isPrimaryKey"].ToString());
						try
						{
							//string columnTypename = columnReader["datatype"].ToString();
							//if (StringHelper.Match(columnTypename, "numeric", true))
							//  currentColumn.DataType = SqlDbType.Decimal;
							//else
							//  currentColumn.DataType = (SqlDbType)Enum.Parse(typeof(SqlDbType), columnTypename, true);
							currentColumn.DataType = DatabaseHelper.GetSQLDataType((SqlNativeTypes)int.Parse(columnReader["xtype"].ToString()));
						}
						catch { }

						var defaultvalue = columnReader["defaultValue"].ToString();
						SetupDefault(currentColumn, defaultvalue);

						currentColumn.Length = (int)columnReader["length"];

						if (CanUseExtendedProperty(connectionString))
						{
							var columnAttributeReader = (SqlDataReader)DatabaseHelper.ExecuteReader(connection, CommandType.Text, "SELECT name, value FROM  ::fn_listextendedproperty (default,'user', 'dbo', 'table', '" + tableName + "', 'column', '" + currentColumn + "')");
							while (columnAttributeReader.Read())
							{
								var attribName = string.Empty;
								attribName = columnAttributeReader["name"].ToString();
								if (attribName.ToLower().Equals("ms_description"))
								{
									currentColumn.Description = columnAttributeReader["value"].ToString();
								}

							}
							columnAttributeReader.Close();
						}

						retval.Add(currentColumn);
					} //Create New Column
				}
				columnReader.Close();
				return retval;

			}
			catch (Exception ex)
			{
				throw;
			}
		}

		private static void SetupDefault(Column field, string defaultvalue)
		{
			if (defaultvalue == null) defaultvalue = string.Empty;

			//This is some sort of default pointer, we do not handle this.
			if (defaultvalue.Contains("create default ["))
				defaultvalue = string.Empty;

			//Just in case some put 'null' in to the default field
			if (field.AllowNull && defaultvalue.ToLower() == "null")
				defaultvalue = string.Empty;

			if (field.IsNumericType || field.DataType == SqlDbType.Bit || field.IsDateType || field.IsBinaryType)
			{
				field.Default = defaultvalue.Replace("(", string.Empty).Replace(")", string.Empty); //remove any parens
			}
			else if (field.DataType == SqlDbType.UniqueIdentifier)
			{
				if (!string.IsNullOrEmpty(defaultvalue) && defaultvalue.Contains("newid"))
					field.Default = "newid";
				else
					field.Default = defaultvalue.Replace("(", string.Empty).Replace(")", string.Empty).Replace("'", string.Empty); //Format: ('000...0000')
			}
			else if (field.IsTextType)
			{
				while (defaultvalue.StartsWith("('")) defaultvalue = defaultvalue.Substring(2, defaultvalue.Length - 2);
				while (defaultvalue.EndsWith("')")) defaultvalue = defaultvalue.Substring(0, defaultvalue.Length - 2);
				field.Default = defaultvalue;
			}
			else
				field.Default = defaultvalue;

		}

		#region Private Methods

		public static int GetTableCount(string connectionString)
		{
			var ds = DatabaseHelper.ExecuteDataset(connectionString, "select count(*) from sysobjects where Type = 'U'");
			return (int)ds.Tables[0].Rows[0][0];
		}

		private static void LoadViews(nHydrateGeneratorProject project, string connectionString)
		{
			var root = (ModelRoot)project.RootController.Object;
			var dsView = DatabaseHelper.ExecuteDataset(connectionString, GetSqlForViews());
			var dsViewColumn = DatabaseHelper.ExecuteDataset(connectionString, GetSqlForViewsColumns());

			//Add the Views
			if (dsView.Tables.Count > 0)
			{
				foreach (DataRow rowView in dsView.Tables[0].Rows)
				{
					var name = (string)rowView["name"];
					var sql = (string)rowView["definition"];
					var customView = root.Database.CustomViews.FirstOrDefault(x => x.Name == name);
					if (customView == null)
					{
						customView = ((ModelRoot)project.RootController.Object).Database.CustomViews.Add();
						customView.Name = name;
						var regEx = new Regex(@"CREATE VIEW.*[\r\n]*AS.*[\r\n]*([\s\S\r\n]*)");
						var match = regEx.Match(sql);
						if (match != null && match.Groups != null && match.Groups.Count == 2)
							sql = match.Groups[1].Value;

						customView.SQL = sql;
					}
				}
			}

			//Add the columns
			if (dsViewColumn.Tables.Count > 0)
			{
				foreach (DataRow rowView in dsViewColumn.Tables[0].Rows)
				{
					var viewName = (string)rowView["viewname"];
					var columnName = (string)rowView["columnname"];
					var length = int.Parse(rowView["max_length"].ToString());
					var customView = root.Database.CustomViews.FirstOrDefault(x => x.Name == viewName);
					if (customView != null)
					{
						var column = root.Database.CustomViewColumns.Add();
						column.Name = columnName;
						column.DataType = DatabaseHelper.GetSQLDataType((SqlNativeTypes)int.Parse(rowView["system_type_id"].ToString()));
						column.Length = length;
						column.Scale = int.Parse(rowView["scale"].ToString());
						customView.Columns.Add(column.CreateRef());
						column.ParentViewRef = customView.CreateRef();
					}
				}
			}

		}

		private static void LoadStoredProcedures(nHydrateGeneratorProject project, string connectionString)
		{
			try
			{
				var root = (ModelRoot)project.RootController.Object;
				var dsSP = DatabaseHelper.ExecuteDataset(connectionString, GetSqlForStoredProcedures((project.Model as ModelRoot).StoredProcedurePrefix));
				var dsSPColumn = DatabaseHelper.ExecuteDataset(connectionString, GetSqlForStoredProceduresParameters((project.Model as ModelRoot).StoredProcedurePrefix));

				//Add the Stored Procedures
				foreach (DataRow rowSP in dsSP.Tables[0].Rows)
				{
					var id = (int)rowSP["id"];
					var name = (string)rowSP["name"];
					var customStoredProcedure = root.Database.CustomStoredProcedures.FirstOrDefault(x => x.Name == name);
					if (customStoredProcedure == null)
					{
						customStoredProcedure = ((ModelRoot)project.RootController.Object).Database.CustomStoredProcedures.Add();
						customStoredProcedure.Name = name;
						customStoredProcedure.SQL = GetSqlForStoredProceduresBody(name, connectionString);
					}

				}

				////Add the columns
				//foreach (DataRow rowSP in dsSPColumn.Tables[0].Rows)
				//{
				//  int id = (int)rowSP["id"];
				//  string spName = (string)rowSP["name"];
				//  string name = (string)rowSP["ColName"];
				//  string typeName = (string)rowSP["ColType"];
				//  CustomStoredProcedure customStoredProcedure = root.Database.CustomStoredProcedures.FirstOrDefault(x => x.Name == spName);
				//  if (customStoredProcedure != null)
				//  {
				//    CustomStoredProcedureColumn column = root.Database.CustomStoredProcedureColumns.Add();
				//    column.Name = name;
				//    column.DataType = DatabaseHelper.GetSQLDataType(typeName);
				//    customStoredProcedure.Columns.Add(column.CreateRef());
				//    column.ParentRef = customStoredProcedure.CreateRef();
				//  }
				//}

				//Add the parameters
				foreach (DataRow rowSP in dsSPColumn.Tables[0].Rows)
				{
					var id = (int)rowSP["id"];
					var spName = (string)rowSP["name"];
					var name = (string)rowSP["ColName"];
					var typeName = (string)rowSP["ColType"];
					var length = int.Parse(rowSP["length"].ToString());
					var customStoredProcedure = root.Database.CustomStoredProcedures.FirstOrDefault(x => x.Name == spName);
					if (customStoredProcedure != null)
					{
						var parameter = root.Database.CustomRetrieveRuleParameters.Add();
						parameter.Name = name.Replace("@", string.Empty);
						parameter.DataType = DatabaseHelper.GetSQLDataType((SqlNativeTypes)int.Parse(rowSP["xtype"].ToString()));
						parameter.Length = length;
						customStoredProcedure.Parameters.Add(parameter.CreateRef());
						parameter.ParentTableRef = customStoredProcedure.CreateRef();
					}
				}

			}
			catch (Exception ex)
			{
				throw;
			}
		}

		public static void LoadRelations(nHydrateGeneratorProject project, bool assumeInheritance, string connectionString)
		{
			var root = (ModelRoot)project.RootController.Object;
			var dsRelationship = DatabaseHelper.ExecuteDataset(connectionString, GetSqlForRelationships());
			foreach (DataRow rowRelationship in dsRelationship.Tables[0].Rows)
			{
				var constraintName = rowRelationship["FK_CONSTRAINT_NAME"].ToString();
				var parentTableName = (string)rowRelationship["UQ_TABLE_NAME"];
				var childTableName = (string)rowRelationship["FK_TABLE_NAME"];
				var parentTable = root.Database.Tables[parentTableName];
				var childTable = root.Database.Tables[childTableName];

				if ((parentTable != null) && (childTable != null))
				{
					Relation relation = null;
					var isAdd = false;
					if (!root.Database.Relations.Contains(constraintName))
					{
						var roleName = string.Empty;
						relation = root.Database.Relations.Add();
						relation.ParentTableRef = parentTable.CreateRef();
						relation.ChildTableRef = childTable.CreateRef();
						relation.ConstraintName = constraintName;
						var search = ("_" + childTable.DatabaseName + "_" + parentTable.DatabaseName).ToLower();
						roleName = constraintName.ToLower().Replace(search, string.Empty);
						if (roleName.Length >= 3) roleName = roleName.Remove(0, 3);
						var v = roleName.ToLower();
						if (v != "fk") relation.RoleName = v;
						isAdd = true;
					}
					else
					{
						relation = root.Database.Relations.GetByName(constraintName);
					}

					//add the column relationship to the relation
					var columnRelationship = new ColumnRelationship(relation.Root);
					var parentColumnName = (string)rowRelationship["UQ_COLUMN_NAME"];
					var childColumnName = (string)rowRelationship["FK_COLUMN_NAME"];
					var parentColumns = parentTable.GetColumns().ToList();
					var childColumns = childTable.GetColumns().ToList();
					if (parentColumns.Count(x => x.Name == parentColumnName) == 1 && (childColumns.Count(x => x.Name == childColumnName) == 1))
					{
						var parentColumn = parentTable.Columns[parentColumnName].Object as Column;
						var childColumn = childTable.Columns[childColumnName].Object as Column;
						columnRelationship.ParentColumnRef = parentColumn.CreateRef();
						columnRelationship.ChildColumnRef = childColumn.CreateRef();
						relation.ColumnRelationships.Add(columnRelationship);

						//ONLY ADD THIS RELATION IF ALL WENT WELL
						if (isAdd)
							parentTable.Relationships.Add(relation.CreateRef());
					}
					else
					{
						System.Diagnostics.Debug.Write(string.Empty);
					}
				} //Not Contains constraint

			}

			//Map parent tables if there is 1-1 relation and PK match
			//Make sure we have choosen to assume inheritance
			if (assumeInheritance)
			{
				foreach (Relation relation in root.Database.Relations)
				{
					if (relation.IsOneToOne)
					{
						var parentTable = (Table)relation.ParentTableRef.Object;
						var childTable = (Table)relation.ChildTableRef.Object;
						if (parentTable.PrimaryKeyColumns.Count == childTable.PrimaryKeyColumns.Count)
						{
							var pkMatch = true;
							foreach (var k in parentTable.PrimaryKeyColumns)
							{
								pkMatch |= (childTable.PrimaryKeyColumns.Count(x => x.Name == k.Name) == 1);
							}

							if (pkMatch && childTable.CanInherit(parentTable))
							{
								childTable.ParentTable = parentTable;
							}

						}
					}
				}
			}

			//Check for associative tables
			foreach (Relation relation in root.Database.Relations)
			{
				var parentTable = (Table)relation.ParentTableRef.Object;
				var childTable = (Table)relation.ChildTableRef.Object;
				//If there are 2 PK in the child table and that is all the columns
				//and it is a base table
				if ((childTable.PrimaryKeyColumns.Count == 2) &&
					(childTable.Columns.Count == 2) &&
					childTable.ParentTable == null)
				{
					//If child table has 2 relations comming in
					var allRelations = childTable.GetRelationsWhereChild();
					if (allRelations.Count() == 2)
					{
						//Relation relation2 = allRelations.FirstOrDefault(x => x != relation);
						//Table parentTable2 = (Table)relation2.ParentTableRef.Object;
						childTable.AssociativeTable = true;
					}
				}
			}

		}

		public static bool IsValidConnectionString(string connectionString)
		{
			var valid = false;
			var conn = new System.Data.SqlClient.SqlConnection();
			try
			{
				conn.ConnectionString = connectionString;
				conn.Open();
				valid = true;
			}
			catch (Exception ex)
			{
				valid = false;
			}
			finally
			{
				conn.Close();
			}
			return valid;
		}

		public static bool IsSupportedSQLVersion(string connectionString)
		{
			var ds = DatabaseHelper.ExecuteDataset(connectionString, "SELECT SERVERPROPERTY('productversion')");
			var version = (string)ds.Tables[0].Rows[0][0];
			if (version.StartsWith("10."))
				return true;
			else if (version.StartsWith("9."))
				return true;
			else
				return false;
		}

		public static SQLServerTypeConstants GetSQLVersion(string connectionString)
		{
			var ds = DatabaseHelper.ExecuteDataset(connectionString, "SELECT SERVERPROPERTY('productversion')");
			var version = (string)ds.Tables[0].Rows[0][0];
			if (version.StartsWith("10."))
			{
				var ds2 = DatabaseHelper.ExecuteDataset(connectionString, "SELECT SERVERPROPERTY('Edition')");
				var version2 = (string)ds2.Tables[0].Rows[0][0];
				if (version2 == "SQL Azure")
					return SQLServerTypeConstants.SQLAzure;
				else
					return SQLServerTypeConstants.SQL2008;
			}
			else
			{
				return SQLServerTypeConstants.SQL2005;
			}
		}

		private static bool? extendedPropertyEnabled = null;
		private static bool CanUseExtendedProperty(string connectionString)
		{
			if (extendedPropertyEnabled == null)
			{
				var conn = new System.Data.SqlClient.SqlConnection();
				try
				{
					conn.ConnectionString = connectionString;
					conn.Open();
					var cmdGetExtProp = new SqlCommand();
					cmdGetExtProp.CommandText = "SELECT value FROM ::fn_listextendedproperty('', '', '', '', '', '', '')";
					cmdGetExtProp.CommandType = System.Data.CommandType.Text;
					cmdGetExtProp.Connection = conn;
					cmdGetExtProp.ExecuteNonQuery();
					extendedPropertyEnabled = true;
				}
				catch (Exception ex)
				{
					extendedPropertyEnabled = false;
				}
				finally
				{
					if (conn != null)
						conn.Close();
				}
			}
			return extendedPropertyEnabled.Value;
		}

		public static string GetProjectName(string connectionString)
		{
			string retval = null;
			if (CanUseExtendedProperty(connectionString))
			{
				var reader = (SqlDataReader)DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, "SELECT value FROM ::fn_listextendedproperty ( N'projectName',   NULL, NULL,NULL, NULL,NULL,NULL)");
				if (reader.Read()) retval = reader["value"].ToString();
				reader.Close();
			}
			return retval;
		}

		public static string GetCompanyName(string connectionString)
		{
			string retval = null;
			if (CanUseExtendedProperty(connectionString))
			{
				try
				{
					var reader = (SqlDataReader)DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, "SELECT value FROM ::fn_listextendedproperty ( N'companyName',NULL, NULL,NULL, NULL,NULL,NULL)");
					if (reader.Read()) retval = reader["value"].ToString();
					reader.Close();
				}
				catch (Exception ex)
				{
					WSLog.LogError(ex);
					throw ex;
				}
			}
			return retval;
		}

		public static string GetDatabaseName(string connectionString)
		{
			return (new System.Data.SqlClient.SqlConnection(connectionString)).Database;
		}

		private static string GetSqlDatabaseTables()
		{
			var sb = new StringBuilder();
			sb.AppendLine("DECLARE @bar varchar(150)");
			sb.AppendLine("DECLARE @val varchar(150)");
			sb.AppendLine("DECLARE @tab table");
			sb.AppendLine("(");
			sb.AppendLine("xName varchar(150) NOT NULL,");
			sb.AppendLine("xValue varchar(150) NULL,");
			sb.AppendLine("xSchema varchar(150) NOT NULL");
			sb.AppendLine(")");
			sb.AppendLine("INSERT INTO @tab SELECT so.name, null, sc.name [schema] FROM sys.tables so INNER JOIN sys.schemas sc ON so.schema_id = sc.schema_id WHERE so.name <> 'dtproperties' AND (so.name <> 'sysdiagrams') AND (so.name <> '__nhydrateschema') AND NOT (so.name like '__AUDIT__%')");
			//sb.AppendLine("SET @bar = (SELECT TOP 1 xName FROM @tab ORDER BY xName ASC)");
			//sb.AppendLine("WHILE @bar is not null");
			//sb.AppendLine("BEGIN");
			//sb.AppendLine("SET @val = (SELECT CONVERT(varchar(150), value) FROM ::fn_listextendedproperty ( N'selectionCriteria', N'user', N'dbo', N'table',@bar,NULL,NULL))");
			//sb.AppendLine("UPDATE @tab SET xValue = @val where xName = @bar");
			//sb.AppendLine("SET @bar = (SELECT TOP 1 xName FROM @tab where xName > @bar ORDER BY xName ASC)");
			//sb.AppendLine("END");
			sb.AppendLine("select xName as name, xSchema as [schema], xValue selectionCriteria from @tab WHERE xName <> 'dtproperties' ORDER BY xName");
			return sb.ToString();
		}

		private static string GetSqlColumsDescription(string tableName)
		{
			var sb = new StringBuilder();
			sb.AppendLine("SELECT sys.objects.name AS TableName, sys.columns.name AS ColumnName,");
			sb.AppendLine("       ep.value AS Description");
			sb.AppendLine("FROM sys.objects");
			sb.AppendLine("INNER JOIN sys.columns ON sys.objects.object_id = sys.columns.object_id");
			sb.AppendLine("CROSS APPLY fn_listextendedproperty(default,");
			sb.AppendLine("                  'SCHEMA', schema_name(schema_id),");
			sb.AppendLine("                  'TABLE', sys.objects.name, 'COLUMN', sys.columns.name) ep");
			sb.AppendLine("WHERE sys.objects.name = '" + tableName + "'");
			return sb.ToString();
		}

		public static string GetDatabaseCollation(string connectionString)
		{
			System.Data.SqlClient.SqlConnection connection = null;
			try
			{
				var sql = "SELECT DATABASEPROPERTYEX('" + GetDatabaseName(connectionString) + "', 'Collation') SQLCOLLATION";
				connection = new System.Data.SqlClient.SqlConnection(connectionString);
				var command = new SqlCommand(sql, connection);
				connection.Open();
				var retval = (string)command.ExecuteScalar();
				return retval;
			}
			catch (Exception ex)
			{
				throw;
			}
			finally
			{
				if (connection != null && connection.State == ConnectionState.Open)
					connection.Close();
			}
		}

		private static string GetSqlColumnInfoAuxForTable()
		{
			var sb = new StringBuilder();
			sb.AppendLine("select o.name as tablename, c.name as columnname, c.definition from sys.computed_columns c inner join sys.objects o on c.object_id = o.object_id");
			return sb.ToString();
		}

		private static string GetSqlIndexesForTable()
		{
			var sb = new StringBuilder();

			sb.AppendLine("select t.name as tablename, i.name as indexname, c.name as columnname, i.is_primary_key");
			sb.AppendLine("from sys.tables t");
			sb.AppendLine("inner join sys.indexes i on i.object_id = t.object_id");
			sb.AppendLine("inner join sys.index_columns ic on ic.object_id = t.object_id");
			sb.AppendLine("inner join sys.columns c on c.object_id = t.object_id and");
			sb.AppendLine("ic.column_id = c.column_id");

			//sb.AppendLine("select o.name as tablename, i.name as indexname, i.is_primary_key from sys.objects o inner join sys.indexes i on o.object_id = i.object_id where o.[type] = 'U'");
			return sb.ToString();
		}

		private static string GetSqlColumnsForTable()
		{
			return GetSqlColumnsForTable(null);
		}

		private static string GetSqlColumnsForTable(string tableName)
		{
			var sb = new StringBuilder();
			sb.AppendLine(" SELECT ");
			sb.AppendLine(" 	c.ORDINAL_POSITION as colorder,");
			sb.AppendLine(" 	c.TABLE_NAME as tablename,");
			sb.AppendLine(" 	c.COLUMN_NAME as columnname,");
			sb.AppendLine("(");
			sb.AppendLine("select top 1 c1.name");
			sb.AppendLine("from sys.indexes i");
			sb.AppendLine("join sysobjects o ON i.object_id = o.id");
			sb.AppendLine("join sysobjects pk ON i.name = pk.name");
			sb.AppendLine("AND pk.parent_obj = i.object_id");
			sb.AppendLine("AND pk.xtype = 'PK'");
			sb.AppendLine("join sys.index_columns ik on i.object_id = ik.object_id");
			sb.AppendLine("and i.index_id = ik.index_id");
			sb.AppendLine("join syscolumns c1 ON ik.object_id = c1.id");
			sb.AppendLine("AND ik.column_id = c1.colid");
			sb.AppendLine("AND c1.name = c.COLUMN_NAME");
			sb.AppendLine("where o.name = c.TABLE_NAME");
			sb.AppendLine(") as [isPrimaryKey],");
			sb.AppendLine(" 	case WHEN");
			sb.AppendLine(" 	(");
			sb.AppendLine(" 		SELECT ");
			sb.AppendLine(" 				count(*) ");
			sb.AppendLine(" 			FROM ");
			sb.AppendLine(" 				INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE foreignkeyccu");
			sb.AppendLine(" 				INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS foreignkeytc on foreignkeyccu.CONSTRAINT_NAME = foreignkeytc.CONSTRAINT_NAME AND");
			sb.AppendLine(" 																												foreignkeyccu.CONSTRAINT_SCHEMA = foreignkeytc.CONSTRAINT_SCHEMA AND");
			sb.AppendLine(" 																												foreignkeytc.CONSTRAINT_TYPE = 'FOREIGN KEY'");
			sb.AppendLine(" 			WHERE");
			sb.AppendLine(" 				foreignkeyccu.TABLE_SCHEMA = c.TABLE_SCHEMA AND");
			sb.AppendLine(" 				foreignkeyccu.TABLE_NAME = c.TABLE_NAME AND");
			sb.AppendLine(" 				foreignkeyccu.COLUMN_NAME = c.COLUMN_NAME ");
			sb.AppendLine(" 	) > 0 THEN 'true' ELSE 'false' END as isForeignKey,");
			sb.AppendLine(" 	c.DATA_TYPE as datatype,");
			sb.AppendLine(" 	s.xtype,");
			sb.AppendLine(" 	c.numeric_precision AS [precision], c.numeric_scale AS [scale],");
			sb.AppendLine(" 		case when	c.CHARACTER_MAXIMUM_LENGTH is null or c.CHARACTER_MAXIMUM_LENGTH > 8000 then s.length else c.CHARACTER_MAXIMUM_LENGTH end as length,");
			sb.AppendLine(" 	case when c.IS_NULLABLE = 'No' then 'false' else 'true' end as allowNull, ");
			//sb.AppendLine(" 	case when c.COLUMN_DEFAULT is null then '' else REPLACE(REPLACE(REPLACE(REPLACE(c.COLUMN_DEFAULT,'(N''',''),')',''),'(',''),'''','') end as defaultValue,");
			sb.AppendLine(" 	case when c.COLUMN_DEFAULT is null then '' else c.COLUMN_DEFAULT end as defaultValue,");
			sb.AppendLine(" 	case when COLUMNPROPERTY(OBJECT_ID(c.TABLE_SCHEMA+'.'+c.TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 then 'true' else 'false' end as isIdentity,");
			sb.AppendLine(" 	collation");
			sb.AppendLine(" FROM ");
			sb.AppendLine(" 	INFORMATION_SCHEMA.COLUMNS c ");
			sb.AppendLine(" 	INNER JOIN systypes s on s.name = c.DATA_TYPE");
			if (!string.IsNullOrEmpty(tableName))
				sb.AppendLine(" WHERE c.TABLE_NAME = '" + tableName + "'");
			sb.AppendLine(" ORDER BY");
			sb.AppendLine(" 	c.TABLE_NAME,");
			sb.AppendLine(" 	c.COLUMN_NAME");
			return sb.ToString();
		}

		private static string GetSqlForRelationships()
		{
			var sb = new StringBuilder();
			sb.AppendLine("SELECT ");
			sb.AppendLine("		 KCU1.CONSTRAINT_NAME AS 'FK_CONSTRAINT_NAME'");
			sb.AppendLine("	, KCU1.TABLE_NAME AS 'FK_TABLE_NAME'");
			sb.AppendLine("	, KCU1.COLUMN_NAME AS 'FK_COLUMN_NAME' ");
			sb.AppendLine("	, KCU2.TABLE_NAME AS 'UQ_TABLE_NAME'");
			sb.AppendLine("	, KCU2.COLUMN_NAME AS 'UQ_COLUMN_NAME' ");
			sb.AppendLine("FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC");
			sb.AppendLine("JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU1");
			sb.AppendLine("ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG ");
			sb.AppendLine("	AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA");
			sb.AppendLine("	AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME");
			sb.AppendLine("JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU2");
			sb.AppendLine("ON KCU2.CONSTRAINT_CATALOG = ");
			sb.AppendLine("RC.UNIQUE_CONSTRAINT_CATALOG ");
			sb.AppendLine("	AND KCU2.CONSTRAINT_SCHEMA = ");
			sb.AppendLine("RC.UNIQUE_CONSTRAINT_SCHEMA");
			sb.AppendLine("	AND KCU2.CONSTRAINT_NAME = ");
			sb.AppendLine("RC.UNIQUE_CONSTRAINT_NAME");
			sb.AppendLine("	AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION");
			sb.AppendLine("ORDER BY");
			sb.AppendLine("	KCU1.CONSTRAINT_NAME,");
			sb.AppendLine("	KCU1.ORDINAL_POSITION");
			return sb.ToString();
		}

		private static string GetSqlForViews()
		{
			var sb = new StringBuilder();
			sb.AppendLine("select v.name, m.definition from sys.views v inner join sys.sql_modules m on v.object_id = m.object_id");
			return sb.ToString();
		}

		private static string GetSqlForViewsColumns()
		{
			var sb = new StringBuilder();
			sb.AppendLine("select v.name as viewname, c.name as columnname, c.system_type_id, c.max_length, c.precision, c.scale, c.is_nullable from sys.views v inner join sys.columns c on v.object_id = c.object_id order by v.name, c.name");
			return sb.ToString();
		}

		private static string GetSqlForStoredProceduresParameters(string spPrefix)
		{
			var sb = new StringBuilder();
			sb.AppendLine("SELECT	dbo.syscolumns.xtype, dbo.sysobjects.name, dbo.sysobjects.id,");
			sb.AppendLine("		dbo.syscolumns.name AS ColName,");
			sb.AppendLine("		dbo.systypes.name AS ColType,");
			sb.AppendLine("		dbo.syscolumns.length");
			sb.AppendLine("FROM	dbo.sysobjects INNER JOIN");
			sb.AppendLine("		dbo.syscolumns ON dbo.sysobjects.id = dbo.syscolumns.id INNER JOIN");
			sb.AppendLine("		dbo.systypes ON dbo.syscolumns.xtype = dbo.systypes.xtype");
			sb.AppendLine("WHERE	(dbo.sysobjects.category = 0) AND");
			sb.AppendLine("		(dbo.sysobjects.xtype = 'P') AND");
			sb.AppendLine("		NOT (dbo.sysobjects.name LIKE '" + spPrefix + "_%') AND");
			sb.AppendLine("		NOT (dbo.sysobjects.name LIKE 'sp[_]%diagram%') AND");
			sb.AppendLine("		dbo.systypes.name <> 'sysname' AND");
			sb.AppendLine("		(dbo.sysobjects.uid in (select uid from dbo.sysusers))");
			sb.AppendLine("ORDER BY");
			sb.AppendLine("		dbo.sysobjects.name, dbo.syscolumns.name");
			return sb.ToString();
		}

		private static string GetSqlForStoredProceduresBody(string spName, string connectionString)
		{
			var sb = new StringBuilder();

			var ds = DatabaseHelper.ExecuteDataset(connectionString, "sp_helptext [" + spName + "]");
			if (ds.Tables.Count > 0)
			{
				foreach (DataRow dr in ds.Tables[0].Rows)
				{
					sb.Append((string)dr[0]);
				}

				var arr = sb.ToString().Split('\n');
				sb = new StringBuilder();

				var inBody = false;
				foreach (var lineText in arr)
				{
					if (inBody)
					{
						sb.AppendLine(lineText);
					}
					else if (!inBody && lineText.ToLower() == "as")
					{
						inBody = true;
					}
				}
			}

			return sb.ToString();
		}

		private static string GetSqlForStoredProcedures(string spPrefix)
		{
			var sb = new StringBuilder();
			sb.AppendLine("SELECT	dbo.sysobjects.id, dbo.sysobjects.xtype, dbo.sysobjects.name");
			sb.AppendLine("FROM	dbo.sysobjects");
			sb.AppendLine("WHERE (dbo.sysobjects.category = 0) AND");
			sb.AppendLine("		(dbo.sysobjects.xtype = 'P') AND");
			sb.AppendLine("		NOT (dbo.sysobjects.name LIKE '" + spPrefix + "_%') AND");
			sb.AppendLine("		NOT (dbo.sysobjects.name LIKE 'sp[_]%diagram%') AND");
			sb.AppendLine("		(dbo.sysobjects.uid in (select uid from dbo.sysusers))");
			sb.AppendLine("ORDER BY dbo.sysobjects.name");
			return sb.ToString();
		}

		//private static string GetSqlForForeignKeys(string parentTable, string childTable, string constraintName)
		//{
		//  var sb = new StringBuilder();
		//  sb.Append("DECLARE @parent_table varchar(256) ");
		//  sb.Append("DECLARE @child_table varchar(256) ");
		//  sb.Append("DECLARE @constraint varchar(256) ");
		//  sb.Append("SET @parent_table = '").Append(parentTable).Append("' ");
		//  sb.Append("SET @child_table = '").Append(childTable).Append("' ");
		//  sb.Append("SET @constraint = '").Append(constraintName).Append("' ");
		//  sb.Append("DECLARE @FKeys TABLE (parentTable varchar(100) NOT NULL,   childTable varchar(100) NOT NULL,   childColumn varchar(100) NOT NULL,   constid int NOT NULL,   keyno smallint NOT NULL  ) ");
		//  sb.Append("DECLARE @PKeys TABLE (parentTable varchar(100) NOT NULL,  childTable varchar(100) NOT NULL,  parentColumn varchar(100) NOT NULL,  constid int NOT NULL,   keyno smallint NOT NULL  ) ");
		//  sb.Append("INSERT INTO @FKeys   SELECT DISTINCT   	parent.name parentTable,   	child.name childTable, ");
		//  sb.Append("	syscolumns.name as childColumn,    	sysforeignkeys.constid,   	sysforeignkeys.keyno   FROM    	sysforeignkeys ");
		//  sb.Append("		inner join sysobjects child on fkeyid = child.id ");
		//  sb.Append("		inner join sysobjects parent on rkeyid = parent.id ");
		//  sb.Append("		inner join syscolumns on syscolumns.id = sysforeignkeys.fkeyid AND syscolumns.colorder = sysforeignkeys.fkey ");
		//  sb.Append("INSERT INTO @PKeys ");
		//  sb.Append("SELECT    	parent.name parentTable,   	child.name childTable,   	syscolumns.name as parentColumn,  	sysforeignkeys.constid,   	sysforeignkeys.keyno ");
		//  sb.Append("FROM ");
		//  sb.Append("	sysforeignkeys ");
		//  sb.Append("	inner join sysobjects child on fkeyid = child.id ");
		//  sb.Append("	inner join sysobjects parent on rkeyid = parent.id ");
		//  sb.Append("	inner join syscolumns on syscolumns.id = sysforeignkeys.rkeyid AND syscolumns.colorder = sysforeignkeys.rkey ");
		//  sb.Append("SELECT ");
		//  sb.Append("	p.parentTable , ");
		//  sb.Append("	p.parentColumn, ");
		//  sb.Append("	f.childTable, ");
		//  sb.Append("	f.ChildColumn , ");
		//  sb.Append("	so.name as roleName ");
		//  sb.Append("	FROM @FKeys f ");
		//  sb.Append("		INNER JOIN @PKeys p on f.constid=p.constID and f.keyno=p.keyno ");
		//  sb.Append("		INNER JOIN sysobjects so on so.id = p.constid ");
		//  sb.Append("WHERE ");
		//  sb.Append("	f.parentTable = @parent_table ");
		//  sb.Append("AND ");
		//  sb.Append("	f.childTable = @child_table ");
		//  sb.Append("AND ");
		//  sb.Append("	so.name = @constraint ");
		//  sb.Append("union ");
		//  sb.Append("SELECT ");
		//  sb.Append("@parent_table as parentTable, ");
		//  sb.Append("lower (@parent_table) + '_id' as parentColumn, ");
		//  sb.Append("@child_table as child_table, ");
		//  sb.Append("c.COLUMN_NAME as child_column, ");
		//  sb.Append("@constraint as roleName ");
		//  sb.Append("FROM INFORMATION_SCHEMA.COLUMNS c WHERE ");
		//  sb.Append("   c.TABLE_NAME = @child_table ");
		//  sb.Append("AND ");
		//  sb.Append("	c.COLUMN_NAME like 'fk_to_' + @parent_table + '%' ");
		//  sb.Append("AND ");
		//  sb.Append("@parent_table like '%_HIST' ");
		//  sb.Append("	AND ");
		//  sb.Append("SUBSTRING(@constraint,	CHARINDEX ('__',@constraint)+ 2 ,LEN(@constraint)- CHARINDEX ('__',@constraint)) ");
		//  sb.Append(" = ");
		//  sb.Append("SUBSTRING(c.COLUMN_NAME,	CHARINDEX ('__',c.COLUMN_NAME)+ 2 ,LEN(c.COLUMN_NAME)- CHARINDEX ('__',c.COLUMN_NAME)) ");
		//  return sb.ToString();
		//}

		#endregion

		public enum ImportReturnConstants
		{
			Aborted,
			Success,
			NoChange,
		}

		/// <summary>
		/// Show a windows to refresh teh model from a database
		/// </summary>
		public static ImportReturnConstants ImportModel(ModelRoot currentGraph,
			ModelRoot newGraph, 
			ImportModelSettings settings,
			List<string> selectedTables,
			List<string> selectedViews)
		{
			var processKey = string.Empty;
			try
			{
				//var newProject = new nHydrateGeneratorProject();
				//newProject.FileName = currentGraph.FileName;
				//var newRoot = newProject.RootController.Object as ModelRoot;
				var oldRoot = currentGraph;
				//newRoot.TransformNames = oldRoot.TransformNames;
				//newRoot.Database.CreatedByColumnName = oldRoot.Database.CreatedByColumnName;
				//newRoot.Database.CreatedDateColumnName = oldRoot.Database.CreatedDateColumnName;
				//newRoot.Database.ModifiedByColumnName = oldRoot.Database.ModifiedByColumnName;
				//newRoot.Database.ModifiedDateColumnName = oldRoot.Database.ModifiedDateColumnName;
				//newRoot.Database.TimestampColumnName = oldRoot.Database.TimestampColumnName;
				//if (!GetProjectFromSqlSchema(newProject))
				//{
				//  return ImportReturnConstants.Aborted;
				//}

				var newDatabase = newGraph.Database;
				var oldDatabase = currentGraph.Database;

				////Check if there are any changes and if so show the form
				//if (F.GetChangeCount() == 0)
				//{
				//  return ImportReturnConstants.NoChange;
				//}
				//else if (F.ShowDialog() != System.Windows.Forms.DialogResult.OK)
				//{
				//  return ImportReturnConstants.Aborted;
				//}
				//var settings = F.Settings;
				//var connectionString = F.GetConnectionString();

				processKey = UIHelper.ProgressingStarted();
				try
				{
					UpdateTables(newDatabase, oldDatabase, selectedTables, settings);

					#region Relations
					var oldList = new List<Relation>();
					foreach (Relation r in oldDatabase.Relations)
						oldList.Add(r);

					oldDatabase.Relations.Clear();
					UpdateRelations(newDatabase, oldDatabase);

					//Now reset the role names where necessary
					foreach (Relation r1 in oldDatabase.Relations)
					{
						foreach (var r2 in oldList)
						{
							if (r1.Equals(r2) && (r1.RoleName != r2.RoleName)) r1.RoleName = r2.RoleName;
						}
					}

					#endregion

					UpdateViews(newDatabase, oldDatabase, selectedViews, settings);

					//this.UpdateStoredProcedures(newDatabase, oldDatabase, settings);

					//Refresh the tree
					//currentGraph.RootController.Node.RefreshDeep();
					((ModelRootController)currentGraph.Controller).ClearTree();
				}
				catch (Exception ex)
				{
					throw;
				}
				finally
				{
					UIHelper.ProgressingComplete(processKey);
				}
				return ImportReturnConstants.Success;

			}
			catch (SqlException ex)
			{
				MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Information);
				return ImportReturnConstants.Aborted;
			}
			catch (Exception ex)
			{
				throw;
			}
			finally
			{
				UIHelper.ProgressingComplete(processKey);
			}

		}

		private static void UpdateTables(
			nHydrate.Generator.Models.Database newDatabase, 
			nHydrate.Generator.Models.Database oldDatabase,
			List<string> selectedTables,
			ImportModelSettings settings)
		{
			#region Add new tables
			foreach (Table t in newDatabase.Tables)
			{
				if (!oldDatabase.Tables.Contains(t.Name) && selectedTables.Contains(t.Name.ToLower()))
				{
					var newT = oldDatabase.Tables.Add(t.Name);
					var doc = new XmlDocument();
					var tableId = newT.Id;
					doc.LoadXml("<a></a>");
					t.XmlAppend(doc.DocumentElement);
					newT.XmlLoad(doc.DocumentElement);
					newT.SetId(tableId);

					newT.Columns.Clear();
					foreach (Reference r in t.Columns)
					{
						var newCol = oldDatabase.Columns.Add(((Column)r.Object).Name);
						var colId = newCol.Id;
						var doc3 = new XmlDocument();
						doc3.LoadXml("<a></a>");
						((Column)r.Object).XmlAppend(doc3.DocumentElement);
						newCol.XmlLoad(doc3.DocumentElement);
						newCol.SetId(colId);
						newCol.ParentTableRef = newT.CreateRef();

						var newRef = new Reference(newT.Root);
						newRef.Ref = newCol.Id;
						newRef.RefType = ReferenceType.Column;
						newT.Columns.Add(newRef);
					}
					newT.Relationships.Clear();
				}
			}
			#endregion

			#region Update existing tables
			foreach (var t in oldDatabase.Tables.OrderBy(x => x.Name))
			{
				if (selectedTables.Contains(t.Name.ToLower()))
				{
					var newT = newDatabase.Tables[t.Name];
					if (newT != null)
					{
						#region Update matching columns
						var delRefList = new List<Reference>();
						foreach (Reference r in t.Columns)
						{
							var oldCol = (Column)r.Object;
							var newColRef = newT.Columns.FindByName(oldCol.Name);
							Column newCol = null;
							if (newColRef != null) newCol = (Column)newColRef.Object;

							var doUpdate = ((newCol != null) && (oldCol.CorePropertiesHash != newCol.CorePropertiesHash));
							if (doUpdate && settings.OverridePrimaryKey)
								doUpdate = (oldCol.CorePropertiesHashNoPK != newCol.CorePropertiesHashNoPK);

							if (doUpdate)
							{
								oldCol.CancelUIEvents = true;
								var colId = oldCol.Id;
								var colKey = oldCol.Key;
								var isPrimaryKey = oldCol.PrimaryKey;
								newCol.CodeFacade = oldCol.CodeFacade;
								//newCol.SetId(colId);
								//newCol.SetKey(colKey);
								var doc = new XmlDocument();
								doc.LoadXml("<a></a>");
								newCol.XmlAppend(doc.DocumentElement);
								oldCol.XmlLoad(doc.DocumentElement);
								oldCol.SetId(colId);
								oldCol.SetKey(colKey);
								//oldCol.PrimaryKey = isPrimaryKey;
								oldCol.ParentTableRef = newDatabase.Tables[(newCol.ParentTableRef.Object as Table).Name].CreateRef();
								oldCol.CancelUIEvents = false;
							}
							else if (newCol == null)
							{
								delRefList.Add(r);
							}

						}

						//Remove deleted fields
						foreach (var r in delRefList)
						{
							t.Columns.Remove(r);
						}
						#endregion

						#region Add new columns
						foreach (var c in newT.GetColumns())
						{
							if (t.GetColumns().FirstOrDefault(x => x.Name == c.Name) == null)
							{
								var newCol = oldDatabase.Columns.Add(c.Name);
								var colId = newCol.Id;
								var doc = new XmlDocument();
								doc.LoadXml("<a></a>");
								c.XmlAppend(doc.DocumentElement);
								newCol.XmlLoad(doc.DocumentElement);
								newCol.SetId(colId);
								newCol.ParentTableRef = t.CreateRef();

								var newRef = new Reference(t.Root);
								newRef.Ref = newCol.Id;
								newRef.RefType = ReferenceType.Column;
								t.Columns.Add(newRef);
							}
						}
						#endregion

						#region Delete old columns
						var delColumnList = new List<Column>();
						foreach (Reference r in t.Columns)
						{
							if (newT.GetColumns().FirstOrDefault(x => x.Name == ((Column)r.Object).Name) == null)
							{
								delColumnList.Add((Column)r.Object);
							}
						}
						foreach (var c in delColumnList)
						{
							oldDatabase.Columns.Remove(c);
						}
						#endregion

						#region Update table properties
						t.CancelUIEvents = true;
						t.Description = newT.Description;
						t.AssociativeTable = newT.AssociativeTable;
						t.Generated = newT.Generated;
						t.HasHistory = newT.HasHistory;
						//t.AllowModifiedAudit = newT.AllowModifiedAudit;
						//t.AllowCreateAudit = newT.AllowCreateAudit;
						//t.AllowTimestamp = newT.AllowTimestamp;
						t.IsTypeTable = newT.IsTypeTable;
						t.CreateMetaData = newT.CreateMetaData;
						t.FullIndexSearch = newT.FullIndexSearch;
						t.IsMetaData = newT.IsMetaData;
						t.IsMetaDataDefinition = newT.IsMetaDataDefinition;
						t.IsMetaDataMaster = newT.IsMetaDataMaster;
						t.DBSchema = newT.DBSchema;
						t.CancelUIEvents = false;
						#endregion
					}
				}
			}
			#endregion

			#region Delete removed tables
			var delTableList = new List<Table>();
			foreach (Table t in oldDatabase.Tables)
			{
				if (selectedTables.Contains(t.Name.ToLower()))
				{
					if (!newDatabase.Tables.Contains(t.Name))
						delTableList.Add(t);
				}
			}
			foreach (var t in delTableList)
			{
				oldDatabase.Tables.Remove(t);
			}
			#endregion

			#region DEBUG
			foreach (var t in oldDatabase.Tables.OrderBy(x => x.Name))
			{
				#region Columns
				foreach (var c in t.GetColumns())
				{
					if (c.ParentTableRef == null)
					{
						System.Diagnostics.Debug.Write("");
					}
					else if (c.ParentTableRef.Object == null)
					{
						System.Diagnostics.Debug.Write("");
					}
				}
				#endregion

				#region Relations
				foreach (Relation r in t.GetRelations())
				{
					if (r.ChildTableRef == null)
					{
						System.Diagnostics.Debug.Write("");
					}
					else if (r.ChildTableRef.Object == null)
					{
						System.Diagnostics.Debug.Write("");
					}

					if (r.ParentTableRef == null)
					{
						System.Diagnostics.Debug.Write("");
					}
					else if (r.ParentTableRef.Object == null)
					{
						System.Diagnostics.Debug.Write("");
					}

				}
				#endregion
			}
			#endregion
		}

		private static void UpdateRelations(
			nHydrate.Generator.Models.Database newDatabase, 
			nHydrate.Generator.Models.Database oldDatabase)
		{
			foreach (Relation relation in newDatabase.Relations)
			{
				var pTable = oldDatabase.Tables[relation.ParentTable.Name];
				var cTable = oldDatabase.Tables[relation.ChildTable.Name];
				if (pTable != null && cTable != null)
				{
					var newRelation = oldDatabase.Relations.Add();
					newRelation.RoleName = relation.RoleName;
					newRelation.ParentTableRef = pTable.CreateRef();
					newRelation.ChildTableRef = cTable.CreateRef();
					foreach (ColumnRelationship cr in relation.ColumnRelationships)
					{
						var pColumn = pTable.GetColumns().FirstOrDefault(x => x.Name == cr.ParentColumn.Name);
						var cColumn = cTable.GetColumns().FirstOrDefault(x => x.Name == cr.ChildColumn.Name);

						if (pColumn != null && cColumn != null)
						{
							var newCR = new ColumnRelationship(oldDatabase.Root);
							newCR.ParentColumnRef = pColumn.CreateRef();
							newCR.ChildColumnRef = cColumn.CreateRef();
							newRelation.ColumnRelationships.Add(newCR);
						}
					}
					
					pTable.Relationships.Add(newRelation.CreateRef());
				}
			}
		}

		private static void UpdateViews(
			nHydrate.Generator.Models.Database newDatabase, 
			nHydrate.Generator.Models.Database oldDatabase,
			List<string> selectedViews,
			ImportModelSettings settings)
		{
			#region Update existing items
			foreach (CustomView t in oldDatabase.CustomViews)
			{
				if (selectedViews.Contains(t.Name.ToLower()))
				{
					var newV = newDatabase.CustomViews[t.Name];
					if (newV != null)
					{
						#region Update matching columns
						var delRefList = new List<Reference>();
						foreach (Reference r in t.Columns)
						{
							var oldCol = (CustomViewColumn)r.Object;
							var newColRef = newV.Columns.FindByName(oldCol.Name);
							CustomViewColumn newCol = null;
							if (newColRef != null) newCol = (CustomViewColumn)newColRef.Object;

							var doUpdate = ((newCol != null) && (oldCol.CorePropertiesHash != newCol.CorePropertiesHash));
							if (doUpdate && settings.OverridePrimaryKey)
								doUpdate = (oldCol.CorePropertiesHashNoPK != newCol.CorePropertiesHashNoPK);

							if (doUpdate)
							{
								oldCol.CancelUIEvents = true;
								var colId = oldCol.Id;
								var colKey = oldCol.Key;
								newCol.CodeFacade = oldCol.CodeFacade;
								//newCol.SetId(colId);
								//newCol.SetKey(colKey);
								var doc = new XmlDocument();
								doc.LoadXml("<a></a>");
								newCol.XmlAppend(doc.DocumentElement);
								oldCol.XmlLoad(doc.DocumentElement);
								oldCol.SetId(colId);
								oldCol.SetKey(colKey);
								oldCol.CancelUIEvents = false;
							}
							else if (newCol == null)
							{
								delRefList.Add(r);
							}

						}

						//Remove deleted fields
						foreach (var r in delRefList)
						{
							t.Columns.Remove(r);
						}
						#endregion

						#region Add new columns
						foreach (Reference r in newV.Columns)
						{
							var c = (CustomViewColumn)r.Object;
							if (t.GetColumns().FirstOrDefault(x => x.Name == c.Name) == null)
							{
								var newCol = oldDatabase.CustomViewColumns.Add(c.Name);
								var colId = newCol.Id;
								var doc = new XmlDocument();
								doc.LoadXml("<a></a>");
								c.XmlAppend(doc.DocumentElement);
								newCol.XmlLoad(doc.DocumentElement);
								newCol.SetId(colId);
								newCol.ParentViewRef = t.CreateRef();

								var newRef = new Reference(t.Root);
								newRef.Ref = newCol.Id;
								newRef.RefType = ReferenceType.CustomViewColumn;
								t.Columns.Add(newRef);
							}
						}
						#endregion

						#region Delete old columns
						var delColumnList = new List<CustomViewColumn>();
						foreach (Reference r in t.Columns)
						{
							if (newV.GetColumns().FirstOrDefault(x => x.Name == ((CustomViewColumn)r.Object).Name) == null)
							{
								delColumnList.Add((CustomViewColumn)r.Object);
Back to Top