forked from olejorgensen/CompactView
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainForm.cs
1148 lines (992 loc) · 42.3 KB
/
MainForm.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
/**************************************************************************
Copyright (C) 2011-2017 Iván Costales Suárez
This file is part of CompactView.
CompactView is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CompactView is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with CompactView. If not, see <http://www.gnu.org/licenses/>.
CompactView web site <http://sourceforge.net/p/compactview/>.
**************************************************************************/
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
namespace CompactView
{
public partial class MainForm : Form
{
private const string formText = "CompactView";
private SqlCeDb db = new SqlCeDb();
private Settings settings = new Settings();
// It is used to find the words "create", "drop" or "alter" that are not quoted
//private Regex regexCreateAlterDrop = new Regex(@"(?<=^(([^']*'[^']*'[^']*)*|[^']*))\b(create|alter|drop)\b", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase);
private Regex regexDropQuotesAndBrackets = new Regex(@"'[^']*'|\[[^\]]*\]", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private Regex regexCreateAlterDrop = new Regex("create|alter|drop", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private Regex regexInsertUpdateDelete = new Regex("insert|update|delete", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public MainForm()
{
InitializeComponent();
Text = formText;
splitterHorizontal.Panel1Collapsed = true;
LoadSettings();
// Set culture code to the default current culture
GlobalText.CultureCode = Thread.CurrentThread.CurrentUICulture.Name;
SetCultureTexts();
UpdateStatus();
}
private void LoadSettings()
{
settings.Load();
Left = settings.X >= 0 ? settings.X : 0;
Top = settings.Y >= 0 ? settings.Y : 0;
Width = settings.Width >= 580 ? settings.Width : 580;
Height = settings.Height >= 380 ? settings.Height : 380;
WindowState = settings.Maximized ? FormWindowState.Maximized : FormWindowState.Normal;
if (settings.TextColor1 == 0 && settings.TextColor2 == 0 && settings.BackColor1 == 0 && settings.BackColor2 == 0)
{
settings.TextColor1 = Color.Black.ToArgb();
settings.TextColor2 = Color.Black.ToArgb();
settings.BackColor1 = Color.LightYellow.ToArgb();
settings.BackColor2 = Color.LemonChiffon.ToArgb();
}
OptionsForm.SelectColors(dataGrid, settings, settings.ColorSet);
UpdateRecentFilesMenu();
}
private void SaveSettings()
{
if (WindowState != FormWindowState.Maximized)
{
settings.X = Left >= 0 ? Left : 0;
settings.Y = Top >= 0 ? Top : 0;
settings.Width = Width >= 580 ? Width : 580;
settings.Height = Height >= 380 ? Height : 380;
}
settings.Maximized = WindowState == FormWindowState.Maximized;
settings.Save();
}
private void UpdateRecentFilesMenu()
{
EventHandler e = new EventHandler(RecentFiles_Click);
recentFilesMenuItem.DropDownItems.Clear();
foreach (string fileName in settings.RecentFiles)
recentFilesMenuItem.DropDownItems.Add(fileName, images.Images[0], e);
}
private void RecentFiles_Click(object sender, EventArgs e)
{
string fileName = ((ToolStripMenuItem)sender).Text;
LoadDatabase(fileName);
}
private void SetCultureTexts()
{
btnOpen.Text = GlobalText.GetValue("OpenDatabase");
cbReadOnly.Items[0] = GlobalText.GetValue("ReadOnly");
cbReadOnly.Items[1] = GlobalText.GetValue("AllowEditing");
btnQuery.Text = GlobalText.GetValue("Query");
btnExecute.Text = GlobalText.GetValue("Execute");
btnClear.Text = GlobalText.GetValue("Clear");
btnCut.Text = GlobalText.GetValue("Cut");
btnCopy.Text = GlobalText.GetValue("Copy");
btnPaste.Text = GlobalText.GetValue("Paste");
tabControl1.TabPages[0].Text = GlobalText.GetValue("Data");
tabControl1.TabPages[1].Text = GlobalText.GetValue("SqlSchema");
lbResult.Text = GlobalText.GetValue("QueryNote");
cutToolStripMenuItem.Text = GlobalText.GetValue("Cut");
copyToolStripMenuItem.Text = GlobalText.GetValue("Copy");
pasteToolStripMenuItem.Text = GlobalText.GetValue("Paste");
loadFromFileToolStripMenuItem.Text = $"{GlobalText.GetValue("LoadFromFile")}...";
saveToFileToolStripMenuItem.Text = $"{GlobalText.GetValue("SaveToFile")}...";
printToolStripMenuItem.Text = $"{GlobalText.GetValue("Print")}...";
fileMenuItem.Text = GlobalText.GetValue("File");
openDatabaseMenuItem.Text = $"{GlobalText.GetValue("OpenDatabase")}...";
recentFilesMenuItem.Text = GlobalText.GetValue("RecentFiles");
allowEditingMenuItem.Text = GlobalText.GetValue("AllowEditing");
importMenuItem.Text = $"{GlobalText.GetValue("Import")}...";
exportMenuItem.Text = $"{GlobalText.GetValue("Export")}...";
exitMenuItem.Text = GlobalText.GetValue("Exit");
editMenuItem.Text = GlobalText.GetValue("Edit");
cutMenuItem.Text = GlobalText.GetValue("Cut");
copyMenuItem.Text = GlobalText.GetValue("Copy");
pasteMenuItem.Text = GlobalText.GetValue("Paste");
deleteMenuItem.Text = GlobalText.GetValue("Delete");
queryMenuItem.Text = GlobalText.GetValue("Query");
showEditorMenuItem.Text = GlobalText.GetValue("ShowEditor");
executeMenuItem.Text = GlobalText.GetValue("Execute");
clearMenuItem.Text = GlobalText.GetValue("Clear");
toolsMenuItem.Text = GlobalText.GetValue("Tools");
databaseToolsMenuItem.Text = $"{GlobalText.GetValue("DatabaseTools")}...";
optionsMenuItem.Text = $"{GlobalText.GetValue("Options")}...";
helpMenuItem.Text = GlobalText.GetValue("Help");
aboutCompactViewMenuItem.Text = $"{GlobalText.GetValue("About")} CompactView";
loadSqlMenuItem.Text = $"{GlobalText.GetValue("LoadSqlQuery")}...";
saveSqlMenuItem.Text = $"{GlobalText.GetValue("SaveSqlQuery")}...";
saveSchemaMenuItem.Text = $"{GlobalText.GetValue("SaveSqlSchema")}...";
closeDatabaseMenuItem.Text = GlobalText.GetValue("CloseDatabase");
printMenuItem.Text = $"{GlobalText.GetValue("Print")}...";
previewMenuItem.Text = GlobalText.GetValue("Preview");
}
private DataTable DatabaseInfoLocale(DataTable table)
{
if (table.Columns.Count != 2)
return table;
table.Columns[0].ColumnName = GlobalText.GetValue("Property");
table.Columns[1].ColumnName = GlobalText.GetValue("Value");
foreach (DataRow row in table.Rows)
{
string key = row[0].ToString().Replace(" ", string.Empty);
string s = GlobalText.GetValue(key);
if (!string.IsNullOrEmpty(s))
row[0] = s;
if (key == "CaseSensitive")
{
s = GlobalText.GetValue(row[1].ToString());
if (!string.IsNullOrEmpty(s))
row[1] = s;
}
}
return table;
}
private void UpdateStatus()
{
btnQuery.Enabled = showEditorMenuItem.Enabled = cutMenuItem.Enabled = copyMenuItem.Enabled = pasteMenuItem.Enabled = db.IsOpen;
btnExecute.Enabled = btnClear.Enabled = executeMenuItem.Enabled = clearMenuItem.Enabled = btnQuery.Enabled && btnQuery.Checked;
closeDatabaseMenuItem.Enabled = exportMenuItem.Enabled = importMenuItem.Enabled = db.IsOpen;
bool queryFocused = btnQuery.Enabled && btnQuery.Checked && rtbQuery.Focused;
btnCut.Enabled = cutMenuItem.Enabled = deleteMenuItem.Enabled = queryFocused && rtbQuery.SelectionLength > 0;
btnCopy.Enabled = copyMenuItem.Enabled = db.IsOpen && (queryFocused || tabControl1.SelectedIndex == 1);
btnPaste.Enabled = pasteMenuItem.Enabled = queryFocused && rtbQuery.CanPaste(DataFormats.GetFormat(DataFormats.Text));
loadSqlMenuItem.Enabled = saveSqlMenuItem.Enabled = btnQuery.Enabled && btnQuery.Checked;
saveSchemaMenuItem.Enabled = db.IsOpen;
printMenuItem.Enabled = previewMenuItem.Enabled = btnCopy.Enabled;
}
/// <summary>
/// Load database without password
/// </summary>
/// <param name="fileName">Database file name</param>
private void LoadDatabase(string fileName)
{
LoadDatabase(fileName, null);
}
/// <summary>
/// Load database with password
/// </summary>
/// <param name="fileName">Database file name</param>
/// <param name="password">Database password</param>
private void LoadDatabase(string fileName, string password)
{
Reset();
try
{
if (!File.Exists(fileName))
throw new Exception($"{GlobalText.GetValue("FileNotFound")}: '{fileName}'");
Cursor = Cursors.WaitCursor;
if (db.Open(fileName, password))
{
Text = string.Concat(formText, " - ", db.FileName);
var allDdls = db.AllAvailableEntireDdls();
rtbDdl.RtfSqlCache.SetRange(allDdls);
// Fill tree with database name and table names
using (_ = treeDb.UpdateSection())
{
treeDb.Nodes.Clear();
TreeNode main = treeDb.Nodes.Add("Database", Path.GetFileNameWithoutExtension(fileName), 0, 0);
foreach (string tableName in db.TableNames)
main.Nodes.Add(tableName, tableName, 1, 1);
main.Expand();
}
treeDb.SelectedNode = treeDb.Nodes[0];
// Show query panel immediately
btnQuery.Checked = true;
UpdateQueryPanelState();
settings.AddToRecentFiles(fileName);
UpdateRecentFilesMenu();
}
else
{
bool badPassword = db.BadPassword;
Reset();
if (badPassword)
{
var form = new GetPassForm();
if (form.ShowDialog() == DialogResult.OK)
LoadDatabase(fileName, form.edPass.Text.Trim());
}
}
}
catch (Exception ex)
{
GlobalText.ShowError("UnableToOpen", ex.Message);
btnQuery.Enabled = btnExecute.Enabled = btnClear.Enabled = false;
settings.RecentFiles.Remove(fileName);
UpdateRecentFilesMenu();
}
Cursor = Cursors.Default;
UpdateStatus();
}
/// <summary>
/// Reset components and close database connection
/// </summary>
private void Reset()
{
dataGrid.DataSource = null;
db.Close();
treeDb.Nodes.Clear();
rtbDdl.Clear();
rtbQuery.Clear();
btnQuery.Checked = btnQuery.Enabled = btnExecute.Enabled = btnClear.Enabled = importMenuItem.Enabled =
exportMenuItem.Enabled = saveSchemaMenuItem.Enabled = saveSqlMenuItem.Enabled = closeDatabaseMenuItem.Enabled =
loadSqlMenuItem.Enabled = printMenuItem.Enabled = previewMenuItem.Enabled = false;
splitterHorizontal.Panel1Collapsed = splitterHorizontal.IsSplitterFixed = true;
Text = formText;
tabControl1.SelectedIndex = 0;
}
/// <summary>
/// Update the TreeDb to show all tables of the database
/// </summary>
private void UpdateTreeDb()
{
string selected = treeDb.SelectedNode == null ? string.Empty : treeDb.SelectedNode.Text;
if (treeDb.SelectedNode == treeDb.Nodes[0])
selected = string.Empty;
var mainNode = treeDb.Nodes[0];
using (_ = treeDb.UpdateSection())
{
mainNode.Nodes.Clear();
foreach (string tableName in db.TableNames)
mainNode.Nodes.Add(tableName, tableName, 1, 1);
mainNode.Expand();
}
treeDb.SelectedNode = null;
if (!string.IsNullOrEmpty(selected))
{
int i = mainNode.Nodes.IndexOfKey(selected);
if (i >= 0)
treeDb.SelectedNode = mainNode.Nodes[i];
}
else
{
treeDb.SelectedNode = treeDb.Nodes[0];
}
}
private Bitmap CreateBmp(string text, IntPtr handle, Font font, Color foreColor)
{
var g = Graphics.FromHwnd(handle);
var size = g.MeasureString(text, font).ToSize();
var bmp = new Bitmap(size.Width, size.Height, g);
g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.AntiAlias;
g.DrawString(text, font, new SolidBrush(foreColor), 0, 0);
g.Flush();
return (bmp);
}
private Image CreatePng(string text, IntPtr handle, Font font, Color foreColor)
{
var g = Graphics.FromHwnd(handle);
var size = g.MeasureString(text, font).ToSize();
var bmp = new Bitmap(size.Width, size.Height, g);
g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.AntiAlias;
g.DrawString(text, font, new SolidBrush(foreColor), 0, 0);
g.Flush();
var ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Png);
bmp.Dispose();
return Image.FromStream(ms);
}
private void btnOpen_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
LoadDatabase(openFileDialog1.FileName);
}
private void UpdateQueryPanelState()
{
splitterHorizontal.Panel1Collapsed = splitterHorizontal.IsSplitterFixed = !btnQuery.Checked;
showEditorMenuItem.Checked = btnQuery.Checked;
rtbQuery.Select();
UpdateStatus();
}
private void btnQuery_Click(object sender, EventArgs e)
{
UpdateQueryPanelState();
}
private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
SaveSettings();
}
private void treeDb_MouseDown(object sender, MouseEventArgs e)
{
var hitTest = treeDb.HitTest(e.X, e.Y);
treeDb.SelectedNode = hitTest.Node;
}
private void treeDb_AfterSelect(object sender, TreeViewEventArgs e)
{
if (!db.IsOpen)
return;
using (_ = dataGrid.LayoutSuspension())
{
if (e.Node.ImageIndex == 0)
{
// Database node
dataGrid.ReadOnly = true;
dataGrid.DataSource = DatabaseInfoLocale(db.DatabaseInfo);
rtbDdl.SqlString = db.GetDatabaseDdlSql();
}
else
{
// Table node
dataGrid.ReadOnly = cbReadOnly.SelectedIndex == 0;
dataGrid.Columns.Clear();
var tableDdl = db.GetTableDdl(e.Node.Name);
if (tabControl1.SelectedIndex == 0)
{
dataGrid.DataSource = db.GetTableData(e.Node.Text, null, SortOrder.None);
rtbDdl.SqlString = tableDdl;
}
else
{
rtbDdl.SqlString = tableDdl;
dataGrid.DataSource = db.GetTableData(e.Node.Text, null, SortOrder.None);
}
}
dataGrid.AllowUserToAddRows = dataGrid.AllowUserToDeleteRows = !dataGrid.ReadOnly;
}
}
private void dataGrid_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
// Error when show/edit field
GlobalText.ShowError("ChangingDataError", e.Exception.Message);
e.Cancel = true;
}
private void dataGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
// Double click to switch row height
if (dataGrid.CurrentRow.Height == dataGrid.RowTemplate.Height)
dataGrid.AutoResizeRow(dataGrid.CurrentCell.RowIndex, DataGridViewAutoSizeRowMode.AllCells);
else
dataGrid.CurrentRow.Height = dataGrid.RowTemplate.Height;
}
private void mainForm_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyData)
{
// On F5 key press, execute the query
case Keys.F5:
if (rtbQuery.Focused)
{
ExecuteQuery(true);
}
break;
}
}
private void btnExecute_Click(object sender, EventArgs e)
{
ExecuteQuery(true);
}
private void ExecuteQuery(bool shouldWarnPartialSelection)
{
bool isEmptySql = string.IsNullOrWhiteSpace(rtbQuery.Text);
if (isEmptySql)
return;
bool isPartialSelection = !string.IsNullOrWhiteSpace(rtbQuery.SelectedText);
shouldWarnPartialSelection &= isPartialSelection
&& !settings.OmitSelectedTextExecutionPopup;
if (shouldWarnPartialSelection)
{
DialogResult result = MessageBox.Show(GlobalText.GetValue("SelectedTextQuery"), GlobalText.GetValue("Confirm"),
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
if (result == DialogResult.Cancel)
return;
isPartialSelection = result == DialogResult.Yes;
}
string sql = isPartialSelection
? rtbQuery.SelectedText.Trim()
: rtbQuery.Text.Trim();
dataGrid.DataSource = null;
// Initial time
DateTime initTime = DateTime.Now;
object resultSet = db.ExecuteSql(sql, false);
long ms = (long)(DateTime.Now - initTime).TotalMilliseconds;
dataGrid.DataSource = resultSet;
if (resultSet != null || string.IsNullOrEmpty(db.LastError))
{
lbResult.ForeColor = Color.Black;
lbResult.Text = $"{db.QueryCount} {GlobalText.GetValue("Queries")}, {dataGrid.RowCount} {GlobalText.GetValue("Rows")}, {ms} {GlobalText.GetValue("Milliseconds")}";
if (resultSet == null && regexCreateAlterDrop.IsMatch(regexDropQuotesAndBrackets.Replace(rtbQuery.Text, string.Empty)))
{
db.RebuildDdl();
UpdateTreeDb();
}
else
{
tabControl1.SelectedIndex = 0;
if (resultSet == null && regexInsertUpdateDelete.IsMatch(regexDropQuotesAndBrackets.Replace(rtbQuery.Text, string.Empty)))
{
TreeNode node = treeDb.SelectedNode; // Update data view
treeDb.SelectedNode = null;
treeDb.SelectedNode = node;
}
}
}
else
{
lbResult.ForeColor = Color.Red;
lbResult.Text = db.LastError;
}
}
private void btnClear_Click(object sender, EventArgs e)
{
rtbQuery.Clear();
lbResult.Text = string.Empty;
}
private void cbReadOnly_SelectedIndexChanged(object sender, EventArgs e)
{
TreeNode node = treeDb.SelectedNode;
if (node != null && node.ImageIndex == 1)
treeDb_AfterSelect(treeDb, new TreeViewEventArgs(node));
allowEditingMenuItem.Checked = cbReadOnly.SelectedIndex == 1;
}
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl1.SelectedIndex == 0)
dataGrid.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
UpdateStatus();
}
private void timer1_Tick(object sender, EventArgs e)
{
// Runs only once when the application just finish of display the form
timer1.Stop();
// Initialize regex
regexDropQuotesAndBrackets.Match(string.Empty);
regexCreateAlterDrop.Match(string.Empty);
regexInsertUpdateDelete.Match(string.Empty);
}
private void rtbDdl_Click(object sender, EventArgs e)
{
// If the query is enabled, clicking on the fields are added to the query
if (!btnQuery.Checked)
return;
char c = ' ';
int start = rtbDdl.SelectionStart;
if (start >= rtbDdl.Text.Length)
start = rtbDdl.Text.Length - 1;
while (start >= 0 && (c = rtbDdl.Text[start]) != '[')
if (c == ']' || c == (char)10)
break;
else
start--;
if (c != '[')
return;
int stop = start;
while (stop < rtbDdl.Text.Length && (c = rtbDdl.Text[stop]) != ']')
if (c == (char)10)
break;
else
stop++;
if (c != ']')
return;
rtbDdl.SelectionStart = start;
rtbDdl.SelectionLength = stop - start + 1;
InsertIntoQuery(rtbDdl.SelectedText);
}
private void InsertIntoQuery(string text)
{
rtbQuery.SelectedText = text;
rtbQuery.Focus();
}
private void MainForm_Shown(object sender, EventArgs e)
{
Application.DoEvents();
// Open the database file if specified on the command line
string[] cmdLine = Environment.GetCommandLineArgs();
if (cmdLine.Length > 1 && !string.IsNullOrEmpty(cmdLine[1]))
LoadDatabase(Path.GetFullPath(cmdLine[1]));
}
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
bool onQuery = (sender as ContextMenuStrip).SourceControl == rtbQuery;
cutToolStripMenuItem.Visible = pasteToolStripMenuItem.Visible = loadFromFileToolStripMenuItem.Visible = onQuery;
cutToolStripMenuItem.Enabled = rtbQuery.SelectionLength > 0;
pasteToolStripMenuItem.Enabled = rtbQuery.CanPaste(DataFormats.GetFormat(DataFormats.Text));
}
private void loadFromFileToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog2.ShowDialog() != DialogResult.OK)
return;
rtbQuery.LoadFile(openFileDialog2.FileName, RichTextBoxStreamType.PlainText);
}
private void saveToFileToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() != DialogResult.OK)
return;
bool onQuery = ((sender as ToolStripMenuItem).Owner as ContextMenuStrip).SourceControl == rtbQuery;
RichTextBox rtb = onQuery ? rtbQuery : rtbDdl;
bool all = rtb.SelectionLength == 0;
var writer = new StreamWriter(saveFileDialog1.FileName, false, Encoding.UTF8);
writer.Write(all ? rtb.Text : rtb.SelectedText);
writer.Close();
}
private void dataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0)
{ // Cell is row header, therefore should be select the entire row
dataGrid.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2;
bool readOnly = dataGrid.ReadOnly;
dataGrid.ReadOnly = true;
dataGrid.ReadOnly = readOnly;
}
else
{ // Normal cell
dataGrid.EditMode = DataGridViewEditMode.EditOnEnter;
}
}
private void aboutCompactViewMenuItem_Click(object sender, EventArgs e)
{
new AboutBox1().ShowDialog();
}
private void exitMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void databaseToolsMenuItem_Click(object sender, EventArgs e)
{
string sFilename = db.FileName;
string sPassword = db.Password;
Reset();
UpdateStatus();
new ToolsForm(sFilename, sPassword).ShowDialog();
}
private void optionsMenuItem_Click(object sender, EventArgs e)
{
if (new OptionsForm(dataGrid, settings).ShowDialog() != DialogResult.OK)
return;
}
private void exportMenuItem_Click(object sender, EventArgs e)
{
new ExportForm(db, treeDb.SelectedNode).ShowDialog();
}
private void allowEditingMenuItem_Click(object sender, EventArgs e)
{
allowEditingMenuItem.Checked = !allowEditingMenuItem.Checked;
cbReadOnly.SelectedIndex = allowEditingMenuItem.Checked ? 1 : 0;
}
private void showEditorMenuItem_Click(object sender, EventArgs e)
{
btnQuery.Checked = !btnQuery.Checked;
showEditorMenuItem.Checked = btnQuery.Checked;
btnQuery_Click(null, null);
}
private void rtbQuery_Enter_Leave_SelectionChanged(object sender, EventArgs e)
{
UpdateStatus();
}
private void rtbQuery_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyData)
{
case Keys.Enter | Keys.Control:
// Only select the text around the current statement
if (rtbQuery.SelectionLength == 0)
{
SelectCurrentStatementAroundCursor();
}
ExecuteQuery(false);
e.Handled = true;
break;
}
}
private void SelectCurrentStatementAroundCursor()
{
int selectedIndex = rtbQuery.SelectionStart;
if (selectedIndex >= rtbQuery.Text.Length)
selectedIndex = rtbQuery.Text.Length - 1;
var statements = db.GetSqlStatements(rtbQuery.Text).ToArray();
// The statements are always ordered in ascending index of occurrence
// As a result, this simple traversal suffices for preserving the order
foreach (var statement in statements)
{
bool shouldSelect = ShouldSelectStatement(statement, selectedIndex);
if (shouldSelect)
{
SelectStatement(statement);
return;
}
}
if (statements.Length > 0)
{
var lastStatement = statements.Last();
SelectStatement(lastStatement);
}
}
private void SelectStatement(Match statement)
{
string sql = statement.Value;
int startIndex = Math.Max(0, IndexOfNonWhitespace(sql));
int endIndex = Math.Min(sql.Length - 1, LastIndexOfNonWhitespace(sql));
int length = endIndex - startIndex + 1;
rtbQuery.Select(statement.Index + startIndex, length);
}
private static int IndexOfNonWhitespace(string text)
{
int index = 0;
while (index < text.Length)
{
if (!char.IsWhiteSpace(text[index]))
{
return index;
}
index++;
}
return -1;
}
private static int LastIndexOfNonWhitespace(string text)
{
int index = text.Length - 1;
while (index >= 0)
{
if (!char.IsWhiteSpace(text[index]))
{
return index;
}
index--;
}
return -1;
}
private static bool ShouldSelectStatement(Match statement, int selectedIndex)
{
if (statement.Index > selectedIndex)
return true;
var statementEndIndex = statement.Index + statement.Length + 1;
return statement.Index <= selectedIndex
&& selectedIndex <= statementEndIndex;
}
private void btnCut_Click(object sender, EventArgs e)
{
rtbQuery.Cut();
}
private void btnCopy_Click(object sender, EventArgs e)
{
bool queryFocused = btnQuery.Enabled && btnQuery.Checked && rtbQuery.Focused;
RichTextBox rtb = queryFocused ? rtbQuery : rtbDdl;
bool all = rtb.SelectionLength == 0;
if (all)
rtb.SelectAll();
rtb.Copy();
if (all)
rtb.DeselectAll();
}
private void btnPaste_Click(object sender, EventArgs e)
{
rtbQuery.Paste(DataFormats.GetFormat(DataFormats.Text));
}
private void deleteMenuItem_Click(object sender, EventArgs e)
{
rtbQuery.SelectedText = string.Empty;
}
private bool queryPrint = false;
private void previewMenuItem_Click(object sender, EventArgs e)
{
queryPrint = btnQuery.Enabled && btnQuery.Checked && rtbQuery.Focused;
RichTextBox rtb = queryPrint ? rtbQuery : rtbDdl;
rtb.Print(PrintType.PrintPreview);
}
private void printMenuItem_Click(object sender, EventArgs e)
{
queryPrint = btnQuery.Enabled && btnQuery.Checked && rtbQuery.Focused;
RichTextBox rtb = queryPrint ? rtbQuery : rtbDdl;
rtb.Print(PrintType.ShowPrintDialog);
}
private void loadSqlMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog2.ShowDialog() != DialogResult.OK)
return;
rtbQuery.Text = File.ReadAllText(openFileDialog2.FileName);
}
private void saveSqlMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() != DialogResult.OK)
return;
bool all = rtbQuery.SelectionLength == 0;
TextWriter writer = new StreamWriter(saveFileDialog1.FileName, false, Encoding.UTF8);
writer.Write(all ? rtbQuery.Text : rtbQuery.SelectedText);
writer.Close();
}
private void saveSchemaMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() != DialogResult.OK)
return;
bool all = rtbDdl.SelectionLength == 0;
TextWriter writer = new StreamWriter(saveFileDialog1.FileName, false, Encoding.UTF8);
writer.Write(all ? rtbDdl.Text : rtbDdl.SelectedText);
writer.Close();
}
private void closeDatabaseMenuItem_Click(object sender, EventArgs e)
{
Reset();
}
private void importMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
if (new ImportForm(db, openFileDialog2.FileName).ShowDialog() == DialogResult.OK)
{
db.ResetDdl(); // Update DDL
UpdateTreeDb();
}
}
}
private int GetOleHeaderPos(byte[] bytes)
{
const string BITMAP_ID_BLOCK = "BM";
const string JPG_ID_BLOCK = "\u00FF\u00D8\u00FF";
const string PNG_ID_BLOCK = "\u0089PNG\r\n\u001a\n";
const string GIF_ID_BLOCK = "GIF8";
const string TIFF_ID_BLOCK = "II*\u0000";
int length = bytes.Length;
if (length > 300)
length = 300;
string s = Encoding.UTF7.GetString(bytes, 0, length);
if (s.Length > 300)
s = s.Remove(300);
int i = s.IndexOf(BITMAP_ID_BLOCK);
if (i >= 0)
return i;
i = s.IndexOf(JPG_ID_BLOCK);
if (i >= 0)
return i;
i = s.IndexOf(PNG_ID_BLOCK);
if (i >= 0)
return i;
i = s.IndexOf(GIF_ID_BLOCK);
if (i >= 0)
return i;
i = s.IndexOf(TIFF_ID_BLOCK);
if (i >= 0)
return i;
return 0;
}
private Image GetImage(byte[] bytes)
{
try
{
int i = GetOleHeaderPos(bytes);
Image image;
using (var ms = new MemoryStream(bytes, i, bytes.Length - i))
image = Image.FromStream(ms);
return image;
}
catch (ArgumentException)
{
return null;
}
}
private void dataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGrid.Columns[e.ColumnIndex].ValueType != typeof(byte[]))
return;
object val = e.Value;
if (val != null && val.GetType() == typeof(byte[]) && ((byte[])val).Length > 0)
{
if (GetImage((byte[])val) != null)
return;
int length = ((byte[])val).Length;
string s = string.Empty;
if (length > 100)
{
length = 100;
s = "...";
}
e.Value = CreatePng(BitConverter.ToString((byte[])val, 0, length) + s, dataGrid.Handle, e.CellStyle.Font, e.CellStyle.ForeColor);
}
else
{
e.Value = CreatePng(" ", dataGrid.Handle, e.CellStyle.Font, e.CellStyle.ForeColor);
}
e.FormattingApplied = true;
}
private void dataGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCell cell = dataGrid[e.ColumnIndex, e.RowIndex];
if (cell.ValueType == typeof(string) && cell.Value == DBNull.Value)
dataGrid[e.ColumnIndex, e.RowIndex].Value = string.Empty;
}
private void copyToolStripMenuItem1_Click(object sender, EventArgs e)
{
if (dataGrid.SelectedCells.Count != 1)
return;
object val = dataGrid.SelectedCells[0].Value;
Type t = dataGrid.SelectedCells[0].ValueType;
if (t == typeof(byte[]))
{
Image image = GetImage((byte[])val);
if (image == null)
Clipboard.SetText($"0x{BitConverter.ToString((byte[])val).Replace("-", string.Empty)}");
else
Clipboard.SetImage(image);
}
else
{
Clipboard.SetText(val.ToString());
}
}
private void dataGrid_MouseDown(object sender, MouseEventArgs e)
{
var hit = dataGrid.HitTest(e.X, e.Y);
switch (hit.Type)
{
case DataGridViewHitTestType.Cell:
{
dataGrid.ContextMenuStrip = dataGridMenuStrip;
dataGrid.CurrentCell = dataGrid[hit.ColumnIndex, hit.RowIndex];
foreach (DataGridViewCell cell in dataGrid.SelectedCells)
if (cell != dataGrid.CurrentCell)
cell.Selected = false;
break;
}
case DataGridViewHitTestType.ColumnHeader:
case DataGridViewHitTestType.TopLeftHeader:
UpdateEnabledOptionsColumnHeaderMenuStrip(hit.Type);
dataGrid.ContextMenuStrip = columnHeaderMenuStrip;
break;