From 8d8f199d3c12aa49e3b2d5c8b26007b42341b0a7 Mon Sep 17 00:00:00 2001 From: Saranga Athukorale Date: Fri, 12 Apr 2019 23:43:32 +0530 Subject: [PATCH] Fixing Some Coverity Issues Signed-off-by: Saranga Athukorale --- .../classes/mysql/DatabaseManager.cs | 101 ++-- .../classes/sqlce/DatabaseManager.cs | 431 +++++++++--------- 2 files changed, 280 insertions(+), 252 deletions(-) diff --git a/libDatabaseHelper/classes/mysql/DatabaseManager.cs b/libDatabaseHelper/classes/mysql/DatabaseManager.cs index 8dd5b06..9b82ed8 100644 --- a/libDatabaseHelper/classes/mysql/DatabaseManager.cs +++ b/libDatabaseHelper/classes/mysql/DatabaseManager.cs @@ -326,70 +326,77 @@ public override void FillDataTable(Type type, ref DataTable table, Selector[] se if (obj == null) return; - var commandString = DatabaseEntity.GetSelectCommandString(type); - var whereQuery = ""; - var command = GenericConnectionManager.GetConnectionManager(GetSupportedDatabase()).GetConnection(type).CreateCommand(); - - if (selectors != null && selectors.Any()) + using (var command = GenericConnectionManager.GetConnectionManager(GetSupportedDatabase()).GetConnection(type).CreateCommand()) { - whereQuery = selectors.Aggregate(whereQuery, (current, selector) => current + ((current == "" ? "" : " AND ") + selector.SetToCommand(ref command))); - } + var commandString = DatabaseEntity.GetSelectCommandString(type); + var whereQuery = ""; - command.CommandText = commandString + (whereQuery != "" ? (" WHERE " + whereQuery) : "") + (limit > 0 ? (" LIMIT " + limit) : ""); + if (selectors != null && selectors.Any()) + { + whereQuery = selectors.Aggregate(whereQuery, (current, selector) => + { + var dbCommand = command; + return current + ((current == "" ? "" : " AND ") + selector.SetToCommand(ref dbCommand)); + }); + } - var reader = command.ExecuteReader(); + command.CommandText = commandString + (whereQuery != "" ? (" WHERE " + whereQuery) : "") + (limit > 0 ? (" LIMIT " + limit) : ""); - var fieldInfos = obj.GetColumns(true).GetOtherColumns().Where(i => ((TableColumn)i.GetCustomAttributes(typeof(TableColumn), true)[0]).IsRetrievableFromDatabase).ToArray(); + var reader = command.ExecuteReader(); - table.Rows.Clear(); - table.Columns.Clear(); + var fieldInfos = obj.GetColumns(true).GetOtherColumns().Where(i => ((TableColumn)i.GetCustomAttributes(typeof(TableColumn), true)[0]).IsRetrievableFromDatabase).ToArray(); - var translators = new List(); + table.Rows.Clear(); + table.Columns.Clear(); - foreach (var fieldInfo in fieldInfos) - { - var cInfo = ((TableColumn)fieldInfo.GetCustomAttributes(typeof(TableColumn), true)[0]); - if (fieldInfo.FieldType == typeof(bool)) - table.Columns.Add(cInfo.GridDisplayName ?? fieldInfo.Name, typeof(bool)); - else - table.Columns.Add(cInfo.GridDisplayName ?? fieldInfo.Name); + var translators = new List(); - var translator = cInfo.TranslatorType == null ? null : TranslatorRegistry.Instance.Get(cInfo.TranslatorType); - translators.Add(translator); - } + foreach (var fieldInfo in fieldInfos) + { + var cInfo = ((TableColumn)fieldInfo.GetCustomAttributes(typeof(TableColumn), true)[0]); + if (fieldInfo.FieldType == typeof(bool)) + table.Columns.Add(cInfo.GridDisplayName ?? fieldInfo.Name, typeof(bool)); + else + table.Columns.Add(cInfo.GridDisplayName ?? fieldInfo.Name); + + var translator = cInfo.TranslatorType == null ? null : TranslatorRegistry.Instance.Get(cInfo.TranslatorType); + translators.Add(translator); + } - if (!reader.Read()) - { - try { reader.Close(); } catch { /* IGNORED */ } - command.Dispose(); - return; - } + if (!reader.Read()) + { + reader.Close(); + return; + } - frmLoadingDialog.ShowWindow(); - do - { - if (frmLoadingDialog.GetStatus()) - break; - var row = table.Rows.Add(); - for (var i = 0; i < table.Columns.Count; i++) + frmLoadingDialog.ShowWindow(); + + do { - try + if (frmLoadingDialog.GetStatus()) + break; + + var row = table.Rows.Add(); + for (var i = 0; i < table.Columns.Count; i++) { - if (translators[i] != null) + try { - var value = reader[i]; - row[i] = (translators.Count > i && i >= 0) ? translators[i].ToTranslated(value) : value.ToString(); + if (translators[i] != null) + { + var value = reader[i]; + row[i] = (translators.Count > i && i >= 0) ? translators[i].ToTranslated(value) : value.ToString(); + } + else + row[i] = reader[i]; } - else - row[i] = reader[i]; + catch { /* IGNORED */ } } - catch { } } + while (reader.Read()); + + reader.Close(); + frmLoadingDialog.HideWindow(); } - while (reader.Read()); - try { reader.Close(); } catch { /* IGNORED */ } - frmLoadingDialog.HideWindow(); - command.Dispose(); } public override PrimaryKeyConstraintDetails GetPrimaryKeyDetails(Type type) diff --git a/libDatabaseHelper/classes/sqlce/DatabaseManager.cs b/libDatabaseHelper/classes/sqlce/DatabaseManager.cs index 1bcf8f9..e74db82 100644 --- a/libDatabaseHelper/classes/sqlce/DatabaseManager.cs +++ b/libDatabaseHelper/classes/sqlce/DatabaseManager.cs @@ -28,31 +28,37 @@ public DatabaseManager() : base(DatabaseType.SqlCE) private bool ExecuteNonQuery(DbConnection connection, string commandString, FillArguments argumentFiller = null) { - var command = connection.CreateCommand(); - var status = false; - var transaction = (null as SqlCeTransaction); - - try + using (var command = connection.CreateCommand()) { - transaction = (SqlCeTransaction) connection.BeginTransaction(IsolationLevel.ReadCommitted); + var status = false; + var transaction = (null as SqlCeTransaction); - command.Transaction = transaction; - command.CommandText = commandString; + try + { + transaction = (SqlCeTransaction)connection.BeginTransaction(IsolationLevel.ReadCommitted); - if (argumentFiller != null) argumentFiller.Invoke(ref command); + command.Transaction = transaction; + command.CommandText = commandString; - command.ExecuteNonQuery(); - transaction.Commit(CommitMode.Immediate); + if (argumentFiller != null) + { + var dbCommand = command; + argumentFiller.Invoke(ref dbCommand); + } - status = true; - } - catch (System.Exception) - { - if (transaction != null) transaction.Rollback(); - } + command.ExecuteNonQuery(); + transaction.Commit(CommitMode.Immediate); - command.Dispose(); - return status; + status = true; + } + catch (System.Exception) + { + if (transaction != null) transaction.Rollback(); + } + + + return status; + } } public override bool TableExist(Type type) @@ -197,7 +203,8 @@ public override bool CreateTable(Type type) { throw new DatabaseException(DatabaseException.ErrorType.NoColumnsFound); } - else if (result.GetPrimaryKeys() == null || !result.GetPrimaryKeys().Any()) + + if (result.GetPrimaryKeys() == null || !result.GetPrimaryKeys().Any()) { throw new DatabaseException(DatabaseException.ErrorType.NoPrimaryKeyColumnsFound); } @@ -208,48 +215,52 @@ public override bool CreateTable(Type type) throw new DatabaseConnectionException(DatabaseConnectionException.ConnectionErrorType.UnableToConnectToTheDatabase); } - var command = connection.CreateCommand(); - - var variabeDeclarations = ""; - foreach (var column in result.GetOtherColumns()) + using (var command = connection.CreateCommand()) { - var columnAttributes = (TableColumn)column.GetCustomAttributes(typeof(TableColumn), true)[0]; - variabeDeclarations += (variabeDeclarations == "" ? " " : ", ") + column.Name + " " + - FieldTools.GetDbTypeString(column.FieldType, columnAttributes.Length); - if (GenericFieldTools.IsTypeNumber(column.FieldType) && columnAttributes.IsAutogenerated && - columnAttributes.AutogenrationMethod == null) + var variableDeclarations = ""; + foreach (var column in result.GetOtherColumns()) { - variabeDeclarations += " IDENTITY "; + var columnAttributes = (TableColumn)column.GetCustomAttributes(typeof(TableColumn), true)[0]; + variableDeclarations += (variableDeclarations == "" ? " " : ", ") + column.Name + " " + + FieldTools.GetDbTypeString(column.FieldType, columnAttributes.Length); + if (GenericFieldTools.IsTypeNumber(column.FieldType) && columnAttributes.IsAutogenerated && + columnAttributes.AutogenrationMethod == null) + { + variableDeclarations += " IDENTITY "; + } + else if (columnAttributes.IsUnique) + { + variableDeclarations += " UNIQUE "; + } } - else if (columnAttributes.IsUnique) + + var primaryVariableDeclarations = result.GetPrimaryKeys().Aggregate("", (current, column) => current + ((current == "" ? "" : ", ") + column.Name)); + if (primaryVariableDeclarations != "") { - variabeDeclarations += " UNIQUE "; + primaryVariableDeclarations = ", PRIMARY KEY (" + primaryVariableDeclarations + ")"; } - } - var primaryVariabeDeclarations = result.GetPrimaryKeys().Aggregate("", (current, column) => current + ((current == "" ? "" : ", ") + column.Name)); - if (primaryVariabeDeclarations != "") - { - primaryVariabeDeclarations = ", PRIMARY KEY (" + primaryVariabeDeclarations + ")"; - } - var createStatement = "CREATE TABLE " + obj.GetType().Name + "(" + variabeDeclarations + primaryVariabeDeclarations + ")"; - var transaction = (SqlCeTransaction) connection.BeginTransaction(IsolationLevel.ReadCommitted); - try - { - command.Transaction = transaction; - command.CommandText = createStatement; - var executionResult = command.ExecuteNonQuery(); + var createStatement = "CREATE TABLE " + obj.GetType().Name + "(" + variableDeclarations + primaryVariableDeclarations + ")"; + var transaction = (SqlCeTransaction)connection.BeginTransaction(IsolationLevel.ReadCommitted); - transaction.Commit(); - command.Dispose(); + try + { + command.Transaction = transaction; + command.CommandText = createStatement; + var executionResult = command.ExecuteNonQuery(); - return executionResult >= 0; - } - catch (System.Exception) - { - transaction.Rollback(); + transaction.Commit(); + command.Dispose(); + + return executionResult >= 0; + } + catch + { + transaction.Rollback(); + } + + return false; } - return false; } public override bool DropTable(Type type) @@ -277,28 +288,28 @@ public override bool DropTable(Type type) } var connection = GenericConnectionManager.GetConnectionManager(GetSupportedDatabase()).GetConnection(type); - var command = connection.CreateCommand(); + using (var command = connection.CreateCommand()) + { + var createStatement = "DROP TABLE " + type.Name; + var transaction = (SqlCeTransaction)connection.BeginTransaction(IsolationLevel.ReadCommitted); + var success = false; - var createStatement = "DROP TABLE " + type.Name; - var transaction = (SqlCeTransaction) connection.BeginTransaction(IsolationLevel.ReadCommitted); - var success = false; + try + { + command.Transaction = transaction; + command.CommandText = createStatement; + var executionResult = command.ExecuteNonQuery(); - try - { - command.Transaction = transaction; - command.CommandText = createStatement; - var executionResult = command.ExecuteNonQuery(); + transaction.Commit(CommitMode.Immediate); + success = (executionResult >= 0); + } + catch + { + transaction.Rollback(); + } - transaction.Commit(CommitMode.Immediate); - success = (executionResult >= 0); - } - catch (System.Exception) - { - transaction.Rollback(); + return success; } - - command.Dispose(); - return success; } public override GenericDatabaseEntity[] Select(Type type, Selector[] selectors) @@ -318,27 +329,27 @@ public override GenericDatabaseEntity[] Select(Type type, Selector[] selectors) .Aggregate("", (current, selector) => current + ((current == "" ? "" : ", ") + selector.Name)); var connection = GenericConnectionManager.GetConnectionManager(GetSupportedDatabase()).GetConnection(type); - var command = connection.CreateCommand(); - - var whereStatement = ""; - if (selectors != null) + using (var command = connection.CreateCommand()) { - whereStatement = selectors.Aggregate("", - (current, selector) => - current + ((current == "" ? "" : " AND ") + selector.SetToCommand(ref command))); - } - - var selectStatement = "SELECT " + selectFields + " FROM " + obj.GetType().Name + - (selectors != null && selectors.Any() ? (" WHERE " + whereStatement) : ""); + var whereStatement = ""; + if (selectors != null) + { + whereStatement = selectors.Aggregate("", (current, selector) => + { + var dbCommand = command; + return current + ((current == "" ? "" : " AND ") + selector.SetToCommand(ref dbCommand)); + }); + } - command.CommandText = selectStatement; + var selectStatement = "SELECT " + selectFields + " FROM " + obj.GetType().Name + (selectors != null && selectors.Any() ? (" WHERE " + whereStatement) : ""); - var reader = command.ExecuteReader(); - var results = ParseDataReader(type, reader); + command.CommandText = selectStatement; - command.Dispose(); + var reader = command.ExecuteReader(); + var results = ParseDataReader(type, reader); - return results; + return results; + } } public override bool DeleteMatching(Type type, Selector[] selectors) @@ -353,41 +364,43 @@ public override bool DeleteMatching(Type type, Selector[] selectors) } var connection = GenericConnectionManager.GetConnectionManager(GetSupportedDatabase()).GetConnection(type); - var command = connection.CreateCommand(); + using (var command = connection.CreateCommand()) + { + var whereStatement = ""; + if (selectors != null) + whereStatement = selectors.Aggregate("", (current, selector) => + { + var dbCommand = command; + return current + ((current == "" ? "" : " AND ") + selector.SetToCommand(ref dbCommand)); + }); - var whereStatement = ""; - if (selectors != null) - whereStatement = selectors.Aggregate("", - (current, selector) => - current + ((current == "" ? "" : " AND ") + selector.SetToCommand(ref command))); + var selectStatement = "DELETE FROM " + obj.GetType().Name + (selectors != null && selectors.Any() ? (string.Format(" WHERE {0}", whereStatement)) : ""); + var success = false; + var transaction = null as DbTransaction; - var selectStatement = "DELETE FROM " + obj.GetType().Name + (selectors != null && selectors.Any() ? (string.Format(" WHERE {0}", whereStatement)) : ""); - var success = false; - var transaction = null as DbTransaction; + try + { + transaction = (SqlCeTransaction)connection.BeginTransaction(IsolationLevel.ReadCommitted); - try - { - transaction = (SqlCeTransaction)connection.BeginTransaction(IsolationLevel.ReadCommitted); + command.Transaction = transaction; + command.CommandText = selectStatement; - command.Transaction = transaction; - command.CommandText = selectStatement; + var executionResult = command.ExecuteNonQuery(); + if (executionResult >= 0) + { + transaction.Commit(); + success = true; - var executionResult = command.ExecuteNonQuery(); - if (executionResult >= 0) + _OnBulkDelete(type, selectors); + } + } + catch { - transaction.Commit(); - success = true; - - _OnBulkDelete(type, selectors); + if (transaction != null) transaction.Rollback(); } - } - catch - { - if (transaction != null) transaction.Rollback(); - } - command.Dispose(); - return success; + return success; + } } public override void FillDataTable(Type type, ref DataTable table, Selector[] selectors, int limit) @@ -396,146 +409,154 @@ public override void FillDataTable(Type type, ref DataTable table, Selector[] se if (obj == null) return; - var commandString = DatabaseEntity.GetSelectCommandString(type); - var whereQuery = ""; - var command = GenericConnectionManager.GetConnectionManager(GetSupportedDatabase()).GetConnection(type).CreateCommand(); - - if (selectors != null && selectors.Any()) + using (var command = GenericConnectionManager.GetConnectionManager(GetSupportedDatabase()).GetConnection(type).CreateCommand()) { - whereQuery = selectors.Aggregate(whereQuery, (current, selector) => current + ((current == "" ? "" : " AND ") + selector.SetToCommand(ref command))); - } + var commandString = DatabaseEntity.GetSelectCommandString(type); + var whereQuery = ""; - if (limit > 0) - { - commandString = commandString.Replace("SELECT ", "SELECT TOP (" + limit + ")"); - } + if (selectors != null && selectors.Any()) + { + whereQuery = selectors.Aggregate(whereQuery, (current, selector) => + { + var dbCommand = command; + return current + ((current == "" ? "" : " AND ") + selector.SetToCommand(ref dbCommand)); + }); + } - command.CommandText = commandString + (whereQuery != "" ? (" WHERE " + whereQuery) : ""); + if (limit > 0) + { + commandString = commandString.Replace("SELECT ", "SELECT TOP (" + limit + ")"); + } - var reader = command.ExecuteReader(); - var fieldInfos = obj.GetColumns(true).GetOtherColumns().Where(i => ((TableColumn)i.GetCustomAttributes(typeof(TableColumn), true)[0]).IsRetrievableFromDatabase).ToArray(); + command.CommandText = commandString + (whereQuery != "" ? (" WHERE " + whereQuery) : ""); - table.Rows.Clear(); - table.Columns.Clear(); + var reader = command.ExecuteReader(); + var fieldInfos = obj.GetColumns(true).GetOtherColumns().Where(i => ((TableColumn)i.GetCustomAttributes(typeof(TableColumn), true)[0]).IsRetrievableFromDatabase).ToArray(); - var translators = new List(); + table.Rows.Clear(); + table.Columns.Clear(); - foreach (var fieldInfo in fieldInfos) - { - try + var translators = new List(); + + foreach (var fieldInfo in fieldInfos) { - var cInfo = ((TableColumn)fieldInfo.GetCustomAttributes(typeof(TableColumn), true)[0]); + try + { + var cInfo = ((TableColumn)fieldInfo.GetCustomAttributes(typeof(TableColumn), true)[0]); - if (fieldInfo.FieldType == typeof(bool)) - table.Columns.Add(cInfo.GridDisplayName ?? fieldInfo.Name, typeof(bool)); - else - table.Columns.Add(cInfo.GridDisplayName ?? fieldInfo.Name); + if (fieldInfo.FieldType == typeof(bool)) + table.Columns.Add(cInfo.GridDisplayName ?? fieldInfo.Name, typeof(bool)); + else + table.Columns.Add(cInfo.GridDisplayName ?? fieldInfo.Name); - var translator = cInfo.TranslatorType == null ? null : TranslatorRegistry.Instance.Get(cInfo.TranslatorType); - translators.Add(translator); + var translator = cInfo.TranslatorType == null ? null : TranslatorRegistry.Instance.Get(cInfo.TranslatorType); + translators.Add(translator); + } + catch { /* IGNORED */ } } - catch { /* IGNORED */ } - } - - if (!reader.Read()) - { - try { reader.Close(); } catch { /* IGNORED */ } - command.Dispose(); - return; - } - frmLoadingDialog.ShowWindow(); + if (!reader.Read()) + { + reader.Close(); + return; + } - do - { - if (frmLoadingDialog.GetStatus()) - break; + frmLoadingDialog.ShowWindow(); - var row = table.Rows.Add(); - for (var i = 0; i < table.Columns.Count; i++) + do { - try + if (frmLoadingDialog.GetStatus()) + break; + + var row = table.Rows.Add(); + for (var i = 0; i < table.Columns.Count; i++) { - if (translators[i] != null) + try { - var value = reader[i]; - row[i] = (translators.Count > i && i >= 0) ? translators[i].ToTranslated(value) : value.ToString(); + if (translators[i] != null) + { + var value = reader[i]; + row[i] = (translators.Count > i && i >= 0) ? translators[i].ToTranslated(value) : value.ToString(); + } + else + row[i] = reader[i]; } - else - row[i] = reader[i]; + catch { /* IGNORED */ } } - catch { /* IGNORED */ } } - } - while (reader.Read()); + while (reader.Read()); - try { reader.Close(); } catch { /* IGNORED */ } - frmLoadingDialog.HideWindow(); - command.Dispose(); + reader.Close(); + frmLoadingDialog.HideWindow(); + } } public override PrimaryKeyConstraintDetails GetPrimaryKeyDetails(Type type) { - var command = GenericConnectionManager.GetConnectionManager(GetSupportedDatabase()).GetConnection(type).CreateCommand(); - var commandString = string.Format("SELECT INDEX_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.INDEXES WHERE PRIMARY_KEY = 1 AND TABLE_NAME = '{0}'", type.Name); + using (var command = GenericConnectionManager.GetConnectionManager(GetSupportedDatabase()).GetConnection(type).CreateCommand()) + { + var commandString = string.Format("SELECT INDEX_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.INDEXES WHERE PRIMARY_KEY = 1 AND TABLE_NAME = '{0}'", type.Name); - command.CommandText = commandString; + command.CommandText = commandString; - var reader = command.ExecuteReader(); - var primaryKeysPerConstraint = new Dictionary>(); + var reader = command.ExecuteReader(); + var primaryKeysPerConstraint = new Dictionary>(); - try - { - while (reader.Read()) + try { - try + while (reader.Read()) { - var constraintName = reader.GetString(0); - var fieldName = reader.GetString(1).ToLower(); + try + { + var constraintName = reader.GetString(0); + var fieldName = reader.GetString(1).ToLower(); - if (primaryKeysPerConstraint.ContainsKey(constraintName) == false) primaryKeysPerConstraint.Add(constraintName, new List()); + if (primaryKeysPerConstraint.ContainsKey(constraintName) == false) primaryKeysPerConstraint.Add(constraintName, new List()); - primaryKeysPerConstraint[constraintName].Add(fieldName); + primaryKeysPerConstraint[constraintName].Add(fieldName); + } + catch { /* IGNORED */ } } - catch { /* IGNORED */ } } - } - catch { /* IGNORED */ } + catch { /* IGNORED */ } - try { reader.Close(); } catch { /* IGNORED */ } - command.Dispose(); + reader.Close(); - if (primaryKeysPerConstraint.Any() == false) return null; - if (primaryKeysPerConstraint.Count > 1) throw new InvalidDataException(string.Format("Due to some reason the table '{0}' has more than 1 primary key.", type.Name)); + if (primaryKeysPerConstraint.Any() == false) return null; + if (primaryKeysPerConstraint.Count > 1) throw new InvalidDataException(string.Format("Due to some reason the table '{0}' has more than 1 primary key.", type.Name)); - var firstEntry = primaryKeysPerConstraint.First(); - return new PrimaryKeyConstraintDetails(firstEntry.Key, firstEntry.Value.ToArray()); + var firstEntry = primaryKeysPerConstraint.First(); + return new PrimaryKeyConstraintDetails(firstEntry.Key, firstEntry.Value.ToArray()); + } } public override string[] GetTableFields(Type type) { var connection = GenericConnectionManager.GetConnectionManager(GetSupportedDatabase()).GetConnection(type); - var command = connection.CreateCommand(); - - command.CommandText = string.Format("SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='{0}'", type.Name); + using (var command = connection.CreateCommand()) + { + command.CommandText = string.Format("SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='{0}'", type.Name); - var reader = command.ExecuteReader(); - var columns = new List(); + var reader = command.ExecuteReader(); + var columns = new List(); - while (reader.Read()) - { try { - var columnName = reader.GetString(0).ToLower(); - columns.Add(columnName); + while (reader.Read()) + { + try + { + var columnName = reader.GetString(0).ToLower(); + columns.Add(columnName); + } + catch { /* IGNORED */ } + } } catch { /* IGNORED */ } - } - - try { reader.Close(); } catch { /* IGNORED */ } - command.Dispose(); - return columns.ToArray(); + reader.Close(); + return columns.ToArray(); + } } } }