**** Merged from MCS ****
[mono-project.git] / mcs / tools / SqlSharp / gui / gtk-sharp / sqlsharpgtk.cs
blobbb5fd6505b9f3bedc613f3b4a0e1a766a4177f49
1 //
2 // SqlSharpGtk - Mono SQL# For GTK# - SQL Query and Configuration tool for
3 // Mono.Data providers
4 //
5 // Author:
6 // Daniel Morgan <danielmorgan@verizon.net>
7 //
8 // (C)Copyright 2002, 2003 by Daniel Morgan
9 //
10 // To be included with Mono as a SQL query tool licensed under the GPL license.
13 namespace Mono.Data.SqlSharp.Gui.GtkSharp
15 using System;
16 using System.Collections;
17 using System.Data;
18 using System.Data.Common;
19 using System.Data.Odbc;
20 using System.Data.OleDb;
21 using System.Data.SqlClient;
22 using System.Drawing;
23 using System.Text;
24 using System.IO;
25 using System.Reflection;
26 using System.Runtime.Remoting;
27 using System.Runtime.InteropServices;
28 using System.Diagnostics;
30 using Gdk;
31 using Gtk;
32 using GtkSharp;
34 using Mono.GtkSharp.Goodies;
36 using Gtk.Controls;
38 using SqlEditorSharp;
40 public enum OutputResults
42 TextView,
43 DataGrid
46 public enum ExecuteOutputType
48 Normal,
49 XmlFile,
50 HtmlFile,
51 CsvFile
54 public class EditorTab
56 public SqlEditorSharp editor;
57 public Label label;
58 public string filename;
59 public string basefilename;
60 public int page;
63 public class SqlSharpGtk
65 static int SqlWindowCount = 0;
67 private IDbConnection conn = null;
68 public DbProvider dbProvider = null;
69 private Type connectionType = null;
70 private Type adapterType = null;
71 public Assembly providerAssembly = null;
72 public string connectionString = "";
74 private Statusbar statusBar;
75 private Toolbar toolbar;
77 int lastUnknownFile = 0;
79 // OutputResults
80 private VBox outbox;
81 // OutputResults.TextView
82 private ScrolledWindow swin;
83 public TextBuffer buf;
84 private TextView textView;
85 private TextTag textTag;
86 // OutputResults.DataGrid
87 private DataGrid grid;
89 private Gtk.Window win;
91 public static readonly string ApplicationName = "Mono SQL# For GTK#";
93 private OutputResults outputResults;
95 public DbProviderCollection providerList;
96 Notebook sourceFileNotebook;
97 Notebook resultsNotebook;
98 ArrayList editorTabs = new ArrayList();
100 public SqlSharpGtk ()
102 CreateGui ();
103 SqlWindowCount ++;
104 LoadProviders ();
107 public void Show ()
109 win.ShowAll ();
112 public void CreateGui()
114 win = new Gtk.Window (ApplicationName);
115 win.DeleteEvent += new GtkSharp.DeleteEventHandler(OnWindow_Delete);
116 win.BorderWidth = 4;
117 win.DefaultSize = new Size (450, 300);
119 VBox vbox = new VBox (false, 4);
120 win.Add (vbox);
122 // Menu Bar
123 MenuBar mb = CreateMenuBar ();
124 vbox.PackStart(mb, false, false, 0);
126 // Tool Bar
127 toolbar = CreateToolbar ();
128 vbox.PackStart (toolbar, false, false, 0);
130 // Panels
131 VPaned paned = new VPaned ();
132 vbox.PackStart (paned, true, true, 0);
134 // SQL Editor (top TextView panel)
135 sourceFileNotebook = new Notebook();
136 sourceFileNotebook.Scrollable = true;
137 NewEditorTab();
138 paned.Add1 (sourceFileNotebook);
139 sourceFileNotebook.SwitchPage += new
140 GtkSharp.SwitchPageHandler(OnEditorTabSwitched);
142 // bottom panel
143 resultsNotebook = CreateOutputResultsGui ();
144 paned.Add2 (resultsNotebook);
146 statusBar = new Statusbar ();
147 vbox.PackEnd (statusBar, false, false, 0);
149 outputResults = OutputResults.TextView;
150 ToggleResultsOutput ();
153 EditorTab NewEditorTab ()
155 SqlEditorSharp editor;
156 editor = new SqlEditorSharp ();
157 editor.UseSyntaxHiLighting = true;
158 editor.View.Show ();
159 editor.View.KeyPressEvent +=
160 new GtkSharp.KeyPressEventHandler(OnKeyPressEventKey);
162 lastUnknownFile ++;
163 string unknownFile = "Unknown" +
164 lastUnknownFile.ToString() + ".sql";
165 Label label = new Label(unknownFile);
166 label.Show();
167 sourceFileNotebook.AppendPage(editor, label);
168 sourceFileNotebook.ShowAll ();
169 sourceFileNotebook.ResizeChildren ();
171 sourceFileNotebook.CurrentPage = -1;
173 EditorTab tab = new EditorTab();
174 tab.editor = editor;
175 tab.label = label;
176 tab.filename = "";
177 tab.basefilename = unknownFile;
178 tab.page = sourceFileNotebook.CurrentPage;
179 editorTabs.Add(tab);
180 editor.Tab = tab;
181 UpdateTitleBar(tab);
183 return tab;
186 // bottom panel
187 Notebook CreateOutputResultsGui ()
189 Label label;
190 Notebook results = new Notebook();
191 results.TabPos = PositionType.Bottom;
193 grid = CreateOutputResultsDataGrid ();
194 grid.Show();
195 label = new Label("Grid");
196 results.AppendPage(grid, label);
198 swin = CreateOutputResultsTextView ();
199 swin.Show();
200 label = new Label("Log");
201 results.AppendPage(swin, label);
203 sourceFileNotebook.ShowAll ();
204 sourceFileNotebook.ResizeChildren ();
206 return results;
210 DataGrid CreateOutputResultsDataGrid ()
212 return new DataGrid ();
215 ScrolledWindow CreateOutputResultsTextView ()
217 ScrolledWindow sw;
218 sw = new ScrolledWindow (
219 new Adjustment (0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
220 new Adjustment (0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
221 sw.HscrollbarPolicy = Gtk.PolicyType.Automatic;
222 sw.VscrollbarPolicy = Gtk.PolicyType.Automatic;
223 sw.ShadowType = Gtk.ShadowType.In;
225 textView = new TextView ();
226 buf = textView.Buffer;
227 textView.Editable = false;
228 textView.ModifyFont (Pango.FontDescription.FromString ("courier new"));
229 sw.Add (textView);
231 return sw;
234 void OnKeyPressEventKey(object o, GtkSharp.KeyPressEventArgs args)
236 if (o is TextView) {
237 TextView tv = (TextView) o;
238 //Gdk.EventKey k = args.Event;
240 // if the F5 key was pressed
241 if (args.Event.keyval == 0xFFC2) {
242 if (tv.Editable == true) {
243 // execute SQL
244 ExecuteSQL (ExecuteOutputType.Normal, "");
250 Toolbar CreateToolbar ()
252 Toolbar toolbar = new Toolbar ();
254 toolbar.ToolbarStyle = ToolbarStyle.Icons;
256 toolbar.AppendItem ("Execute",
257 "Execute SQL Commands.", String.Empty,
258 new Gtk.Image (Stock.Execute, IconSize.SmallToolbar),
259 new Gtk.SignalFunc (OnToolbar_Execute));
261 toolbar.AppendItem ("DataGrid",
262 "Toggle Results to DataGrid or TextView", String.Empty,
263 new Gtk.Image (Stock.GoDown, IconSize.SmallToolbar),
264 new Gtk.SignalFunc (OnToolbar_ToggleResultsOutput));
266 return toolbar;
269 // TODO: use the ProviderFactory in Mono.Data
270 // to load providers
271 // instead of what's below
272 public void LoadProviders ()
274 providerList = new DbProviderCollection ();
276 providerList.Add (new DbProvider (
277 "MYSQL",
278 "MySQL (Mono)",
279 "Mono.Data.MySql",
280 "Mono.Data.MySql.MySqlConnection",
281 "Mono.Data.MySql.MySqlDataAdapter",
282 false ));
283 providerList.Add (new DbProvider (
284 "MYSQLNET",
285 "MySQL (ByteFX)",
286 "ByteFX.Data",
287 "ByteFX.Data.MySQLClient.MySQLConnection",
288 "ByteFX.Data.MySQLClient.MySQLDataAdapter",
289 false ));
290 providerList.Add (new DbProvider (
291 "POSTGRESQL",
292 "PostgreSQL (Mono)",
293 "Mono.Data.PostgreSqlClient",
294 "Mono.Data.PostgreSqlClient.PgSqlConnection",
295 "Mono.Data.PostgreSqlClient.PgSqlDataAdapter",
296 false ));
297 providerList.Add (new DbProvider (
298 "NPGSQL",
299 "PostgreSQL (Npgsql)",
300 "Npgsql",
301 "Npgsql.NpgsqlConnection",
302 "Npgsql.NpgsqlDataAdapter",
303 false ));
304 providerList.Add (new DbProvider (
305 "SQLCLIENT",
306 "Microsoft SQL Server",
310 true ));
311 providerList.Add (new DbProvider (
312 "TDS",
313 "TDS Generic",
314 "Mono.Data.TdsClient",
315 "Mono.Data.TdsClient.TdsConnection",
316 "Mono.Data.TdsClient.TdsDataAdapter",
317 false ));
318 providerList.Add (new DbProvider (
319 "ODBC",
320 "ODBC",
324 true ));
325 providerList.Add (new DbProvider (
326 "OLEDB",
327 "OLE DB",
331 true ));
332 providerList.Add (new DbProvider (
333 "SQLITE",
334 "SQL Lite",
335 "Mono.Data.SqliteClient",
336 "Mono.Data.SqliteClient.SqliteConnection",
337 "Mono.Data.SqliteClient.SqliteDataAdapter",
338 false ));
339 providerList.Add (new DbProvider (
340 "SYBASE",
341 "Sybase",
342 "Mono.Data.SybaseClient",
343 "Mono.Data.SybaseClient.SybaseConnection",
344 "Mono.Data.SybaseClient.SybaseDataAdapter",
345 false ));
346 providerList.Add (new DbProvider (
347 "DB2",
348 "IBM DB2",
349 "Mono.Data.DB2Client",
350 "Mono.Data.DB2Client.DB2ClientConnection",
351 "Mono.Data.DB2Client.DB2ClientDataAdapter",
352 false ));
353 providerList.Add (new DbProvider (
354 "ORACLE",
355 "Oracle",
356 "System.Data.OracleClient",
357 "System.Data.OracleClient.OracleConnection",
358 "System.Data.OracleClient.OracleDataAdapter",
359 false ));
362 public MenuBar CreateMenuBar ()
364 MenuBar menuBar = new MenuBar ();
365 Menu menu;
366 Menu submenu;
367 MenuItem item;
368 MenuItem barItem;
369 MenuItem subitem;
371 // File menu
372 menu = new Menu ();
374 item = new MenuItem ("New SQL# _Window");
375 item.Activated += new EventHandler (OnMenu_FileNewSqlWindow);
376 menu.Append (item);
378 menu.Append (new SeparatorMenuItem ());
380 item = new MenuItem ("_New");
381 item.Activated += new EventHandler (OnMenu_FileNew);
382 menu.Append (item);
384 item = new MenuItem ("_Open...");
385 item.Activated += new EventHandler (OnMenu_FileOpen);
386 menu.Append (item);
388 item = new MenuItem ("_Save");
389 item.Activated += new EventHandler (OnMenu_FileSave);
390 menu.Append (item);
392 item = new MenuItem ("Save _As...");
393 item.Activated += new EventHandler (OnMenu_FileSaveAs);
394 menu.Append (item);
396 item = new MenuItem ("Close");
397 item.Activated += new EventHandler (OnMenu_FileClose);
398 menu.Append (item);
400 menu.Append (new SeparatorMenuItem ());
402 // TODO: submenu Save Output
403 submenu = new Menu ();
404 subitem = new MenuItem ("CSV - Comma Separated Values");
405 //subitem.Activated += new EventHandler (OnMenu_FileSaveOutput_CSV);
406 submenu.Append(subitem);
407 subitem = new MenuItem ("TAB - Tab Separated Values");
408 //subitem.Activated += new EventHandler (OnMenu_FileSaveOutput_TAB);
409 submenu.Append(subitem);
410 subitem = new MenuItem ("XML");
411 //subitem.Activated += new EventHandler (OnMenu_FileSaveOutput_XML);
412 submenu.Append(subitem);
414 item = new MenuItem ("Save _Output...");
415 item.Submenu = submenu;
416 menu.Append (item);
418 menu.Append (new SeparatorMenuItem ());
420 item = new MenuItem ("E_xit");
421 item.Activated += new EventHandler (OnMenu_FileExit);
422 menu.Append (item);
424 barItem = new MenuItem ("_File");
425 barItem.Submenu = menu;
426 menuBar.Append (barItem);
428 // Edit menu
430 menu = new Menu ();
432 item = new MenuItem ("_Undo");
433 //item.Activated += new EventHandler (OnMenu_EditUndo);
434 menu.Append (item);
436 item = new MenuItem ("_Redo");
437 //item.Activated += new EventHandler (OnMenu_EditRedo);
438 menu.Append (item);
440 menu.Append (new SeparatorMenuItem ());
442 item = new MenuItem ("Cu_t");
443 //item.Activated += new EventHandler (OnMenu_EditCut);
444 menu.Append (item);
446 item = new MenuItem ("_Copy");
447 //item.Activated += new EventHandler (OnMenu_EditCopy);
448 menu.Append (item);
450 item = new MenuItem ("_Paste");
451 //item.Activated += new EventHandler (OnMenu_EditPaste);
452 menu.Append (item);
454 item = new MenuItem ("_Delete");
455 //item.Activated += new EventHandler (OnMenu_EditDelete);
456 menu.Append (item);
458 menu.Append (new SeparatorMenuItem ());
460 item = new MenuItem ("_Find and Replace...");
461 //item.Activated += new EventHandler (OnMenu_EditFindReplace);
462 menu.Append (item);
464 menu.Append (new SeparatorMenuItem ());
466 item = new MenuItem ("_Options");
467 //item.Activated += new EventHandler (OnMenu_EditOptions);
468 menu.Append (item);
470 barItem = new MenuItem ("_Edit");
471 barItem.Submenu = menu;
472 menuBar.Append (barItem);
474 // Session menu
475 menu = new Menu ();
477 item = new MenuItem ("_Connect");
478 item.Activated += new EventHandler (OnMenu_SessionConnect);
479 menu.Append (item);
481 item = new MenuItem ("_Disconnect");
482 item.Activated += new EventHandler (OnMenu_SessionDisconnect);
483 menu.Append (item);
485 barItem = new MenuItem ("_Session");
486 barItem.Submenu = menu;
487 menuBar.Append (barItem);
489 // Command menu
490 menu = new Menu ();
492 item = new MenuItem ("_Execute");
493 item.Activated += new EventHandler (OnMenu_CommandExecute);
494 menu.Append (item);
496 item = new MenuItem ("_Execute With Output to XML");
497 item.Activated += new EventHandler (OnMenu_CommandExecuteXML);
498 menu.Append (item);
500 item = new MenuItem ("_Execute With Output to CSV");
501 item.Activated += new EventHandler (OnMenu_CommandExecuteCSV);
502 menu.Append (item);
504 item = new MenuItem ("_Execute With Output to HTML");
505 item.Activated += new EventHandler (OnMenu_CommandExecuteHTML);
506 menu.Append (item);
508 barItem = new MenuItem ("_Command");
509 barItem.Submenu = menu;
510 menuBar.Append (barItem);
512 return menuBar;
515 void AppendText (string text)
517 AppendText (buf, text);
520 public void AppendTextWithoutScroll (TextBuffer buffer, string text)
522 TextIter iter;
523 text = text.Replace("\0","");
524 buffer.MoveMark(buf.InsertMark, buffer.EndIter);
525 if (text.Equals ("") == false) {
526 iter = buffer.EndIter;
527 buffer.Insert (iter, text);
529 iter = buffer.EndIter;
530 buffer.Insert (iter, "\n");
533 // WriteLine() to output text to bottom TextView
534 // for displaying result sets and logging messages
535 public void AppendText (TextBuffer buffer, string text)
537 AppendTextWithoutScroll(buffer,text);
538 while (Application.EventsPending ())
539 Application.RunIteration ();
540 textView.ScrollToMark (buf.InsertMark, 0.4, true, 0.0, 1.0);
543 public bool LoadExternalProvider (string strProviderAssembly,
544 string providerConnectionClass)
546 try {
547 SqlSharpGtk.DebugWriteLine ("Loading external provider...");
548 providerAssembly = null;
549 providerAssembly = Assembly.Load (strProviderAssembly);
550 Type typ = providerAssembly.GetType (providerConnectionClass);
551 conn = (IDbConnection) Activator.CreateInstance (typ);
553 SqlSharpGtk.DebugWriteLine ("External provider loaded.");
555 catch (Exception f) {
556 string errorMessage = String.Format (
557 "Error: unable to load the assembly of the provider: {1} because: {2}",
558 providerAssembly,
559 f.Message);
560 Error (errorMessage);
561 return false;
563 return true;
566 void QuitApplication()
568 if(conn != null)
569 if(conn.State == ConnectionState.Open) {
570 Console.WriteLine("Closing connection...");
571 conn.Close();
572 conn = null;
573 Console.WriteLine("Connection closed.");
576 if(grid.DataSource != null) {
577 grid.Clear ();
578 grid.DataSource = null;
579 grid.DataMember = "";
580 grid = null;
583 SqlWindowCount --;
584 if(SqlWindowCount == 0)
585 Application.Quit ();
586 else
587 win.Destroy ();
590 void UpdateTitleBar(EditorTab tab)
592 string title = "";
593 if(tab != null) {
594 if(tab.filename.Equals(""))
595 title = tab.label.Text + " - " + ApplicationName;
596 else
597 title = tab.filename + " - " + ApplicationName;
599 else {
600 title = ApplicationName;
602 win.Title = title;
605 void OnEditorTabSwitched (object o, GtkSharp.SwitchPageArgs args)
607 int page = (int) args.PageNum;
608 EditorTab tab = FindEditorTab(page);
609 UpdateTitleBar (tab);
612 void OnWindow_Delete (object o, GtkSharp.DeleteEventArgs args)
614 QuitApplication();
617 void OnExit (Gtk.Object o)
619 QuitApplication();
622 void OnMenu_FileNewSqlWindow (object o, EventArgs args)
624 SqlSharpGtk sqlSharp = new SqlSharpGtk ();
625 sqlSharp.Show ();
628 void OnMenu_FileNew (object o, EventArgs args)
630 NewEditorTab();
631 sourceFileNotebook.CurrentPage = -1;
634 void OnMenu_FileOpen (object o, EventArgs args)
636 FileSelectionDialog openFileDialog =
637 new FileSelectionDialog ("Open File",
638 new FileSelectionEventHandler (OnOpenFile));
641 void OnOpenFile (object o, FileSelectionEventArgs args)
643 EditorTab etab = NewEditorTab();
644 try {
645 etab.editor.LoadFromFile (args.Filename);
647 catch(Exception openFileException) {
648 Error("Error: Could not open file: \n" +
649 args.Filename +
650 "\n\nReason: " +
651 openFileException.Message);
652 return;
654 TextBuffer buf = etab.editor.Buffer;
655 buf.Modified = false;
656 string basefile = Path.GetFileName (args.Filename);
657 etab.label.Text = basefile;
658 etab.basefilename = basefile;
659 etab.filename = args.Filename;
660 sourceFileNotebook.CurrentPage = -1;
661 UpdateTitleBar(etab);
664 EditorTab FindEditorTab (int searchPage)
666 EditorTab tab = null;
667 for (int t = 0; t < editorTabs.Count; t++) {
668 tab = (EditorTab) editorTabs[t];
669 if (tab.page == searchPage)
670 return tab;
672 return tab;
675 void OnMenu_FileSave (object o, EventArgs args)
677 int page = sourceFileNotebook.CurrentPage;
678 EditorTab tab = FindEditorTab(page);
680 if(tab.filename.Equals(""))
681 SaveAs();
682 else {
683 SaveFile(tab.filename);
684 tab.label.Text = tab.basefilename;
688 void SaveFile (string filename)
690 int page = sourceFileNotebook.CurrentPage;
691 EditorTab etab = FindEditorTab(page);
693 try {
694 // FIXME: if file exists, ask if you want to
695 // overwrite. currently, it overwrites
696 // without asking.
697 etab.editor.SaveToFile (filename);
698 } catch(Exception saveFileException) {
699 Error("Error: Could not open file: \n" +
700 filename +
701 "\n\nReason: " +
702 saveFileException.Message);
703 return;
705 TextBuffer buf = etab.editor.Buffer;
706 buf.Modified = false;
709 void OnMenu_FileSaveAs (object o, EventArgs args)
711 SaveAs();
714 void SaveAs()
716 FileSelectionDialog openFileDialog =
717 new FileSelectionDialog ("File Save As",
718 new FileSelectionEventHandler (OnSaveAsFile));
721 void OnSaveAsFile (object o, FileSelectionEventArgs args)
723 int page = sourceFileNotebook.CurrentPage;
724 EditorTab etab = FindEditorTab(page);
726 SaveFile(args.Filename);
728 string basefile = Path.GetFileName (args.Filename);
729 etab.label.Text = basefile;
730 etab.basefilename = basefile;
731 etab.filename = args.Filename;
732 UpdateTitleBar(etab);
735 void OnMenu_FileClose (object o, EventArgs args)
737 CloseEditor();
740 void OnCloseEditor (object obj, EventArgs args)
742 CloseEditor();
745 void CloseEditor ()
747 int page = sourceFileNotebook.CurrentPage;
748 SqlEditorSharp sqlEditor;
749 sqlEditor = (SqlEditorSharp) sourceFileNotebook.GetNthPage(page);
750 TextBuffer buffer = sqlEditor.Buffer;
751 if(buffer.Modified) {
752 // TODO: if text modified,
753 // ask if user wants to save
754 // before closing.
755 // use MessageDialog to prompt
756 RemoveEditorTab (sqlEditor.Tab, page);
758 else {
759 RemoveEditorTab (sqlEditor.Tab, page);
761 sqlEditor = null;
762 buffer = null;
765 void RemoveEditorTab (EditorTab tab, int page)
767 tab.editor.Clear();
768 tab.editor.Tab = null;
769 tab.editor = null;
770 tab.label = null;
771 editorTabs.Remove(tab);
772 sourceFileNotebook.RemovePage (page);
773 sourceFileNotebook.QueueDraw();
774 tab = null;
777 void OnMenu_FileExit (object o, EventArgs args)
779 QuitApplication ();
782 void OnMenu_SessionConnect (object o, EventArgs args)
784 LoginDialog login = new LoginDialog (this);
785 login = null;
788 void OnMenu_SessionDisconnect (object o, EventArgs args)
790 AppendText(buf, "Disconnecting...");
791 try {
792 conn.Close ();
793 conn = null;
795 catch (Exception e) {
796 Error ("Error: Unable to disconnect." +
797 e.Message);
798 conn = null;
799 return;
801 AppendText (buf, "Disconnected.");
804 void OnToolbar_ToggleResultsOutput ()
806 ToggleResultsOutput ();
809 void ToggleResultsOutput ()
811 if (outputResults == OutputResults.TextView) {
812 outputResults = OutputResults.DataGrid;
814 else if (outputResults == OutputResults.DataGrid) {
815 outputResults = OutputResults.TextView;
819 public void OnToolbar_Execute ()
821 ExecuteSQL (ExecuteOutputType.Normal, "");
824 // Execute SQL Commands
825 void ExecuteSQL (ExecuteOutputType outputType, string filename)
827 if (conn == null) {
828 AppendText (buf, "Error: Not Connected.");
829 return;
832 DataTable schemaTable = null;
834 int page = sourceFileNotebook.CurrentPage;
835 EditorTab tab = FindEditorTab(page);
837 string msg = "";
838 string sql = "";
840 IDbCommand cmd;
842 try {
843 cmd = conn.CreateCommand ();
845 catch (Exception ec) {
846 AppendText (buf,
847 "Error: Unable to create command to execute: " +
848 ec.Message);
849 return;
852 SqlSharpGtk.DebugWriteLine ("get text from SQL editor...");
854 // get text from SQL editor
855 try {
856 TextIter start_iter, end_iter;
857 TextBuffer exeBuff;
858 exeBuff = tab.editor.Buffer;
859 start_iter = exeBuff.StartIter;
860 end_iter = exeBuff.EndIter;
861 sql = exeBuff.GetText(start_iter, end_iter, false);
863 catch (Exception et) {
864 AppendText (buf,
865 "Error: Unable to get text from SQL editor: " +
866 et.Message);
867 return;
870 try {
871 cmd.CommandText = sql;
873 catch (Exception e) {
874 AppendText (buf,
875 "Error: Unable to set SQL text to command.");
878 IDataReader reader = null;
879 SqlSharpGtk.DebugWriteLine ("Executing SQL: " + sql);
881 if ((outputResults == OutputResults.TextView &&
882 outputType == ExecuteOutputType.Normal) ||
883 outputType == ExecuteOutputType.HtmlFile ||
884 outputType == ExecuteOutputType.CsvFile) {
886 try {
887 reader = cmd.ExecuteReader ();
889 catch (Exception e) {
890 //msg = "SQL Execution Error: " + e.Message;
891 msg = "SQL Execution Error: " + e;
892 Error (msg);
893 return;
896 if (reader == null) {
897 Error("Error: reader is null");
898 return;
902 try {
903 if (outputResults == OutputResults.TextView &&
904 outputType == ExecuteOutputType.Normal) {
906 DisplayData (reader);
907 // clean up
908 reader.Close ();
909 reader.Dispose ();
910 reader = null;
912 else if(outputType == ExecuteOutputType.HtmlFile) {
913 schemaTable = reader.GetSchemaTable();
914 if(schemaTable != null && reader.FieldCount > 0) {
915 OutputDataToHtmlFile(reader, schemaTable, filename);
917 else {
918 AppendText("Command executed.");
920 // clean up
921 reader.Close ();
922 reader.Dispose ();
923 reader = null;
925 else if(outputType == ExecuteOutputType.CsvFile) {
926 schemaTable = reader.GetSchemaTable();
927 if(schemaTable != null && reader.FieldCount > 0) {
928 OutputDataToCsvFile(reader, schemaTable, filename);
930 else {
931 AppendText("Command executed.");
933 // clean up
934 reader.Close ();
935 reader.Dispose ();
936 reader = null;
938 else {
939 DataTable dataTable = LoadDataTable (cmd);
940 switch(outputType) {
941 case ExecuteOutputType.Normal:
942 AppendText("set DataGrid.DataSource to DataTable...");
943 grid.DataSource = dataTable;
944 AppendText("DataBind...");
945 grid.DataBind ();
946 AppendText("Clean up...");
947 // clean up
948 grid.DataSource = null;
949 break;
950 case ExecuteOutputType.XmlFile:
951 AppendText("Create DataSet...");
952 DataSet dataSet = new DataSet();
953 AppendText("Add DataTable to DataSet's DataTableCollection...");
954 dataSet.Tables.Add(dataTable);
955 AppendText("Write DataSet to XML file: " +
956 filename);
957 dataSet.WriteXml(filename);
958 AppendText("Clean up...");
959 dataSet = null;
960 break;
962 // clean up
963 dataTable.Clear();
964 dataTable.Dispose();
965 dataTable = null;
966 AppendText("Done.");
967 cmd.Dispose();
968 cmd = null;
971 catch (Exception e) {
972 //msg = "Error Displaying Data: " + e.Message;
973 msg = "Error Displaying Data: " + e;
974 Error (msg);
978 public void OutputDataToHtmlFile(IDataReader rdr, DataTable dt, string file)
980 AppendText("Outputting results to HTML file " + file + "...");
981 StreamWriter outputFilestream = null;
982 try {
983 outputFilestream = new StreamWriter(file);
985 catch(Exception e) {
986 Error("Error: Unable to setup output results file. " +
987 e.Message);
988 return;
991 StringBuilder strHtml = new StringBuilder();
993 strHtml.Append("<html>\n<head><title>");
994 strHtml.Append("Results");
995 strHtml.Append("</title></head>\n");
996 strHtml.Append("<body>\n");
997 strHtml.Append("<h1>Results</h1>\n");
998 strHtml.Append("\t<table border=1>\n");
1000 outputFilestream.WriteLine(strHtml.ToString());
1002 strHtml = null;
1003 strHtml = new StringBuilder();
1005 strHtml.Append("\t\t<tr>\n");
1006 for (int c = 0; c < rdr.FieldCount; c++) {
1007 strHtml.Append("\t\t\t<td><b>");
1008 string sColumnName = rdr.GetName(c);
1009 strHtml.Append(sColumnName);
1010 strHtml.Append("</b></td>\n");
1012 strHtml.Append("\t\t</tr>\n");
1013 outputFilestream.WriteLine(strHtml.ToString());
1014 strHtml = null;
1016 int col = 0;
1017 string dataValue = "";
1019 while(rdr.Read()) {
1020 strHtml = new StringBuilder();
1022 strHtml.Append("\t\t<tr>\n");
1023 for(col = 0; col < rdr.FieldCount; col++) {
1025 // column data
1026 if(rdr.IsDBNull(col) == true)
1027 dataValue = "NULL";
1028 else {
1029 object obj = rdr.GetValue(col);
1030 dataValue = obj.ToString();
1032 strHtml.Append("\t\t\t<td>");
1033 strHtml.Append(dataValue);
1034 strHtml.Append("</td>\n");
1036 strHtml.Append("\t\t</tr>\n");
1037 outputFilestream.WriteLine(strHtml.ToString());
1038 strHtml = null;
1040 outputFilestream.WriteLine("\t</table>\n</body>\n</html>\n");
1041 strHtml = null;
1042 outputFilestream.Close();
1043 outputFilestream = null;
1044 AppendText("Outputting file done.");
1047 public void OutputDataToCsvFile(IDataReader rdr, DataTable dt, string file)
1049 AppendText("Outputting results to CSV file " + file + "...");
1050 StreamWriter outputFilestream = null;
1051 try {
1052 outputFilestream = new StreamWriter(file);
1054 catch(Exception e) {
1055 Error("Error: Unable to setup output results file. " +
1056 e.Message);
1057 return;
1060 StringBuilder strCsv = null;
1062 int col = 0;
1063 string dataValue = "";
1065 while(rdr.Read()) {
1066 strCsv = new StringBuilder();
1068 for(col = 0; col < rdr.FieldCount; col++) {
1069 if(col > 0)
1070 strCsv.Append(",");
1072 // column data
1073 if(rdr.IsDBNull(col) == true)
1074 dataValue = "\"\"";
1075 else {
1076 object obj = rdr.GetValue(col);
1077 dataValue = "\"" + obj.ToString() + "\"";
1079 strCsv.Append(dataValue);
1081 outputFilestream.WriteLine(strCsv.ToString());
1082 strCsv = null;
1084 strCsv = null;
1085 outputFilestream.Close();
1086 outputFilestream = null;
1087 AppendText("Outputting file done.");
1090 void OnMenu_CommandExecute (object o, EventArgs args)
1092 ExecuteSQL (ExecuteOutputType.Normal, "");
1095 void OnMenu_CommandExecuteXML (object o, EventArgs args)
1097 ExecuteAndSaveResultsToFile (ExecuteOutputType.XmlFile);
1100 void OnMenu_CommandExecuteCSV (object o, EventArgs args)
1102 ExecuteAndSaveResultsToFile (ExecuteOutputType.CsvFile);
1105 void OnMenu_CommandExecuteHTML (object o, EventArgs args)
1107 ExecuteAndSaveResultsToFile (ExecuteOutputType.HtmlFile);
1110 ExecuteOutputType outType;
1111 void ExecuteAndSaveResultsToFile(ExecuteOutputType oType)
1113 outType = oType;
1114 FileSelectionDialog openFileDialog =
1115 new FileSelectionDialog ("Results File Save As",
1116 new FileSelectionEventHandler (OnSaveExeOutFile));
1119 void OnSaveExeOutFile (object o, FileSelectionEventArgs args)
1121 ExecuteSQL (outType, args.Filename);
1124 public void DisplayResult (IDataReader reader, DataTable schemaTable)
1126 const string zero = "0";
1127 StringBuilder column = null;
1128 StringBuilder line = null;
1129 StringBuilder hdrUnderline = null;
1130 string outData = "";
1131 int hdrLen = 0;
1133 int spacing = 0;
1134 int columnSize = 0;
1135 int c;
1137 char spacingChar = ' '; // a space
1138 char underlineChar = '='; // an equal sign
1140 string dataType; // .NET Type
1141 Type theType;
1142 string dataTypeName; // native Database type
1143 DataRow row; // schema row
1145 line = new StringBuilder ();
1146 hdrUnderline = new StringBuilder ();
1148 try {
1149 OutputLine ("Fields in Query Result: " +
1150 reader.FieldCount);
1152 catch(Exception e){
1153 Error ("Error: Unable to get FieldCount: " +
1154 e.Message);
1155 return;
1158 OutputLine ("");
1160 for(c = 0; c < reader.FieldCount; c++) {
1161 try {
1162 DataRow schemaRow = schemaTable.Rows[c];
1163 string columnHeader = reader.GetName (c);
1164 if (columnHeader.Equals (""))
1165 columnHeader = "column";
1166 if (columnHeader.Length > 32)
1167 columnHeader = columnHeader.Substring (0,32);
1169 // spacing
1170 columnSize = (int) schemaRow["ColumnSize"];
1171 theType = reader.GetFieldType(c);
1172 dataType = theType.ToString();
1173 //dataTypeName = reader.GetDataTypeName(c);
1175 switch(dataType) {
1176 case "System.DateTime":
1177 columnSize = 19;
1178 break;
1179 case "System.Boolean":
1180 columnSize = 5;
1181 break;
1184 hdrLen = Math.Max (columnHeader.Length, columnSize);
1186 if(hdrLen < 0)
1187 hdrLen = 0;
1188 if(hdrLen > 32)
1189 hdrLen = 32;
1191 line.Append(columnHeader);
1192 if(columnHeader.Length < hdrLen) {
1193 spacing = hdrLen - columnHeader.Length;
1194 line.Append(spacingChar, spacing);
1196 hdrUnderline.Append(underlineChar, hdrLen);
1198 line.Append(" ");
1199 hdrUnderline.Append(" ");
1201 catch(Exception e) {
1202 Error ("Error: Unable to display header: " +
1203 e.Message);
1204 return;
1207 OutputHeader(line.ToString());
1208 line = null;
1210 OutputHeader(hdrUnderline.ToString());
1211 OutputHeader("");
1212 hdrUnderline = null;
1214 int numRows = 0;
1216 // column data
1217 try {
1218 while(reader.Read()) {
1219 numRows++;
1221 line = new StringBuilder();
1222 for(c = 0; c < reader.FieldCount; c++) {
1223 int dataLen = 0;
1224 string dataValue = "";
1225 column = new StringBuilder();
1226 outData = "";
1228 row = schemaTable.Rows[c];
1229 string colhdr = (string) reader.GetName(c);
1230 if(colhdr.Equals(""))
1231 colhdr = "column";
1232 if(colhdr.Length > 32)
1233 colhdr = colhdr.Substring(0, 32);
1235 columnSize = (int) row["ColumnSize"];
1236 theType = reader.GetFieldType(c);
1237 dataType = theType.ToString();
1239 //dataTypeName = reader.GetDataTypeName(c);
1241 switch(dataType) {
1242 case "System.DateTime":
1243 columnSize = 19;
1244 break;
1245 case "System.Boolean":
1246 columnSize = 5;
1247 break;
1250 columnSize = Math.Max(colhdr.Length, columnSize);
1252 if(columnSize < 0)
1253 columnSize = 0;
1254 if(columnSize > 32)
1255 columnSize = 32;
1257 dataValue = "";
1259 if(reader.IsDBNull(c)) {
1260 dataValue = "";
1261 dataLen = 0;
1263 else {
1264 StringBuilder sb;
1265 DateTime dt;
1266 if(dataType.Equals("System.DateTime")) {
1268 // display date in ISO format
1269 // "YYYY-MM-DD HH:MM:SS"
1270 dt = reader.GetDateTime(c);
1271 sb = new StringBuilder();
1272 // year
1273 if(dt.Year < 10)
1274 sb.Append("000" + dt.Year);
1275 else if(dt.Year < 100)
1276 sb.Append("00" + dt.Year);
1277 else if(dt.Year < 1000)
1278 sb.Append("0" + dt.Year);
1279 else
1280 sb.Append(dt.Year);
1281 sb.Append("-");
1282 // month
1283 if(dt.Month < 10)
1284 sb.Append(zero + dt.Month);
1285 else
1286 sb.Append(dt.Month);
1287 sb.Append("-");
1288 // day
1289 if(dt.Day < 10)
1290 sb.Append(zero + dt.Day);
1291 else
1292 sb.Append(dt.Day);
1293 sb.Append(" ");
1294 // hour
1295 if(dt.Hour < 10)
1296 sb.Append(zero + dt.Hour);
1297 else
1298 sb.Append(dt.Hour);
1299 sb.Append(":");
1300 // minute
1301 if(dt.Minute < 10)
1302 sb.Append(zero + dt.Minute);
1303 else
1304 sb.Append(dt.Minute);
1305 sb.Append(":");
1306 // second
1307 if(dt.Second < 10)
1308 sb.Append(zero + dt.Second);
1309 else
1310 sb.Append(dt.Second);
1312 dataValue = sb.ToString();
1314 else {
1315 object o = reader.GetValue(c);
1316 dataValue = o.ToString();
1319 dataLen = dataValue.Length;
1320 if(dataLen <= 0) {
1321 dataValue = "";
1322 dataLen = 0;
1324 if(dataLen > 32) {
1325 dataValue = dataValue.Substring(0,32);
1326 dataLen = 32;
1329 columnSize = Math.Max (columnSize, dataLen);
1331 if(dataLen < columnSize) {
1332 switch(dataType) {
1333 case "System.Byte":
1334 case "System.SByte":
1335 case "System.Int16":
1336 case "System.UInt16":
1337 case "System.Int32":
1338 case "System.UInt32":
1339 case "System.Int64":
1340 case "System.UInt64":
1341 case "System.Single":
1342 case "System.Double":
1343 case "System.Decimal":
1344 outData = dataValue.PadLeft(columnSize);
1345 break;
1346 default:
1347 outData = dataValue.PadRight(columnSize);
1348 break;
1350 outData = outData + " ";
1352 else
1353 outData = dataValue;
1355 line.Append (outData);
1356 line.Append (" ");
1358 OutputData (line.ToString ());
1359 line = null;
1362 catch (Exception rr) {
1363 Error ("Error: Unable to read next row: " +
1364 rr.Message);
1365 return;
1368 OutputLine ("\nRows retrieved: " + numRows.ToString());
1369 AppendText("");
1372 public void DisplayData(IDataReader reader)
1374 bool another = false;
1375 DataTable schemaTable = null;
1376 int ResultSet = 0;
1378 OutputLine ("Display any result sets...");
1380 do {
1381 // by Default, data reader has the
1382 // first Result set if any
1384 ResultSet++;
1385 OutputLine ("Display the result set " + ResultSet);
1387 if (reader.FieldCount > 0) {
1388 // SQL Query (SELECT)
1389 // RecordsAffected -1 and DataTable has a reference
1390 try {
1391 schemaTable = reader.GetSchemaTable ();
1393 catch (Exception es) {
1394 Error ("Error: Unable to get schema table: " +
1395 es.Message);
1396 return;
1399 AppendText (buf, "Display Result...");
1400 DisplayResult (reader, schemaTable);
1402 else if (reader.RecordsAffected >= 0) {
1403 // SQL Command (INSERT, UPDATE, or DELETE)
1404 // RecordsAffected >= 0
1405 int records = 0;
1406 try {
1407 records = reader.RecordsAffected;
1408 AppendText (buf, "SQL Command Records Affected: " +
1409 records);
1411 catch (Exception er) {
1412 Error ("Error: Unable to get records affected: " +
1413 er.Message);
1414 return;
1417 else {
1418 // SQL Command (not INSERT, UPDATE, nor DELETE)
1419 // RecordsAffected -1 and DataTable has a null reference
1420 AppendText (buf, "SQL Command Executed.");
1423 // get next result set (if anymore is left)
1424 try {
1425 another = reader.NextResult ();
1427 catch(Exception e) {
1428 Error ("Error: Unable to read next result: " +
1429 e.Message);
1430 return;
1432 } while(another == true);
1435 // used for outputting message, but if silent is set,
1436 // don't display
1437 public void OutputLine(string line)
1439 //if(silent == false)
1440 OutputData(line);
1443 // used for outputting the header columns of a result
1444 public void OutputHeader(string line)
1446 //if(showHeader == true)
1447 OutputData(line);
1450 // OutputData() - used for outputting data
1451 // if an output filename is set, then the data will
1452 // go to a file; otherwise, it will go to the Console.
1453 public void OutputData(string line)
1455 //if(outputFilestream == null)
1456 // Console.WriteLine(line);
1457 //else
1458 // outputFilestream.WriteLine(line);
1459 AppendTextWithoutScroll(buf,line);
1462 public void Error(string message)
1464 Console.WriteLine(message);
1465 Console.Out.Flush();
1466 AppendText(buf, message);
1469 bool OpenInternalProvider ()
1471 string msg;
1473 string providerKey = dbProvider.Key;
1474 switch (providerKey.ToUpper ()) {
1475 case "SQLCLIENT":
1476 try {
1477 conn = new SqlConnection ();
1479 catch (Exception e) {
1480 msg = "Error: unable to create connection: " +
1481 e.Message;
1482 Error (msg);
1483 return false;
1485 break;
1486 case "ODBC":
1487 try {
1488 conn = new OdbcConnection ();
1490 catch (Exception e) {
1491 msg = "Error: unable to create connection: " +
1492 e.Message;
1493 Error (msg);
1494 return false;
1496 break;
1497 case "OLEDB":
1498 try {
1499 conn = new OleDbConnection ();
1501 catch (Exception e) {
1502 msg = "Error: unable to create connection: " +
1503 e.Message;
1504 Error (msg);
1505 return false;
1507 break;
1508 default:
1509 msg = "Error: provider not supported.";
1510 Error (msg);
1511 return false;
1513 return true;
1516 bool OpenExternalProvider()
1518 bool success = false;
1520 success = LoadExternalProvider (
1521 dbProvider.Assembly,
1522 dbProvider.ConnectionClass);
1524 return success;
1527 public DbDataAdapter CreateDbDataAdapter (IDbCommand cmd)
1529 string msg = "";
1530 DbDataAdapter dbAdapter = null;
1531 if (dbProvider.InternalProvider == true) {
1532 dbAdapter = CreateInternalDataAdapter (cmd);
1534 else {
1535 dbAdapter = CreateExternalDataAdapter (dbProvider.AdapterClass, cmd);
1537 return dbAdapter;
1540 public DbDataAdapter CreateInternalDataAdapter (IDbCommand cmd)
1542 string msg = "";
1543 DbDataAdapter dbAdapter = null;
1544 string providerKey = dbProvider.Key;
1545 switch (providerKey.ToUpper ()) {
1546 case "SQLCLIENT":
1547 try {
1548 dbAdapter = new SqlDataAdapter (cmd as SqlCommand);
1550 catch (Exception e) {
1551 msg = "Error: unable to create adapter: " +
1552 e.Message;
1553 Error (msg);
1554 return null;
1556 break;
1558 case "OLEDB":
1559 try {
1560 dbAdapter = new OleDbDataAdapter (cmd as OleDbCommand);
1562 catch (Exception e) {
1563 msg = "Error: unable to create adapter: " +
1564 e.Message;
1565 Error (msg);
1566 return null;
1568 break;
1569 case "ODBC":
1570 try {
1571 dbAdapter = new OdbcDataAdapter (cmd as OdbcCommand);
1573 catch (Exception e) {
1574 msg = "Error: unable to create adapter: " +
1575 e.Message;
1576 Error (msg);
1577 return null;
1579 break;
1581 return dbAdapter;
1584 public DbDataAdapter CreateExternalDataAdapter (string adapterClass, IDbCommand cmd)
1586 adapterType = providerAssembly.GetType (adapterClass);
1587 System.Object ad = Activator.CreateInstance (adapterType);
1589 // set property SelectCommand on DbDataAdapter
1590 PropertyInfo prop = adapterType.GetProperty("SelectCommand");
1591 prop.SetValue (ad, cmd, null);
1593 return (DbDataAdapter) ad;
1596 public DataTable LoadDataTable (IDbCommand dbcmd)
1598 string status = String.Empty;
1600 AppendText("Create DbDataAdapter...");
1601 SqlSharpDataAdapter adapter = new SqlSharpDataAdapter (dbcmd);
1603 AppendText("Create DataTable...");
1604 DataTable dataTable = new DataTable ();
1606 AppendText("Fill data into DataTable via DbDataAdapter...");
1608 int rowsAddedOrRefreshed = 0;
1609 IDataReader reader = null;
1611 try {
1612 reader = dbcmd.ExecuteReader ();
1613 if (reader.FieldCount > 0)
1614 rowsAddedOrRefreshed = adapter.FillTable (dataTable, reader);
1616 catch(Exception sqle) {
1617 status = "Error: " + sqle.Message;
1620 if (status.Equals(String.Empty)) {
1621 AppendText("Rows successfully Added or Refreshed in the DataTable: " +
1622 rowsAddedOrRefreshed);
1623 int rowsAffected = reader.RecordsAffected;
1624 AppendText("Rows Affected: " + rowsAffected);
1626 int fields = ((IDataRecord) reader).FieldCount;
1627 AppendText("Field Count: " + fields);
1629 if (fields > 0) {
1630 status = "Rows Selected: " + rowsAddedOrRefreshed +
1631 " Fields: " + fields;
1633 else {
1634 status = "Rows Modified: " + rowsAffected;
1637 AppendText("Status: " + status);
1639 adapter.Dispose();
1640 adapter = null;
1642 AppendText("Return DataTable...");
1643 return dataTable;
1646 public bool OpenDataSource ()
1648 string msg;
1649 bool gotClass = false;
1651 msg = "Attempt to open connection...";
1652 AppendText (buf, msg);
1654 conn = null;
1656 try {
1657 if (dbProvider.InternalProvider == true) {
1658 gotClass = OpenInternalProvider ();
1660 else {
1661 gotClass = OpenExternalProvider ();
1664 catch (Exception e) {
1665 msg = "Error: Unable to create Connection object. " +
1666 e.Message;
1667 Error (msg);
1668 return false;
1671 if (gotClass == false)
1672 return false;
1674 conn.ConnectionString = connectionString;
1676 try {
1677 conn.Open ();
1678 if( conn.State == ConnectionState.Open)
1679 AppendText (buf, "Open was successfull.");
1680 else {
1681 AppendText (buf, "Error: Open failed.");
1682 return false;
1685 catch (Exception e) {
1686 msg = "Error: Could not open data source: " + e.Message;
1687 Error (msg);
1688 conn = null;
1690 return true;
1693 public static void DebugWriteLine (string text)
1695 #if DEBUG
1696 Console.WriteLine (text);
1697 Console.Out.Flush ();
1698 #endif // DEBUG
1701 public static int Main (string[] args)
1703 Application.Init ();
1704 SqlSharpGtk sqlSharp = new SqlSharpGtk ();
1705 sqlSharp.Show ();
1706 Application.Run ();
1707 return 0;