// khi đưa sự kiện cho người dùng xử lí, có thể họ sẽ xử lí những tác vụ khá nặng, làm cho client phải chờ đợi lâu.
        // Vì vậy, khi đưa cho người dùng xử lí, ta đưa vào một thread để giúp việc trả lời client nhanh hơn

        private void OnDbInteractionErrorOccurred(System.Data.SqlClient.SqlException Sqlex)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(((o) =>
            {
                _Param.DBInteractionErrorOccurred(Sqlex);
            }));
        }
Esempio n. 2
0
        /// <summary>
        /// Llama a método Insert de ClienteDAL y le pasa una entidad para insertarla en la base
        /// </summary>
        /// <param name="entity">Cliente</param>
        /// <returns>Cliente</returns>
        public Cliente Insert(Cliente entity)
        {
            int age         = Methods.CalculateAge(entity.fecha_nacimiento);
            int errorExiste = 0;

            if (age >= 18)
            {
                try
                {
                    entity = cliDAL.Insert(entity);
                    return(entity);
                }
                catch (Exception ex)
                {
                    System.Data.SqlClient.SqlException sqlException = ex as System.Data.SqlClient.SqlException;
                    errorExiste = sqlException.Number;

                    if (errorExiste == Convert.ToInt32(ConfigurationManager.AppSettings["existe"]))
                    {
                        throw new Exception(EValidaciones.existe);
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
            else
            {
                throw new Exception(EValidaciones.menor);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Tries to save the item and in case of unique key constraint violation,
        /// tries again four more times.
        /// </summary>
        /// <param name="action">The action of save the item</param>
        private void TryAgainSave(System.Action action)
        {
            int  tries   = 0;
            bool success = false;

            System.Data.SqlClient.SqlException lastException = null;
            while (tries < 5 && !success)
            {
                try {
                    action();
                    success = true;
                } catch (System.Data.UpdateException ex) {
                    lastException = ex.InnerException as System.Data.SqlClient.SqlException;
                    if (lastException == null)
                    {
                        throw ex;
                    }
                    if (lastException.Number != 2601 && lastException.Number != 2627)
                    {
                        throw ex;
                    }
                    tries++;
                }
            }
            // if after 4 times
            if (!success)
            {
                throw lastException;
            }
        }
Esempio n. 4
0
        /// <summary>
        /// 尝试解析SqlException数据库异常。
        /// </summary>
        /// <param name="sex">SqlException</param>
        /// <param name="delete">是否是删除命令。</param>
        public static void ParseSqlException(System.Data.SqlClient.SqlException sex, bool?delete)
        {
            if (sex.Errors.Count > 0)
            {
                switch (sex.Errors[0].Number)
                {
                case 547:       // %1! 语句与 %2! %3! 约束 ''%4!'' 冲突。该冲突发生于数据库 ''%6!'',表 ''%8!''%10!%11!%13!。
                    if (delete.HasValue)
                    {
                        if (delete.Value)
                        {
                            throw new DeletingDataUsedException("要删除的数据被其他数据引用:" + sex.Message, sex);
                        }
                        else
                        {
                            throw new ReferDataNotExistException("引用的数据不存在:" + sex.Message, sex);
                        }
                    }
                    else
                    {
                        throw new ViolateReferenceException(sex.Message, sex);
                    }

                case 515:       // 无法将 NULL 值插入列 ''%1!'',表 ''%3!'';该列不允许空值。%ls 失败。
                    throw new DBNotNullException("无法插入空值:" + sex.Message, sex);
                }
            }

            throw sex;
        }
Esempio n. 5
0
        /// <summary>
        /// Action to remove staff
        /// </summary>
        /// <param name="id">staff id</param>
        /// <returns></returns>
        public ActionResult RemoveStaff(int id)
        {
            string previousAction = Request.UrlReferrer.AbsolutePath.ToString();

            try
            {
                HttpCookie conString = Request.Cookies.Get("rwxgqlb");
                Staff      s         = new Staff(id, Cryptography.Decrypt(conString.Value));
                if (s.Delete())
                {
                    return(Redirect(previousAction + "?s=true"));
                }
                else
                {
                    return(Redirect(previousAction));
                }
            }
            catch (Exception ex)
            {
                System.Data.SqlClient.SqlException sqlEx = (System.Data.SqlClient.SqlException)ex.InnerException;
                if (sqlEx.Number == 547)
                {
                    return(Redirect(previousAction));
                }
                return(Content(ex.Message));
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Writes error to error log file.
        /// </summary>
        /// <param name="virtualServer">Virtual server name.</param>
        /// <param name="x"></param>
        /// <param name="stackTrace"></param>
        public static void DumpError(string virtualServer, Exception x, StackTrace stackTrace)
        {
            try{
                string source = stackTrace.GetFrame(0).GetMethod().DeclaringType.FullName + "." + stackTrace.GetFrame(0).GetMethod().Name + "()";

                string errorText = x.Message + "\r\n";
                errorText += "//------------- function: " + source + "  " + DateTime.Now.ToString() + "------------//\r\n";
                errorText += new StackTrace().ToString() + "\r\n";
                errorText += "//--- Excetption info: -------------------------------------------------\r\n";
                errorText += x.ToString() + "\r\n";

                if (x is System.Data.SqlClient.SqlException)
                {
                    System.Data.SqlClient.SqlException sX = (System.Data.SqlClient.SqlException)x;
                    errorText += "\r\n\r\nSql errors:\r\n";

                    foreach (System.Data.SqlClient.SqlError sErr in sX.Errors)
                    {
                        errorText += "\n";
                        errorText += "Procedure: '" + sErr.Procedure + "'  line: " + sErr.LineNumber.ToString() + "  error: " + sErr.Number.ToString() + "\r\n";
                        errorText += "Message: " + sErr.Message + "\r\n";
                    }
                }

                if (x.InnerException != null)
                {
                    errorText += "\r\n\r\n//------------- Innner Exception ----------\r\n" + x.Message + "\r\n";
                    errorText += x.InnerException.ToString();
                }

                DumpError(virtualServer, errorText);
            }
            catch {
            }
        }
Esempio n. 7
0
        public static string ShowErrors(System.Data.SqlClient.SqlException e)
        {
            StringBuilder bld   = new StringBuilder();
            Exception     inner = e.InnerException;

            if (null != inner)
            {
                bld.Append("Inner Exception: " + inner.ToString());
            }
            if (e.Errors != null)
            {
                System.Data.SqlClient.SqlErrorCollection errorCollection = e.Errors;
                foreach (System.Data.SqlClient.SqlError err in errorCollection)
                {
                    bld.AppendLine("Message   : " + err.Message);
                    bld.AppendLine("Level     : " + err.Class);
                    bld.AppendLine("State     : " + err.State);
                    bld.AppendLine("Procedure : " + err.Procedure);
                    bld.AppendLine("Line      : " + err.LineNumber);
                    bld.AppendLine("Source    : " + err.Source);
                    bld.AppendLine("Number    : " + err.Number);
                    bld.AppendLine("Server    : " + err.Server);
                }
            }
            return(bld.ToString());
        }
Esempio n. 8
0
        /// <summary>
        /// context.SaveChanges()
        /// </summary>
        public bool Update()
        {
            Logger.Debug("Update()");

            try
            {
                cmsCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                Logger.Error("", ex);
                errMsg = ex.Message;
                System.Data.SqlClient.SqlException sqlex = ex.GetBaseException() as System.Data.SqlClient.SqlException;

                if (sqlex != null)
                {
                    errMsg       = sqlex.Message;
                    sqlErrNumber = sqlex.Number;
                    sqlErrState  = sqlex.State;
                }

                return(false);
            }

            return(true);
        }
Esempio n. 9
0
        public bool UpdateAllCols <TEntity>(TEntity entity) where TEntity : class
        {
            Logger.DebugFormat("UpdateAllCols<TEntity>(entity) - TEntity[{0}]", typeof(TEntity).Name);

            try
            {
                cmsCtx.Entry <TEntity>(entity).State = EntityState.Modified;
                cmsCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                Logger.Error("", ex);
                errMsg = ex.Message;
                System.Data.SqlClient.SqlException sqlex = ex.GetBaseException() as System.Data.SqlClient.SqlException;

                if (sqlex != null)
                {
                    errMsg       = sqlex.Message;
                    sqlErrNumber = sqlex.Number;
                    sqlErrState  = sqlex.State;
                }

                return(false);
            }

            return(true);
        }
Esempio n. 10
0
        /// <summary>
        /// Wraps the SqlException, add contextual information (SqlQuery, parameter values), and then you should rethrow (do not swallow/ignore exceptions)
        /// According to the SQL error code, we can create a more meaningful message (parsing information from the DB error), which can later be translated by i18n
        /// </summary>
        /// <param name="ex"></param>
        public static DataException WrapSqlException(System.Data.SqlClient.SqlException ex, string sqlQuery = null, object parms = null)
        {
            // By default we keep the original SQL message
            string message = ex.Message;

            // According to the SQL error code, we can create a more meaningful message - see fields in https://stackoverflow.com/a/22126876/3606250 and codes in ...
            switch (ex.Errors[0].Number)
            {
            case 8134:
            {
                var    match      = System.Text.RegularExpressions.Regex.Match(ex.Message, "Msg 17001, Violation of Unique Key (<Constraint>)");
                string constraint = match.Groups["Constraint"].Value;
                //message = string.Format("[[[VIOLATION_UNIQUE_INDEX|||(((constraint)))]]"); // throw error with i18n-translatable message
                //this.ViolatedConstraint = constraint //TODO: save this in logs - DataException.SaveToLog?
                break;
            }

            default:
                break;
            }

            DataException wrappedException = new DataException(null, ex, sqlQuery, parms);

            return(wrappedException);
        }
Esempio n. 11
0
        /// <summary>
        /// This method allows you to reset the parameter object. Please note that this
        /// method resets all the parameters members except the connection information and
        /// the command time-out which are left in their current state.
        /// </summary>
        public void Reset()
        {
            this.internal_Param_RETURN_VALUE = System.Data.SqlTypes.SqlInt32.Null;

            this.internal_Param_JobId = System.Data.SqlTypes.SqlInt32.Null;
            this.internal_Param_JobId_UseDefaultValue = this.useDefaultValue;

            this.internal_Param_Description = System.Data.SqlTypes.SqlString.Null;
            this.internal_Param_Description_UseDefaultValue = this.useDefaultValue;

            this.internal_Param_Price = System.Data.SqlTypes.SqlMoney.Null;
            this.internal_Param_Price_UseDefaultValue = this.useDefaultValue;

            this.internal_Param_StartDate = System.Data.SqlTypes.SqlDateTime.Null;
            this.internal_Param_StartDate_UseDefaultValue = this.useDefaultValue;

            this.internal_Param_EndDate = System.Data.SqlTypes.SqlDateTime.Null;
            this.internal_Param_EndDate_UseDefaultValue = this.useDefaultValue;

            this.internal_Param_CustomerId = System.Data.SqlTypes.SqlInt32.Null;
            this.internal_Param_CustomerId_UseDefaultValue = this.useDefaultValue;

            this.errorSource    = ErrorSource.NotAvailable;
            this.sqlException   = null;
            this.otherException = null;
        }
Esempio n. 12
0
        /// <summary>
        /// Llama a método Insert de ProductoDAL y le pasa una entidad para insertarla en la base
        /// </summary>
        /// <param name="entity">Producto</param>
        /// <returns>Producto</returns>
        public Producto Insert(Producto entity)
        {
            int      errorExiste = 0;
            StockDAL stockDAL    = new StockDAL();

            try
            {
                entity = prodDAL.Insert(entity);

                Stock stock = new Stock();
                stock.fk_id_producto = entity.id;
                stock.cantidad       = 0;
                stockDAL.Insert(stock);

                return(entity);
            }
            catch (Exception ex)
            {
                System.Data.SqlClient.SqlException sqlException = ex as System.Data.SqlClient.SqlException;
                errorExiste = sqlException.Number;

                if (errorExiste == Convert.ToInt32(ConfigurationManager.AppSettings["existe"]))
                {
                    throw new Exception(EValidaciones.existe);
                }
                else
                {
                    throw ex;
                }
            }
        }
Esempio n. 13
0
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext != null)
            {
                HttpResponseMessage response = null;
                String message = "";

                // Ошибки на стороне SQL
                if (actionExecutedContext.Exception is System.Data.SqlClient.SqlException)
                {
                    System.Data.SqlClient.SqlException ex = (System.Data.SqlClient.SqlException)actionExecutedContext.Exception;
                    response = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);

                    switch (ex.Number)
                    {
                    case 2:
                    {
                        message = "Отсутствует подключение к базе данных";
                        break;
                    }

                    case 2627:
                    {
                        message = "Такой элемент уже сушествует";
                        break;
                    }

                    default:
                    {
                        message = "Необработанная ошибка при обращении к базе данных" + Environment.NewLine + actionExecutedContext.Exception.ToString();
                        break;
                    }
                    }
                }

                if (actionExecutedContext.Exception is NotFoundException)
                {
                    response = new HttpResponseMessage(System.Net.HttpStatusCode.NotFound);
                    message  = actionExecutedContext.Exception.Message;
                }

                if (actionExecutedContext.Exception is FalledLogin)
                {
                    response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
                    message  = actionExecutedContext.Exception.Message;
                }

                // Если необработанная ошибка
                if (response == null)
                {
                    // Дефолтные значения
                    response = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
                    message  = actionExecutedContext.Exception.Message;
                }

                response.Content = new StringContent(message);
                throw new HttpResponseException(response);
            }
        }
Esempio n. 14
0
 /// <summary>記錄錯誤事件</summary>
 /// <param name="logger">log4Net.ILog</param>
 /// <param name="sessionKey">關鍵索引鍵</param>
 /// <param name="ex">錯誤類別</param>
 /// <param name="sendMail">是否寄發信件</param>
 private static void LogException(ILog logger, string sessionKey, Exception ex, bool sendMail)
 {
     try
     {
         logger.ErrorFormat("[{0}]EX:Type:{1}", sessionKey, ex.GetType());
         if (ex.GetType().Equals(typeof(NullReferenceException)))
         {
             NullReferenceException ne = (NullReferenceException)ex;
             logger.ErrorFormat("[{0}]EX:Source:{1}", sessionKey, ne.Source);
             logger.ErrorFormat("[{0}]EX:TargetSite:{1}", sessionKey, ne.TargetSite.Name);
         }
         else if (ex.GetType().Equals(typeof(System.Net.Sockets.SocketException)))
         {
             System.Net.Sockets.SocketException se = (System.Net.Sockets.SocketException)ex;
             logger.ErrorFormat("[{0}]EX:ErrorCode:{1}", sessionKey, se.ErrorCode);
             logger.ErrorFormat("[{0}]EX:SocketErrorCode:{1}:{2}", sessionKey, se.SocketErrorCode, (int)se.SocketErrorCode);
             logger.ErrorFormat("[{0}]EX:NativeErrorCode:{1}", sessionKey, se.NativeErrorCode);
         }
         else if (ex.GetType().Equals(typeof(System.Net.HttpListenerException)))
         {
             System.Net.HttpListenerException se = (System.Net.HttpListenerException)ex;
             logger.ErrorFormat("[{0}]EX:ErrorCode:{1}", sessionKey, se.ErrorCode);
             logger.ErrorFormat("[{0}]EX:NativeErrorCode:{1}", sessionKey, se.NativeErrorCode);
         }
         else if (ex.GetType().Equals(typeof(System.Data.SqlClient.SqlException)))
         {
             System.Data.SqlClient.SqlException se = (System.Data.SqlClient.SqlException)ex;
             logger.ErrorFormat("[{0}]EX:Class:{1:X2}", sessionKey, se.Class);
             logger.ErrorFormat("[{0}]EX:Number:{1}", sessionKey, se.Number);
             logger.ErrorFormat("[{0}]EX:LineNumber:{1}", sessionKey, se.LineNumber);
             logger.ErrorFormat("[{0}]EX:ErrorCode:{1}", sessionKey, se.ErrorCode);
             logger.ErrorFormat("[{0}]EX:Errors:{1}", sessionKey, se.Errors);
         }
         logger.ErrorFormat("[{0}]EX:Message:{1}", sessionKey, ex.Message);
         logger.ErrorFormat("[{0}]EX:Source:{1}", sessionKey, ex.Source);
         logger.ErrorFormat("[{0}]EX:StackTrace:{1}", sessionKey, ex.StackTrace);
         foreach (System.Collections.DictionaryEntry de in ex.Data)
         {
             logger.ErrorFormat("[{0}]EX:Data:{1}:{2}", sessionKey, de.Key, de.Value);
         }
         if (ex.InnerException != null)
         {
             logger.ErrorFormat("[{0}]EX:InnerException", sessionKey);
             LogException(logger, sessionKey, ex.InnerException, false);
         }
         if (sendMail)
         {
             string content = GetExceptionLogString(sessionKey, ex);
             System.Threading.Tasks.Task.Factory.StartNew(() => SendMail("Exception Notice", content, false));
         }
     }
     catch (Exception nex)
     {
         logger.ErrorFormat("[LOG]EX:Type:{0}", nex.GetType());
         logger.ErrorFormat("[LOG]EX:Message:{0}", nex.Message);
         logger.ErrorFormat("[LOG]EX:Source:{0}", nex.Source);
         logger.ErrorFormat("[LOG]EX:StackTrace:{0}", nex.StackTrace);
     }
 }
        /// <summary>
        /// This method allows you to reset the parameter object. Please note that this
        /// method resets all the parameters members except the connection information and
        /// the command time-out which are left in their current state.
        /// </summary>
        public void Reset()
        {
            this.internal_Param_RETURN_VALUE = System.Data.SqlTypes.SqlInt32.Null;

            this.errorSource    = ErrorSource.NotAvailable;
            this.sqlException   = null;
            this.otherException = null;
        }
Esempio n. 16
0
        /// <summary>
        /// guarda los cambios
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnGuardar_Click(object sender, EventArgs e)
        {
            Entities.Categoria categoria = new Entities.Categoria();
            categoria.categoria = TxtNombre.Text;

            var  validation = new Helps.DataValidations(categoria).Validate();
            bool valid      = validation.Item1;

            if (valid == true)
            {
                if (editarse == false)
                {
                    try
                    {
                        categoria = bll.Insert(categoria);

                        InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.Insert, 1, this.GetType().FullName, MethodInfo.GetCurrentMethod().Name, "Categoria: " + categoria.categoria, "", ""));

                        Notifications.FrmSuccess.SuccessForm(Language.SearchValue("guardadoOK"));
                        RefrescarTabla();
                        LimpiarTxt();
                    }
                    catch (Exception ex)
                    {
                        System.Data.SqlClient.SqlException sqlException = ex as System.Data.SqlClient.SqlException;
                        erro = sqlException.Number;
                        InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.InsertError, 1, ex.TargetSite.DeclaringType.FullName, ex.TargetSite.Name, "Categoria: " + categoria.categoria, ex.StackTrace, ex.Message));
                        Notifications.FrmError.ErrorForm(Language.SearchValue("guardadoError") + "\n" + ex.Message);
                    }
                }
                if (editarse == true)
                {
                    try
                    {
                        categoria.id = id;

                        bll.Update(categoria);

                        InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.Update, 1, this.GetType().FullName, MethodInfo.GetCurrentMethod().Name, "Categoria: " + categoria.categoria, "", ""));

                        Notifications.FrmSuccess.SuccessForm(Language.SearchValue("editadoOK"));
                        RefrescarTabla();
                        LimpiarTxt();
                        editarse = false;
                    }
                    catch (Exception ex)
                    {
                        InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.UpdateError, 1, ex.TargetSite.DeclaringType.FullName, ex.TargetSite.Name, "Categoria: " + categoria.categoria, ex.StackTrace, ex.Message));
                        Notifications.FrmError.ErrorForm(Language.SearchValue("editadoError") + "\n" + ex.Message);
                    }
                }
            }
            else
            {
                string messageValid = validation.Item2;
                Notifications.FrmInformation.InformationForm(messageValid);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Determines if this exception is likely to be transient and the cause is likely to go away
        /// </summary>
        /// <param name="e">Exception to validate</param>
        /// <returns>True if looks transient</returns>
        public static bool IsTransient(Exception e)
        {
            switch (e.GetType().FullName)
            {
            case "System.FormatException":
                return(false);                               //When we have a good case of it being transient we will implement it

            case "System.Data.SqlClient.SqlException":
                System.Data.SqlClient.SqlException SQLEx = (System.Data.SqlClient.SqlException)e.GetBaseException();
                if (SQLEx != null)
                {
                    switch (SQLEx.Number)                                //not sure all the versions have the same meaning of these numbers
                    {
                    case 207:                                            //Invalid column name XXX. In reality, when attempting to insert text into numeric field, we get the same error if using SELECT, and we have to use SELECT to be able to run T-SQL within insert command
                    case 229:                                            //The SELECT permission was denied on the object
                    case 245:                                            //Conversion failed when converting the %ls value '%.*ls' to data type %ls.
                    case 8115:                                           //Arithmetic overflow error converting expression to data type int. Too large number sent to us. Or may be our column is too small!
                    case 8152:                                           //String or binary data would be truncated.
                        return(true);

                    default:
                        return(false);
                    }
                }
                break;

            case "System.Data.Odbc.OdbcException":
                System.Data.Odbc.OdbcException OdbcEx = (System.Data.Odbc.OdbcException)e.GetBaseException();
                if (OdbcEx != null)
                {
                    switch (OdbcEx.ErrorCode)                                    //not sure all the versions have the same meaning of these numbers
                    {
                    case -2146232009:                                            //ERROR [23505] ERROR: duplicate key value violates unique constraint \"IX_Test_Nchar1\"\nKey (\"Nchar1\")=(Recip-1-1           ) already exists.;\nError while executing the query
                        return(true);

                    default:
                        return(false);
                    }
                }
                break;

            case "System.InvalidCastException":
                return(false);                               //It's not something that resolves itself or gets recolved by changing surrounding conditions

            case "Npgsql.NpgsqlException":
                return(false);                               //At hte moment we don't even want to depend on their reference

            case "System.InvalidOperationException": return(false);

            case "System.Web.HttpException":
            case "System.Web.HttpParseException":
            case "System.Web.HttpRequestValidationException":
            case "System.Web.HttpUnhandledException":
                throw new NotImplementedException("Method is not implemented for exception Type=[" + e.GetType().FullName + "]");
            }
            throw new NotImplementedException("Method is not implemented for exception Type=[" + e.GetType().FullName + "]");
        }
        public void Create_ShouldNotReturnNull()
        {
            var fixture   = new Fixture();
            var message   = fixture.Create <string>();
            var errorCode = fixture.Create <int>();

            System.Data.SqlClient.SqlException exception = SqlExceptionCreator.Create(message, errorCode);

            Assert.That(exception, Is.Not.Null);
        }
Esempio n. 19
0
        protected void HandleException(Exception e)
        {
            if (Dal == null)
            {
                Output = "No database found. Please check your connection and restart the program.";
            }
            else if (e is NullReferenceException)
            {
                Output = "Please select a course";
            }
            else if (e is ArgumentOutOfRangeException)
            {
                Output = "Database did not find any data, please ensure you entered the right information";
            }
            else if (e is FormatException)
            {
                Output = "Max participants must be a number";
            }
            else if (e is System.Data.SqlClient.SqlException)
            {
                System.Data.SqlClient.SqlException ex = e as System.Data.SqlClient.SqlException;
                switch (ex.Number)
                {
                default:
                    Output = "Unexpected SQLexception, exception number: \"" + ex.Number + "\"";
                    Console.WriteLine(e.Message + "\n" + e.StackTrace);
                    break;

                case 8152:
                    Output = "Data was longer than database limit. Make sure that no field has an excessively long entry or contact sysadmin";
                    break;

                case 2627:
                    if (this is ViewModel.AdminViewModel)
                    {
                        Output = "ID already in use. Please pick a new ID";
                    }
                    else if (this is MemberViewModel)
                    {
                        Output = "Already registered on course.";
                    }
                    else
                    {
                        Output = "Unexpected Unique key violation";
                    }
                    break;
                }
            }
            else
            {
                Output = "Unexpected exception";
            }
            Console.WriteLine(e.Message + "\n" + e.StackTrace);
        }
        public void Create_ShouldCreateSqlException()
        {
            var fixture   = new Fixture();
            var message   = fixture.Create <string>();
            var errorCode = fixture.Create <int>();

            System.Data.SqlClient.SqlException exception = SqlExceptionCreator.Create(message, errorCode);

            Assert.That(exception.Message, Is.EqualTo(message));
            Assert.That(exception.Number, Is.EqualTo(errorCode));
        }
Esempio n. 21
0
        /// <summary>
        /// 返回Exception Code
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public static int GetExceptionCode(System.Exception ex)
        {
            System.Type type = ex.GetType();

            if (type.FullName == "System.Data.SqlClient.SqlException")
            {
                System.Data.SqlClient.SqlException sqlex = (System.Data.SqlClient.SqlException)ex;
                return(GetSQLExceptionCode(sqlex));
            }
            return(GetSystemExceptionCode(ex));
        }
        /// <summary>
        /// This method allows you to reset the parameter object. Please note that this
        /// method resets all the parameters members except the connection information and
        /// the command time-out which are left in their current state.
        /// </summary>
        public void Reset()
        {
            this.internal_Param_RETURN_VALUE = System.Data.SqlTypes.SqlInt32.Null;

            this.internal_Param_Ord_GuidID = System.Data.SqlTypes.SqlGuid.Null;
            this.internal_Param_Ord_GuidID_UseDefaultValue = this.useDefaultValue;

            this.errorSource    = ErrorSource.NotAvailable;
            this.sqlException   = null;
            this.otherException = null;
        }
Esempio n. 23
0
        public string SaveChanges()
        {
            string message = null;

            try
            {
                Employee employeeDataModel = new Employee();
                employeeDataModel.ID       = ID;
                employeeDataModel.DNI      = DNI;
                employeeDataModel.Nombre   = Nombre;
                employeeDataModel.Mail     = Mail;
                employeeDataModel.Birthday = Birthday;

                switch (State)
                {
                case EntityState.Added:
                    //Ejecutar reglas comerciales
                    employeeRepository.Add(employeeDataModel);
                    message = "Successfully Added";
                    break;

                case EntityState.Deleted:
                    //Ejecutar reglas comerciales
                    employeeRepository.Remove(ID);
                    message = "Successfully Removed";
                    break;

                case EntityState.Modified:
                    //Ejecutar reglas comerciales
                    employeeRepository.Edit(employeeDataModel);
                    message = "Successfully Edited";
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                System.Data.SqlClient.SqlException sqlEx = ex as System.Data.SqlClient.SqlException;

                if (sqlEx != null && sqlEx.Number == 2627)
                {
                    message = "Duplicate record";
                }
                else
                {
                    message = ex.Message;
                }
            }

            return(message);
        }
Esempio n. 24
0
        public SaveResult Complete()
        {
            SaveResult SaveResult = new SaveResult {
            };

            SaveResult.Result       = 0;
            SaveResult.ErrorMessage = string.Empty;

            try
            {
                SaveResult.Result = _context.SaveChanges();   //attempt to save changes to DB
                SaveResult.Result = 1;                        //if success set to 1
                return(SaveResult);
            }
            catch (DbEntityValidationException e)             //if fails record the error message
            {
                foreach (var error in e.EntityValidationErrors)
                {
                    System.Diagnostics.Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                                       error.Entry.Entity.GetType().Name, error.Entry.State);
                    foreach (var validation_error in error.ValidationErrors)
                    {
                        System.Diagnostics.Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                                           validation_error.PropertyName, validation_error.ErrorMessage);
                    }
                }
                SaveResult.ErrorMessage = e.Message;
                return(SaveResult);
            }
            catch (DbUpdateException e)
            {
                System.Diagnostics.Debug.WriteLine(e.InnerException);

                System.Data.Entity.Core.UpdateException update_error = (System.Data.Entity.Core.UpdateException)e.InnerException;
                System.Data.SqlClient.SqlException      error        = (System.Data.SqlClient.SqlException)update_error.InnerException;

                SaveResult.ErrorMessage = error.Message;
                return(SaveResult);
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                SaveResult.ErrorMessage = e.Message;
                return(SaveResult);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                SaveResult.ErrorMessage = e.Message;
                return(SaveResult);
            }
        }
Esempio n. 25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DataServicesException"/> class.
 /// </summary>
 /// <param name="ex">The ex.</param>
 /// <param name="message">The message.</param>
 public DataServicesException(Exception ex, string message)
     : base(ex)
 {
     _ex = ex;
     if (ex.GetType() == typeof(System.Data.SqlClient.SqlException))
     {
         System.Data.SqlClient.SqlException sqlEx = (System.Data.SqlClient.SqlException)ex;
         SqlErrorNumber = sqlEx.Number;
         _message = string.Format(KK.DealMaker.Core.Constraint.FormatTemplate.SQL_ERROR_NO, ((System.Data.SqlClient.SqlException)ex).Number) + message;
     }
     else
         _message = message;
 }
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.internal_Param_RETURN_VALUE = System.Data.SqlTypes.SqlInt32.Null;

                this.sqlException     = null;
                this.otherException   = null;
                this.connectionString = null;
                this.sqlConnection    = null;
                this.sqlTransaction   = null;
            }
        }
Esempio n. 27
0
        public string SaveChanges()
        {
            string message = null;

            try
            {
                var empleadoDataModel = new Empleado();
                empleadoDataModel.ID       = ID;
                empleadoDataModel.Nombre   = Nombre;
                empleadoDataModel.Apellido = Apellido;
                empleadoDataModel.Codigo   = Codigo;

                switch (State)
                {
                case EntityState.Added:
                {
                    // Ejecutar reglas comerciales / calculos
                    empleadoRepository.Add(empleadoDataModel);
                    message = "Añadido satisfactoriamente.";
                    break;
                }

                case EntityState.Modified:
                {
                    empleadoRepository.Edit(empleadoDataModel);
                    message = "Actualizado satisfactoriamente.";
                    break;
                }

                case EntityState.Deleted:
                {
                    empleadoRepository.Delete(ID);
                    message = "Eliminado satisfactoriamente.";
                    break;
                }
                }
            }
            catch (Exception ex)
            {
                System.Data.SqlClient.SqlException sqlEx = ex as System.Data.SqlClient.SqlException;
                if (sqlEx != null && sqlEx.Number == 2627)
                {
                    message = "Registro duplicado.";
                }
                else
                {
                    message = ex.ToString();
                }
            }
            return(message);
        }
Esempio n. 28
0
        /// <summary>
        /// This method allows you to reset the parameter object. Please note that this
        /// method resets all the parameters members except the connection information and
        /// the command time-out which are left in their current state.
        /// </summary>
        public void Reset()
        {
            this.internal_Param_RETURN_VALUE = System.Data.SqlTypes.SqlInt32.Null;

            this.internal_Param_TitleId = System.Data.SqlTypes.SqlInt32.Null;
            this.internal_Param_TitleId_UseDefaultValue = this.useDefaultValue;

            this.internal_Param_Title = System.Data.SqlTypes.SqlString.Null;
            this.internal_Param_Title_UseDefaultValue = this.useDefaultValue;

            this.errorSource    = ErrorSource.NotAvailable;
            this.sqlException   = null;
            this.otherException = null;
        }
Esempio n. 29
0
 private void BtnGuardar_Click(object sender, EventArgs e)
 {
     try
     {
         Empleado empl = null;
         if (modo == "I")
         {
             empl = ObtenerEmpleadoFormulario();
             if (empl != null)
             {
                 Empleado.AgregarEmpleado(empl);
                 MessageBox.Show("Registro insertado correctamente", "Alta", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 ListarEmpleado();
                 limpiar();
                 panel3.Enabled = false;
                 panel1.Enabled = true;
             }
         }
         else if (modo == "E")
         {
             int index = Convert.ToInt32(dgvEmpleado.CurrentRow.Cells[0].Value);
             empl = ObtenerEmpleadoFormulario();
             if (empl != null)
             {
                 Empleado.EditarEmpleado(index, empl);
                 MessageBox.Show("Registro editado correctamente", "Modificación", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 ListarEmpleado();
                 limpiar();
                 panel3.Enabled = false;
                 panel1.Enabled = true;
             }
             txtBuscar.Focus();
         }
     }
     catch (Exception ex)
     {
         System.Data.SqlClient.SqlException sqlEx = ex as System.Data.SqlClient.SqlException;
         if (sqlEx != null && sqlEx.Number == 2601)
         {
             MessageBox.Show("No se pude insertar el registro. Registro duplicado", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
             txtIDNumero.Focus();
         }
         else
         {
             MessageBox.Show(ex.ToString(), "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
             txtIDNumero.Focus();
         }
     }
 }
Esempio n. 30
0
        protected override void PageError(object sender, EventArgs e)
        {
            string errMsg = "";

            Model.SysManage.ErrorLog model = new Model.SysManage.ErrorLog();
            Exception currentError         = Server.GetLastError();

            if (currentError is System.Data.SqlClient.SqlException)
            {
                System.Data.SqlClient.SqlException sqlerr = (System.Data.SqlClient.SqlException)currentError;
                if (sqlerr != null)
                {
                    string sqlMsg = GetSqlExceptionMessage(sqlerr.Number);
                    if (sqlerr.Number == 547)
                    {
                        errMsg += "<h1 class=\"SystemTip\">" + Resources.Site.ErrorSystemTip + "</h1><br/> " +
                                  "<font class=\"ErrorPageText\">" + sqlMsg + "</font>";
                    }
                    else
                    {
                        errMsg += "<h1 class=\"ErrorMessage\">" + Resources.Site.ErrorSystemTip + "</h1><hr/> " +
                                  "该信息已被系统记录,请稍后重试或与管理员联系。<br/>" +
                                  "错误信息: <font class=\"ErrorPageText\">" + sqlMsg + "</font>";
                        model.Loginfo    = sqlMsg;
                        model.StackTrace = currentError.ToString();
                        model.Url        = Request.Url.AbsoluteUri;
                    }
                }
            }
            else
            {
                errMsg += "<h1 class=\"ErrorMessage\">" + Resources.Site.ErrorSystemTip + "</h1><hr/> " +
                          "该信息已被系统记录,请稍后重试或与管理员联系。<br/>" +
                          "错误信息: <font class=\"ErrorPageText\">" + currentError.Message.ToString() + "<hr/>" +
                          "<b>Stack Trace:</b><br/>" + currentError.StackTrace + "</font>";

                model.Loginfo    = currentError.Message;
                model.StackTrace = currentError.StackTrace;
                model.Url        = Request.Url.AbsoluteUri;
            }
            ColoPay.BLL.SysManage.ErrorLog.Add(model);

            Session["ErrorMsg"] = errMsg;
            Server.Transfer("~/Supplier/ErrorPage.aspx", true);

            //考虑不Response当前页面,直接弹出信息提示。根据不同信息做不同的样式处理:系统提示,系统错误
            //Response.Write(errMsg);
            //Server.ClearError();
        }
		public TestConnectionResult(string message,System.Data.SqlClient.SqlException e) {
			_failed = true;
			_exception = e;
			_message = message;
		}
		TestConnectionResult() {
			_failed = false;
			_exception = null;
			_message = "Connection successful";
		}