/// <summary> /// SQLs the error handling. This method convert System.Data.SqlClient.SqlError to Exceptions: /// LongFieldException,NotUniqueException,ExceptionParentObjectNotExists,ChildObjectExistsException /// </summary> /// <param name="exception">The exception.</param> /// <param name="err">The SQL Error.</param> /// <returns></returns> private DbException SqlErrorHandling(DbException exception, System.Data.SqlClient.SqlError err) { DbException result = null; switch (err.Number) { case (int)ErrorsCode.TruncateData: result = new LongFieldException(); break; case (int)ErrorsCode.InsertDuplicatedKey: case (int)ErrorsCode.ConstraintInsertDuplicatedKey: var sp = err.Message.Split('\''); var name = (sp.Length > 3) ? sp[1] + '.' + sp[3] : ""; result = new NotUniqueException(name, exception); break; case (int)ErrorsCode.ConstraintStatementConflicted: result = ParseConstraintStatementConflicted(err.Message); break; case (int)ErrorsCode.InputParameterDBNull: result = new SPParameterNullException("Some SP parameters is DbNull"); break; case (int)ErrorsCode.CannotInsertDBNull: var m = _messageParser.CannotInsertNULLParser.Match(err.Message); if (m.Success == false) { return(null); } var column = m.Groups["COLUMN"].Value; var tableName = Parser.ParseTableName(m.Groups["NAME"].Value); result = new MandatoryFieldEmptyException(tableName, column, exception); break; case (int)ErrorsCode.StoredProcedureNotFind: result = new SPNotFindException(err.Message, exception); break; case (int)ErrorsCode.StoredProcedureNotFindParrameter: case (int)ErrorsCode.StoredProcedureExpectParrameter: result = new SPIncorrectCountParameters(err.Message, exception); break; case (int)ErrorsCode.UserDefinedValidateException: result = new ValidateException(err.Message); break; default: if (err.Number > 50001) { result = new UserDefinedSqlException(err); } break; } return(result); }
internal SqlException (string message, Exception inner, SqlError sqlError) : base (message == null ? DEF_MESSAGE : message, inner) { HResult = -2146232060; errors = new SqlErrorCollection (); if (sqlError != null) errors.Add (sqlError); }
private static void OnInfoMessage(object sender, System.Data.SqlClient.SqlInfoMessageEventArgs args) { System.Data.SqlClient.SqlError sqlEvent = null; foreach (System.Data.SqlClient.SqlError sqlEvent_loopVariable in args.Errors) { sqlEvent = sqlEvent_loopVariable; aaa = sqlEvent.Message; } //return aaa; }
private SqlErrorCollection CreateErrorCollection(SqlError error) { // Create instance via reflection... var sqlErrorCollectionCtor = typeof(SqlErrorCollection).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0]; SqlErrorCollection errorCollection = sqlErrorCollectionCtor.Invoke(new object[] { }) as SqlErrorCollection; // Add error... typeof(SqlErrorCollection).GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(errorCollection, new object[] { error }); return errorCollection; }
/// <summary> /// Initializes a new instance of the VLogSqlError class. /// </summary> /// <param name="error">Sql Server error</param> public VLogSqlError(SqlError error) : this() { Ensure.IsNotNull(error, "VLogSqlError.VLogSqlError()-error"); this.Message = error.Message; this.Procedure = error.Procedure; this.Severity = error.Class; this.LineNumber = error.LineNumber; this.Number = error.Number; this.Server = error.Server; this.Source = error.Source; this.State = error.State; }
private static string FormatError(SqlError err) { var message = err.Message; // print statements if (err.Class == 0) return message; // errors that can be traced to a spot in a procedure/trigger/module if (!string.IsNullOrEmpty(err.Procedure)) return message + " (" + err.Procedure + ":line " + err.LineNumber + ")"; // generic errors return string.Format("{0} (Msg {1}, Level {2}, State {3}, Line {4})", err.Message, err.Number, err.Class, err.State, err.LineNumber); }
/// <summary> /// It the function returns null, the exception should not be changed. In that case simply use "throw;". /// </summary> public static Exception ProcessSqlException(Exception ex) { if (ex == null || !(ex is SqlException)) return null; var sqlException = (SqlException)ex; SqlError[] errorArray = new SqlError[sqlException.Errors.Count]; sqlException.Errors.CopyTo(errorArray, 0); var errors = from e in errorArray orderby e.LineNumber select e; foreach (var err in errors) if (err.State == 101) // Our convention for an error raised in SQL that is intended as a message to the end user. return new UserException(err.Message); return sqlException; }
internal override void MessagePosted(int number, byte state, byte errorClass, string server, string message, string procedure, int lineNumber) { if (this._parent == null) { if (Bid.AdvancedOn) { Bid.Trace("<sc.SmiEventSink_Default.MessagePosted|ADV> %d#, number=%d state=%d errorClass=%d server='%ls' message='%ls' procedure='%ls' linenumber=%d.\n", 0, number, state, errorClass, (server != null) ? server : "<null>", (message != null) ? message : "<null>", (procedure != null) ? procedure : "<null>", lineNumber); } SqlError error = new SqlError(number, state, errorClass, server, message, procedure, lineNumber); if (error.Class < 11) { this.Warnings.Add(error); } else { this.Errors.Add(error); } } else { this._parent.MessagePosted(number, state, errorClass, server, message, procedure, lineNumber); } }
public void ProcessSniPacket(IntPtr packet, uint error) { if (((this._parser.State != TdsParserState.Closed) && (this._parser.State != TdsParserState.Broken)) || (error == 0)) { if (error != 0) { if (this._parser._fAwaitingPreLogin && (error != 0x102)) { this._parser._fPreLoginErrorOccurred = true; } else { this._error = this._parser.ProcessSNIError(this); } } else { SNINativeMethodWrapper.SNIPacketGetConnection(packet); uint dataSize = 0; IntPtr ptrZero = ADP.PtrZero; SNINativeMethodWrapper.SNIPacketGetData(packet, ref ptrZero, ref dataSize); if (this._inBuff.Length < dataSize) { throw SQL.InvalidInternalPacketSize(Res.GetString("SqlMisc_InvalidArraySizeMessage")); } Marshal.Copy(ptrZero, this._inBuff, 0, (int) dataSize); this._inBytesRead = (int) dataSize; this._inBytesUsed = 0; } } }
private static void ErrorCallback(SqlError sqlError) { Console.WriteLine(sqlError.Message); }
/// <summary> /// Determines the throttling conditions from the specified SQL error. /// </summary> /// <param name="error">The <see cref="SqlError"/> object containing information relevant to a warning or error returned by SQL Server.</param> /// <returns>An instance of the object holding the decoded reason codes returned from SQL Azure when encountering throttling conditions.</returns> public static ThrottlingCondition FromError(SqlError error) { if (error != null) { var match = sqlErrorCodeRegEx.Match(error.Message); int reasonCode; if (match.Success && int.TryParse(match.Groups[1].Value, out reasonCode)) { return FromReasonCode(reasonCode); } } return Unknown; }
private static string ReportSqlErrors(SqlException ex) { StringBuilder sb = new StringBuilder(); SqlError[] errors = new SqlError[ex.Errors.Count]; ex.Errors.CopyTo(errors, 0); foreach (var err in errors.OrderBy(e => e.LineNumber)) { if (err.Class > 0) { sb.Append("Msg ").Append(err.Number); sb.Append(", Level ").Append(err.Class); sb.Append(", State ").Append(err.State); if (!string.IsNullOrEmpty(err.Procedure)) sb.Append(", Procedure ").Append(err.Procedure); sb.Append(", Line ").Append(err.LineNumber); sb.AppendLine(); } sb.AppendLine(err.Message); } return sb.ToString(); }
internal bool TryProcessError(byte token, TdsParserStateObject stateObj, out SqlError error) { ushort shortLen; byte byteLen; int number; byte state; byte errorClass; error = null; if (!stateObj.TryReadInt32(out number)) { return false; } if (!stateObj.TryReadByte(out state)) { return false; } if (!stateObj.TryReadByte(out errorClass)) { return false; } Debug.Assert(((errorClass >= TdsEnums.MIN_ERROR_CLASS) && token == TdsEnums.SQLERROR) || ((errorClass < TdsEnums.MIN_ERROR_CLASS) && token == TdsEnums.SQLINFO), "class and token don't match!"); if (!stateObj.TryReadUInt16(out shortLen)) { return false; } string message; if (!stateObj.TryReadString(shortLen, out message)) { return false; } if (!stateObj.TryReadByte(out byteLen)) { return false; } string server; // If the server field is not received use the locally cached value. if (byteLen == 0) { server = _server; } else { if (!stateObj.TryReadString(byteLen, out server)) { return false; } } if (!stateObj.TryReadByte(out byteLen)) { return false; } string procedure; if (!stateObj.TryReadString(byteLen, out procedure)) { return false; } int line; if (_isYukon) { if (!stateObj.TryReadInt32(out line)) { return false; } } else { ushort shortLine; if (!stateObj.TryReadUInt16(out shortLine)) { return false; } line = shortLine; // If we haven't yet completed processing login token stream yet, we may be talking to a Yukon server // In that case we still have to read another 2 bytes if (_state == TdsParserState.OpenNotLoggedIn) { // Login incomplete byte b; if (!stateObj.TryPeekByte(out b)) { return false; } if (b == 0) { // This is an invalid token value ushort value; if (!stateObj.TryReadUInt16(out value)) { return false; } line = (line << 16) + value; } } } error = new SqlError(number, state, errorClass, _server, message, procedure, line); return true; }
internal void Add(SqlError error) => _errors.Add(error);
internal void Add(byte theClass, int lineNumber, string message, int number, string procedure, string server, string source, byte state) { SqlError error = new SqlError (theClass, lineNumber, message, number, procedure, server, source, state); Add (error); }
public void CopyTo(SqlError[] array, int index) { this.errors.CopyTo(array, index); }
internal void Add(SqlError error) { this.errors.Add(error); }
internal SqlPercentCompleteEventArgs(SqlError sqlError,int percent) { Error=sqlError; Percent = percent; }
/// <summary> /// This method is used to capture any exception or informational messages generated by the current command execution call. /// </summary> /// <param name="sender">The object which raised the event.</param> /// <param name="e">The event arguments passed in.</param> private void SqlConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e) { string errorMessage = String.Empty; int errorcount = 0; bool foundError = false; while (errorcount < e.Errors.Count) { // Checks if the current error was already printed. if (this.previousError != null) { if (Object.Equals(this.previousError, e.Errors[errorcount])) { errorcount = errorcount + 1; continue; } else { this.previousError = e.Errors[errorcount]; } } else { this.previousError = e.Errors[errorcount]; } byte myclasses = e.Errors[errorcount].Class; if (myclasses < 1) { // Usually a print statement, not an actual error. this.ExecutionInfoMessages += e.Errors[errorcount].Message; errorcount = errorcount + 1; continue; } errorMessage = errorMessage + e.Errors[errorcount].Message; foundError = true; errorcount = errorcount + 1; } if (errorcount > 0 && foundError) { // Throw the error(s). this.ExecutionError = errorMessage; } }
internal void ReadSniSyncOverAsync() { if ((this._parser.State != TdsParserState.Broken) && (this._parser.State != TdsParserState.Closed)) { try { if (!((IAsyncResult) this._cachedAsyncResult).AsyncWaitHandle.WaitOne(TdsParserStaticMethods.GetTimeoutMilliseconds(this.TimeoutTime), false)) { bool flag = false; if (this._internalTimeout) { flag = true; } else { this._internalTimeout = true; this._parser.Errors.Add(new SqlError(-2, 0, 11, this._parser.Server, SQLMessage.Timeout(), "", 0)); if (!this._attentionSent) { if (this._parser.State == TdsParserState.OpenLoggedIn) { this.SendAttention(); } else { flag = true; } if (!((IAsyncResult) this._cachedAsyncResult).AsyncWaitHandle.WaitOne(TdsParserStaticMethods.GetTimeoutMilliseconds(this.TimeoutTime), false)) { flag = true; } } } if (flag) { this._parser.State = TdsParserState.Broken; this._parser.Connection.BreakConnection(); this._parser.ThrowExceptionAndWarning(); } } if (this._error != null) { this.Parser.Errors.Add(this._error); this._error = null; this._parser.ThrowExceptionAndWarning(); } } finally { if (this._cachedAsyncResult != null) { this._cachedAsyncResult.Reset(); } } } }
internal void Add(SqlError error) { list.Add (error); }
internal static SqlException FromTdsInternalException (TdsInternalException e) { SqlError sqlError = new SqlError (e.Class, e.LineNumber, e.Message, e.Number, e.Procedure, e.Server, "Mono SqlClient Data Provider", e.State); return new SqlException (null, e, sqlError); }
public void CopyTo(SqlError[] array, int index) => _errors.CopyTo(array, index);
internal void Add(SqlError error) { list.Add(error); }
/// <summary> /// Initializes a new instance of the <see cref="SqlErrorPrototype" /> class. /// </summary> /// <param name="error">The error.</param> /// <remarks></remarks> public SqlErrorPrototype([NotNull] SqlError error) { if (error == null) throw new ArgumentNullException("error"); SqlError = error; }
/// <summary> /// Convert from SqlError object to VLogSqlError /// </summary> /// <param name="error">SqlError instance</param> /// <returns>The VLogSqlError instance from SqlError</returns> public static VLogSqlError ConvertFrom(SqlError error) { return new VLogSqlError(error); }
/// <summary> /// Adds an warning to the warning collection /// </summary> /// <param name="error"></param> internal void AddWarning(SqlError error) { Debug.Assert(error != null, "Trying to add a null error"); // Switch to sync once we see a warning _syncOverAsync = true; lock (_errorAndWarningsLock) { _hasErrorOrWarning = true; if (_warnings == null) { _warnings = new SqlErrorCollection(); } _warnings.Add(error); } }
// Fires a single InfoMessageEvent private void FireInfoMessageEvent(SqlConnection connection, TdsParserStateObject stateObj, SqlError error) { string serverVersion = null; Debug.Assert(connection != null && _connHandler.Connection == connection); if (_state == TdsParserState.OpenLoggedIn) { serverVersion = _connHandler.ServerVersion; } SqlErrorCollection sqlErs = new SqlErrorCollection(); sqlErs.Add(error); SqlException exc = SqlException.CreateException(sqlErs, serverVersion, _connHandler); bool notified; connection.OnInfoMessage(new SqlInfoMessageEventArgs(exc), out notified); if (notified) { // observable side-effects, no retry stateObj._syncOverAsync = true; } return; }
internal void Add(byte theClass, int lineNumber, string message, int number, string procedure, string server, string source, byte state) { SqlError error = new SqlError(theClass, lineNumber, message, number, procedure, server, source, state); Add(error); }
internal void Add(SqlError error) { _errors.Add(error); }
private uint SNIWriteAsync(SNIHandle handle, SNIPacket packet, DbAsyncResult asyncResult) { uint num; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { this.IncrementPendingCallbacks(); num = SNINativeMethodWrapper.SNIWriteAsync(handle, packet); if ((num == 0) || (num != 0x3e5)) { this.DecrementPendingCallbacks(false); } } if (num != 0) { if (num != 0x3e5) { Bid.Trace("<sc.TdsParser.WritePacket|Info> write async returned error code %d\n", (int) num); this._parser.Errors.Add(this._parser.ProcessSNIError(this)); this.ThrowExceptionAndWarning(); return num; } if (num != 0x3e5) { return num; } try { ((IAsyncResult) asyncResult).AsyncWaitHandle.WaitOne(); if (this._error != null) { this._parser.Errors.Add(this._error); this._error = null; Bid.Trace("<sc.TdsParser.WritePacket|Info> write async returned error code %d\n", (int) num); this.ThrowExceptionAndWarning(); } } finally { asyncResult.Reset(); } } return num; }
internal bool TryProcessError(byte token, TdsParserStateObject stateObj, out SqlError error) { ushort shortLen; byte byteLen; int number; byte state; byte errorClass; error = null; if (!stateObj.TryReadInt32(out number)) { return false; } if (!stateObj.TryReadByte(out state)) { return false; } if (!stateObj.TryReadByte(out errorClass)) { return false; } Debug.Assert(((errorClass >= TdsEnums.MIN_ERROR_CLASS) && token == TdsEnums.SQLERROR) || ((errorClass < TdsEnums.MIN_ERROR_CLASS) && token == TdsEnums.SQLINFO), "class and token don't match!"); if (!stateObj.TryReadUInt16(out shortLen)) { return false; } string message; if (!stateObj.TryReadString(shortLen, out message)) { return false; } if (!stateObj.TryReadByte(out byteLen)) { return false; } string server; // If the server field is not recieved use the locally cached value. if (byteLen == 0) { server = _server; } else { if (!stateObj.TryReadString(byteLen, out server)) { return false; } } if (!stateObj.TryReadByte(out byteLen)) { return false; } string procedure; if (!stateObj.TryReadString(byteLen, out procedure)) { return false; } int line; if (!stateObj.TryReadInt32(out line)) { return false; } error = new SqlError(number, state, errorClass, _server, message, procedure, line); return true; }
public void WriteAsyncCallback(IntPtr key, IntPtr packet, uint error) { DbAsyncResult result = this._asyncResult; if ((this._sniAsyncAttnPacket != null) && (this._sniAsyncAttnPacket.DangerousGetHandle() == packet)) { result = this._asyncAttentionResult; } bool flag = true; try { if (this._parser.MARSOn) { this.CheckSetResetConnectionState(error, CallbackType.Read); } if (error != 0) { this._error = this._parser.ProcessSNIError(this); } } catch (Exception exception) { flag = ADP.IsCatchableExceptionType(exception); throw; } finally { this.DecrementPendingCallbacks(false); if (flag) { result.SetCompleted(); } } }
internal SqlCompletedEventArgs(SqlError sqlError) { Error=sqlError; }
public void CopyTo (SqlError [] array, int index) { base.CopyTo (array, index); }