2005-01-31 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mcs / tools / sqlsharp / gui / gtk-sharp / sqlsharpgtk.cs
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.
11 //
12
13 namespace Mono.Data.SqlSharp.Gui.GtkSharp 
14 {
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;
29
30         using Gdk;
31         using Gtk;
32         using GtkSharp;
33         
34         using Mono.GtkSharp.Goodies;
35
36         using Gtk.Controls;
37
38         using SqlEditorSharp;
39
40         public enum OutputResults 
41         {
42                 TextView,
43                 DataGrid
44         }
45
46         public enum ExecuteOutputType 
47         {
48                 Normal,
49                 XmlFile,
50                 HtmlFile,
51                 CsvFile
52         }
53
54         public class EditorTab 
55         {
56                 public SqlEditorSharp editor;
57                 public Label label;
58                 public string filename;
59                 public string basefilename;
60                 public int page;
61         }
62
63         public class SqlSharpGtk 
64         {
65                 static int SqlWindowCount = 0;
66
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 = "";    
73                 
74                 private Statusbar statusBar;
75                 private Toolbar toolbar;
76
77                 int lastUnknownFile = 0;
78
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;
88
89                 private Gtk.Window win;
90
91                 public static readonly string ApplicationName = "Mono SQL# For GTK#";
92
93                 private OutputResults outputResults;
94
95                 public DbProviderCollection providerList;
96                 Notebook sourceFileNotebook;
97                 Notebook resultsNotebook;
98                 ArrayList editorTabs = new ArrayList();
99
100                 public SqlSharpGtk () 
101                 {
102                         CreateGui ();
103                         SqlWindowCount ++;
104                         LoadProviders ();
105                 }
106
107                 public void Show () 
108                 {
109                         win.ShowAll ();
110                 }
111
112                 public void CreateGui() 
113                 {
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);
118                         
119                         VBox vbox = new VBox (false, 4);
120                         win.Add (vbox);
121                         
122                         // Menu Bar
123                         MenuBar mb = CreateMenuBar ();
124                         vbox.PackStart(mb, false, false, 0);
125
126                         // Tool Bar
127                         toolbar = CreateToolbar ();
128                         vbox.PackStart (toolbar, false, false, 0);
129                         
130                         // Panels
131                         VPaned paned = new VPaned ();
132                         vbox.PackStart (paned, true, true, 0);
133
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);
141
142                         // bottom panel
143                         resultsNotebook = CreateOutputResultsGui ();
144                         paned.Add2 (resultsNotebook);
145
146                         statusBar = new Statusbar ();
147                         vbox.PackEnd (statusBar, false, false, 0);
148                         
149                         outputResults = OutputResults.TextView;
150                         ToggleResultsOutput ();
151                 }
152
153                 EditorTab NewEditorTab () 
154                 {
155                         SqlEditorSharp editor;
156                         editor = new SqlEditorSharp ();
157                         editor.UseSyntaxHiLighting = true;
158                         editor.View.Show ();
159                         editor.View.KeyPressEvent +=\r
160                                 new GtkSharp.KeyPressEventHandler(OnKeyPressEventKey);\r
161
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 ();
170
171                         sourceFileNotebook.CurrentPage = -1;
172                         
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);
182
183                         return tab;
184                 }
185
186                 // bottom panel
187                 Notebook CreateOutputResultsGui () 
188                 {
189                         Label label;
190                         Notebook results = new Notebook();
191                         results.TabPos = PositionType.Bottom;
192                         
193                         grid = CreateOutputResultsDataGrid ();
194                         grid.Show();
195                         label = new Label("Grid");
196                         results.AppendPage(grid, label);        
197
198                         swin = CreateOutputResultsTextView ();
199                         swin.Show();
200                         label = new Label("Log");
201                         results.AppendPage(swin, label);
202                         
203                         sourceFileNotebook.ShowAll ();
204                         sourceFileNotebook.ResizeChildren ();
205
206                         return results;
207
208                 }
209
210                 DataGrid CreateOutputResultsDataGrid () 
211                 {
212                         return new DataGrid ();
213                 }
214
215                 ScrolledWindow CreateOutputResultsTextView () 
216                 {
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;              
224                         
225                         textView = new TextView ();
226                         buf = textView.Buffer;
227                         textView.Editable = false;
228                         textView.ModifyFont (Pango.FontDescription.FromString ("courier new"));
229                         sw.Add (textView);              
230
231                         return sw;
232                 }
233
234                 void OnKeyPressEventKey(object o, GtkSharp.KeyPressEventArgs args) \r
235                 {\r
236                         if (o is TextView) {\r
237                                 TextView tv = (TextView) o;\r
238                                 //Gdk.EventKey k = args.Event;\r
239 \r
240                                 // if the F5 key was pressed\r
241                                 if (args.Event.keyval == 0xFFC2) {\r
242                                         if (tv.Editable == true) {\r
243                                                 // execute SQL\r
244                                                 ExecuteSQL (ExecuteOutputType.Normal, "");\r
245                                         }\r
246                                 }\r
247                         }\r
248                 }
249
250                 Toolbar CreateToolbar () 
251                 {
252                         Toolbar toolbar = new Toolbar ();
253
254                         toolbar.ToolbarStyle = ToolbarStyle.Icons;
255
256                         toolbar.AppendItem ("Execute", 
257                                 "Execute SQL Commands.", String.Empty,
258                                 new Gtk.Image (Stock.Execute, IconSize.SmallToolbar),
259                                 new Gtk.SignalFunc (OnToolbar_Execute));        
260                         
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));    
265
266                         return toolbar;
267                 }
268
269                 // TODO: use the ProviderFactory in Mono.Data 
270                 //       to load providers
271                 //       instead of what's below
272                 public void LoadProviders () 
273                 {
274                         providerList = new DbProviderCollection ();
275                         
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",
307                                 "",
308                                 "",
309                                 "",
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",
321                                 "",
322                                 "",
323                                 "",
324                                 true ));
325                         providerList.Add (new DbProvider (
326                                 "OLEDB",
327                                 "OLE DB",
328                                 "",
329                                 "",
330                                 "",
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 ));
360                 }
361                 
362                 public MenuBar CreateMenuBar () 
363                 {
364                         MenuBar menuBar = new MenuBar ();
365                         Menu menu;
366                         Menu submenu;
367                         MenuItem item;
368                         MenuItem barItem;
369                         MenuItem subitem;
370
371                         // File menu
372                         menu = new Menu ();
373
374                         item = new MenuItem ("New SQL# _Window");
375                         item.Activated += new EventHandler (OnMenu_FileNewSqlWindow);
376                         menu.Append (item);
377
378                         menu.Append (new SeparatorMenuItem ());
379
380                         item = new MenuItem ("_New");
381                         item.Activated += new EventHandler (OnMenu_FileNew);
382                         menu.Append (item);
383
384                         item = new MenuItem ("_Open...");
385                         item.Activated += new EventHandler (OnMenu_FileOpen);
386                         menu.Append (item);
387
388                         item = new MenuItem ("_Save");
389                         item.Activated += new EventHandler (OnMenu_FileSave);
390                         menu.Append (item);
391
392                         item = new MenuItem ("Save _As...");
393                         item.Activated += new EventHandler (OnMenu_FileSaveAs);
394                         menu.Append (item);
395
396                         item = new MenuItem ("Close");
397                         item.Activated += new EventHandler (OnMenu_FileClose);
398                         menu.Append (item);
399
400                         menu.Append (new SeparatorMenuItem ());
401
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);
413
414                         item = new MenuItem ("Save _Output...");
415                         item.Submenu = submenu;
416                         menu.Append (item);
417
418                         menu.Append (new SeparatorMenuItem ());
419
420                         item = new MenuItem ("E_xit");
421                         item.Activated += new EventHandler (OnMenu_FileExit);
422                         menu.Append (item);
423
424                         barItem = new MenuItem ("_File");
425                         barItem.Submenu = menu;
426                         menuBar.Append (barItem);
427
428                         // Edit menu
429
430                         menu = new Menu ();
431
432                         item = new MenuItem ("_Undo");
433                         //item.Activated += new EventHandler (OnMenu_EditUndo);
434                         menu.Append (item);
435
436                         item = new MenuItem ("_Redo");
437                         //item.Activated += new EventHandler (OnMenu_EditRedo);
438                         menu.Append (item);
439
440                         menu.Append (new SeparatorMenuItem ());
441
442                         item = new MenuItem ("Cu_t");
443                         //item.Activated += new EventHandler (OnMenu_EditCut);
444                         menu.Append (item);
445
446                         item = new MenuItem ("_Copy");
447                         //item.Activated += new EventHandler (OnMenu_EditCopy);
448                         menu.Append (item);
449
450                         item = new MenuItem ("_Paste");
451                         //item.Activated += new EventHandler (OnMenu_EditPaste);
452                         menu.Append (item);
453
454                         item = new MenuItem ("_Delete");
455                         //item.Activated += new EventHandler (OnMenu_EditDelete);
456                         menu.Append (item);
457
458                         menu.Append (new SeparatorMenuItem ());
459
460                         item = new MenuItem ("_Find and Replace...");
461                         //item.Activated += new EventHandler (OnMenu_EditFindReplace);
462                         menu.Append (item);
463
464                         menu.Append (new SeparatorMenuItem ());
465
466                         item = new MenuItem ("_Options");
467                         //item.Activated += new EventHandler (OnMenu_EditOptions);
468                         menu.Append (item);
469
470                         barItem = new MenuItem ("_Edit");
471                         barItem.Submenu = menu;
472                         menuBar.Append (barItem);
473
474                         // Session menu
475                         menu = new Menu ();
476
477                         item = new MenuItem ("_Connect");
478                         item.Activated += new EventHandler (OnMenu_SessionConnect);
479                         menu.Append (item);
480
481                         item = new MenuItem ("_Disconnect");
482                         item.Activated += new EventHandler (OnMenu_SessionDisconnect);
483                         menu.Append (item);
484
485                         barItem = new MenuItem ("_Session");
486                         barItem.Submenu = menu;
487                         menuBar.Append (barItem);
488
489                         // Command menu
490                         menu = new Menu ();
491
492                         item = new MenuItem ("_Execute");
493                         item.Activated += new EventHandler (OnMenu_CommandExecute);
494                         menu.Append (item);
495
496                         item = new MenuItem ("_Execute With Output to XML");
497                         item.Activated += new EventHandler (OnMenu_CommandExecuteXML);
498                         menu.Append (item);
499
500                         item = new MenuItem ("_Execute With Output to CSV");
501                         item.Activated += new EventHandler (OnMenu_CommandExecuteCSV);
502                         menu.Append (item);
503
504                         item = new MenuItem ("_Execute With Output to HTML");
505                         item.Activated += new EventHandler (OnMenu_CommandExecuteHTML);
506                         menu.Append (item);
507
508                         barItem = new MenuItem ("_Command");
509                         barItem.Submenu = menu;
510                         menuBar.Append (barItem);
511
512                         return menuBar;
513                 }
514
515                 void AppendText (string text) 
516                 {
517                         AppendText (buf, text);
518                 }
519
520                 public void AppendTextWithoutScroll (TextBuffer buffer, string text) 
521                 {
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);
528                         }
529                         iter = buffer.EndIter;
530                         buffer.Insert (iter, "\n");
531                 }
532
533                 // WriteLine() to output text to bottom TextView
534                 // for displaying result sets and logging messages
535                 public void AppendText (TextBuffer buffer, string text) 
536                 {
537                         AppendTextWithoutScroll(buffer,text);
538                         while (Application.EventsPending ()) 
539                                 Application.RunIteration ();
540                         textView.ScrollToMark (buf.InsertMark, 0.4, true, 0.0, 1.0);
541                 }
542
543                 public bool LoadExternalProvider (string strProviderAssembly,
544                                                 string providerConnectionClass) 
545                 {               
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);
552                                                                 
553                                 SqlSharpGtk.DebugWriteLine ("External provider loaded.");
554                         }
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;
562                         }
563                         return true;
564                 }
565
566                 void QuitApplication() 
567                 {
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.");
574                                 }
575
576                         if(grid.DataSource != null) {
577                                 grid.Clear ();
578                                 grid.DataSource = null;
579                                 grid.DataMember = "";
580                                 grid = null;
581                         }
582
583                         SqlWindowCount --;
584                         if(SqlWindowCount == 0)
585                                 Application.Quit ();
586                         else
587                                 win.Destroy ();
588                 }
589
590                 void UpdateTitleBar(EditorTab tab) 
591                 {
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;
598                         }
599                         else {
600                                 title = ApplicationName;
601                         }
602                         win.Title = title;
603                 }
604
605                 void OnEditorTabSwitched (object o, GtkSharp.SwitchPageArgs args) 
606                 {
607                         int page = (int) args.PageNum;
608                         EditorTab tab = FindEditorTab(page);
609                         UpdateTitleBar (tab);
610                 }
611
612                 void OnWindow_Delete (object o, GtkSharp.DeleteEventArgs args) 
613                 {
614                         QuitApplication();
615                 }
616
617                 void OnExit (Gtk.Object o) 
618                 {
619                         QuitApplication();
620                 }
621
622                 void OnMenu_FileNewSqlWindow (object o, EventArgs args) 
623                 {
624                         SqlSharpGtk sqlSharp = new SqlSharpGtk ();
625                         sqlSharp.Show ();
626                 }
627
628                 void OnMenu_FileNew (object o, EventArgs args) 
629                 {
630                         NewEditorTab();
631                         sourceFileNotebook.CurrentPage = -1;
632                 }
633
634                 void OnMenu_FileOpen (object o, EventArgs args) 
635                 {
636                         FileSelectionDialog openFileDialog = 
637                                 new FileSelectionDialog ("Open File",
638                                 new FileSelectionEventHandler (OnOpenFile));
639                 }
640
641                 void OnOpenFile (object o, FileSelectionEventArgs args) 
642                 {
643                         EditorTab etab = NewEditorTab();
644                         try {
645                                 etab.editor.LoadFromFile (args.Filename);
646                         }
647                         catch(Exception openFileException) {
648                                 Error("Error: Could not open file: \n" + 
649                                         args.Filename + 
650                                         "\n\nReason: " + 
651                                         openFileException.Message);
652                                 return;
653                         }
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);
662                 }
663
664                 EditorTab FindEditorTab (int searchPage) 
665                 {
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;
671                         }
672                         return tab;
673                 }
674
675                 void OnMenu_FileSave (object o, EventArgs args) 
676                 {
677                         int page = sourceFileNotebook.CurrentPage;
678                         EditorTab tab = FindEditorTab(page);
679
680                         if(tab.filename.Equals(""))
681                                 SaveAs();
682                         else {
683                                 SaveFile(tab.filename);
684                                 tab.label.Text = tab.basefilename;
685                         }
686                 }
687
688                 void SaveFile (string filename) 
689                 {
690                         int page = sourceFileNotebook.CurrentPage;
691                         EditorTab etab = FindEditorTab(page);
692
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;
704                         }
705                         TextBuffer buf = etab.editor.Buffer;
706                         buf.Modified = false;
707                 }
708
709                 void OnMenu_FileSaveAs (object o, EventArgs args) 
710                 {
711                         SaveAs();
712                 }
713
714                 void SaveAs() 
715                 {
716                         FileSelectionDialog openFileDialog = 
717                                 new FileSelectionDialog ("File Save As",
718                                 new FileSelectionEventHandler (OnSaveAsFile));
719                 }
720
721                 void OnSaveAsFile (object o, FileSelectionEventArgs args) 
722                 {
723                         int page = sourceFileNotebook.CurrentPage;
724                         EditorTab etab = FindEditorTab(page);
725
726                         SaveFile(args.Filename);
727
728                         string basefile = Path.GetFileName (args.Filename);
729                         etab.label.Text = basefile;
730                         etab.basefilename = basefile;
731                         etab.filename = args.Filename;
732                         UpdateTitleBar(etab);
733                 }
734
735                 void OnMenu_FileClose (object o, EventArgs args) 
736                 {
737                         CloseEditor();
738                 }
739
740                 void OnCloseEditor (object obj, EventArgs args) 
741                 {
742                         CloseEditor();
743                 }
744
745                 void CloseEditor () 
746                 {
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);
757                         }
758                         else {
759                                 RemoveEditorTab (sqlEditor.Tab, page);
760                         }
761                         sqlEditor = null;
762                         buffer = null;
763                 }
764
765                 void RemoveEditorTab (EditorTab tab, int page) 
766                 {
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;
775                 }
776
777                 void OnMenu_FileExit (object o, EventArgs args) 
778                 {
779                         QuitApplication ();
780                 }
781
782                 void OnMenu_SessionConnect (object o, EventArgs args) 
783                 {       
784                         LoginDialog login = new LoginDialog (this);
785                         login = null;
786                 }
787
788                 void OnMenu_SessionDisconnect (object o, EventArgs args) 
789                 {
790                         AppendText(buf, "Disconnecting...");
791                         try {
792                                 conn.Close ();
793                                 conn = null;
794                         }
795                         catch (Exception e) {
796                                 Error ("Error: Unable to disconnect." + 
797                                         e.Message);
798                                 conn = null;
799                                 return;
800                         }
801                         AppendText (buf, "Disconnected.");
802                 }
803
804                 void OnToolbar_ToggleResultsOutput () 
805                 {
806                         ToggleResultsOutput ();
807                 }
808
809                 void ToggleResultsOutput () 
810                 {
811                         if (outputResults == OutputResults.TextView) {
812                                 outputResults = OutputResults.DataGrid;
813                         }
814                         else if (outputResults == OutputResults.DataGrid) {
815                                 outputResults = OutputResults.TextView;
816                         }
817                 }
818
819                 public void OnToolbar_Execute () 
820                 {
821                         ExecuteSQL (ExecuteOutputType.Normal, "");
822                 }
823
824                 // Execute SQL Commands
825                 void ExecuteSQL (ExecuteOutputType outputType, string filename) 
826                 {               
827                         if (conn == null) {
828                                 AppendText (buf, "Error: Not Connected.");
829                                 return;
830                         }
831
832                         DataTable schemaTable = null;
833
834                         int page = sourceFileNotebook.CurrentPage;
835                         EditorTab tab = FindEditorTab(page);
836
837                         string msg = "";
838                         string sql = "";        
839
840                         IDbCommand cmd;
841
842                         try {
843                                 cmd = conn.CreateCommand ();
844                         }
845                         catch (Exception ec) {
846                                 AppendText (buf, 
847                                         "Error: Unable to create command to execute: " + 
848                                         ec.Message);
849                                 return;
850                         }
851
852                         SqlSharpGtk.DebugWriteLine ("get text from SQL editor...");
853
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);
862                         }
863                         catch (Exception et) {
864                                 AppendText (buf, 
865                                         "Error: Unable to get text from SQL editor: " + 
866                                         et.Message);
867                                 return;
868                         }
869                         
870                         try {
871                                 cmd.CommandText = sql;
872                         }
873                         catch (Exception e) {
874                                 AppendText (buf, 
875                                         "Error: Unable to set SQL text to command.");
876                         }
877                         
878                         IDataReader reader = null;
879                         SqlSharpGtk.DebugWriteLine ("Executing SQL: " + sql);
880                         
881                         if ((outputResults == OutputResults.TextView && 
882                                 outputType == ExecuteOutputType.Normal) ||
883                                 outputType == ExecuteOutputType.HtmlFile ||
884                                 outputType == ExecuteOutputType.CsvFile) {
885
886                                 try {
887                                         reader = cmd.ExecuteReader ();
888                                 }
889                                 catch (Exception e) {
890                                         //msg = "SQL Execution Error: " + e.Message;
891                                         msg = "SQL Execution Error: " + e;
892                                         Error (msg);
893                                         return;
894                                 }
895                         
896                                 if (reader == null) {
897                                         Error("Error: reader is null");
898                                         return;
899                                 }
900                         }
901
902                         try {
903                                 if (outputResults == OutputResults.TextView && 
904                                         outputType == ExecuteOutputType.Normal) {
905
906                                         DisplayData (reader);
907                                         // clean up
908                                         reader.Close ();
909                                         reader.Dispose ();
910                                         reader = null;
911                                 }
912                                 else if(outputType == ExecuteOutputType.HtmlFile) {
913                                         schemaTable = reader.GetSchemaTable();
914                                         if(schemaTable != null && reader.FieldCount > 0) {
915                                                 OutputDataToHtmlFile(reader, schemaTable, filename);
916                                         }
917                                         else {
918                                                 AppendText("Command executed.");
919                                         }
920                                         // clean up
921                                         reader.Close ();
922                                         reader.Dispose ();
923                                         reader = null;
924                                 }
925                                 else if(outputType == ExecuteOutputType.CsvFile) {
926                                         schemaTable = reader.GetSchemaTable();
927                                         if(schemaTable != null && reader.FieldCount > 0) {
928                                                 OutputDataToCsvFile(reader, schemaTable, filename);
929                                         }
930                                         else {
931                                                 AppendText("Command executed.");
932                                         }
933                                         // clean up
934                                         reader.Close ();
935                                         reader.Dispose ();
936                                         reader = null;
937                                 }
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;
961                                         }
962                                         // clean up
963                                         dataTable.Clear();
964                                         dataTable.Dispose();
965                                         dataTable = null;
966                                         AppendText("Done.");
967                                         cmd.Dispose();
968                                         cmd = null;
969                                 }
970                         }
971                         catch (Exception e) {
972                                 //msg = "Error Displaying Data: " + e.Message;
973                                 msg = "Error Displaying Data: " + e;
974                                 Error (msg);
975                         }
976                 }
977
978                 public void OutputDataToHtmlFile(IDataReader rdr, DataTable dt, string file) 
979                 {               
980                         AppendText("Outputting results to HTML file " + file + "...");
981                         StreamWriter outputFilestream = null;
982                         try {
983                                 outputFilestream = new StreamWriter(file);
984                         }
985                         catch(Exception e) {
986                                 Error("Error: Unable to setup output results file. " + 
987                                         e.Message);
988                                 return;
989                         }
990
991                         StringBuilder strHtml = new StringBuilder();
992
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");
999                 
1000                         outputFilestream.WriteLine(strHtml.ToString());
1001
1002                         strHtml = null;
1003                         strHtml = new StringBuilder();
1004
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");
1011                         }
1012                         strHtml.Append("\t\t</tr>\n");
1013                         outputFilestream.WriteLine(strHtml.ToString());
1014                         strHtml = null;
1015
1016                         int col = 0;
1017                         string dataValue = "";
1018                         
1019                         while(rdr.Read()) {
1020                                 strHtml = new StringBuilder();
1021
1022                                 strHtml.Append("\t\t<tr>\n");
1023                                 for(col = 0; col < rdr.FieldCount; col++) {
1024                                                 
1025                                         // column data
1026                                         if(rdr.IsDBNull(col) == true)
1027                                                 dataValue = "NULL";
1028                                         else {
1029                                                 object obj = rdr.GetValue(col);
1030                                                 dataValue = obj.ToString();
1031                                         }
1032                                         strHtml.Append("\t\t\t<td>");
1033                                         strHtml.Append(dataValue);
1034                                         strHtml.Append("</td>\n");
1035                                 }
1036                                 strHtml.Append("\t\t</tr>\n");
1037                                 outputFilestream.WriteLine(strHtml.ToString());
1038                                 strHtml = null;
1039                         }
1040                         outputFilestream.WriteLine("\t</table>\n</body>\n</html>\n");
1041                         strHtml = null;
1042                         outputFilestream.Close();
1043                         outputFilestream = null;
1044                         AppendText("Outputting file done.");
1045                 }
1046
1047                 public void OutputDataToCsvFile(IDataReader rdr, DataTable dt, string file) 
1048                 {               
1049                         AppendText("Outputting results to CSV file " + file + "...");
1050                         StreamWriter outputFilestream = null;
1051                         try {
1052                                 outputFilestream = new StreamWriter(file);
1053                         }
1054                         catch(Exception e) {
1055                                 Error("Error: Unable to setup output results file. " + 
1056                                         e.Message);
1057                                 return;
1058                         }
1059
1060                         StringBuilder strCsv = null;
1061
1062                         int col = 0;
1063                         string dataValue = "";
1064                         
1065                         while(rdr.Read()) {
1066                                 strCsv = new StringBuilder();
1067                                 
1068                                 for(col = 0; col < rdr.FieldCount; col++) {
1069                                         if(col > 0)
1070                                                 strCsv.Append(",");
1071
1072                                         // column data
1073                                         if(rdr.IsDBNull(col) == true)
1074                                                 dataValue = "\"\"";
1075                                         else {
1076                                                 object obj = rdr.GetValue(col);
1077                                                 dataValue = "\"" + obj.ToString() + "\"";
1078                                         }
1079                                         strCsv.Append(dataValue);
1080                                 }
1081                                 outputFilestream.WriteLine(strCsv.ToString());
1082                                 strCsv = null;
1083                         }
1084                         strCsv = null;
1085                         outputFilestream.Close();
1086                         outputFilestream = null;
1087                         AppendText("Outputting file done.");
1088                 }
1089
1090                 void OnMenu_CommandExecute (object o, EventArgs args) 
1091                 {
1092                         ExecuteSQL (ExecuteOutputType.Normal, "");
1093                 }
1094
1095                 void OnMenu_CommandExecuteXML (object o, EventArgs args) 
1096                 {
1097                         ExecuteAndSaveResultsToFile (ExecuteOutputType.XmlFile);
1098                 }
1099
1100                 void OnMenu_CommandExecuteCSV (object o, EventArgs args) 
1101                 {
1102                         ExecuteAndSaveResultsToFile (ExecuteOutputType.CsvFile);
1103                 }
1104
1105                 void OnMenu_CommandExecuteHTML (object o, EventArgs args) 
1106                 {
1107                         ExecuteAndSaveResultsToFile (ExecuteOutputType.HtmlFile);
1108                 }
1109
1110                 ExecuteOutputType outType;
1111                 void ExecuteAndSaveResultsToFile(ExecuteOutputType oType) 
1112                 {
1113                         outType = oType;
1114                         FileSelectionDialog openFileDialog = 
1115                                 new FileSelectionDialog ("Results File Save As",
1116                                 new FileSelectionEventHandler (OnSaveExeOutFile));
1117                 }
1118
1119                 void OnSaveExeOutFile (object o, FileSelectionEventArgs args) 
1120                 {
1121                         ExecuteSQL (outType, args.Filename);
1122                 }
1123
1124                 public void DisplayResult (IDataReader reader, DataTable schemaTable) 
1125                 {
1126                         const string zero = "0";
1127                         StringBuilder column = null;
1128                         StringBuilder line = null;
1129                         StringBuilder hdrUnderline = null;
1130                         string outData = "";
1131                         int hdrLen = 0;
1132                         
1133                         int spacing = 0;
1134                         int columnSize = 0;
1135                         int c;
1136                         
1137                         char spacingChar = ' '; // a space
1138                         char underlineChar = '='; // an equal sign
1139
1140                         string dataType; // .NET Type
1141                         Type theType; 
1142                         string dataTypeName; // native Database type
1143                         DataRow row; // schema row
1144
1145                         line = new StringBuilder ();
1146                         hdrUnderline = new StringBuilder ();
1147
1148                         try {
1149                                 OutputLine ("Fields in Query Result: " + 
1150                                         reader.FieldCount);
1151                         }
1152                         catch(Exception e){
1153                                 Error ("Error: Unable to get FieldCount: " +
1154                                         e.Message);
1155                                 return;
1156                         }
1157                         
1158                         OutputLine ("");
1159                         
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);
1168                                         
1169                                         // spacing
1170                                         columnSize = (int) schemaRow["ColumnSize"];
1171                                         theType = reader.GetFieldType(c);
1172                                         dataType = theType.ToString();
1173                                         //dataTypeName = reader.GetDataTypeName(c);
1174
1175                                         switch(dataType) {
1176                                         case "System.DateTime":
1177                                                 columnSize = 19;
1178                                                 break;
1179                                         case "System.Boolean":
1180                                                 columnSize = 5;
1181                                                 break;
1182                                         }
1183
1184                                         hdrLen = Math.Max (columnHeader.Length, columnSize);
1185
1186                                         if(hdrLen < 0)
1187                                                 hdrLen = 0;
1188                                         if(hdrLen > 32)
1189                                                 hdrLen = 32;
1190
1191                                         line.Append(columnHeader);
1192                                         if(columnHeader.Length < hdrLen) {
1193                                                 spacing = hdrLen - columnHeader.Length;
1194                                                 line.Append(spacingChar, spacing);
1195                                         }
1196                                         hdrUnderline.Append(underlineChar, hdrLen);
1197
1198                                         line.Append(" ");
1199                                         hdrUnderline.Append(" ");
1200                                 }
1201                                 catch(Exception e) {
1202                                         Error ("Error: Unable to display header: " +
1203                                                 e.Message);
1204                                         return;
1205                                 }
1206                         }
1207                         OutputHeader(line.ToString());
1208                         line = null;
1209                         
1210                         OutputHeader(hdrUnderline.ToString());
1211                         OutputHeader("");
1212                         hdrUnderline = null;            
1213                                                                 
1214                         int numRows = 0;
1215
1216                         // column data
1217                         try {
1218                                 while(reader.Read()) {
1219                                         numRows++;
1220                                 
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 = "";
1227                                         
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);
1234
1235                                                 columnSize = (int) row["ColumnSize"];
1236                                                 theType = reader.GetFieldType(c);
1237                                                 dataType = theType.ToString();
1238                                         
1239                                                 //dataTypeName = reader.GetDataTypeName(c);
1240
1241                                                 switch(dataType) {
1242                                                 case "System.DateTime":
1243                                                         columnSize = 19;
1244                                                         break;
1245                                                 case "System.Boolean":
1246                                                         columnSize = 5;
1247                                                         break;
1248                                                 }
1249
1250                                                 columnSize = Math.Max(colhdr.Length, columnSize);
1251
1252                                                 if(columnSize < 0)
1253                                                         columnSize = 0;
1254                                                 if(columnSize > 32)
1255                                                         columnSize = 32;                                                        
1256                                         
1257                                                 dataValue = ""; 
1258                                         
1259                                                 if(reader.IsDBNull(c)) {
1260                                                         dataValue = "";
1261                                                         dataLen = 0;
1262                                                 }
1263                                                 else {                                                                                  
1264                                                         StringBuilder sb;
1265                                                         DateTime dt;
1266                                                         if(dataType.Equals("System.DateTime")) {
1267                                         
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);
1311
1312                                                                 dataValue = sb.ToString();
1313                                                         }
1314                                                         else {
1315                                                                 object o = reader.GetValue(c);
1316                                                                 dataValue = o.ToString();
1317                                                         }
1318
1319                                                         dataLen = dataValue.Length;
1320                                                         if(dataLen <= 0) {
1321                                                                 dataValue = "";
1322                                                                 dataLen = 0;
1323                                                         }
1324                                                         if(dataLen > 32) {
1325                                                                 dataValue = dataValue.Substring(0,32);
1326                                                                 dataLen = 32;
1327                                                         }
1328                                                 }
1329                                                 columnSize = Math.Max (columnSize, dataLen);
1330                                         
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;
1349                                                         }
1350                                                         outData = outData + " ";
1351                                                 }
1352                                                 else
1353                                                         outData = dataValue;
1354
1355                                                 line.Append (outData);
1356                                                 line.Append (" ");
1357                                         }
1358                                         OutputData (line.ToString ());
1359                                         line = null;
1360                                 }
1361                         }
1362                         catch (Exception rr) {
1363                                 Error ("Error: Unable to read next row: " +
1364                                         rr.Message);
1365                                 return;
1366                         }
1367                 
1368                         OutputLine ("\nRows retrieved: " + numRows.ToString());
1369                         AppendText("");
1370                 }
1371
1372                 public void DisplayData(IDataReader reader) 
1373                 {
1374                         bool another = false;
1375                         DataTable schemaTable = null;
1376                         int ResultSet = 0;
1377
1378                         OutputLine ("Display any result sets...");
1379                         
1380                         do {
1381                                 // by Default, data reader has the 
1382                                 // first Result set if any
1383
1384                                 ResultSet++;
1385                                 OutputLine ("Display the result set " + ResultSet);                     
1386                                 
1387                                 if (reader.FieldCount > 0) {
1388                                         // SQL Query (SELECT)
1389                                         // RecordsAffected -1 and DataTable has a reference
1390                                         try {
1391                                                 schemaTable = reader.GetSchemaTable ();
1392                                         }
1393                                         catch (Exception es) {
1394                                                 Error ("Error: Unable to get schema table: " + 
1395                                                         es.Message);
1396                                                 return;
1397                                         }
1398
1399                                         AppendText (buf, "Display Result...");
1400                                         DisplayResult (reader, schemaTable);
1401                                 }
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);
1410                                         }
1411                                         catch (Exception er) {
1412                                                 Error ("Error: Unable to get records affected: " +
1413                                                         er.Message);
1414                                                 return;
1415                                         }
1416                                 }
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.");
1421                                 }
1422                                 
1423                                 // get next result set (if anymore is left)
1424                                 try {
1425                                         another = reader.NextResult ();
1426                                 }
1427                                 catch(Exception e) {
1428                                         Error ("Error: Unable to read next result: " +
1429                                                 e.Message);
1430                                         return;
1431                                 }
1432                         } while(another == true);
1433                 }
1434
1435                 // used for outputting message, but if silent is set,
1436                 // don't display
1437                 public void OutputLine(string line) 
1438                 {
1439                         //if(silent == false)
1440                         OutputData(line);
1441                 }
1442
1443                 // used for outputting the header columns of a result
1444                 public void OutputHeader(string line) 
1445                 {
1446                         //if(showHeader == true)
1447                         OutputData(line);
1448                 }
1449
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) 
1454                 {
1455                         //if(outputFilestream == null)
1456                         //      Console.WriteLine(line);
1457                         //else
1458                         //      outputFilestream.WriteLine(line);
1459                         AppendTextWithoutScroll(buf,line);
1460                 }
1461
1462                 public void Error(string message) 
1463                 {
1464                         Console.WriteLine(message);
1465                         Console.Out.Flush();
1466                         AppendText(buf, message);
1467                 }
1468
1469                 bool OpenInternalProvider () 
1470                 {
1471                         string msg;
1472
1473                         string providerKey = dbProvider.Key;
1474                         switch (providerKey.ToUpper ()) {
1475                         case "SQLCLIENT":
1476                                 try {
1477                                         conn = new SqlConnection ();
1478                                 }
1479                                 catch (Exception e) {
1480                                         msg = "Error: unable to create connection: " +
1481                                                 e.Message;
1482                                         Error (msg);
1483                                         return false;
1484                                 }
1485                                 break;
1486                         case "ODBC":
1487                                 try {
1488                                         conn = new OdbcConnection ();
1489                                 }
1490                                 catch (Exception e) {
1491                                         msg = "Error: unable to create connection: " +
1492                                                 e.Message;
1493                                         Error (msg);
1494                                         return false;
1495                                 }
1496                                 break;
1497                         case "OLEDB":
1498                                 try {
1499                                         conn = new OleDbConnection ();
1500                                 }
1501                                 catch (Exception e) {
1502                                         msg = "Error: unable to create connection: " +
1503                                                 e.Message;
1504                                         Error (msg);
1505                                         return false;
1506                                 }
1507                                 break;
1508                         default:
1509                                 msg = "Error: provider not supported.";
1510                                 Error (msg);
1511                                 return false;
1512                         }
1513                         return true;
1514                 }
1515
1516                 bool OpenExternalProvider() 
1517                 {
1518                         bool success = false;
1519                         
1520                         success = LoadExternalProvider (
1521                                         dbProvider.Assembly,
1522                                         dbProvider.ConnectionClass);
1523                                                 
1524                         return success;
1525                 }
1526
1527                 public DbDataAdapter CreateDbDataAdapter (IDbCommand cmd) 
1528                 {
1529                         string msg = "";
1530                         DbDataAdapter dbAdapter = null;
1531                         if (dbProvider.InternalProvider == true) {
1532                                 dbAdapter = CreateInternalDataAdapter (cmd);
1533                         }
1534                         else {
1535                                 dbAdapter = CreateExternalDataAdapter (dbProvider.AdapterClass, cmd);
1536                         }
1537                         return dbAdapter;
1538                 }
1539
1540                 public DbDataAdapter CreateInternalDataAdapter (IDbCommand cmd) 
1541                 {               
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);
1549                                 }
1550                                 catch (Exception e) {
1551                                         msg = "Error: unable to create adapter: " +
1552                                                 e.Message;
1553                                         Error (msg);
1554                                         return null;
1555                                 }
1556                                 break;
1557                                 
1558                         case "OLEDB":
1559                                 try {
1560                                         dbAdapter = new OleDbDataAdapter (cmd as OleDbCommand);
1561                                 }
1562                                 catch (Exception e) {
1563                                         msg = "Error: unable to create adapter: " +
1564                                                 e.Message;
1565                                         Error (msg);
1566                                         return null;
1567                                 }
1568                                 break;
1569                         case "ODBC":
1570                                         try {
1571                                                 dbAdapter = new OdbcDataAdapter (cmd as OdbcCommand);
1572                                         }
1573                                         catch (Exception e) {
1574                                                 msg = "Error: unable to create adapter: " +
1575                                                         e.Message;
1576                                                 Error (msg);
1577                                                 return null;
1578                                         }
1579                                 break;
1580                         }
1581                         return dbAdapter;
1582                 }
1583
1584                 public DbDataAdapter CreateExternalDataAdapter (string adapterClass, IDbCommand cmd) 
1585                 {
1586                         adapterType = providerAssembly.GetType (adapterClass);
1587                         System.Object ad = Activator.CreateInstance (adapterType);
1588
1589                         // set property SelectCommand on DbDataAdapter
1590                         PropertyInfo prop = adapterType.GetProperty("SelectCommand");
1591                         prop.SetValue (ad, cmd, null);
1592
1593                         return (DbDataAdapter) ad;
1594                 }
1595
1596                 public DataTable LoadDataTable (IDbCommand dbcmd) 
1597                 {
1598                         string status = String.Empty;
1599
1600                         AppendText("Create DbDataAdapter...");
1601                         SqlSharpDataAdapter adapter = new SqlSharpDataAdapter (dbcmd);
1602                         
1603                         AppendText("Create DataTable...");
1604                         DataTable dataTable = new DataTable ();
1605
1606                         AppendText("Fill data into DataTable via DbDataAdapter...");
1607
1608                         int rowsAddedOrRefreshed = 0;
1609                         IDataReader reader = null;
1610                         
1611                         try {
1612                                 reader = dbcmd.ExecuteReader ();
1613                                 if (reader.FieldCount > 0)
1614                                         rowsAddedOrRefreshed = adapter.FillTable (dataTable, reader);
1615                         }
1616                         catch(Exception sqle) {
1617                                 status = "Error: " + sqle.Message;
1618                         }
1619
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);
1625
1626                                 int fields = ((IDataRecord) reader).FieldCount;
1627                                 AppendText("Field Count: " + fields);
1628                         
1629                                 if (fields > 0) {
1630                                         status = "Rows Selected: " + rowsAddedOrRefreshed +
1631                                                 "  Fields: " + fields;
1632                                 }
1633                                 else {
1634                                         status = "Rows Modified: " + rowsAffected;
1635                                 }
1636                         }
1637                         AppendText("Status: " + status);
1638
1639                         adapter.Dispose();
1640                         adapter = null;
1641
1642                         AppendText("Return DataTable...");
1643                         return dataTable;
1644                 }
1645
1646                 public bool OpenDataSource () 
1647                 {
1648                         string msg;
1649                         bool gotClass = false;
1650                         
1651                         msg = "Attempt to open connection...";
1652                         AppendText (buf, msg);
1653
1654                         conn = null;
1655
1656                         try {
1657                                 if (dbProvider.InternalProvider == true) {
1658                                         gotClass = OpenInternalProvider ();
1659                                 } 
1660                                 else {
1661                                         gotClass = OpenExternalProvider ();
1662                                 }
1663                         }
1664                         catch (Exception e) {
1665                                 msg = "Error: Unable to create Connection object. " + 
1666                                         e.Message;
1667                                 Error (msg);
1668                                 return false;
1669                         }
1670
1671                         if (gotClass == false)
1672                                 return false;
1673
1674                         conn.ConnectionString = connectionString;
1675                         
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;
1683                                 }
1684                         }
1685                         catch (Exception e) {
1686                                 msg = "Error: Could not open data source: " + e.Message;
1687                                 Error (msg);
1688                                 conn = null;
1689                         }
1690                         return true;
1691                 }
1692
1693                 public static void DebugWriteLine (string text) 
1694                 {
1695 #if DEBUG
1696                         Console.WriteLine (text);
1697                         Console.Out.Flush ();
1698 #endif // DEBUG
1699                 }
1700
1701                 public static int Main (string[] args) 
1702                 {               
1703                         Application.Init ();
1704                         SqlSharpGtk sqlSharp = new SqlSharpGtk ();
1705                         sqlSharp.Show ();                       
1706                         Application.Run ();
1707                         return 0;
1708                 }
1709         }
1710 }