sqlsharpgtk.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710
  1. //
  2. // SqlSharpGtk - Mono SQL# For GTK# - SQL Query and Configuration tool for
  3. // Mono.Data providers
  4. //
  5. // Author:
  6. // Daniel Morgan <[email protected]>
  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. namespace Mono.Data.SqlSharp.Gui.GtkSharp
  13. {
  14. using System;
  15. using System.Collections;
  16. using System.Data;
  17. using System.Data.Common;
  18. using System.Data.Odbc;
  19. using System.Data.OleDb;
  20. using System.Data.SqlClient;
  21. using System.Drawing;
  22. using System.Text;
  23. using System.IO;
  24. using System.Reflection;
  25. using System.Runtime.Remoting;
  26. using System.Runtime.InteropServices;
  27. using System.Diagnostics;
  28. using Gdk;
  29. using Gtk;
  30. using GtkSharp;
  31. using Mono.GtkSharp.Goodies;
  32. using Gtk.Controls;
  33. using SqlEditorSharp;
  34. public enum OutputResults
  35. {
  36. TextView,
  37. DataGrid
  38. }
  39. public enum ExecuteOutputType
  40. {
  41. Normal,
  42. XmlFile,
  43. HtmlFile,
  44. CsvFile
  45. }
  46. public class EditorTab
  47. {
  48. public SqlEditorSharp editor;
  49. public Label label;
  50. public string filename;
  51. public string basefilename;
  52. public int page;
  53. }
  54. public class SqlSharpGtk
  55. {
  56. static int SqlWindowCount = 0;
  57. private IDbConnection conn = null;
  58. public DbProvider dbProvider = null;
  59. private Type connectionType = null;
  60. private Type adapterType = null;
  61. public Assembly providerAssembly = null;
  62. public string connectionString = "";
  63. private Statusbar statusBar;
  64. private Toolbar toolbar;
  65. int lastUnknownFile = 0;
  66. // OutputResults
  67. private VBox outbox;
  68. // OutputResults.TextView
  69. private ScrolledWindow swin;
  70. public TextBuffer buf;
  71. private TextView textView;
  72. private TextTag textTag;
  73. // OutputResults.DataGrid
  74. private DataGrid grid;
  75. private Gtk.Window win;
  76. public static readonly string ApplicationName = "Mono SQL# For GTK#";
  77. private OutputResults outputResults;
  78. public DbProviderCollection providerList;
  79. Notebook sourceFileNotebook;
  80. Notebook resultsNotebook;
  81. ArrayList editorTabs = new ArrayList();
  82. public SqlSharpGtk ()
  83. {
  84. CreateGui ();
  85. SqlWindowCount ++;
  86. LoadProviders ();
  87. }
  88. public void Show ()
  89. {
  90. win.ShowAll ();
  91. }
  92. public void CreateGui()
  93. {
  94. win = new Gtk.Window (ApplicationName);
  95. win.DeleteEvent += new GtkSharp.DeleteEventHandler(OnWindow_Delete);
  96. win.BorderWidth = 4;
  97. win.DefaultSize = new Size (450, 300);
  98. VBox vbox = new VBox (false, 4);
  99. win.Add (vbox);
  100. // Menu Bar
  101. MenuBar mb = CreateMenuBar ();
  102. vbox.PackStart(mb, false, false, 0);
  103. // Tool Bar
  104. toolbar = CreateToolbar ();
  105. vbox.PackStart (toolbar, false, false, 0);
  106. // Panels
  107. VPaned paned = new VPaned ();
  108. vbox.PackStart (paned, true, true, 0);
  109. // SQL Editor (top TextView panel)
  110. sourceFileNotebook = new Notebook();
  111. sourceFileNotebook.Scrollable = true;
  112. NewEditorTab();
  113. paned.Add1 (sourceFileNotebook);
  114. sourceFileNotebook.SwitchPage += new
  115. GtkSharp.SwitchPageHandler(OnEditorTabSwitched);
  116. // bottom panel
  117. resultsNotebook = CreateOutputResultsGui ();
  118. paned.Add2 (resultsNotebook);
  119. statusBar = new Statusbar ();
  120. vbox.PackEnd (statusBar, false, false, 0);
  121. outputResults = OutputResults.TextView;
  122. ToggleResultsOutput ();
  123. }
  124. EditorTab NewEditorTab ()
  125. {
  126. SqlEditorSharp editor;
  127. editor = new SqlEditorSharp ();
  128. editor.UseSyntaxHiLighting = true;
  129. editor.View.Show ();
  130. editor.View.KeyPressEvent +=
  131. new GtkSharp.KeyPressEventHandler(OnKeyPressEventKey);
  132. lastUnknownFile ++;
  133. string unknownFile = "Unknown" +
  134. lastUnknownFile.ToString() + ".sql";
  135. Label label = new Label(unknownFile);
  136. label.Show();
  137. sourceFileNotebook.AppendPage(editor, label);
  138. sourceFileNotebook.ShowAll ();
  139. sourceFileNotebook.ResizeChildren ();
  140. sourceFileNotebook.CurrentPage = -1;
  141. EditorTab tab = new EditorTab();
  142. tab.editor = editor;
  143. tab.label = label;
  144. tab.filename = "";
  145. tab.basefilename = unknownFile;
  146. tab.page = sourceFileNotebook.CurrentPage;
  147. editorTabs.Add(tab);
  148. editor.Tab = tab;
  149. UpdateTitleBar(tab);
  150. return tab;
  151. }
  152. // bottom panel
  153. Notebook CreateOutputResultsGui ()
  154. {
  155. Label label;
  156. Notebook results = new Notebook();
  157. results.TabPos = PositionType.Bottom;
  158. grid = CreateOutputResultsDataGrid ();
  159. grid.Show();
  160. label = new Label("Grid");
  161. results.AppendPage(grid, label);
  162. swin = CreateOutputResultsTextView ();
  163. swin.Show();
  164. label = new Label("Log");
  165. results.AppendPage(swin, label);
  166. sourceFileNotebook.ShowAll ();
  167. sourceFileNotebook.ResizeChildren ();
  168. return results;
  169. }
  170. DataGrid CreateOutputResultsDataGrid ()
  171. {
  172. return new DataGrid ();
  173. }
  174. ScrolledWindow CreateOutputResultsTextView ()
  175. {
  176. ScrolledWindow sw;
  177. sw = new ScrolledWindow (
  178. new Adjustment (0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
  179. new Adjustment (0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
  180. sw.HscrollbarPolicy = Gtk.PolicyType.Automatic;
  181. sw.VscrollbarPolicy = Gtk.PolicyType.Automatic;
  182. sw.ShadowType = Gtk.ShadowType.In;
  183. textView = new TextView ();
  184. buf = textView.Buffer;
  185. textView.Editable = false;
  186. textView.ModifyFont (Pango.FontDescription.FromString ("courier new"));
  187. sw.Add (textView);
  188. return sw;
  189. }
  190. void OnKeyPressEventKey(object o, GtkSharp.KeyPressEventArgs args)
  191. {
  192. if (o is TextView) {
  193. TextView tv = (TextView) o;
  194. //Gdk.EventKey k = args.Event;
  195. // if the F5 key was pressed
  196. if (args.Event.keyval == 0xFFC2) {
  197. if (tv.Editable == true) {
  198. // execute SQL
  199. ExecuteSQL (ExecuteOutputType.Normal, "");
  200. }
  201. }
  202. }
  203. }
  204. Toolbar CreateToolbar ()
  205. {
  206. Toolbar toolbar = new Toolbar ();
  207. toolbar.ToolbarStyle = ToolbarStyle.Icons;
  208. toolbar.AppendItem ("Execute",
  209. "Execute SQL Commands.", String.Empty,
  210. new Gtk.Image (Stock.Execute, IconSize.SmallToolbar),
  211. new Gtk.SignalFunc (OnToolbar_Execute));
  212. toolbar.AppendItem ("DataGrid",
  213. "Toggle Results to DataGrid or TextView", String.Empty,
  214. new Gtk.Image (Stock.GoDown, IconSize.SmallToolbar),
  215. new Gtk.SignalFunc (OnToolbar_ToggleResultsOutput));
  216. return toolbar;
  217. }
  218. // TODO: use the ProviderFactory in Mono.Data
  219. // to load providers
  220. // instead of what's below
  221. public void LoadProviders ()
  222. {
  223. providerList = new DbProviderCollection ();
  224. providerList.Add (new DbProvider (
  225. "MYSQL",
  226. "MySQL (Mono)",
  227. "Mono.Data.MySql",
  228. "Mono.Data.MySql.MySqlConnection",
  229. "Mono.Data.MySql.MySqlDataAdapter",
  230. false ));
  231. providerList.Add (new DbProvider (
  232. "MYSQLNET",
  233. "MySQL (ByteFX)",
  234. "ByteFX.Data",
  235. "ByteFX.Data.MySQLClient.MySQLConnection",
  236. "ByteFX.Data.MySQLClient.MySQLDataAdapter",
  237. false ));
  238. providerList.Add (new DbProvider (
  239. "POSTGRESQL",
  240. "PostgreSQL (Mono)",
  241. "Mono.Data.PostgreSqlClient",
  242. "Mono.Data.PostgreSqlClient.PgSqlConnection",
  243. "Mono.Data.PostgreSqlClient.PgSqlDataAdapter",
  244. false ));
  245. providerList.Add (new DbProvider (
  246. "NPGSQL",
  247. "PostgreSQL (Npgsql)",
  248. "Npgsql",
  249. "Npgsql.NpgsqlConnection",
  250. "Npgsql.NpgsqlDataAdapter",
  251. false ));
  252. providerList.Add (new DbProvider (
  253. "SQLCLIENT",
  254. "Microsoft SQL Server",
  255. "",
  256. "",
  257. "",
  258. true ));
  259. providerList.Add (new DbProvider (
  260. "TDS",
  261. "TDS Generic",
  262. "Mono.Data.TdsClient",
  263. "Mono.Data.TdsClient.TdsConnection",
  264. "Mono.Data.TdsClient.TdsDataAdapter",
  265. false ));
  266. providerList.Add (new DbProvider (
  267. "ODBC",
  268. "ODBC",
  269. "",
  270. "",
  271. "",
  272. true ));
  273. providerList.Add (new DbProvider (
  274. "OLEDB",
  275. "OLE DB",
  276. "",
  277. "",
  278. "",
  279. true ));
  280. providerList.Add (new DbProvider (
  281. "SQLITE",
  282. "SQL Lite",
  283. "Mono.Data.SqliteClient",
  284. "Mono.Data.SqliteClient.SqliteConnection",
  285. "Mono.Data.SqliteClient.SqliteDataAdapter",
  286. false ));
  287. providerList.Add (new DbProvider (
  288. "SYBASE",
  289. "Sybase",
  290. "Mono.Data.SybaseClient",
  291. "Mono.Data.SybaseClient.SybaseConnection",
  292. "Mono.Data.SybaseClient.SybaseDataAdapter",
  293. false ));
  294. providerList.Add (new DbProvider (
  295. "DB2",
  296. "IBM DB2",
  297. "Mono.Data.DB2Client",
  298. "Mono.Data.DB2Client.DB2ClientConnection",
  299. "Mono.Data.DB2Client.DB2ClientDataAdapter",
  300. false ));
  301. providerList.Add (new DbProvider (
  302. "ORACLE",
  303. "Oracle",
  304. "System.Data.OracleClient",
  305. "System.Data.OracleClient.OracleConnection",
  306. "System.Data.OracleClient.OracleDataAdapter",
  307. false ));
  308. }
  309. public MenuBar CreateMenuBar ()
  310. {
  311. MenuBar menuBar = new MenuBar ();
  312. Menu menu;
  313. Menu submenu;
  314. MenuItem item;
  315. MenuItem barItem;
  316. MenuItem subitem;
  317. // File menu
  318. menu = new Menu ();
  319. item = new MenuItem ("New SQL# _Window");
  320. item.Activated += new EventHandler (OnMenu_FileNewSqlWindow);
  321. menu.Append (item);
  322. menu.Append (new SeparatorMenuItem ());
  323. item = new MenuItem ("_New");
  324. item.Activated += new EventHandler (OnMenu_FileNew);
  325. menu.Append (item);
  326. item = new MenuItem ("_Open...");
  327. item.Activated += new EventHandler (OnMenu_FileOpen);
  328. menu.Append (item);
  329. item = new MenuItem ("_Save");
  330. item.Activated += new EventHandler (OnMenu_FileSave);
  331. menu.Append (item);
  332. item = new MenuItem ("Save _As...");
  333. item.Activated += new EventHandler (OnMenu_FileSaveAs);
  334. menu.Append (item);
  335. item = new MenuItem ("Close");
  336. item.Activated += new EventHandler (OnMenu_FileClose);
  337. menu.Append (item);
  338. menu.Append (new SeparatorMenuItem ());
  339. // TODO: submenu Save Output
  340. submenu = new Menu ();
  341. subitem = new MenuItem ("CSV - Comma Separated Values");
  342. //subitem.Activated += new EventHandler (OnMenu_FileSaveOutput_CSV);
  343. submenu.Append(subitem);
  344. subitem = new MenuItem ("TAB - Tab Separated Values");
  345. //subitem.Activated += new EventHandler (OnMenu_FileSaveOutput_TAB);
  346. submenu.Append(subitem);
  347. subitem = new MenuItem ("XML");
  348. //subitem.Activated += new EventHandler (OnMenu_FileSaveOutput_XML);
  349. submenu.Append(subitem);
  350. item = new MenuItem ("Save _Output...");
  351. item.Submenu = submenu;
  352. menu.Append (item);
  353. menu.Append (new SeparatorMenuItem ());
  354. item = new MenuItem ("E_xit");
  355. item.Activated += new EventHandler (OnMenu_FileExit);
  356. menu.Append (item);
  357. barItem = new MenuItem ("_File");
  358. barItem.Submenu = menu;
  359. menuBar.Append (barItem);
  360. // Edit menu
  361. menu = new Menu ();
  362. item = new MenuItem ("_Undo");
  363. //item.Activated += new EventHandler (OnMenu_EditUndo);
  364. menu.Append (item);
  365. item = new MenuItem ("_Redo");
  366. //item.Activated += new EventHandler (OnMenu_EditRedo);
  367. menu.Append (item);
  368. menu.Append (new SeparatorMenuItem ());
  369. item = new MenuItem ("Cu_t");
  370. //item.Activated += new EventHandler (OnMenu_EditCut);
  371. menu.Append (item);
  372. item = new MenuItem ("_Copy");
  373. //item.Activated += new EventHandler (OnMenu_EditCopy);
  374. menu.Append (item);
  375. item = new MenuItem ("_Paste");
  376. //item.Activated += new EventHandler (OnMenu_EditPaste);
  377. menu.Append (item);
  378. item = new MenuItem ("_Delete");
  379. //item.Activated += new EventHandler (OnMenu_EditDelete);
  380. menu.Append (item);
  381. menu.Append (new SeparatorMenuItem ());
  382. item = new MenuItem ("_Find and Replace...");
  383. //item.Activated += new EventHandler (OnMenu_EditFindReplace);
  384. menu.Append (item);
  385. menu.Append (new SeparatorMenuItem ());
  386. item = new MenuItem ("_Options");
  387. //item.Activated += new EventHandler (OnMenu_EditOptions);
  388. menu.Append (item);
  389. barItem = new MenuItem ("_Edit");
  390. barItem.Submenu = menu;
  391. menuBar.Append (barItem);
  392. // Session menu
  393. menu = new Menu ();
  394. item = new MenuItem ("_Connect");
  395. item.Activated += new EventHandler (OnMenu_SessionConnect);
  396. menu.Append (item);
  397. item = new MenuItem ("_Disconnect");
  398. item.Activated += new EventHandler (OnMenu_SessionDisconnect);
  399. menu.Append (item);
  400. barItem = new MenuItem ("_Session");
  401. barItem.Submenu = menu;
  402. menuBar.Append (barItem);
  403. // Command menu
  404. menu = new Menu ();
  405. item = new MenuItem ("_Execute");
  406. item.Activated += new EventHandler (OnMenu_CommandExecute);
  407. menu.Append (item);
  408. item = new MenuItem ("_Execute With Output to XML");
  409. item.Activated += new EventHandler (OnMenu_CommandExecuteXML);
  410. menu.Append (item);
  411. item = new MenuItem ("_Execute With Output to CSV");
  412. item.Activated += new EventHandler (OnMenu_CommandExecuteCSV);
  413. menu.Append (item);
  414. item = new MenuItem ("_Execute With Output to HTML");
  415. item.Activated += new EventHandler (OnMenu_CommandExecuteHTML);
  416. menu.Append (item);
  417. barItem = new MenuItem ("_Command");
  418. barItem.Submenu = menu;
  419. menuBar.Append (barItem);
  420. return menuBar;
  421. }
  422. void AppendText (string text)
  423. {
  424. AppendText (buf, text);
  425. }
  426. public void AppendTextWithoutScroll (TextBuffer buffer, string text)
  427. {
  428. TextIter iter;
  429. text = text.Replace("\0","");
  430. buffer.MoveMark(buf.InsertMark, buffer.EndIter);
  431. if (text.Equals ("") == false) {
  432. iter = buffer.EndIter;
  433. buffer.Insert (iter, text);
  434. }
  435. iter = buffer.EndIter;
  436. buffer.Insert (iter, "\n");
  437. }
  438. // WriteLine() to output text to bottom TextView
  439. // for displaying result sets and logging messages
  440. public void AppendText (TextBuffer buffer, string text)
  441. {
  442. AppendTextWithoutScroll(buffer,text);
  443. while (Application.EventsPending ())
  444. Application.RunIteration ();
  445. textView.ScrollToMark (buf.InsertMark, 0.4, true, 0.0, 1.0);
  446. }
  447. public bool LoadExternalProvider (string strProviderAssembly,
  448. string providerConnectionClass)
  449. {
  450. try {
  451. SqlSharpGtk.DebugWriteLine ("Loading external provider...");
  452. providerAssembly = null;
  453. providerAssembly = Assembly.Load (strProviderAssembly);
  454. Type typ = providerAssembly.GetType (providerConnectionClass);
  455. conn = (IDbConnection) Activator.CreateInstance (typ);
  456. SqlSharpGtk.DebugWriteLine ("External provider loaded.");
  457. }
  458. catch (Exception f) {
  459. string errorMessage = String.Format (
  460. "Error: unable to load the assembly of the provider: {1} because: {2}",
  461. providerAssembly,
  462. f.Message);
  463. Error (errorMessage);
  464. return false;
  465. }
  466. return true;
  467. }
  468. void QuitApplication()
  469. {
  470. if(conn != null)
  471. if(conn.State == ConnectionState.Open) {
  472. Console.WriteLine("Closing connection...");
  473. conn.Close();
  474. conn = null;
  475. Console.WriteLine("Connection closed.");
  476. }
  477. if(grid.DataSource != null) {
  478. grid.Clear ();
  479. grid.DataSource = null;
  480. grid.DataMember = "";
  481. grid = null;
  482. }
  483. SqlWindowCount --;
  484. if(SqlWindowCount == 0)
  485. Application.Quit ();
  486. else
  487. win.Destroy ();
  488. }
  489. void UpdateTitleBar(EditorTab tab)
  490. {
  491. string title = "";
  492. if(tab != null) {
  493. if(tab.filename.Equals(""))
  494. title = tab.label.Text + " - " + ApplicationName;
  495. else
  496. title = tab.filename + " - " + ApplicationName;
  497. }
  498. else {
  499. title = ApplicationName;
  500. }
  501. win.Title = title;
  502. }
  503. void OnEditorTabSwitched (object o, GtkSharp.SwitchPageArgs args)
  504. {
  505. int page = (int) args.PageNum;
  506. EditorTab tab = FindEditorTab(page);
  507. UpdateTitleBar (tab);
  508. }
  509. void OnWindow_Delete (object o, GtkSharp.DeleteEventArgs args)
  510. {
  511. QuitApplication();
  512. }
  513. void OnExit (Gtk.Object o)
  514. {
  515. QuitApplication();
  516. }
  517. void OnMenu_FileNewSqlWindow (object o, EventArgs args)
  518. {
  519. SqlSharpGtk sqlSharp = new SqlSharpGtk ();
  520. sqlSharp.Show ();
  521. }
  522. void OnMenu_FileNew (object o, EventArgs args)
  523. {
  524. NewEditorTab();
  525. sourceFileNotebook.CurrentPage = -1;
  526. }
  527. void OnMenu_FileOpen (object o, EventArgs args)
  528. {
  529. FileSelectionDialog openFileDialog =
  530. new FileSelectionDialog ("Open File",
  531. new FileSelectionEventHandler (OnOpenFile));
  532. }
  533. void OnOpenFile (object o, FileSelectionEventArgs args)
  534. {
  535. EditorTab etab = NewEditorTab();
  536. try {
  537. etab.editor.LoadFromFile (args.Filename);
  538. }
  539. catch(Exception openFileException) {
  540. Error("Error: Could not open file: \n" +
  541. args.Filename +
  542. "\n\nReason: " +
  543. openFileException.Message);
  544. return;
  545. }
  546. TextBuffer buf = etab.editor.Buffer;
  547. buf.Modified = false;
  548. string basefile = Path.GetFileName (args.Filename);
  549. etab.label.Text = basefile;
  550. etab.basefilename = basefile;
  551. etab.filename = args.Filename;
  552. sourceFileNotebook.CurrentPage = -1;
  553. UpdateTitleBar(etab);
  554. }
  555. EditorTab FindEditorTab (int searchPage)
  556. {
  557. EditorTab tab = null;
  558. for (int t = 0; t < editorTabs.Count; t++) {
  559. tab = (EditorTab) editorTabs[t];
  560. if (tab.page == searchPage)
  561. return tab;
  562. }
  563. return tab;
  564. }
  565. void OnMenu_FileSave (object o, EventArgs args)
  566. {
  567. int page = sourceFileNotebook.CurrentPage;
  568. EditorTab tab = FindEditorTab(page);
  569. if(tab.filename.Equals(""))
  570. SaveAs();
  571. else {
  572. SaveFile(tab.filename);
  573. tab.label.Text = tab.basefilename;
  574. }
  575. }
  576. void SaveFile (string filename)
  577. {
  578. int page = sourceFileNotebook.CurrentPage;
  579. EditorTab etab = FindEditorTab(page);
  580. try {
  581. // FIXME: if file exists, ask if you want to
  582. // overwrite. currently, it overwrites
  583. // without asking.
  584. etab.editor.SaveToFile (filename);
  585. } catch(Exception saveFileException) {
  586. Error("Error: Could not open file: \n" +
  587. filename +
  588. "\n\nReason: " +
  589. saveFileException.Message);
  590. return;
  591. }
  592. TextBuffer buf = etab.editor.Buffer;
  593. buf.Modified = false;
  594. }
  595. void OnMenu_FileSaveAs (object o, EventArgs args)
  596. {
  597. SaveAs();
  598. }
  599. void SaveAs()
  600. {
  601. FileSelectionDialog openFileDialog =
  602. new FileSelectionDialog ("File Save As",
  603. new FileSelectionEventHandler (OnSaveAsFile));
  604. }
  605. void OnSaveAsFile (object o, FileSelectionEventArgs args)
  606. {
  607. int page = sourceFileNotebook.CurrentPage;
  608. EditorTab etab = FindEditorTab(page);
  609. SaveFile(args.Filename);
  610. string basefile = Path.GetFileName (args.Filename);
  611. etab.label.Text = basefile;
  612. etab.basefilename = basefile;
  613. etab.filename = args.Filename;
  614. UpdateTitleBar(etab);
  615. }
  616. void OnMenu_FileClose (object o, EventArgs args)
  617. {
  618. CloseEditor();
  619. }
  620. void OnCloseEditor (object obj, EventArgs args)
  621. {
  622. CloseEditor();
  623. }
  624. void CloseEditor ()
  625. {
  626. int page = sourceFileNotebook.CurrentPage;
  627. SqlEditorSharp sqlEditor;
  628. sqlEditor = (SqlEditorSharp) sourceFileNotebook.GetNthPage(page);
  629. TextBuffer buffer = sqlEditor.Buffer;
  630. if(buffer.Modified) {
  631. // TODO: if text modified,
  632. // ask if user wants to save
  633. // before closing.
  634. // use MessageDialog to prompt
  635. RemoveEditorTab (sqlEditor.Tab, page);
  636. }
  637. else {
  638. RemoveEditorTab (sqlEditor.Tab, page);
  639. }
  640. sqlEditor = null;
  641. buffer = null;
  642. }
  643. void RemoveEditorTab (EditorTab tab, int page)
  644. {
  645. tab.editor.Clear();
  646. tab.editor.Tab = null;
  647. tab.editor = null;
  648. tab.label = null;
  649. editorTabs.Remove(tab);
  650. sourceFileNotebook.RemovePage (page);
  651. sourceFileNotebook.QueueDraw();
  652. tab = null;
  653. }
  654. void OnMenu_FileExit (object o, EventArgs args)
  655. {
  656. QuitApplication ();
  657. }
  658. void OnMenu_SessionConnect (object o, EventArgs args)
  659. {
  660. LoginDialog login = new LoginDialog (this);
  661. login = null;
  662. }
  663. void OnMenu_SessionDisconnect (object o, EventArgs args)
  664. {
  665. AppendText(buf, "Disconnecting...");
  666. try {
  667. conn.Close ();
  668. conn = null;
  669. }
  670. catch (Exception e) {
  671. Error ("Error: Unable to disconnect." +
  672. e.Message);
  673. conn = null;
  674. return;
  675. }
  676. AppendText (buf, "Disconnected.");
  677. }
  678. void OnToolbar_ToggleResultsOutput ()
  679. {
  680. ToggleResultsOutput ();
  681. }
  682. void ToggleResultsOutput ()
  683. {
  684. if (outputResults == OutputResults.TextView) {
  685. outputResults = OutputResults.DataGrid;
  686. }
  687. else if (outputResults == OutputResults.DataGrid) {
  688. outputResults = OutputResults.TextView;
  689. }
  690. }
  691. public void OnToolbar_Execute ()
  692. {
  693. ExecuteSQL (ExecuteOutputType.Normal, "");
  694. }
  695. // Execute SQL Commands
  696. void ExecuteSQL (ExecuteOutputType outputType, string filename)
  697. {
  698. if (conn == null) {
  699. AppendText (buf, "Error: Not Connected.");
  700. return;
  701. }
  702. DataTable schemaTable = null;
  703. int page = sourceFileNotebook.CurrentPage;
  704. EditorTab tab = FindEditorTab(page);
  705. string msg = "";
  706. string sql = "";
  707. IDbCommand cmd;
  708. try {
  709. cmd = conn.CreateCommand ();
  710. }
  711. catch (Exception ec) {
  712. AppendText (buf,
  713. "Error: Unable to create command to execute: " +
  714. ec.Message);
  715. return;
  716. }
  717. SqlSharpGtk.DebugWriteLine ("get text from SQL editor...");
  718. // get text from SQL editor
  719. try {
  720. TextIter start_iter, end_iter;
  721. TextBuffer exeBuff;
  722. exeBuff = tab.editor.Buffer;
  723. start_iter = exeBuff.StartIter;
  724. end_iter = exeBuff.EndIter;
  725. sql = exeBuff.GetText(start_iter, end_iter, false);
  726. }
  727. catch (Exception et) {
  728. AppendText (buf,
  729. "Error: Unable to get text from SQL editor: " +
  730. et.Message);
  731. return;
  732. }
  733. try {
  734. cmd.CommandText = sql;
  735. }
  736. catch (Exception e) {
  737. AppendText (buf,
  738. "Error: Unable to set SQL text to command.");
  739. }
  740. IDataReader reader = null;
  741. SqlSharpGtk.DebugWriteLine ("Executing SQL: " + sql);
  742. if ((outputResults == OutputResults.TextView &&
  743. outputType == ExecuteOutputType.Normal) ||
  744. outputType == ExecuteOutputType.HtmlFile ||
  745. outputType == ExecuteOutputType.CsvFile) {
  746. try {
  747. reader = cmd.ExecuteReader ();
  748. }
  749. catch (Exception e) {
  750. //msg = "SQL Execution Error: " + e.Message;
  751. msg = "SQL Execution Error: " + e;
  752. Error (msg);
  753. return;
  754. }
  755. if (reader == null) {
  756. Error("Error: reader is null");
  757. return;
  758. }
  759. }
  760. try {
  761. if (outputResults == OutputResults.TextView &&
  762. outputType == ExecuteOutputType.Normal) {
  763. DisplayData (reader);
  764. // clean up
  765. reader.Close ();
  766. reader.Dispose ();
  767. reader = null;
  768. }
  769. else if(outputType == ExecuteOutputType.HtmlFile) {
  770. schemaTable = reader.GetSchemaTable();
  771. if(schemaTable != null && reader.FieldCount > 0) {
  772. OutputDataToHtmlFile(reader, schemaTable, filename);
  773. }
  774. else {
  775. AppendText("Command executed.");
  776. }
  777. // clean up
  778. reader.Close ();
  779. reader.Dispose ();
  780. reader = null;
  781. }
  782. else if(outputType == ExecuteOutputType.CsvFile) {
  783. schemaTable = reader.GetSchemaTable();
  784. if(schemaTable != null && reader.FieldCount > 0) {
  785. OutputDataToCsvFile(reader, schemaTable, filename);
  786. }
  787. else {
  788. AppendText("Command executed.");
  789. }
  790. // clean up
  791. reader.Close ();
  792. reader.Dispose ();
  793. reader = null;
  794. }
  795. else {
  796. DataTable dataTable = LoadDataTable (cmd);
  797. switch(outputType) {
  798. case ExecuteOutputType.Normal:
  799. AppendText("set DataGrid.DataSource to DataTable...");
  800. grid.DataSource = dataTable;
  801. AppendText("DataBind...");
  802. grid.DataBind ();
  803. AppendText("Clean up...");
  804. // clean up
  805. grid.DataSource = null;
  806. break;
  807. case ExecuteOutputType.XmlFile:
  808. AppendText("Create DataSet...");
  809. DataSet dataSet = new DataSet();
  810. AppendText("Add DataTable to DataSet's DataTableCollection...");
  811. dataSet.Tables.Add(dataTable);
  812. AppendText("Write DataSet to XML file: " +
  813. filename);
  814. dataSet.WriteXml(filename);
  815. AppendText("Clean up...");
  816. dataSet = null;
  817. break;
  818. }
  819. // clean up
  820. dataTable.Clear();
  821. dataTable.Dispose();
  822. dataTable = null;
  823. AppendText("Done.");
  824. cmd.Dispose();
  825. cmd = null;
  826. }
  827. }
  828. catch (Exception e) {
  829. //msg = "Error Displaying Data: " + e.Message;
  830. msg = "Error Displaying Data: " + e;
  831. Error (msg);
  832. }
  833. }
  834. public void OutputDataToHtmlFile(IDataReader rdr, DataTable dt, string file)
  835. {
  836. AppendText("Outputting results to HTML file " + file + "...");
  837. StreamWriter outputFilestream = null;
  838. try {
  839. outputFilestream = new StreamWriter(file);
  840. }
  841. catch(Exception e) {
  842. Error("Error: Unable to setup output results file. " +
  843. e.Message);
  844. return;
  845. }
  846. StringBuilder strHtml = new StringBuilder();
  847. strHtml.Append("<html>\n<head><title>");
  848. strHtml.Append("Results");
  849. strHtml.Append("</title></head>\n");
  850. strHtml.Append("<body>\n");
  851. strHtml.Append("<h1>Results</h1>\n");
  852. strHtml.Append("\t<table border=1>\n");
  853. outputFilestream.WriteLine(strHtml.ToString());
  854. strHtml = null;
  855. strHtml = new StringBuilder();
  856. strHtml.Append("\t\t<tr>\n");
  857. for (int c = 0; c < rdr.FieldCount; c++) {
  858. strHtml.Append("\t\t\t<td><b>");
  859. string sColumnName = rdr.GetName(c);
  860. strHtml.Append(sColumnName);
  861. strHtml.Append("</b></td>\n");
  862. }
  863. strHtml.Append("\t\t</tr>\n");
  864. outputFilestream.WriteLine(strHtml.ToString());
  865. strHtml = null;
  866. int col = 0;
  867. string dataValue = "";
  868. while(rdr.Read()) {
  869. strHtml = new StringBuilder();
  870. strHtml.Append("\t\t<tr>\n");
  871. for(col = 0; col < rdr.FieldCount; col++) {
  872. // column data
  873. if(rdr.IsDBNull(col) == true)
  874. dataValue = "NULL";
  875. else {
  876. object obj = rdr.GetValue(col);
  877. dataValue = obj.ToString();
  878. }
  879. strHtml.Append("\t\t\t<td>");
  880. strHtml.Append(dataValue);
  881. strHtml.Append("</td>\n");
  882. }
  883. strHtml.Append("\t\t</tr>\n");
  884. outputFilestream.WriteLine(strHtml.ToString());
  885. strHtml = null;
  886. }
  887. outputFilestream.WriteLine("\t</table>\n</body>\n</html>\n");
  888. strHtml = null;
  889. outputFilestream.Close();
  890. outputFilestream = null;
  891. AppendText("Outputting file done.");
  892. }
  893. public void OutputDataToCsvFile(IDataReader rdr, DataTable dt, string file)
  894. {
  895. AppendText("Outputting results to CSV file " + file + "...");
  896. StreamWriter outputFilestream = null;
  897. try {
  898. outputFilestream = new StreamWriter(file);
  899. }
  900. catch(Exception e) {
  901. Error("Error: Unable to setup output results file. " +
  902. e.Message);
  903. return;
  904. }
  905. StringBuilder strCsv = null;
  906. int col = 0;
  907. string dataValue = "";
  908. while(rdr.Read()) {
  909. strCsv = new StringBuilder();
  910. for(col = 0; col < rdr.FieldCount; col++) {
  911. if(col > 0)
  912. strCsv.Append(",");
  913. // column data
  914. if(rdr.IsDBNull(col) == true)
  915. dataValue = "\"\"";
  916. else {
  917. object obj = rdr.GetValue(col);
  918. dataValue = "\"" + obj.ToString() + "\"";
  919. }
  920. strCsv.Append(dataValue);
  921. }
  922. outputFilestream.WriteLine(strCsv.ToString());
  923. strCsv = null;
  924. }
  925. strCsv = null;
  926. outputFilestream.Close();
  927. outputFilestream = null;
  928. AppendText("Outputting file done.");
  929. }
  930. void OnMenu_CommandExecute (object o, EventArgs args)
  931. {
  932. ExecuteSQL (ExecuteOutputType.Normal, "");
  933. }
  934. void OnMenu_CommandExecuteXML (object o, EventArgs args)
  935. {
  936. ExecuteAndSaveResultsToFile (ExecuteOutputType.XmlFile);
  937. }
  938. void OnMenu_CommandExecuteCSV (object o, EventArgs args)
  939. {
  940. ExecuteAndSaveResultsToFile (ExecuteOutputType.CsvFile);
  941. }
  942. void OnMenu_CommandExecuteHTML (object o, EventArgs args)
  943. {
  944. ExecuteAndSaveResultsToFile (ExecuteOutputType.HtmlFile);
  945. }
  946. ExecuteOutputType outType;
  947. void ExecuteAndSaveResultsToFile(ExecuteOutputType oType)
  948. {
  949. outType = oType;
  950. FileSelectionDialog openFileDialog =
  951. new FileSelectionDialog ("Results File Save As",
  952. new FileSelectionEventHandler (OnSaveExeOutFile));
  953. }
  954. void OnSaveExeOutFile (object o, FileSelectionEventArgs args)
  955. {
  956. ExecuteSQL (outType, args.Filename);
  957. }
  958. public void DisplayResult (IDataReader reader, DataTable schemaTable)
  959. {
  960. const string zero = "0";
  961. StringBuilder column = null;
  962. StringBuilder line = null;
  963. StringBuilder hdrUnderline = null;
  964. string outData = "";
  965. int hdrLen = 0;
  966. int spacing = 0;
  967. int columnSize = 0;
  968. int c;
  969. char spacingChar = ' '; // a space
  970. char underlineChar = '='; // an equal sign
  971. string dataType; // .NET Type
  972. Type theType;
  973. string dataTypeName; // native Database type
  974. DataRow row; // schema row
  975. line = new StringBuilder ();
  976. hdrUnderline = new StringBuilder ();
  977. try {
  978. OutputLine ("Fields in Query Result: " +
  979. reader.FieldCount);
  980. }
  981. catch(Exception e){
  982. Error ("Error: Unable to get FieldCount: " +
  983. e.Message);
  984. return;
  985. }
  986. OutputLine ("");
  987. for(c = 0; c < reader.FieldCount; c++) {
  988. try {
  989. DataRow schemaRow = schemaTable.Rows[c];
  990. string columnHeader = reader.GetName (c);
  991. if (columnHeader.Equals (""))
  992. columnHeader = "column";
  993. if (columnHeader.Length > 32)
  994. columnHeader = columnHeader.Substring (0,32);
  995. // spacing
  996. columnSize = (int) schemaRow["ColumnSize"];
  997. theType = reader.GetFieldType(c);
  998. dataType = theType.ToString();
  999. //dataTypeName = reader.GetDataTypeName(c);
  1000. switch(dataType) {
  1001. case "System.DateTime":
  1002. columnSize = 19;
  1003. break;
  1004. case "System.Boolean":
  1005. columnSize = 5;
  1006. break;
  1007. }
  1008. hdrLen = Math.Max (columnHeader.Length, columnSize);
  1009. if(hdrLen < 0)
  1010. hdrLen = 0;
  1011. if(hdrLen > 32)
  1012. hdrLen = 32;
  1013. line.Append(columnHeader);
  1014. if(columnHeader.Length < hdrLen) {
  1015. spacing = hdrLen - columnHeader.Length;
  1016. line.Append(spacingChar, spacing);
  1017. }
  1018. hdrUnderline.Append(underlineChar, hdrLen);
  1019. line.Append(" ");
  1020. hdrUnderline.Append(" ");
  1021. }
  1022. catch(Exception e) {
  1023. Error ("Error: Unable to display header: " +
  1024. e.Message);
  1025. return;
  1026. }
  1027. }
  1028. OutputHeader(line.ToString());
  1029. line = null;
  1030. OutputHeader(hdrUnderline.ToString());
  1031. OutputHeader("");
  1032. hdrUnderline = null;
  1033. int numRows = 0;
  1034. // column data
  1035. try {
  1036. while(reader.Read()) {
  1037. numRows++;
  1038. line = new StringBuilder();
  1039. for(c = 0; c < reader.FieldCount; c++) {
  1040. int dataLen = 0;
  1041. string dataValue = "";
  1042. column = new StringBuilder();
  1043. outData = "";
  1044. row = schemaTable.Rows[c];
  1045. string colhdr = (string) reader.GetName(c);
  1046. if(colhdr.Equals(""))
  1047. colhdr = "column";
  1048. if(colhdr.Length > 32)
  1049. colhdr = colhdr.Substring(0, 32);
  1050. columnSize = (int) row["ColumnSize"];
  1051. theType = reader.GetFieldType(c);
  1052. dataType = theType.ToString();
  1053. //dataTypeName = reader.GetDataTypeName(c);
  1054. switch(dataType) {
  1055. case "System.DateTime":
  1056. columnSize = 19;
  1057. break;
  1058. case "System.Boolean":
  1059. columnSize = 5;
  1060. break;
  1061. }
  1062. columnSize = Math.Max(colhdr.Length, columnSize);
  1063. if(columnSize < 0)
  1064. columnSize = 0;
  1065. if(columnSize > 32)
  1066. columnSize = 32;
  1067. dataValue = "";
  1068. if(reader.IsDBNull(c)) {
  1069. dataValue = "";
  1070. dataLen = 0;
  1071. }
  1072. else {
  1073. StringBuilder sb;
  1074. DateTime dt;
  1075. if(dataType.Equals("System.DateTime")) {
  1076. // display date in ISO format
  1077. // "YYYY-MM-DD HH:MM:SS"
  1078. dt = reader.GetDateTime(c);
  1079. sb = new StringBuilder();
  1080. // year
  1081. if(dt.Year < 10)
  1082. sb.Append("000" + dt.Year);
  1083. else if(dt.Year < 100)
  1084. sb.Append("00" + dt.Year);
  1085. else if(dt.Year < 1000)
  1086. sb.Append("0" + dt.Year);
  1087. else
  1088. sb.Append(dt.Year);
  1089. sb.Append("-");
  1090. // month
  1091. if(dt.Month < 10)
  1092. sb.Append(zero + dt.Month);
  1093. else
  1094. sb.Append(dt.Month);
  1095. sb.Append("-");
  1096. // day
  1097. if(dt.Day < 10)
  1098. sb.Append(zero + dt.Day);
  1099. else
  1100. sb.Append(dt.Day);
  1101. sb.Append(" ");
  1102. // hour
  1103. if(dt.Hour < 10)
  1104. sb.Append(zero + dt.Hour);
  1105. else
  1106. sb.Append(dt.Hour);
  1107. sb.Append(":");
  1108. // minute
  1109. if(dt.Minute < 10)
  1110. sb.Append(zero + dt.Minute);
  1111. else
  1112. sb.Append(dt.Minute);
  1113. sb.Append(":");
  1114. // second
  1115. if(dt.Second < 10)
  1116. sb.Append(zero + dt.Second);
  1117. else
  1118. sb.Append(dt.Second);
  1119. dataValue = sb.ToString();
  1120. }
  1121. else {
  1122. object o = reader.GetValue(c);
  1123. dataValue = o.ToString();
  1124. }
  1125. dataLen = dataValue.Length;
  1126. if(dataLen <= 0) {
  1127. dataValue = "";
  1128. dataLen = 0;
  1129. }
  1130. if(dataLen > 32) {
  1131. dataValue = dataValue.Substring(0,32);
  1132. dataLen = 32;
  1133. }
  1134. }
  1135. columnSize = Math.Max (columnSize, dataLen);
  1136. if(dataLen < columnSize) {
  1137. switch(dataType) {
  1138. case "System.Byte":
  1139. case "System.SByte":
  1140. case "System.Int16":
  1141. case "System.UInt16":
  1142. case "System.Int32":
  1143. case "System.UInt32":
  1144. case "System.Int64":
  1145. case "System.UInt64":
  1146. case "System.Single":
  1147. case "System.Double":
  1148. case "System.Decimal":
  1149. outData = dataValue.PadLeft(columnSize);
  1150. break;
  1151. default:
  1152. outData = dataValue.PadRight(columnSize);
  1153. break;
  1154. }
  1155. outData = outData + " ";
  1156. }
  1157. else
  1158. outData = dataValue;
  1159. line.Append (outData);
  1160. line.Append (" ");
  1161. }
  1162. OutputData (line.ToString ());
  1163. line = null;
  1164. }
  1165. }
  1166. catch (Exception rr) {
  1167. Error ("Error: Unable to read next row: " +
  1168. rr.Message);
  1169. return;
  1170. }
  1171. OutputLine ("\nRows retrieved: " + numRows.ToString());
  1172. AppendText("");
  1173. }
  1174. public void DisplayData(IDataReader reader)
  1175. {
  1176. bool another = false;
  1177. DataTable schemaTable = null;
  1178. int ResultSet = 0;
  1179. OutputLine ("Display any result sets...");
  1180. do {
  1181. // by Default, data reader has the
  1182. // first Result set if any
  1183. ResultSet++;
  1184. OutputLine ("Display the result set " + ResultSet);
  1185. if (reader.FieldCount > 0) {
  1186. // SQL Query (SELECT)
  1187. // RecordsAffected -1 and DataTable has a reference
  1188. try {
  1189. schemaTable = reader.GetSchemaTable ();
  1190. }
  1191. catch (Exception es) {
  1192. Error ("Error: Unable to get schema table: " +
  1193. es.Message);
  1194. return;
  1195. }
  1196. AppendText (buf, "Display Result...");
  1197. DisplayResult (reader, schemaTable);
  1198. }
  1199. else if (reader.RecordsAffected >= 0) {
  1200. // SQL Command (INSERT, UPDATE, or DELETE)
  1201. // RecordsAffected >= 0
  1202. int records = 0;
  1203. try {
  1204. records = reader.RecordsAffected;
  1205. AppendText (buf, "SQL Command Records Affected: " +
  1206. records);
  1207. }
  1208. catch (Exception er) {
  1209. Error ("Error: Unable to get records affected: " +
  1210. er.Message);
  1211. return;
  1212. }
  1213. }
  1214. else {
  1215. // SQL Command (not INSERT, UPDATE, nor DELETE)
  1216. // RecordsAffected -1 and DataTable has a null reference
  1217. AppendText (buf, "SQL Command Executed.");
  1218. }
  1219. // get next result set (if anymore is left)
  1220. try {
  1221. another = reader.NextResult ();
  1222. }
  1223. catch(Exception e) {
  1224. Error ("Error: Unable to read next result: " +
  1225. e.Message);
  1226. return;
  1227. }
  1228. } while(another == true);
  1229. }
  1230. // used for outputting message, but if silent is set,
  1231. // don't display
  1232. public void OutputLine(string line)
  1233. {
  1234. //if(silent == false)
  1235. OutputData(line);
  1236. }
  1237. // used for outputting the header columns of a result
  1238. public void OutputHeader(string line)
  1239. {
  1240. //if(showHeader == true)
  1241. OutputData(line);
  1242. }
  1243. // OutputData() - used for outputting data
  1244. // if an output filename is set, then the data will
  1245. // go to a file; otherwise, it will go to the Console.
  1246. public void OutputData(string line)
  1247. {
  1248. //if(outputFilestream == null)
  1249. // Console.WriteLine(line);
  1250. //else
  1251. // outputFilestream.WriteLine(line);
  1252. AppendTextWithoutScroll(buf,line);
  1253. }
  1254. public void Error(string message)
  1255. {
  1256. Console.WriteLine(message);
  1257. Console.Out.Flush();
  1258. AppendText(buf, message);
  1259. }
  1260. bool OpenInternalProvider ()
  1261. {
  1262. string msg;
  1263. string providerKey = dbProvider.Key;
  1264. switch (providerKey.ToUpper ()) {
  1265. case "SQLCLIENT":
  1266. try {
  1267. conn = new SqlConnection ();
  1268. }
  1269. catch (Exception e) {
  1270. msg = "Error: unable to create connection: " +
  1271. e.Message;
  1272. Error (msg);
  1273. return false;
  1274. }
  1275. break;
  1276. case "ODBC":
  1277. try {
  1278. conn = new OdbcConnection ();
  1279. }
  1280. catch (Exception e) {
  1281. msg = "Error: unable to create connection: " +
  1282. e.Message;
  1283. Error (msg);
  1284. return false;
  1285. }
  1286. break;
  1287. case "OLEDB":
  1288. try {
  1289. conn = new OleDbConnection ();
  1290. }
  1291. catch (Exception e) {
  1292. msg = "Error: unable to create connection: " +
  1293. e.Message;
  1294. Error (msg);
  1295. return false;
  1296. }
  1297. break;
  1298. default:
  1299. msg = "Error: provider not supported.";
  1300. Error (msg);
  1301. return false;
  1302. }
  1303. return true;
  1304. }
  1305. bool OpenExternalProvider()
  1306. {
  1307. bool success = false;
  1308. success = LoadExternalProvider (
  1309. dbProvider.Assembly,
  1310. dbProvider.ConnectionClass);
  1311. return success;
  1312. }
  1313. public DbDataAdapter CreateDbDataAdapter (IDbCommand cmd)
  1314. {
  1315. string msg = "";
  1316. DbDataAdapter dbAdapter = null;
  1317. if (dbProvider.InternalProvider == true) {
  1318. dbAdapter = CreateInternalDataAdapter (cmd);
  1319. }
  1320. else {
  1321. dbAdapter = CreateExternalDataAdapter (dbProvider.AdapterClass, cmd);
  1322. }
  1323. return dbAdapter;
  1324. }
  1325. public DbDataAdapter CreateInternalDataAdapter (IDbCommand cmd)
  1326. {
  1327. string msg = "";
  1328. DbDataAdapter dbAdapter = null;
  1329. string providerKey = dbProvider.Key;
  1330. switch (providerKey.ToUpper ()) {
  1331. case "SQLCLIENT":
  1332. try {
  1333. dbAdapter = new SqlDataAdapter (cmd as SqlCommand);
  1334. }
  1335. catch (Exception e) {
  1336. msg = "Error: unable to create adapter: " +
  1337. e.Message;
  1338. Error (msg);
  1339. return null;
  1340. }
  1341. break;
  1342. case "OLEDB":
  1343. try {
  1344. dbAdapter = new OleDbDataAdapter (cmd as OleDbCommand);
  1345. }
  1346. catch (Exception e) {
  1347. msg = "Error: unable to create adapter: " +
  1348. e.Message;
  1349. Error (msg);
  1350. return null;
  1351. }
  1352. break;
  1353. case "ODBC":
  1354. try {
  1355. dbAdapter = new OdbcDataAdapter (cmd as OdbcCommand);
  1356. }
  1357. catch (Exception e) {
  1358. msg = "Error: unable to create adapter: " +
  1359. e.Message;
  1360. Error (msg);
  1361. return null;
  1362. }
  1363. break;
  1364. }
  1365. return dbAdapter;
  1366. }
  1367. public DbDataAdapter CreateExternalDataAdapter (string adapterClass, IDbCommand cmd)
  1368. {
  1369. adapterType = providerAssembly.GetType (adapterClass);
  1370. System.Object ad = Activator.CreateInstance (adapterType);
  1371. // set property SelectCommand on DbDataAdapter
  1372. PropertyInfo prop = adapterType.GetProperty("SelectCommand");
  1373. prop.SetValue (ad, cmd, null);
  1374. return (DbDataAdapter) ad;
  1375. }
  1376. public DataTable LoadDataTable (IDbCommand dbcmd)
  1377. {
  1378. string status = String.Empty;
  1379. AppendText("Create DbDataAdapter...");
  1380. SqlSharpDataAdapter adapter = new SqlSharpDataAdapter (dbcmd);
  1381. AppendText("Create DataTable...");
  1382. DataTable dataTable = new DataTable ();
  1383. AppendText("Fill data into DataTable via DbDataAdapter...");
  1384. int rowsAddedOrRefreshed = 0;
  1385. IDataReader reader = null;
  1386. try {
  1387. reader = dbcmd.ExecuteReader ();
  1388. if (reader.FieldCount > 0)
  1389. rowsAddedOrRefreshed = adapter.FillTable (dataTable, reader);
  1390. }
  1391. catch(Exception sqle) {
  1392. status = "Error: " + sqle.Message;
  1393. }
  1394. if (status.Equals(String.Empty)) {
  1395. AppendText("Rows successfully Added or Refreshed in the DataTable: " +
  1396. rowsAddedOrRefreshed);
  1397. int rowsAffected = reader.RecordsAffected;
  1398. AppendText("Rows Affected: " + rowsAffected);
  1399. int fields = ((IDataRecord) reader).FieldCount;
  1400. AppendText("Field Count: " + fields);
  1401. if (fields > 0) {
  1402. status = "Rows Selected: " + rowsAddedOrRefreshed +
  1403. " Fields: " + fields;
  1404. }
  1405. else {
  1406. status = "Rows Modified: " + rowsAffected;
  1407. }
  1408. }
  1409. AppendText("Status: " + status);
  1410. adapter.Dispose();
  1411. adapter = null;
  1412. AppendText("Return DataTable...");
  1413. return dataTable;
  1414. }
  1415. public bool OpenDataSource ()
  1416. {
  1417. string msg;
  1418. bool gotClass = false;
  1419. msg = "Attempt to open connection...";
  1420. AppendText (buf, msg);
  1421. conn = null;
  1422. try {
  1423. if (dbProvider.InternalProvider == true) {
  1424. gotClass = OpenInternalProvider ();
  1425. }
  1426. else {
  1427. gotClass = OpenExternalProvider ();
  1428. }
  1429. }
  1430. catch (Exception e) {
  1431. msg = "Error: Unable to create Connection object. " +
  1432. e.Message;
  1433. Error (msg);
  1434. return false;
  1435. }
  1436. if (gotClass == false)
  1437. return false;
  1438. conn.ConnectionString = connectionString;
  1439. try {
  1440. conn.Open ();
  1441. if( conn.State == ConnectionState.Open)
  1442. AppendText (buf, "Open was successfull.");
  1443. else {
  1444. AppendText (buf, "Error: Open failed.");
  1445. return false;
  1446. }
  1447. }
  1448. catch (Exception e) {
  1449. msg = "Error: Could not open data source: " + e.Message;
  1450. Error (msg);
  1451. conn = null;
  1452. }
  1453. return true;
  1454. }
  1455. public static void DebugWriteLine (string text)
  1456. {
  1457. #if DEBUG
  1458. Console.WriteLine (text);
  1459. Console.Out.Flush ();
  1460. #endif // DEBUG
  1461. }
  1462. public static int Main (string[] args)
  1463. {
  1464. Application.Init ();
  1465. SqlSharpGtk sqlSharp = new SqlSharpGtk ();
  1466. sqlSharp.Show ();
  1467. Application.Run ();
  1468. return 0;
  1469. }
  1470. }
  1471. }