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

/GrinGlobal.Client.Common/GrinGlobal.Client.Common/LocalDatabase.cs

https://gitlab.com/GRIN-Global/GRIN-Global-Curator-tool
C# | 382 lines | 342 code | 28 blank | 12 comment | 44 complexity | 849c331fc4b721cf1070fc84e545f0a5 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. namespace GRINGlobal.Client.Common
  8. {
  9. public class LocalDatabase
  10. {
  11. private string _connectionString;
  12. private Dictionary<string, bool> _tableExistsStatus;
  13. public LocalDatabase(string DatabaseName)
  14. {
  15. _tableExistsStatus = new Dictionary<string, bool>();
  16. System.ServiceProcess.ServiceController[] services = System.ServiceProcess.ServiceController.GetServices();
  17. foreach (System.ServiceProcess.ServiceController service in services)
  18. {
  19. if (service.ServiceName == "MSSQL$SQLEXPRESS" &&
  20. service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
  21. {
  22. _connectionString = @"Data Source=localhost\SQLExpress; Integrated Security=True;";
  23. }
  24. else if (string.IsNullOrEmpty(_connectionString) && service.ServiceName == "MSSQLSERVER" &&
  25. service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
  26. {
  27. _connectionString = @"Data Source=localhost; Integrated Security=True;";
  28. }
  29. }
  30. if (!string.IsNullOrEmpty(_connectionString) &&
  31. !string.IsNullOrEmpty(DatabaseName))
  32. {
  33. if (!DatabaseExists(DatabaseName))
  34. {
  35. CreateDatabase(DatabaseName);
  36. }
  37. _connectionString = _connectionString + "; Initial Catalog=" + DatabaseName;
  38. }
  39. }
  40. public string ConnectionString
  41. {
  42. get
  43. {
  44. return _connectionString;
  45. }
  46. set
  47. {
  48. _connectionString = value;
  49. }
  50. }
  51. public DataTable GetData(string SQLSelect, string[] SQLparms)
  52. {
  53. SqlConnection dbConnection = new SqlConnection(_connectionString);
  54. SqlCommand dbCommand = new SqlCommand(SQLSelect, dbConnection);
  55. foreach (string parmEquation in SQLparms)
  56. {
  57. string[] parm = parmEquation.Split(new char[] { '=' }, 2);
  58. if (parm.Length == 2)
  59. {
  60. dbCommand.Parameters.AddWithValue(parm[0].Trim(), parm[1].TrimStart(' '));
  61. }
  62. }
  63. SqlDataAdapter dbDataAdapter = new SqlDataAdapter(dbCommand);
  64. dbDataAdapter.MissingMappingAction = MissingMappingAction.Passthrough;
  65. dbDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
  66. DataTable dt = new DataTable();
  67. try
  68. {
  69. dbDataAdapter.Fill(dt);
  70. foreach (DataColumn dc in dt.PrimaryKey)
  71. {
  72. dc.AllowDBNull = false;
  73. if (dc.DataType == typeof(int) ||
  74. dc.DataType == typeof(Int16) ||
  75. dc.DataType == typeof(Int32) ||
  76. dc.DataType == typeof(Int64))
  77. {
  78. dc.AutoIncrement = true;
  79. dc.AutoIncrementSeed = -1;
  80. dc.AutoIncrementStep = -1;
  81. }
  82. }
  83. }
  84. catch (Exception e)
  85. {
  86. //throw new Exception("Error retrieving local data in GrinGlobal.Client.Data library.", e);
  87. }
  88. return dt;
  89. }
  90. public bool SaveData(DataTable DataTable)
  91. {
  92. bool success = false;
  93. try
  94. {
  95. SqlConnection dbConnection = new SqlConnection(_connectionString);
  96. SqlDataAdapter dbDataAdapter = new SqlDataAdapter("SELECT * FROM " + DataTable.TableName, dbConnection);
  97. SqlCommandBuilder dbCommandBuilder = new SqlCommandBuilder(dbDataAdapter);
  98. dbDataAdapter.Update(DataTable);
  99. dbCommandBuilder.Dispose();
  100. dbCommandBuilder = null;
  101. dbDataAdapter.Dispose();
  102. dbDataAdapter = null;
  103. dbConnection.Close();
  104. dbConnection.Dispose();
  105. dbConnection = null;
  106. success = true;
  107. }
  108. catch
  109. {
  110. success = false;
  111. }
  112. return success;
  113. }
  114. public void CreateTable(DataTable NewTable, bool CreateSchemaOnly, bool OverwriteTable)
  115. {
  116. SqlConnection dbConnection = new SqlConnection(_connectionString);
  117. SqlCommand dbCommand = new SqlCommand("", dbConnection);
  118. SqlDataAdapter dbDataAdapter = new SqlDataAdapter("SELECT * FROM " + NewTable.TableName, dbConnection);
  119. SqlCommandBuilder dbCommandBuilder = new SqlCommandBuilder(dbDataAdapter);
  120. dbConnection.Open();
  121. if (TableExists(NewTable.TableName))
  122. {
  123. if (OverwriteTable)
  124. {
  125. dbCommand.CommandText = "DROP TABLE " + NewTable.TableName;
  126. dbCommand.ExecuteNonQuery();
  127. }
  128. else
  129. {
  130. return;
  131. }
  132. }
  133. // Build the SQL create table command...
  134. string createTableCommand = "CREATE TABLE " + NewTable.TableName + " (";
  135. foreach (DataColumn dc in NewTable.Columns)
  136. {
  137. createTableCommand += BuildColumnSQL(dc) + ",";
  138. }
  139. createTableCommand = createTableCommand.TrimEnd(',') + ")";
  140. // Add indexes for each column in the table...
  141. if (NewTable.TableName.EndsWith("_lookup"))
  142. {
  143. foreach (DataColumn dc in NewTable.Columns)
  144. {
  145. createTableCommand += "CREATE INDEX " + dc.ColumnName + "_index ON " + NewTable.TableName + " (" + dc.ColumnName + ");";
  146. }
  147. }
  148. dbCommand.CommandText = createTableCommand;
  149. dbCommand.ExecuteNonQuery();
  150. // Add the data if requested...
  151. if (!CreateSchemaOnly && NewTable.Rows.Count > 0)
  152. {
  153. foreach (DataRow dr in NewTable.Rows)
  154. {
  155. if(dr.RowState != DataRowState.Added) dr.SetAdded();
  156. }
  157. dbDataAdapter.Update(NewTable);
  158. }
  159. dbDataAdapter.Dispose();
  160. dbDataAdapter = null;
  161. dbCommand.Dispose();
  162. dbCommand = null;
  163. dbConnection.Close();
  164. dbConnection.Dispose();
  165. dbConnection = null;
  166. }
  167. private string BuildColumnSQL(DataColumn dc)
  168. {
  169. string columnSQL = dc.ColumnName + " ";
  170. string columnTypeName = dc.DataType.Name.ToString().ToUpper();
  171. switch (columnTypeName)
  172. {
  173. case "INT":
  174. case "INT32":
  175. case "INT64":
  176. columnSQL += "INT ";
  177. break;
  178. case "STRING":
  179. if (dc.ExtendedProperties.Contains("is_primary_key") && dc.ExtendedProperties["is_primary_key"].ToString() == "Y")
  180. {
  181. columnSQL += "NVARCHAR(255) ";
  182. }
  183. else
  184. {
  185. if (dc.ExtendedProperties.ContainsKey("table_field_data_type_string") &&
  186. dc.ExtendedProperties["table_field_data_type_string"].ToString().ToUpper().Trim() == "STRING" &&
  187. dc.ExtendedProperties.ContainsKey("gui_hint") &&
  188. dc.ExtendedProperties["gui_hint"].ToString().ToUpper().Trim() == "TEXT_CONTROL" &&
  189. dc.ExtendedProperties.ContainsKey("max_length"))
  190. {
  191. int columnLength;
  192. int.TryParse(dc.ExtendedProperties["max_length"].ToString(), out columnLength);
  193. if (columnLength > 0)
  194. {
  195. columnSQL += "NVARCHAR(" + dc.ExtendedProperties["max_length"].ToString() + ")";
  196. }
  197. else
  198. {
  199. columnSQL += "NVARCHAR(MAX)";
  200. }
  201. }
  202. else
  203. {
  204. // This is most likely a lookup column or code_value - so max number of characters is unknown...
  205. columnSQL += "NVARCHAR(440) "; // using 440 keeps the index size for each column less than the maximum of 900 bytes
  206. }
  207. }
  208. break;
  209. case "DATETIME":
  210. columnSQL += "DATETIME ";
  211. break;
  212. default:
  213. columnSQL += "NVARCHAR(255) ";
  214. break;
  215. }
  216. //if (dc.ExtendedProperties["is_autoincrement"].ToString() == "Y")
  217. //{
  218. // columnSQL += "IDENTITY ";
  219. //}
  220. if (dc.ExtendedProperties.Contains("is_primary_key") && dc.ExtendedProperties["is_primary_key"].ToString() == "Y")
  221. {
  222. columnSQL += "PRIMARY KEY ";
  223. }
  224. return columnSQL;
  225. }
  226. public bool DatabaseExists(string DatabaseName)
  227. {
  228. bool databaseExists = false;
  229. try
  230. {
  231. SqlConnection dbConnection = new SqlConnection(_connectionString);
  232. SqlCommand dbCommand = new SqlCommand("SELECT count(1) from sysdatabases where name = '" + DatabaseName + "'", dbConnection);
  233. dbConnection.Open();
  234. if ((int)dbCommand.ExecuteScalar() == 1)
  235. {
  236. databaseExists = true;
  237. }
  238. else
  239. {
  240. databaseExists = false;
  241. }
  242. }
  243. catch
  244. {
  245. databaseExists = false;
  246. }
  247. return databaseExists;
  248. }
  249. public bool CreateDatabase(string DatabaseName)
  250. {
  251. bool success = false;
  252. try
  253. {
  254. SqlConnection dbConnection = new SqlConnection(_connectionString);
  255. SqlCommand dbCommand = new SqlCommand("CREATE DATABASE " + DatabaseName, dbConnection);
  256. dbConnection.Open();
  257. dbCommand.ExecuteNonQuery();
  258. dbCommand.Dispose();
  259. dbCommand = null;
  260. dbConnection.Close();
  261. dbConnection.Dispose();
  262. dbConnection = null;
  263. success = true;
  264. }
  265. catch
  266. {
  267. success = false;
  268. }
  269. return success;
  270. }
  271. public bool TableExists(string TableName)
  272. {
  273. bool tableExists = false;
  274. // Check the cache first for table existence...
  275. if (_tableExistsStatus.ContainsKey(TableName))
  276. {
  277. tableExists = _tableExistsStatus[TableName];
  278. }
  279. // The cache above may have returned false (but another thread may be building
  280. // the table - so check again...
  281. if(!tableExists)
  282. {
  283. try
  284. {
  285. SqlConnection dbConnection = new SqlConnection(_connectionString);
  286. SqlDataAdapter dbDataAdapter = new SqlDataAdapter("SELECT COUNT(*) FROM " + TableName, dbConnection);
  287. DataTable table = new DataTable();
  288. dbConnection.Open();
  289. dbDataAdapter.Fill(table);
  290. table.Dispose();
  291. table = null;
  292. dbDataAdapter.Dispose();
  293. dbDataAdapter = null;
  294. dbConnection.Close();
  295. dbConnection.Dispose();
  296. dbConnection = null;
  297. tableExists = true;
  298. }
  299. catch
  300. {
  301. tableExists = false;
  302. }
  303. if (_tableExistsStatus.ContainsKey(TableName))
  304. {
  305. _tableExistsStatus[TableName] = tableExists;
  306. }
  307. else
  308. {
  309. _tableExistsStatus.Add(TableName, tableExists);
  310. }
  311. }
  312. return tableExists;
  313. }
  314. public void Remove(string tableName)
  315. {
  316. if (TableExists(tableName))
  317. {
  318. SqlConnection dbConnection = new SqlConnection(_connectionString);
  319. SqlCommand dbCommand = new SqlCommand("DROP TABLE " + tableName, dbConnection);
  320. dbConnection.Open();
  321. dbCommand.ExecuteNonQuery();
  322. dbConnection.Close();
  323. dbConnection.Dispose();
  324. dbConnection = null;
  325. if (_tableExistsStatus.ContainsKey(tableName)) _tableExistsStatus[tableName] = false;
  326. }
  327. }
  328. public bool MakeAccessibleToAllUsers()
  329. {
  330. bool success = false;
  331. try
  332. {
  333. SqlConnection dbConnection = new SqlConnection(_connectionString);
  334. SqlCommand dbCommand = new SqlCommand("sp_addsrvrolemember", dbConnection); // @loginame = N'BUILTIN\Users', @rolename = N'sysadmin'");
  335. dbCommand.CommandType = CommandType.StoredProcedure;
  336. dbCommand.Parameters.AddWithValue("@loginame", "BUILTIN\\Users");
  337. dbCommand.Parameters.AddWithValue("@rolename", "sysadmin");
  338. dbConnection.Open();
  339. dbCommand.ExecuteNonQuery();
  340. dbCommand.Dispose();
  341. dbCommand = null;
  342. dbConnection.Close();
  343. dbConnection.Dispose();
  344. dbConnection = null;
  345. success = true;
  346. }
  347. catch
  348. {
  349. success = false;
  350. }
  351. return success;
  352. }
  353. }
  354. }