PageRenderTime 50ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/Synchrophasor/Current Version/Source/Tools/ConfigurationSetupUtility/MySqlSetup.cs

#
C# | 407 lines | 302 code | 37 blank | 68 comment | 12 complexity | e069455a753ddabfe26e71a68df5cf3f MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, EPL-1.0
  1. //******************************************************************************************************
  2. // MySqlSetup.cs - Gbtc
  3. //
  4. // Copyright © 2010, Grid Protection Alliance. All Rights Reserved.
  5. //
  6. // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
  7. // the NOTICE file distributed with this work for additional information regarding copyright ownership.
  8. // The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the "License"); you may
  9. // not use this file except in compliance with the License. You may obtain a copy of the License at:
  10. //
  11. // http://www.opensource.org/licenses/eclipse-1.0.php
  12. //
  13. // Unless agreed to in writing, the subject software distributed under the License is distributed on an
  14. // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
  15. // License for the specific language governing permissions and limitations.
  16. //
  17. // Code Modification History:
  18. // ----------------------------------------------------------------------------------------------------
  19. // 06/29/2010 - Stephen C. Wills
  20. // Generated original version of source code.
  21. // 02/23/2011 - Mehulbhai Thakkar
  22. // Added "Allow User Variables" setting so that session variables can be created without errors.
  23. // 03/02/2011 - J. Ritchie Carroll
  24. // Added key value delimeters only between settings.
  25. //
  26. //******************************************************************************************************
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Diagnostics;
  30. using System.IO;
  31. using System.Text;
  32. using Microsoft.Win32;
  33. using TVA;
  34. using TVA.IO;
  35. namespace ConfigurationSetupUtility
  36. {
  37. /// <summary>
  38. /// This class is used to aid in the manipulation of a MySQL connection string as well as running the mysql.exe process.
  39. /// </summary>
  40. public class MySqlSetup
  41. {
  42. #region [ Members ]
  43. // Events
  44. /// <summary>
  45. /// This event is triggered when error data is received while executing a SQL Script.
  46. /// </summary>
  47. public event DataReceivedEventHandler ErrorDataReceived;
  48. /// <summary>
  49. /// This event is triggered when output data is received while executing a SQL Script.
  50. /// </summary>
  51. public event DataReceivedEventHandler OutputDataReceived;
  52. // Fields
  53. private Dictionary<string, string> m_settings;
  54. private string m_mysqlExe;
  55. #endregion
  56. #region [ Constructors ]
  57. /// <summary>
  58. /// Creates a new instance of the <see cref="MySqlSetup"/> class.
  59. /// </summary>
  60. public MySqlSetup()
  61. {
  62. m_settings = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
  63. m_settings["Allow User Variables"] = "true"; // This setting allows creation of user defined session variables.
  64. try
  65. {
  66. // Try to get path for mysql executable based on registered Windows service path, if this fails, fall back on just the executable name which will require a proper environmental path to run
  67. m_mysqlExe = FilePath.GetDirectoryName(Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\MySQL", "ImagePath", "mysql.exe").ToString().Split(new string[] { "\" " }, StringSplitOptions.RemoveEmptyEntries)[0].Replace("\"", "")) + "mysql.exe";
  68. if (!File.Exists(m_mysqlExe))
  69. m_mysqlExe = "mysql.exe";
  70. }
  71. catch
  72. {
  73. m_mysqlExe = "mysql.exe";
  74. }
  75. }
  76. #endregion
  77. #region [ Properties ]
  78. /// <summary>
  79. /// Gets or sets the path to the MySQL client executable.
  80. /// </summary>
  81. public string MysqlExe
  82. {
  83. get
  84. {
  85. return m_mysqlExe;
  86. }
  87. set
  88. {
  89. m_mysqlExe = value;
  90. }
  91. }
  92. /// <summary>
  93. /// Gets or sets the host name of the MySQL database.
  94. /// </summary>
  95. public string HostName
  96. {
  97. get
  98. {
  99. return m_settings["Server"];
  100. }
  101. set
  102. {
  103. m_settings["Server"] = value;
  104. }
  105. }
  106. /// <summary>
  107. /// Gets or sets the name of the MySQL database.
  108. /// </summary>
  109. public string DatabaseName
  110. {
  111. get
  112. {
  113. if (m_settings.ContainsKey("Database"))
  114. return m_settings["Database"];
  115. else
  116. return null;
  117. }
  118. set
  119. {
  120. if (string.IsNullOrEmpty(value))
  121. m_settings.Remove("Database");
  122. else
  123. m_settings["Database"] = value;
  124. }
  125. }
  126. /// <summary>
  127. /// Gets or sets the user name for the user whom has access to the database.
  128. /// </summary>
  129. public string UserName
  130. {
  131. get
  132. {
  133. if (m_settings.ContainsKey("Uid"))
  134. return m_settings["Uid"];
  135. else
  136. return null;
  137. }
  138. set
  139. {
  140. if (string.IsNullOrEmpty(value))
  141. m_settings.Remove("Uid");
  142. else
  143. m_settings["Uid"] = value;
  144. }
  145. }
  146. /// <summary>
  147. /// Gets or sets the password for the user whom has access to the database.
  148. /// </summary>
  149. public string Password
  150. {
  151. get
  152. {
  153. if (m_settings.ContainsKey("Pwd"))
  154. return m_settings["Pwd"];
  155. else
  156. return null;
  157. }
  158. set
  159. {
  160. if (string.IsNullOrEmpty(value))
  161. m_settings.Remove("Pwd");
  162. else
  163. m_settings["Pwd"] = value;
  164. }
  165. }
  166. /// <summary>
  167. /// Gets or sets the connection string used to access the database.
  168. /// </summary>
  169. public string ConnectionString
  170. {
  171. get
  172. {
  173. StringBuilder builder = new StringBuilder();
  174. foreach (string key in m_settings.Keys)
  175. {
  176. if (builder.Length > 0)
  177. builder.Append("; ");
  178. builder.Append(key);
  179. builder.Append('=');
  180. builder.Append(m_settings[key]);
  181. }
  182. return builder.ToString();
  183. }
  184. set
  185. {
  186. m_settings = value.ParseKeyValuePairs();
  187. }
  188. }
  189. /// <summary>
  190. /// Converts the current settings to an OleDB connection string.
  191. /// </summary>
  192. public string OleDbConnectionString
  193. {
  194. get
  195. {
  196. StringBuilder builder = new StringBuilder();
  197. builder.Append("Provider=MySQLProv");
  198. builder.Append("; location=");
  199. builder.Append(HostName.Replace("localhost", "MACHINE"));
  200. builder.Append("; Data Source=");
  201. builder.Append(DatabaseName);
  202. if (!string.IsNullOrEmpty(UserName))
  203. {
  204. builder.Append("; User Id=");
  205. builder.Append(UserName);
  206. }
  207. if (!string.IsNullOrEmpty(Password))
  208. {
  209. builder.Append("; Password=");
  210. builder.Append(Password);
  211. }
  212. return builder.ToString();
  213. }
  214. }
  215. #endregion
  216. #region [ Methods ]
  217. /// <summary>
  218. /// Execute a SQL statement using the mysql.exe process.
  219. /// </summary>
  220. /// <param name="statement"></param>
  221. /// <returns></returns>
  222. public bool ExecuteStatement(string statement)
  223. {
  224. Process mySqlProcess = null;
  225. try
  226. {
  227. // Set up arguments for mysql.exe.
  228. StringBuilder args = new StringBuilder();
  229. args.Append("-h");
  230. args.Append(HostName);
  231. args.Append(" -D");
  232. args.Append(DatabaseName);
  233. if (!string.IsNullOrEmpty(UserName))
  234. {
  235. args.Append(" -u");
  236. args.Append(UserName);
  237. }
  238. if (!string.IsNullOrEmpty(Password))
  239. {
  240. args.Append(" -p");
  241. args.Append(Password);
  242. }
  243. args.Append(" -e \"");
  244. args.Append(statement);
  245. args.Append('"');
  246. // Start mysql.exe.
  247. mySqlProcess = new Process();
  248. mySqlProcess.StartInfo.FileName = m_mysqlExe;
  249. mySqlProcess.StartInfo.Arguments = args.ToString();
  250. mySqlProcess.StartInfo.UseShellExecute = false;
  251. mySqlProcess.StartInfo.RedirectStandardError = true;
  252. mySqlProcess.ErrorDataReceived += mySqlProcess_ErrorDataReceived;
  253. mySqlProcess.StartInfo.RedirectStandardOutput = true;
  254. mySqlProcess.OutputDataReceived += mySqlProcess_OutputDataReceived;
  255. mySqlProcess.StartInfo.CreateNoWindow = true;
  256. mySqlProcess.Start();
  257. mySqlProcess.BeginErrorReadLine();
  258. mySqlProcess.BeginOutputReadLine();
  259. // Wait for mysql.exe to finish.
  260. mySqlProcess.WaitForExit();
  261. return mySqlProcess.ExitCode == 0;
  262. }
  263. finally
  264. {
  265. // Close the process.
  266. if (mySqlProcess != null)
  267. mySqlProcess.Close();
  268. }
  269. }
  270. /// <summary>
  271. /// Executes a SQL Script using the mysql.exe process.
  272. /// </summary>
  273. /// <param name="scriptPath">The path of the script to be executed.</param>
  274. /// <returns>True if the script executes successfully. False otherwise.</returns>
  275. public bool ExecuteScript(string scriptPath)
  276. {
  277. Process mySqlProcess = null;
  278. StreamReader scriptStream = null;
  279. StreamWriter processInput = null;
  280. try
  281. {
  282. // Set up arguments for mysql.exe.
  283. StringBuilder args = new StringBuilder();
  284. args.Append("-h");
  285. args.Append(HostName);
  286. if (!string.IsNullOrEmpty(UserName))
  287. {
  288. args.Append(" -u");
  289. args.Append(UserName);
  290. }
  291. if (!string.IsNullOrEmpty(Password))
  292. {
  293. args.Append(" -p");
  294. args.Append(Password);
  295. }
  296. // Start mysql.exe.
  297. mySqlProcess = new Process();
  298. mySqlProcess.StartInfo.FileName = m_mysqlExe;
  299. mySqlProcess.StartInfo.Arguments = args.ToString();
  300. mySqlProcess.StartInfo.UseShellExecute = false;
  301. mySqlProcess.StartInfo.RedirectStandardError = true;
  302. mySqlProcess.ErrorDataReceived += mySqlProcess_ErrorDataReceived;
  303. mySqlProcess.StartInfo.RedirectStandardInput = true;
  304. mySqlProcess.StartInfo.RedirectStandardOutput = true;
  305. mySqlProcess.OutputDataReceived += mySqlProcess_OutputDataReceived;
  306. mySqlProcess.StartInfo.CreateNoWindow = true;
  307. mySqlProcess.Start();
  308. mySqlProcess.BeginErrorReadLine();
  309. mySqlProcess.BeginOutputReadLine();
  310. // Send the script as standard input to mysql.exe.
  311. scriptStream = new StreamReader(new FileStream(scriptPath, FileMode.Open, FileAccess.Read));
  312. processInput = mySqlProcess.StandardInput;
  313. while (!scriptStream.EndOfStream)
  314. {
  315. string line = scriptStream.ReadLine();
  316. if (line.StartsWith("CREATE DATABASE") || line.StartsWith("USE"))
  317. line = line.Replace("openPDC", DatabaseName);
  318. processInput.WriteLine(line);
  319. }
  320. // Wait for mysql.exe to finish.
  321. processInput.Close();
  322. mySqlProcess.WaitForExit();
  323. return mySqlProcess.ExitCode == 0;
  324. }
  325. finally
  326. {
  327. // Close streams and processes.
  328. if (scriptStream != null)
  329. scriptStream.Close();
  330. if (processInput != null)
  331. processInput.Close();
  332. if (mySqlProcess != null)
  333. mySqlProcess.Close();
  334. }
  335. }
  336. private void mySqlProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)
  337. {
  338. if (ErrorDataReceived != null)
  339. ErrorDataReceived(sender, e);
  340. }
  341. private void mySqlProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
  342. {
  343. if (OutputDataReceived != null)
  344. OutputDataReceived(sender, e);
  345. }
  346. #endregion
  347. }
  348. }