public void TestMethod02() // SP de valor nulo { string query = null; String ConnectionStr = ConfigurationManager.AppSettings["ConnStr"]; List <SqlParameter> listparams = new List <SqlParameter>(); listparams.Add(new SqlParameter() { ParameterName = "Caro" }); String Code = ErrorsAndExceptionsCatalog._602_Code; String Message = ErrorsAndExceptionsCatalog._602_StoredProdecureNotFound; DataAccessException resultEX = new DataAccessException(); try { DataTable dt = DataAccessADO.GetDataTable(query, CommandType.StoredProcedure, listparams, ConnectionStr, null); } catch (DataAccessException ex) { resultEX = ex; } Assert.AreEqual(Code, resultEX.code); Assert.AreEqual(Message, resultEX.messageCode); }
/// <summary> /// 提交当前操作的结果 /// </summary> public int Commit() { try { if (dbTransaction != null) { dbTransaction.Commit(); this.Close(); } return(1); } catch (Exception ex) { if (ex.InnerException != null && ex.InnerException.InnerException is SqlException) { SqlException sqlEx = ex.InnerException.InnerException as SqlException; string msg = ExceptionMessage.GetSqlExceptionMessage(sqlEx.Number); throw DataAccessException.ThrowDataAccessException(sqlEx, msg); } throw; } finally { if (dbTransaction == null) { this.Close(); } } }
/// <exception cref="DataAccessException"><c>DataAccessException</c>.</exception> public override System.Data.IDataReader ExecuteDataReader(DataRequest request) { //ãªéÊÓËÃѺ¤ÓÊÑè§ SELECT à·èÒ¹Ñé¹ //DataReader ·Ó§Ò¹à»ç¹ Non-Connectionless ¨Ö§µéͧà»Ô´ Connection äÇéàÊÁÍ // ¨¹¡ÇèҨлԴ DataReader ¨Ö§¨ÐÊÒÁÒö»Ô´ Connection ä´é //´Ñ§¹Ñ鹨֧¨Ðµéͧ¡Ó˹´ KeepConnection = True if (!KeepConnection) { throw new ApplicationException("You should set KeepConnection is True"); } //Check if not has transaction //if database is begin transaction, Connection must be already Open state. if (DBTransactionState == TransactionState.IDLE) { //Reopen connection if (DBConnectionState == ConnectionState.Open) { this.Close(); } this.Open(); } try { OracleCommand cmd = (OracleCommand)CreateCommand(request); return(cmd.ExecuteReader()); } catch (Exception err) { DataAccessException ex = new DataAccessException(err.Message, err); ex.DataRequest = request; throw ex; } }
/// <summary> /// Translate the given <see cref="System.SystemException"/> into a generic data access exception. /// </summary> /// <param name="task">A readable string describing the task being attempted.</param> /// <param name="sql">The SQL query or update that caused the problem. May be null.</param> /// <param name="exception"> /// The <see cref="System.Exception"/> encountered by the ADO.NET implementation. /// </param> /// <returns> /// A <see cref="Spring.Dao.DataAccessException"/> appropriate for the supplied /// <paramref name="exception"/>. /// </returns> public virtual DataAccessException Translate(string task, string sql, Exception exception) { if (task == null) { task = ""; } if (sql == null) { sql = ""; } string errorCode = ExtractErrorCode(exception); DataAccessException dex = DoTranslate(task, sql, errorCode, exception); if (dex != null) { // Specific exception match found. return(dex); } // Looking for a fallback... if (log.IsDebugEnabled) { log.Debug("Unable to translate exception with errorCode '" + errorCode + "', will use the fallback translator"); } IAdoExceptionTranslator fallback = FallbackTranslator; if (fallback != null) { return(FallbackTranslator.Translate(task, sql, exception)); } // We couldn't identify it more precisely. return(new UncategorizedAdoException(task, sql, errorCode, exception)); }
/// <summary> /// 提交当前操作的结果 /// </summary> public int Commit() { try { if (_isusetran == true) { Connection.Ado.CommitTran(); _isusetran = false; this.Close(); } return(1); } catch (Exception ex) { if (ex.InnerException != null && ex.InnerException.InnerException is SqlException) { SqlException sqlEx = ex.InnerException.InnerException as SqlException; string msg = ExceptionMessage.GetSqlExceptionMessage(sqlEx.Number); throw DataAccessException.ThrowDataAccessException(sqlEx, msg); } throw; } finally { if (_isusetran == false) { this.Close(); } } }
/// <summary> /// 提交当前操作的结果 /// </summary> public int Commit() { try { int returnValue = Dbcontext.SaveChanges(); if (DbTransaction != null) { DbTransaction.Commit(); this.Close(); } return(returnValue); } catch (Exception ex) { if (ex.InnerException != null && ex.InnerException.InnerException is SqlException) { SqlException sqlEx = ex.InnerException.InnerException as SqlException; string msg = ExceptionMessageHelper.GetSqlExceptionMessage(sqlEx.Number); throw DataAccessException.ThrowDataAccessException(sqlEx, msg); } throw; } finally { if (DbTransaction == null) { this.Close(); } } }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <returns></returns> /// <exception cref="ApplicationException">You should set KeepConnection is True</exception> /// <exception cref="DataAccessException"><c>DataAccessException</c>.</exception> public override IDataReader ExecuteDataReader(DataRequest request) { //ใช้สำหรับคำสั่ง SELECT เท่านั้น //DataReader ทำงานเป็น Non-Connectionless จึงต้องเปิด Connection ไว้เสมอ // จนกว่าจะปิด DataReader จึงจะสามารถปิด Connection ได้ //ดังนั้นจึงจะต้องกำหนด KeepConnection = True if (!KeepConnection) { throw new ApplicationException("You should set KeepConnection is True"); } //Check if not has transaction //if database is begin transaction, Connection must be already Open state. if (DBTransactionState == TransactionState.IDLE) { //Reopen connection if (DBConnectionState == ConnectionState.Open) { this.Close(); } this.Open(); } try { SqlCommand cmd = (SqlCommand)CreateCommand(request); return(cmd.ExecuteReader()); } catch (Exception err) { DataAccessException ex = new DataAccessException(err.Message, err); ex.DataRequest = request; throw ex; } }
public void TestMethod03() // query mal estructurado { string query = "delect count(*) from Albums"; String ConnectionStr = ConfigurationManager.AppSettings["ConnStr"]; List <SqlParameter> listparams = new List <SqlParameter>(); listparams.Add(new SqlParameter() { ParameterName = "Caro" }); String Code = ErrorsAndExceptionsCatalog._603_Code; String Message = ErrorsAndExceptionsCatalog._603_InvalidQuery; DataAccessException resultEX = new DataAccessException(); try { DataTable dt = DataAccessADO.GetDataTable(query, CommandType.Text, listparams, ConnectionStr, null); } catch (DataAccessException ex) { resultEX = ex; } Assert.AreEqual(Code, resultEX.code); Assert.AreEqual(Message, resultEX.messageCode); }
public override void ClassifyDatabaseException(DataAccessException dataException, IDbCommand command = null) { var npExc = dataException.InnerException as NpgsqlException; if (npExc == null) //should never happen { return; } //npExc.ErrorCode is a strange large number; we use Code (string) instead, converting it to int int iCode; if (int.TryParse(npExc.Code, out iCode)) { dataException.ProviderErrorNumber = iCode; } switch (iCode) { case 23505: //unique index violation dataException.SubType = DataAccessException.SubTypeUniqueIndexViolation; var indexName = ExtractIndexName(npExc.Message); dataException.Data[DataAccessException.KeyDbKeyName] = indexName; break; case 23503: //integrity violation dataException.SubType = DataAccessException.SubTypeIntegrityViolation; break; } }
/// <summary> /// 提交当前操作的结果 /// </summary> public int Commit() { try { int returnValue = dbcontext.SaveChanges(); if (dbTransaction != null) { dbTransaction.Commit(); this.Close(); } return(returnValue); } catch (Exception ex) { LogFactory.GetLogger("Database").Error(ex); if (ex.InnerException != null && ex.InnerException.InnerException is SqlException) { SqlException sqlEx = ex.InnerException.InnerException as SqlException; string msg = ExceptionMessage.GetSqlExceptionMessage(sqlEx.Number); throw DataAccessException.ThrowDataAccessException(sqlEx, msg); } throw; } finally { if (dbTransaction == null) { this.Close(); } } }
/// <summary> /// 提交当前操作的结果 /// </summary> public int Commit() { int result; try { if (this.dbTransaction != null) { this.dbTransaction.Commit(); this.Close(); } result = 1; } catch (Exception ex) { if (ex.InnerException != null && ex.InnerException.InnerException is SqlException) { SqlException ex2 = ex.InnerException.InnerException as SqlException; string sqlExceptionMessage = ExceptionMessage.GetSqlExceptionMessage(ex2.Number); throw DataAccessException.ThrowDataAccessException(ex2, sqlExceptionMessage); } throw; } finally { if (this.dbTransaction == null) { this.Close(); } } return(result); }
/* * public enum SQLiteErrorCode { * Unknown = -1, * Ok = 0, * Error = 1, * Internal = 2, * Perm = 3, * Abort = 4, * Busy = 5, * Locked = 6, * NoMem = 7, * ReadOnly = 8, * Interrupt = 9, * IoErr = 10, * Corrupt = 11, * NotFound = 12, * Full = 13, * CantOpen = 14, * Protocol = 15, * Empty = 16, * Schema = 17, * TooBig = 18, * Constraint = 19, * Mismatch = 20, * Misuse = 21, * NoLfs = 22, * Auth = 23, * Format = 24, * Range = 25, * NotADb = 26, * Notice = 27, * Warning = 28, * Row = 100, * Done = 101, * NonExtendedMask = 255, * } * */ public override void ClassifyDatabaseException(DataAccessException dataException, IDbCommand command = null) { var inner = dataException.InnerException; if (inner == null) { return; } var msg = inner.Message; var errorCode = GetErrorCode(inner); dataException.ProviderErrorNumber = errorCode; switch (errorCode) { case 19: // SqliteErrorCodes.Constraint: if (msg.Contains("UNIQUE")) { dataException.SubType = DataAccessException.SubTypeUniqueIndexViolation; dataException.Data[DataAccessException.KeyDbColumnNames] = GetColumnListFromErrorMessage(msg); } else if (msg.Contains("FOREIGN KEY")) { dataException.SubType = DataAccessException.SubTypeIntegrityViolation; } break; } }
public void TestMethod013() // error no controlado { string query = "Select count(*) from Albums"; List <SqlParameter> listparams = new List <SqlParameter>(); listparams.Add(new SqlParameter() { ParameterName = "Caro" }); String ConnectionStr = "data source =./; initial catalog = MvcMusicStore; integrated security = True; MultipleActiveResultSets = True;"; String Code = ErrorsAndExceptionsCatalog._613_Code; String Message = ErrorsAndExceptionsCatalog._613_ErrorNotHandled; DataAccessException resultEX = new DataAccessException(); try { DataTable dt = DataAccessADO.GetDataTable(query, CommandType.Text, listparams, ConnectionStr, null); } catch (DataAccessException ex) { resultEX = ex; } Assert.AreEqual(Code, resultEX.code); Assert.AreEqual(Message, resultEX.messageCode); }
public int Commit() { try { var result = DbContext.SaveChanges(); if (DbTransaction != null) { DbTransaction.Commit(); Close(); } return(result); } catch (Exception ex) { if (ex.InnerException != null && ex.InnerException.InnerException is SqlException) { var sqlEx = (SqlException)ex.InnerException.InnerException; var msg = ExceptionMessage.GetSqlExceptionMessage(sqlEx.Number); throw DataAccessException.ThrowDataAccessException(sqlEx, msg); } throw; } finally { if (DbTransaction == null) { Close(); } } }
public void TestMethod012() // conexion no establecida { string query = "Select count(*) from Albums"; String ConnectionStr = "sdfnksdf"; List <SqlParameter> listparams = new List <SqlParameter>(); listparams.Add(new SqlParameter() { ParameterName = "Caro" }); String Code = ErrorsAndExceptionsCatalog._612_Code; String Message = ErrorsAndExceptionsCatalog._612_ConnectionFailed; DataAccessException resultEX = new DataAccessException(); try { DataTable dt = DataAccessADO.GetDataTable(query, CommandType.Text, listparams, ConnectionStr, null); } catch (DataAccessException ex) { resultEX = ex; } Assert.AreEqual(Code, resultEX.code); Assert.AreEqual(Message, resultEX.messageCode); }
public void TestMethod011() // no se pudo ejecutar la sentencia { string query = "Select count(*) from Albums"; List <SqlParameter> listparams = new List <SqlParameter>(); listparams.Add(new SqlParameter() { ParameterName = "Caro" }); String ConnectionStr = "data source=./;initial catalog=MvcMusicStore;integrated security=True;MultipleActiveResultSets=True;"; String Code = ErrorsAndExceptionsCatalog._611_Code; String Message = ErrorsAndExceptionsCatalog._611_InvalidSentenceExecution; DataAccessException resultEX = new DataAccessException(); try { bool result = DataAccessADO.ExecuteNonQuery(query, CommandType.Text, listparams, ConnectionStr, null); } catch (DataAccessException ex) { resultEX = ex; } Assert.AreEqual(Code, resultEX.code); Assert.AreEqual(Message, resultEX.messageCode); }
public void TestMethod06() // cadena de conexion mal estructurada { string query = "Select count(*) from Albums"; String ConnectionStr = "user/Caro"; String Code = ErrorsAndExceptionsCatalog._606_Code; String Message = ErrorsAndExceptionsCatalog._606__InvalidConnectionString; DataAccessException resultEX = new DataAccessException(); List <SqlParameter> listparams = new List <SqlParameter>(); listparams.Add(new SqlParameter() { ParameterName = "Caro" }); try { DataTable dt = DataAccessADO.GetDataTable(query, CommandType.Text, listparams, ConnectionStr, null); } catch (DataAccessException ex) { resultEX = ex; } Assert.AreEqual(Code, resultEX.code); Assert.AreEqual(Message, resultEX.messageCode); }
public void TestMethod01() // SP mal estructurado { // var String ConnectionStr = ConfigurationManager.AppSettings["ConnStr"]; List <SqlParameter> listparams = new List <SqlParameter>(); listparams.Add(new SqlParameter() { ParameterName = "Caro" }); String Code = ErrorsAndExceptionsCatalog._601_Code; String Message = ErrorsAndExceptionsCatalog._601_InvalidStoredProcedure; DataAccessException resultEX = new DataAccessException(); //act try { DataTable dt = DataAccessADO.GetDataTable("CountAlbums", CommandType.StoredProcedure, listparams, ConnectionStr, null); } catch (DataAccessException ex) { resultEX = ex; } // arrange Assert.AreEqual(Code, resultEX.code); Assert.AreEqual(Message, resultEX.messageCode); }
/* * public enum SQLiteErrorCode { * Unknown = -1, * Ok = 0, * Error = 1, * Internal = 2, * Perm = 3, * Abort = 4, * Busy = 5, * Locked = 6, * NoMem = 7, * ReadOnly = 8, * Interrupt = 9, * IoErr = 10, * Corrupt = 11, * NotFound = 12, * Full = 13, * CantOpen = 14, * Protocol = 15, * Empty = 16, * Schema = 17, * TooBig = 18, * Constraint = 19, * Mismatch = 20, * Misuse = 21, * NoLfs = 22, * Auth = 23, * Format = 24, * Range = 25, * NotADb = 26, * Notice = 27, * Warning = 28, * Row = 100, * Done = 101, * NonExtendedMask = 255, * } * */ public override void ClassifyDatabaseException(DataAccessException dataException, IDbCommand command = null) { var sqlEx = dataException.InnerException as SQLiteException; if (sqlEx == null) { return; } dataException.ProviderErrorNumber = sqlEx.ErrorCode; var msg = sqlEx.Message; switch (sqlEx.ResultCode) { case SQLiteErrorCode.Constraint: if (msg.Contains("UNIQUE")) { dataException.SubType = DataAccessException.SubTypeUniqueIndexViolation; dataException.Data[DataAccessException.KeyDbColumnNames] = GetColumnListFromErrorMessage(msg); } else if (msg.Contains("FOREIGN KEY")) { dataException.SubType = DataAccessException.SubTypeIntegrityViolation; } break; } }
public override void ClassifyDatabaseException(DataAccessException dataException, IDbCommand command = null) { var oracleEx = dataException.InnerException as OracleException; if (oracleEx == null) { return; } dataException.ProviderErrorNumber = oracleEx.Number; switch (oracleEx.Number) { case 1: //unique index violation //sqlEx.Data contains 6 values which are mostly useless (info about provider) // we need to parse index name - stupidly the ex does not provide it as a separate value. dataException.SubType = DataAccessException.SubTypeUniqueIndexViolation; dataException.Data[DataAccessException.KeyDbKeyName] = ExtractIndexNameFromDuplicateErrorMessage(oracleEx.Message); break; case 60: //Transaction deadlock lock, process killed dataException.SubType = DataAccessException.SubTypeDeadLock; break; case 2291: // FK constraint violation on delete case 2292: dataException.SubType = DataAccessException.SubTypeIntegrityViolation; break; }//switch }
protected void SetDataAccessValues(DataAccessException ex, ErrorMessageType errorMessageType) { var customMessage = ""; switch (errorMessageType) { case ErrorMessageType.AfterInsert: customMessage = $"Gagal menemukan data {_modelName} " + "di database setelah sukses menambahkan data."; break; case ErrorMessageType.ModelNotFound: customMessage = $"{_modelName.FirstToUpper()} tidak dapat diproses, dikarenakan data {_modelName} " + "yang ingin di proses tidak ditemukan/sudah dihapus."; break; case ErrorMessageType.FailedDelete: customMessage = $"Gagal menghapus data {_modelName}. Kemungkinan data sedang digunakan oleh data yang lain"; break; case ErrorMessageType.QtyEmpty: customMessage = $"Qty {_modelName} yang ingin di proses bernilai 0 (Nol)."; break; default: customMessage = "Terjadi keslahan saat melakukan operasi yang diminta."; break; } SetDataAccessValues(ex, customMessage); }
/// <summary> /// Menampilkan pesan error Exception /// </summary> /// <param name="ex">DataAccessException object</param> public static void Error(DataAccessException ex) { MessageBox.Show($"Message: {ex.DataAccessStatusInfo.CustomMessage}\n" + $"Error code: {ex.DataAccessStatusInfo.ErrorCode}\n" + $"Source: {ex.Source}\n", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); }
public override void ClassifyDatabaseException(DataAccessException dataException, IDbCommand command = null) { var sqlEx = dataException.InnerException as MySqlException; if (sqlEx == null) { return; } dataException.ProviderErrorNumber = sqlEx.Number; switch (sqlEx.Number) { case 1062: var indexName = GetIndexName(sqlEx.Message); dataException.SubType = DataAccessException.SubTypeUniqueIndexViolation; dataException.Data[DataAccessException.KeyDbKeyName] = indexName; break; case 1451: //integrity violation dataException.SubType = DataAccessException.SubTypeIntegrityViolation; break; default: break; } //switch }
/// <summary> /// Returns a dataset object for the executed query /// </summary> /// <param name="commandType">Determines the command type</param> /// <param name="strCommandText">Input query string</param> /// <returns>DataSet</returns> public DataSet ExecuteDataSet(CommandType commandType, string strCommandText, SqlParameter[] sqlParameters) { //Validate input parameters if (string.IsNullOrEmpty(strCommandText) || (null == sqlParameters)) { string message = String.Empty; if (string.IsNullOrEmpty(strCommandText)) { message = string.Format(CoreConstants.INVALIDPARAMETER_MSG, "strCommandText"); } else if (null == sqlParameters) { message = string.Format(CoreConstants.INVALIDPARAMETER_MSG, "sqlParameters"); } DataAccessException ex = new DataAccessException(message); throw ex; } //Prepare sql command object this.PrepareCommand(commandType, strCommandText, sqlParameters); //Instantiate new sql data adapter object SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(Command); //instantiate data set DataSet dataSet = new DataSet(); //Fill data adapter with data set sqlDataAdapter.Fill(dataSet); CommitTransaction(); return(dataSet); }
/// <summary> /// Returns the count of the executed transaction /// </summary> /// <param name="commandType"></param> /// <param name="strCommandText"></param> /// <param name="sqlParameters"></param> /// <returns></returns> /// <remarks></remarks> public object ExecuteScalar(CommandType commandType, String strCommandText, SqlParameter[] sqlParameters) { //Validate input parameters if (string.IsNullOrEmpty(strCommandText) || (null == sqlParameters)) { string message = String.Empty; if (string.IsNullOrEmpty(strCommandText)) { message = string.Format(CoreConstants.INVALIDPARAMETER_MSG, "strCommandText"); } else if (null == sqlParameters) { message = string.Format(CoreConstants.INVALIDPARAMETER_MSG, "sqlParameters"); } DataAccessException ex = new DataAccessException(message); throw ex; } //prepare sql command object this.PrepareCommand(commandType, strCommandText, sqlParameters); //Call execute non query method on the sql command object returnValue = Command.ExecuteScalar(); //Commit transaction this.CommitTransaction(); return(returnValue); }
/// <summary> /// Commits transaction. /// </summary> public void Commit() { try { context.SaveChanges(); } catch (DbEntityValidationException ex) { logger.Error(ex); var dataAccess = new DataAccessException("Entity validation has failed.", ex); throw dataAccess; } catch (DbUpdateException ex) { logger.Error(ex); var dataAccess = new DataAccessException("Entity update has failed.", ex); throw dataAccess; } catch (Exception ex) { logger.Error(ex); var dataAccess = new DataAccessException("Required data is inaccessible.", ex); throw dataAccess; } }
private void CheckTranslation(IAdoExceptionTranslator translator, string errorCode, Type exType) { TestSqlException sex = new TestSqlException("", errorCode); DataAccessException ex = translator.Translate("", "", sex); Assert.IsTrue(exType.IsAssignableFrom(ex.GetType())); Assert.IsTrue(ex.InnerException == sex); }
protected void SetDataAccessValues(DataAccessException ex, string customMessage) { ex.DataAccessStatusInfo.Status = "Error"; ex.DataAccessStatusInfo.OperationSucceeded = false; ex.DataAccessStatusInfo.CustomMessage = customMessage; ex.DataAccessStatusInfo.ExceptionMessage = !string.IsNullOrWhiteSpace(ex.Message) ? string.Copy(ex.Message) : ""; ex.DataAccessStatusInfo.StackTrace = !string.IsNullOrWhiteSpace(ex.StackTrace) ? string.Copy(ex.StackTrace) : ""; }
public void DataAccessException_InitTest() { var expected_innerException = new Exception("There's a glitch in the matrix."); var dataAccessException = new DataAccessException(expected_innerException); var actual_innerException = dataAccessException.InnerException; Assert.Equal(expected_innerException, actual_innerException); }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <returns></returns> /// <exception cref="ApplicationException">You should set KeepConnection is True</exception> /// <exception cref="DataAccessException"><c>DataAccessException</c>.</exception> public override int ExecuteNonQuery(DataRequest request) { //Include Function : UPDATE, INSERT, DELETE //Mayby transaction if (DBTransactionState == TransactionState.PROCESSING) { //Transaction ทำงานเป็น Non-Connectionless จึงต้องเปิด Connection ไว้เสมอ // จนกว่าจะ Commit / Rollback จึงจะสามารถปิด Connection ได้ // ดังนั้นจึงจะต้องกำหนด KeepConnection = True if (!KeepConnection) { throw new ApplicationException("You should set KeepConnection is True"); } //Connection จะต้อง Open ไว้แล้ว เนื่องจากมีการใช้ Transaction } else { //ถ้าไม่มีการใช้ Transaction จะต้อง ReOpen connection if (DBConnectionState == ConnectionState.Open) { this.Close(); } this.Open(); } int retCmd = 0; //สร้างตัวแปรสำหรับ Execute Command SqlCommand cmd = (SqlCommand)CreateCommand(request); try { //Execute Command and return number of affected rows. retCmd = cmd.ExecuteNonQuery(); } catch (Exception err) { //Save db exception //byte[] bytes = request.SerializeObject(); //DBExceptionDAO.AddNew(bytes, ex.StackTrace, ex.Message); DataAccessException ex = new DataAccessException(err.Message, err); ex.DataRequest = request; throw ex; } finally { //Close connection when not use transaction and KeepConnection is false. if (DBTransactionState == TransactionState.IDLE) { if (!KeepConnection) { this.Close(); } } } return(retCmd); }