-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathfrmMain.cs
1874 lines (1542 loc) · 71.6 KB
/
frmMain.cs
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
using PRISM;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using ShFolderBrowser.FolderBrowser;
namespace DB_Schema_Export_Tool
{
public partial class frmMain : Form
{
// Ignore Spelling: Ctrl, dms, dmsdev, frm, mts, PostgreSQL, Schemas, Un&pause, Un&pausing, unpause, username
public frmMain()
{
InitializeComponent();
InitializeControls();
}
private const string XML_SETTINGS_FILE_NAME = "DB_Schema_Export_Tool_Settings.xml";
private const string XML_SECTION_DATABASE_SETTINGS = "DBSchemaExportDatabaseSettings";
private const string XML_SECTION_PROGRAM_OPTIONS = "DBSchemaExportOptions";
private const int THREAD_WAIT_MSEC = 150;
private const string ROW_COUNT_SEPARATOR = "\t (";
private enum TableNameSortModeConstants
{
Name = 0,
RowCount = 1
}
private enum MessageTypeConstants
{
Normal = 0,
Debug = 1,
Warning = 2,
Error = 3
}
/// <summary>
/// Schema object types
/// </summary>
public enum SchemaObjectTypeConstants
{
/// <summary>
/// Schemas and roles
/// </summary>
SchemasAndRoles = 0,
/// <summary>
/// Tables
/// </summary>
Tables = 1,
/// <summary>
/// Views
/// </summary>
Views = 2,
/// <summary>
/// Stored procedures
/// </summary>
StoredProcedures = 3,
/// <summary>
/// User defined functions
/// </summary>
UserDefinedFunctions = 4,
/// <summary>
/// User defined data types
/// </summary>
UserDefinedDataTypes = 5,
/// <summary>
/// User defined types
/// </summary>
UserDefinedTypes = 6,
/// <summary>
/// Synonyms
/// </summary>
Synonyms = 7
}
private string mXmlSettingsFilePath;
private readonly SchemaExportOptions mSchemaExportOptions = new();
private readonly List<string> mDatabaseListToProcess = new();
private readonly List<TableDataExportInfo> mTablesForDataExport = new();
/// <summary>
/// Cached table info
/// </summary>
/// <remarks>
/// Keys are instances of TableDataExportInfo, values are row counts; row counts will be 0 if mCachedTableListIncludesRowCounts = False
/// </remarks>
private readonly Dictionary<TableDataExportInfo, long> mCachedTableList = new ();
private bool mCachedTableListIncludesRowCounts;
private readonly SortedSet<string> mTableNamesToAutoSelect = new (StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Regular expressions for auto-selecting table names
/// </summary>
/// <remarks>
/// Must contain valid RegEx statements (will use case-insensitive comparisons)
/// </remarks>
private readonly SortedSet<string> mTableNameAutoSelectRegEx = new (StringComparer.OrdinalIgnoreCase);
private readonly List<string> mDefaultDMSDatabaseList = new();
private readonly List<string> mDefaultMTSDatabaseList = new();
private bool mWorking;
private Thread mThread;
private DBSchemaExportTool mDBSchemaExporter;
private bool mSchemaExportSuccess;
private delegate void AppendNewMessageHandler(string message, MessageTypeConstants msgType);
private delegate void UpdatePauseUnpauseCaptionHandler(DBSchemaExporterBase.PauseStatusConstants pauseStatus);
private delegate void ProgressUpdateHandler(string taskDescription, float percentComplete);
private delegate void ProgressCompleteHandler();
private delegate void HandleDBExportStartingEventHandler(string databaseName);
private void AppendNewMessage(string message, MessageTypeConstants msgType)
{
if (string.IsNullOrWhiteSpace(message))
return;
switch (msgType)
{
case MessageTypeConstants.Error:
lblMessage.Text = message.StartsWith("Error", StringComparison.OrdinalIgnoreCase) ? string.Empty : "Error: " + message;
ConsoleMsgUtils.ShowError(lblMessage.Text);
Console.WriteLine();
break;
case MessageTypeConstants.Warning:
lblMessage.Text = message.StartsWith("Warning", StringComparison.OrdinalIgnoreCase) ? string.Empty : "Warning: " + message;
ConsoleMsgUtils.ShowWarning(lblMessage.Text);
Console.WriteLine();
break;
default:
lblMessage.Text = message;
break;
}
Application.DoEvents();
}
private void ConfirmAbortRequest()
{
if (mDBSchemaExporter == null)
return;
var pauseStatusSaved = mDBSchemaExporter.PauseStatus;
mDBSchemaExporter.RequestPause();
Application.DoEvents();
var response = MessageBox.Show(
"Are you sure you want to abort processing?", "Abort",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
if (response == DialogResult.Yes)
{
mDBSchemaExporter.AbortProcessingNow();
// Note that AbortProcessingNow should have called RequestUnpause, but we'll call it here just in case
mDBSchemaExporter.RequestUnpause();
}
else if (pauseStatusSaved is DBSchemaExporterBase.PauseStatusConstants.Unpaused or DBSchemaExporterBase.PauseStatusConstants.UnpauseRequested)
{
mDBSchemaExporter.RequestUnpause();
}
Application.DoEvents();
}
private void EnableDisableControls()
{
try
{
txtUsername.Enabled = !chkUseIntegratedAuthentication.Checked || chkPostgreSQL.Checked;
txtPassword.Enabled = !chkUseIntegratedAuthentication.Checked || chkPostgreSQL.Checked;
chkUseIntegratedAuthentication.Enabled = !chkPostgreSQL.Checked;
cmdGo.Visible = !mWorking;
cmdExit.Visible = !mWorking;
fraConnectionSettings.Enabled = !mWorking;
fraOutputOptions.Enabled = !mWorking;
mnuEditStart.Enabled = !mWorking;
mnuEditResetOptions.Enabled = !mWorking;
}
catch (Exception ex)
{
MessageBox.Show("Error in EnableDisableControls: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private string GetAppDirectoryPath()
{
return GetAppGetAppDirectoryPath(true);
}
private string GetAppGetAppDirectoryPath(bool returnParentIfDirectoryNamedDebug)
{
const string DEBUG_DIRECTORY_NAME = @"\debug";
var appDirectoryPath = AppUtils.GetAppDirectoryPath();
if (returnParentIfDirectoryNamedDebug && appDirectoryPath.ToLower().EndsWith(DEBUG_DIRECTORY_NAME))
{
return appDirectoryPath.Substring(0, appDirectoryPath.Length - DEBUG_DIRECTORY_NAME.Length);
}
return appDirectoryPath;
}
private List<string> GetSelectedDatabases()
{
return GetSelectedListboxItems(lstDatabasesToProcess);
}
private List<TableDataExportInfo> GetSelectedTableNamesForDataExport(bool warnIfRowCountOverThreshold, out bool cancelExport)
{
var selectedTableNames = GetSelectedListboxItems(lstTableNamesToExportData);
var tablesForDataExport = new List<TableDataExportInfo>();
foreach (var item in selectedTableNames)
{
var tableInfo = new TableDataExportInfo(item)
{
UsePgInsert = chkUsePgInsert.Checked
};
tablesForDataExport.Add(tableInfo);
}
StripRowCountsFromTableNames(selectedTableNames);
if (selectedTableNames.Count == 0 || !mCachedTableListIncludesRowCounts || !warnIfRowCountOverThreshold)
{
cancelExport = false;
return tablesForDataExport;
}
var validTables = new List<TableDataExportInfo>();
// See if any of the tables in selectedTableNames has more than DBSchemaExporterBase.DATA_ROW_COUNT_WARNING_THRESHOLD rows
foreach (var tableName in selectedTableNames)
{
var keepTable = true;
var tableFound = false;
TableDataExportInfo matchedTableItem = null;
foreach (var item in mCachedTableList)
{
if (!item.Key.SourceTableName.Equals(tableName))
continue;
tableFound = true;
matchedTableItem = item.Key;
var tableRowCount = item.Value;
if (tableRowCount >= DBSchemaExporterBase.MAX_ROWS_DATA_TO_EXPORT)
{
var msg = string.Format("Warning, table {0} has {1} rows. Are you sure you want to export data from it?",
tableName, tableRowCount);
var caption = "Row Count Over " + DBSchemaExporterBase.MAX_ROWS_DATA_TO_EXPORT;
var response = MessageBox.Show(
msg, caption,
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
if (response == DialogResult.No)
{
keepTable = false;
}
else if (response == DialogResult.Cancel)
{
cancelExport = true;
return new List<TableDataExportInfo>();
}
}
break;
}
if (!tableFound)
{
// Table not found; keep it anyway
}
if (!keepTable)
continue;
if (matchedTableItem == null)
{
var tableInfo = new TableDataExportInfo(tableName)
{
UsePgInsert = chkUsePgInsert.Checked
};
validTables.Add(tableInfo);
}
else
{
matchedTableItem.UsePgInsert = chkUsePgInsert.Checked;
validTables.Add(matchedTableItem);
}
}
cancelExport = false;
return validTables;
}
private List<string> GetSelectedListboxItems(ListBox listBox)
{
var items = new List<string>(listBox.SelectedItems.Count);
try
{
items.AddRange(from object item in listBox.SelectedItems select item.ToString());
}
catch (Exception)
{
// Ignore errors here
}
return items;
}
private string GetSettingsFilePath()
{
return Path.Combine(GetAppDirectoryPath(), XML_SETTINGS_FILE_NAME);
}
private void HandleDBExportStartingEvent(string databaseName)
{
try
{
lblProgress.Text = "Exporting schema from " + databaseName;
if (mnuEditPauseAfterEachDatabase.Checked)
{
mDBSchemaExporter.RequestPause();
}
}
catch (Exception ex)
{
MessageBox.Show("Error in HandleDBExportStartingEvent: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void InitializeProgressBars()
{
lblProgress.Text = string.Empty;
pbarProgress.Minimum = 0;
pbarProgress.Maximum = 100;
pbarProgress.Value = 0;
}
/// <summary>
/// Prompts the user to select a file to load the options from
/// </summary>
private void IniFileLoadOptions()
{
var fileDialog = new OpenFileDialog
{
AddExtension = true,
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = ".xml",
DereferenceLinks = true,
Multiselect = false,
ValidateNames = true,
Filter = "Settings files (*.xml)|*.xml|All files (*.*)|*.*",
FilterIndex = 1
};
var filePath = mXmlSettingsFilePath;
if (filePath.Length > 0)
{
try
{
fileDialog.InitialDirectory = Directory.GetParent(filePath)?.ToString();
}
catch
{
fileDialog.InitialDirectory = GetAppDirectoryPath();
}
}
else
{
fileDialog.InitialDirectory = GetAppDirectoryPath();
}
fileDialog.FileName = string.Empty;
fileDialog.Title = "Specify file to load options from";
fileDialog.ShowDialog();
if (fileDialog.FileName.Length > 0)
{
mXmlSettingsFilePath = fileDialog.FileName;
IniFileLoadOptions(mXmlSettingsFilePath, true, true);
}
}
private void IniFileLoadOptions(string filePath, bool resetToDefaultsPriorToLoad, bool connectToServer)
{
// Loads options from the given file
var xmlFile = new XmlSettingsFileAccessor();
try
{
if (resetToDefaultsPriorToLoad)
{
ResetToDefaults(false);
}
// Sleep for 100 msec, just to be safe
Thread.Sleep(100);
// Read the settings from the XML file
// Pass True to .LoadSettings() to turn off case sensitive matching
xmlFile.LoadSettings(filePath, false);
try
{
Width = xmlFile.GetParam(XML_SECTION_PROGRAM_OPTIONS, "WindowWidth", Width);
Height = xmlFile.GetParam(XML_SECTION_PROGRAM_OPTIONS, "WindowHeight", Height);
var serverNameSaved = txtServerName.Text;
txtServerName.Text = xmlFile.GetParam(XML_SECTION_DATABASE_SETTINGS, "ServerName", txtServerName.Text);
chkPostgreSQL.Checked = xmlFile.GetParam(XML_SECTION_DATABASE_SETTINGS, "PostgreSQL", chkPostgreSQL.Checked);
chkUseIntegratedAuthentication.Checked = xmlFile.GetParam(XML_SECTION_DATABASE_SETTINGS, "UseIntegratedAuthentication", chkUseIntegratedAuthentication.Checked);
txtUsername.Text = xmlFile.GetParam(XML_SECTION_DATABASE_SETTINGS, "Username", txtUsername.Text);
txtPassword.Text = xmlFile.GetParam(XML_SECTION_DATABASE_SETTINGS, "Password", txtPassword.Text);
txtOutputDirectoryPath.Text = xmlFile.GetParam(XML_SECTION_PROGRAM_OPTIONS, "OutputDirectoryPath", txtOutputDirectoryPath.Text);
mnuEditScriptObjectsThreaded.Checked = xmlFile.GetParam(XML_SECTION_PROGRAM_OPTIONS, "ScriptObjectsThreaded", mnuEditScriptObjectsThreaded.Checked);
mnuEditPauseAfterEachDatabase.Checked = xmlFile.GetParam(XML_SECTION_PROGRAM_OPTIONS, "PauseAfterEachDatabase", mnuEditPauseAfterEachDatabase.Checked);
mnuEditIncludeTimestampInScriptFileHeader.Checked = xmlFile.GetParam(XML_SECTION_PROGRAM_OPTIONS, "IncludeTimestampInScriptFileHeader", mnuEditIncludeTimestampInScriptFileHeader.Checked);
chkCreateDirectoryForEachDB.Checked = xmlFile.GetParam(XML_SECTION_PROGRAM_OPTIONS, "CreateDirectoryForEachDB", chkCreateDirectoryForEachDB.Checked);
txtOutputDirectoryNamePrefix.Text = xmlFile.GetParam(XML_SECTION_PROGRAM_OPTIONS, "OutputDirectoryNamePrefix", txtOutputDirectoryNamePrefix.Text);
chkExportServerSettingsLoginsAndJobs.Checked = xmlFile.GetParam(XML_SECTION_PROGRAM_OPTIONS, "ExportServerSettingsLoginsAndJobs", chkExportServerSettingsLoginsAndJobs.Checked);
txtServerOutputDirectoryNamePrefix.Text = xmlFile.GetParam(XML_SECTION_PROGRAM_OPTIONS, "ServerOutputDirectoryNamePrefix", txtServerOutputDirectoryNamePrefix.Text);
mnuEditIncludeTableRowCounts.Checked = xmlFile.GetParam(XML_SECTION_PROGRAM_OPTIONS, "IncludeTableRowCounts", mnuEditIncludeTableRowCounts.Checked);
mnuEditAutoSelectDefaultTableNames.Checked = xmlFile.GetParam(XML_SECTION_PROGRAM_OPTIONS, "AutoSelectDefaultTableNames", mnuEditAutoSelectDefaultTableNames.Checked);
mnuEditSaveDataAsInsertIntoStatements.Checked = xmlFile.GetParam(XML_SECTION_PROGRAM_OPTIONS, "SaveDataAsInsertIntoStatements", mnuEditSaveDataAsInsertIntoStatements.Checked);
mnuEditWarnOnHighTableRowCount.Checked = xmlFile.GetParam(XML_SECTION_PROGRAM_OPTIONS, "WarnOnHighTableRowCount", mnuEditWarnOnHighTableRowCount.Checked);
if (lstDatabasesToProcess.Items.Count > 0 &&
serverNameSaved.Equals(txtServerName.Text, StringComparison.OrdinalIgnoreCase))
{
return;
}
if (connectToServer)
{
UpdateDatabaseList();
}
}
catch (Exception)
{
var msg = "Invalid parameter in settings file: " + Path.GetFileName(filePath);
MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
catch (Exception)
{
var msg = "Error loading settings from file: " + filePath;
MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
/// <summary>
/// Prompts the user to select a file to load the options from
/// </summary>
private void IniFileSaveOptions()
{
var fileDialog = new SaveFileDialog
{
AddExtension = true,
CheckFileExists = false,
CheckPathExists = true,
DefaultExt = ".xml",
DereferenceLinks = true,
OverwritePrompt = false,
ValidateNames = true,
Filter = "Settings files (*.xml)|*.xml|All files (*.*)|*.*",
FilterIndex = 1
};
var filePath = mXmlSettingsFilePath;
if (filePath.Length > 0)
{
try
{
fileDialog.InitialDirectory = Directory.GetParent(filePath)?.ToString();
}
catch
{
fileDialog.InitialDirectory = GetAppDirectoryPath();
}
}
else
{
fileDialog.InitialDirectory = GetAppDirectoryPath();
}
if (File.Exists(filePath))
{
fileDialog.FileName = Path.GetFileName(filePath);
}
else
{
fileDialog.FileName = XML_SETTINGS_FILE_NAME;
}
fileDialog.Title = "Specify file to save options to";
fileDialog.ShowDialog();
if (fileDialog.FileName.Length > 0)
{
mXmlSettingsFilePath = fileDialog.FileName;
IniFileSaveOptions(mXmlSettingsFilePath);
}
}
private void IniFileSaveOptions(string filePath, bool saveWindowDimensionsOnly = false)
{
var xmlFile = new XmlSettingsFileAccessor();
try
{
// Pass True to .LoadSettings() here so that newly made Xml files will have the correct capitalization
xmlFile.LoadSettings(filePath, true);
try
{
xmlFile.SetParam(XML_SECTION_PROGRAM_OPTIONS, "WindowWidth", Width);
xmlFile.SetParam(XML_SECTION_PROGRAM_OPTIONS, "WindowHeight", Height - 20);
if (!saveWindowDimensionsOnly)
{
xmlFile.SetParam(XML_SECTION_DATABASE_SETTINGS, "ServerName", txtServerName.Text);
xmlFile.SetParam(XML_SECTION_DATABASE_SETTINGS, "PostgreSQL", chkPostgreSQL.Checked);
xmlFile.SetParam(XML_SECTION_DATABASE_SETTINGS, "UseIntegratedAuthentication", chkUseIntegratedAuthentication.Checked);
xmlFile.SetParam(XML_SECTION_DATABASE_SETTINGS, "Username", txtUsername.Text);
xmlFile.SetParam(XML_SECTION_DATABASE_SETTINGS, "Password", txtPassword.Text);
xmlFile.SetParam(XML_SECTION_PROGRAM_OPTIONS, "OutputDirectoryPath", txtOutputDirectoryPath.Text);
xmlFile.SetParam(XML_SECTION_PROGRAM_OPTIONS, "ScriptObjectsThreaded", mnuEditScriptObjectsThreaded.Checked);
xmlFile.SetParam(XML_SECTION_PROGRAM_OPTIONS, "PauseAfterEachDatabase", mnuEditPauseAfterEachDatabase.Checked);
xmlFile.SetParam(XML_SECTION_PROGRAM_OPTIONS, "IncludeTimestampInScriptFileHeader", mnuEditIncludeTimestampInScriptFileHeader.Checked);
xmlFile.SetParam(XML_SECTION_PROGRAM_OPTIONS, "CreateDirectoryForEachDB", chkCreateDirectoryForEachDB.Checked);
xmlFile.SetParam(XML_SECTION_PROGRAM_OPTIONS, "OutputDirectoryNamePrefix", txtOutputDirectoryNamePrefix.Text);
xmlFile.SetParam(XML_SECTION_PROGRAM_OPTIONS, "ExportServerSettingsLoginsAndJobs", chkExportServerSettingsLoginsAndJobs.Checked);
xmlFile.SetParam(XML_SECTION_PROGRAM_OPTIONS, "ServerOutputDirectoryNamePrefix", txtServerOutputDirectoryNamePrefix.Text);
xmlFile.SetParam(XML_SECTION_PROGRAM_OPTIONS, "IncludeTableRowCounts", mnuEditIncludeTableRowCounts.Checked);
xmlFile.SetParam(XML_SECTION_PROGRAM_OPTIONS, "AutoSelectDefaultTableNames", mnuEditAutoSelectDefaultTableNames.Checked);
xmlFile.SetParam(XML_SECTION_PROGRAM_OPTIONS, "SaveDataAsInsertIntoStatements", mnuEditSaveDataAsInsertIntoStatements.Checked);
xmlFile.SetParam(XML_SECTION_PROGRAM_OPTIONS, "WarnOnHighTableRowCount", mnuEditWarnOnHighTableRowCount.Checked);
}
}
catch (Exception)
{
var msg = "Error storing parameter in settings file: " + Path.GetFileName(filePath);
MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
xmlFile.SaveSettings();
}
catch (Exception)
{
var msg = "Error saving settings to file: " + filePath;
MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void PopulateTableNamesToExport(bool enableAutoSelectDefaultTableNames)
{
try
{
if (mCachedTableList.Count == 0)
{
lstTableNamesToExportData.Items.Clear();
return;
}
TableNameSortModeConstants sortOrder;
if (cboTableNamesToExportSortOrder.SelectedIndex >= 0)
{
sortOrder = (TableNameSortModeConstants)cboTableNamesToExportSortOrder.SelectedIndex;
}
else
{
sortOrder = TableNameSortModeConstants.Name;
}
var sortedTables = sortOrder == TableNameSortModeConstants.RowCount
? (from item in mCachedTableList orderby item.Value select item).ToList()
: (from item in mCachedTableList orderby item.Key.ToString() select item).ToList();
const RegexOptions regexOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline;
var regExSpecs = new List<Regex>();
bool autoHighlightRows;
if (mnuEditAutoSelectDefaultTableNames.Checked && enableAutoSelectDefaultTableNames)
{
autoHighlightRows = true;
foreach (var regexItem in mTableNameAutoSelectRegEx)
{
regExSpecs.Add(new Regex(regexItem, regexOptions));
}
}
else
{
autoHighlightRows = false;
}
// Cache the currently selected names so that we can re-highlight them below
var selectedTableNamesSaved = new SortedSet<string>();
foreach (var item in lstTableNamesToExportData.SelectedItems)
{
selectedTableNamesSaved.Add(StripRowCountFromTableName(item.ToString()));
}
lstTableNamesToExportData.Items.Clear();
foreach (var tableItem in sortedTables)
{
// tableItem.Key is Table Name
// tableItem.Value is the number of rows in the table (if mCachedTableListIncludesRowCounts = True)
var tableName = tableItem.Key.SourceTableName;
string textForRow;
if (mCachedTableListIncludesRowCounts)
{
textForRow = tableName + ROW_COUNT_SEPARATOR + ValueToTextEstimate(tableItem.Value);
if (tableItem.Value == 1)
{
textForRow += " row)";
}
else
{
textForRow += " rows)";
}
}
else
{
textForRow = tableName;
}
var itemIndex = lstTableNamesToExportData.Items.Add(textForRow);
var highlightCurrentRow = false;
if (selectedTableNamesSaved.Contains(tableName))
{
// User had previously highlighted this table name; re-highlight it
highlightCurrentRow = true;
}
else if (autoHighlightRows)
{
// Test tableName against the RegEx values from mTableNameAutoSelectRegEx()
foreach (var regexMatcher in regExSpecs)
{
if (regexMatcher.Match(tableName).Success)
{
highlightCurrentRow = true;
break;
}
}
if (!highlightCurrentRow)
{
// No match: test tableName against the names in mTableNamesToAutoSelect
if (mTableNamesToAutoSelect.Contains(tableName))
{
highlightCurrentRow = true;
}
}
}
if (highlightCurrentRow)
{
// Highlight this table name
lstTableNamesToExportData.SetSelected(itemIndex, true);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error in PopulateTableNamesToExport: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void InitializeControls()
{
mCachedTableList.Clear();
mDefaultDMSDatabaseList.Clear();
mDefaultMTSDatabaseList.Clear();
InitializeProgressBars();
PopulateComboBoxes();
SetToolTips();
ResetToDefaults(false);
try
{
mXmlSettingsFilePath = GetSettingsFilePath();
if (!File.Exists(mXmlSettingsFilePath))
{
IniFileSaveOptions(mXmlSettingsFilePath);
}
}
catch (Exception)
{
// Ignore errors here
}
IniFileLoadOptions(mXmlSettingsFilePath, false, false);
EnableDisableControls();
}
private void InitializeDBSchemaExporter()
{
mDBSchemaExporter = new DBSchemaExportTool(mSchemaExportOptions);
mDBSchemaExporter.DBExportStarting += mDBSchemaExporter_DBExportStarting;
mDBSchemaExporter.StatusEvent += mDBSchemaExporter_StatusMessage;
mDBSchemaExporter.DebugEvent += mDBSchemaExporter_DebugMessage;
mDBSchemaExporter.WarningEvent += mDBSchemaExporter_WarningMessage;
mDBSchemaExporter.ErrorEvent += mDBSchemaExporter_ErrorMessage;
mDBSchemaExporter.ProgressUpdate += mDBSchemaExporter_ProgressUpdate;
mDBSchemaExporter.ProgressComplete += mDBSchemaExporter_ProgressComplete;
mDBSchemaExporter.DBExportStarting += mDBSchemaExporter_DBExportStarting;
mDBSchemaExporter.PauseStatusChange += mDBSchemaExporter_PauseStatusChange;
}
private void PopulateComboBoxes()
{
try
{
cboTableNamesToExportSortOrder.Items.Clear();
cboTableNamesToExportSortOrder.Items.Insert((int)TableNameSortModeConstants.Name, "Sort by Name");
cboTableNamesToExportSortOrder.Items.Insert((int)TableNameSortModeConstants.RowCount, "Sort by Row Count");
cboTableNamesToExportSortOrder.SelectedIndex = (int)TableNameSortModeConstants.RowCount;
lstObjectTypesToScript.Items.Clear();
lstObjectTypesToScript.Items.Insert((int)SchemaObjectTypeConstants.SchemasAndRoles, "Schemas and Roles");
lstObjectTypesToScript.Items.Insert((int)SchemaObjectTypeConstants.Tables, "Tables");
lstObjectTypesToScript.Items.Insert((int)SchemaObjectTypeConstants.Views, "Views");
lstObjectTypesToScript.Items.Insert((int)SchemaObjectTypeConstants.StoredProcedures, "Stored Procedures");
lstObjectTypesToScript.Items.Insert((int)SchemaObjectTypeConstants.UserDefinedFunctions, "User Defined Functions");
lstObjectTypesToScript.Items.Insert((int)SchemaObjectTypeConstants.UserDefinedDataTypes, "User Defined Data Types");
lstObjectTypesToScript.Items.Insert((int)SchemaObjectTypeConstants.UserDefinedTypes, "User Defined Types");
lstObjectTypesToScript.Items.Insert((int)SchemaObjectTypeConstants.Synonyms, "Synonyms");
// Auto-select all of the options
for (var index = 0; index < lstObjectTypesToScript.Items.Count; index++)
{
lstObjectTypesToScript.SetSelected(index, true);
}
}
catch (Exception ex)
{
MessageBox.Show("Error in PopulateComboBoxes: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void ProgressUpdate(string taskDescription, float percentComplete)
{
lblProgress.Text = taskDescription;
UpdateProgressBar(pbarProgress, percentComplete);
}
private void ProgressComplete()
{
pbarProgress.Value = pbarProgress.Maximum;
}
private void ScriptDBSchemaObjects()
{
string message;
if (mWorking)
{
return;
}
try
{
// Validate txtOutputDirectoryPath.Text
if (txtOutputDirectoryPath.TextLength == 0)
{
txtOutputDirectoryPath.Text = GetAppDirectoryPath();
}
if (!Directory.Exists(txtOutputDirectoryPath.Text))
{
message = "Output directory not found: " + txtOutputDirectoryPath.Text;
MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
UpdateSchemaExportOptions();
}
catch (Exception ex)
{
MessageBox.Show("Error initializing mSchemaExportOptions in ScriptDBSchemaObjects: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
try
{
// Populate mDatabaseListToProcess and mTablesForDataExport
mDatabaseListToProcess.Clear();
mDatabaseListToProcess.AddRange(GetSelectedDatabases());
var selectedTables = GetSelectedTableNamesForDataExport(mnuEditWarnOnHighTableRowCount.Checked, out var cancelExport);
mTablesForDataExport.Clear();
mTablesForDataExport.AddRange(selectedTables);
if (cancelExport)
{
MessageBox.Show("Operation canceled", "Nothing To Do", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (mDatabaseListToProcess.Count == 0 && !mSchemaExportOptions.ExportServerSettingsLoginsAndJobs)
{
MessageBox.Show("No databases or tables were selected; unable to continue", "Nothing To Do", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
catch (Exception ex)
{
MessageBox.Show("Error determining list of databases (and tables) to process: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
try
{
if (mDBSchemaExporter == null)
{
InitializeDBSchemaExporter();
}
if (mTableNamesToAutoSelect != null)
{
mDBSchemaExporter.StoreTableNamesToAutoExportData(mTableNamesToAutoSelect);
}
if (mTableNameAutoSelectRegEx != null)
{
mDBSchemaExporter.StoreTableNameRegexToAutoExportData(mTableNameAutoSelectRegEx);
}
}
catch (Exception ex)
{
MessageBox.Show("Error instantiating mDBSchemaExporter and updating the data export auto-select lists: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
try
{
mWorking = true;
EnableDisableControls();
UpdatePauseUnpauseCaption(DBSchemaExporterBase.PauseStatusConstants.Unpaused);
Application.DoEvents();
if (!mnuEditScriptObjectsThreaded.Checked)
{
ScriptDBSchemaObjectsThread();
}
else
{
// Use the following to call the SP on a separate thread
mThread = new Thread(ScriptDBSchemaObjectsThread);
mThread.Start();
Thread.Sleep(THREAD_WAIT_MSEC);
while (mThread.ThreadState is
ThreadState.Running or
ThreadState.AbortRequested or
ThreadState.WaitSleepJoin or
ThreadState.Suspended or
ThreadState.SuspendRequested)
{
try
{
if (mThread.Join(THREAD_WAIT_MSEC))
{
// The Join succeeded, meaning the thread has finished running
break;
}
// else if (mRequestCancel)
// mThread.Abort();
}
catch (Exception)
{
// Error joining thread; this can happen if the thread is trying to abort, so I believe we can ignore the error
// Sleep another THREAD_WAIT_MSEC msec, then exit the while loop
Thread.Sleep(THREAD_WAIT_MSEC);
break;
}
Application.DoEvents();
}
}
Application.DoEvents();
if (!mSchemaExportSuccess || mDBSchemaExporter.ErrorCode != DBSchemaExporterBase.DBSchemaExportErrorCodes.NoError)
{
message = string.Format("Error exporting the schema objects (ErrorCode={0}):\n{1}",
mDBSchemaExporter.ErrorCode, mDBSchemaExporter.StatusMessage);
MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
catch (Exception ex)
{
MessageBox.Show("Error calling ScriptDBSchemaObjectsThread in ScriptDBSchemaObjects: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
mWorking = false;
EnableDisableControls();
UpdatePauseUnpauseCaption(DBSchemaExporterBase.PauseStatusConstants.Unpaused);
try
{
if (mThread != null && mThread.ThreadState != ThreadState.Stopped)
{
mThread.Abort();
}
}
catch (Exception)
{
// Ignore errors here
}
}
try
{
lblProgress.Text = "Schema export complete";
}