Ejemplo n.º 1
0
        /// <summary>
        /// Fires a message event
        /// </summary>
        /// <param name="errors">SqlClient errors collection</param>
        /// <remarks>
        /// Sql specific messages.
        /// </remarks>
        protected void HandleSqlMessages(SqlErrorCollection errors)
        {
            foreach (SqlError error in errors)
            {
                if (error.Number == ChangeDatabase)
                {
                    continue;
                }

                string detailedMessage = FormatSqlErrorMessage(error);

                if (error.Class > 10)
                {
                    // expose this event as error
                    Debug.Assert(detailedMessage.Length != 0);
                    RaiseBatchError(detailedMessage, error, textSpan);

                    //at least one error message has been used
                    hasErrors = true;
                }
                else
                {
                    RaiseBatchMessage(detailedMessage, error.Message, error);
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// makes the string containing the full exception report from the given SqlException.
        /// </summary>
        /// <param name="e">OleDbException</param>
        /// <returns>string representing exception report</returns>
        public static string exception_report(SqlException e)
        {
            StringBuilder result = new StringBuilder("SQLSRV2000 ERROR: ");

            try
            {
                SqlErrorCollection myErrors = e.Errors;
                result.AppendFormat("\nClass: {1}", e.Class.ToString());
                result.AppendFormat("\nError #{1}: {2} on line {3}.", e.Number.ToString(), e.Message, e.LineNumber.ToString());
                result.AppendFormat("\nError reported by {1} while connected to {2}", e.Source, e.Server);
                result.Append("\nNeither record was written to database.");
                result.Append("\nErrors collection contains:");

                foreach (SqlError err in myErrors)
                {
                    result.AppendFormat("\nClass: {1}", err.Class.ToString());
                    result.AppendFormat("\nError #{1}: {2} on line {3}.", err.Number.ToString(), err.Message, err.LineNumber.ToString());
                    result.AppendFormat("\nError reported by {1} while connected to {2}", err.Source, err.Server);
                }
            }
            catch (Exception x)
            {
                result.AppendFormat("\nerror in exception_report(): {0}", x.Message);
            }
            return(result.ToString());
        }
Ejemplo n.º 3
0
        protected SqlException ProcessMessages(bool ignoreWarnings, bool ignoreNonFatalMessages)
        {
            SqlException       result = null;
            SqlErrorCollection temp   = null; // temp variable to store that which is being thrown - so that local copies can be deleted

            if (null != _errors)
            {
                Debug.Assert(0 != _errors.Count, "empty error collection?"); // must be something in the collection

                if (ignoreNonFatalMessages)
                {
                    temp = new SqlErrorCollection();
                    foreach (SqlError error in _errors)
                    {
                        if (error.Class >= TdsEnums.FATAL_ERROR_CLASS)
                        {
                            temp.Add(error);
                        }
                    }
                    if (temp.Count <= 0)
                    {
                        temp = null;
                    }
                }
                else
                {
                    if (null != _warnings)
                    {
                        // When we throw an exception we place all the warnings that
                        // occurred at the end of the collection - after all the errors.
                        // That way the user can see all the errors AND warnings that
                        // occurred for the exception.
                        foreach (SqlError warning in _warnings)
                        {
                            _errors.Add(warning);
                        }
                    }
                    temp = _errors;
                }

                _errors   = null;
                _warnings = null;
            }
            else
            {
                Debug.Assert(null == _warnings || 0 != _warnings.Count, "empty warning collection?");// must be something in the collection

                if (!ignoreWarnings)
                {
                    temp = _warnings;
                }
                _warnings = null;
            }

            if (null != temp)
            {
                result = SqlException.CreateException(temp, ServerVersion);
            }
            return(result);
        }
Ejemplo n.º 4
0
        public void GetEnumerator_Success()
        {
            SqlErrorCollection c = CreateCollection();

            IEnumerator e = c.GetEnumerator();

            Assert.NotNull(e);
            Assert.NotSame(e, c.GetEnumerator());

            for (int i = 0; i < 2; i++)
            {
                Assert.Throws <InvalidOperationException>(() => e.Current);

                Assert.True(e.MoveNext());
                Assert.Same(c[0], e.Current);

                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());

                Assert.Throws <InvalidOperationException>(() => e.Current);

                e.Reset();
            }
        }
Ejemplo n.º 5
0
        public void Indexer_Throws()
        {
            SqlErrorCollection c = CreateCollection();

            Assert.Throws <ArgumentOutOfRangeException>("index", () => c[-1]);
            Assert.Throws <ArgumentOutOfRangeException>("index", () => c[c.Count]);
        }
Ejemplo n.º 6
0
        public void Indexer_Success()
        {
            SqlErrorCollection c = CreateCollection();

            Assert.NotNull(c[0]);
            Assert.Same(c[0], c[0]);
        }
Ejemplo n.º 7
0
        private static SqlException CreateLocalDBException(string errorMessage, string instance = null, int localDbError = 0, int sniError = 0)
        {
            Debug.Assert((localDbError == 0) || (sniError == 0), "LocalDB error and SNI error cannot be specified simultaneously");
            Debug.Assert(!string.IsNullOrEmpty(errorMessage), "Error message should not be null or empty");
            SqlErrorCollection collection = new SqlErrorCollection();

            int errorCode = (localDbError == 0) ? sniError : localDbError;

            if (sniError != 0)
            {
                string sniErrorMessage = SQL.GetSNIErrorMessage(sniError);
                errorMessage = String.Format((IFormatProvider)null, "{0} (error: {1} - {2})",
                                             errorMessage, sniError, sniErrorMessage);
            }

            collection.Add(new SqlError(errorCode, 0, TdsEnums.FATAL_ERROR_CLASS, instance, errorMessage, null, 0));

            if (localDbError != 0)
            {
                collection.Add(new SqlError(errorCode, 0, TdsEnums.FATAL_ERROR_CLASS, instance, GetLocalDBMessage(localDbError), null, 0));
            }

            SqlException exc = SqlException.CreateException(collection, null);

            exc._doNotReconnect = true;

            return(exc);
        }
Ejemplo n.º 8
0
 public static void LogSqlErrorCollection(SqlErrorCollection errors)
 {
     for (int i = 0; i < errors.Count; i++)
     {
         LogSqlError(errors[i]);
     }
 }
Ejemplo n.º 9
0
        public SqlException Build()
        {
            SqlError           error           = this.CreateError();
            SqlErrorCollection errorCollection = this.CreateErrorCollection(error);
            SqlException       exception       = this.CreateException(errorCollection);

            return(exception);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SqlErrorCollectionPrototype" /> class.
 /// </summary>
 /// <param name="collection">The collection.</param>
 /// <remarks></remarks>
 public SqlErrorCollectionPrototype([NotNull] SqlErrorCollection collection)
 {
     if (collection == null)
     {
         throw new ArgumentNullException("collection");
     }
     SqlErrorCollection = collection;
 }
Ejemplo n.º 11
0
        private static SqlErrorCollection GetErrorCollection()
        {
            ConstructorInfo constructor = typeof(SqlErrorCollection).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { }, null);

            SqlErrorCollection collection = (SqlErrorCollection)constructor.Invoke(new object[] { });

            return(collection);
        }
Ejemplo n.º 12
0
        private SqlErrorCollection CreateErrorCollection(SqlError error)
        {
            var sqlErrorCollectionCtor         = typeof(SqlErrorCollection).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];
            SqlErrorCollection errorCollection = sqlErrorCollectionCtor.Invoke(new object[] { }) as SqlErrorCollection;

            typeof(SqlErrorCollection).GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(errorCollection, new object[] { error });

            return(errorCollection);
        }
 private static void ProcessErrors(SqlErrorCollection errors)
 {
     if (errors == null)
     {
         return;
     }
     foreach (var error in errors.Cast <SqlError>())
     {
         PrintMessage(string.Format(CultureInfo.CurrentCulture, "Sql Error: '{0}' (Severity {1}, State {2})", error.Message, error.Class, error.State));
     }
 }
        private SqlErrorCollection CreateErrorCollection(SqlError error)
        {
            // Create instance via reflection...
            var sqlErrorCollectionCtor         = typeof(SqlErrorCollection).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];
            SqlErrorCollection errorCollection = sqlErrorCollectionCtor.Invoke(Array.Empty <object>()) as SqlErrorCollection;

            // Add error...
            typeof(SqlErrorCollection).GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(errorCollection, new object[] { error });

            return(errorCollection);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Creates a new instance of <see cref="SqlException"/>.
        /// </summary>
        /// <param name="number">The info number.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns>An instance of <see cref="SqlException"/>.</returns>
        public static SqlException Create(int number, string errorMessage = "Simulated exception.")
        {
            SqlError sqlError = SqlErrorConstructorDelegate(number);

            SqlErrorCollection sqlErrorCollection = SqlErrorCollectionConstructorDelegate();

            SqlErrorCollectionAddDelegate(sqlErrorCollection, sqlError);

            SqlException sqlException = SqlExceptionConstructorDelegate(errorMessage, sqlErrorCollection, null, Guid.NewGuid());

            return(sqlException);
        }
    public static SqlException GenerateFakeSqlException(int errorCode, string errorMessage = "")
    {
        SqlError           sqlError   = GenerateFakeSqlError(errorCode, errorMessage);
        SqlErrorCollection collection = GenerateFakeSqlErrorCollection(sqlError);

        return((SqlException)(Activator.CreateInstance(
                                  typeof(SqlException),
                                  BindingFlags.NonPublic | BindingFlags.Instance,
                                  null,
                                  new object?[] { errorMessage, collection, null, Guid.Empty },
                                  null) ?? throw new InvalidOperationException("Failed to create SqlException.")));
    }
Ejemplo n.º 17
0
        private static void ValidateCopyToThrows(
            Action <SqlErrorCollection, SqlError[], int> copyTo,
            Action <SqlErrorCollection> additionalValidation = null)
        {
            SqlErrorCollection c = CreateCollection();

            Assert.Throws <ArgumentNullException>(() => copyTo(c, null, 0));
            Assert.Throws <ArgumentNullException>(() => copyTo(c, null, -1));
            Assert.Throws <ArgumentOutOfRangeException>(() => copyTo(c, new SqlError[10], -1));
            AssertExtensions.Throws <ArgumentException>("destinationArray", "", () => copyTo(c, new SqlError[10], 1000));

            additionalValidation?.Invoke(c);
        }
        private SqlException CreateException(SqlErrorCollection errorCollection)
        {
            // Create instance via reflection...
            var          ctor         = typeof(SqlException).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];
            SqlException sqlException = ctor.Invoke(new object[] {
                // With message and error collection...
                errorMessage,
                errorCollection,
                null,
                Guid.NewGuid()
            }) as SqlException;

            return(sqlException);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SqlExceptionPrototype" /> class.
 /// </summary>
 /// <param name="errorCollection">The error collection.</param>
 /// <param name="serverVersion">The server version.</param>
 /// <param name="conId">The connection id.</param>
 /// <param name="innerException">The inner exception.</param>
 public SqlExceptionPrototype(
     SqlErrorCollection errorCollection,
     string serverVersion     = null,
     Guid conId               = default(Guid),
     Exception innerException = null)
     : this(
         // ReSharper disable once AssignNullToNotNullAttribute
         _constructor(
             errorCollection,
             serverVersion,
             conId == default(Guid) ? Guid.NewGuid() : conId,
             innerException))
 {
 }
Ejemplo n.º 20
0
        protected SqlException ProcessMessages(bool ignoreWarnings, bool ignoreNonFatalMessages)
        {
            SqlErrorCollection errorCollection = null;
            SqlException       exception       = null;

            if (this._errors != null)
            {
                if (ignoreNonFatalMessages)
                {
                    errorCollection = new SqlErrorCollection();
                    foreach (SqlError error in this._errors)
                    {
                        if (error.Class >= 20)
                        {
                            errorCollection.Add(error);
                        }
                    }
                    if (errorCollection.Count <= 0)
                    {
                        errorCollection = null;
                    }
                }
                else
                {
                    if (this._warnings != null)
                    {
                        foreach (SqlError error2 in this._warnings)
                        {
                            this._errors.Add(error2);
                        }
                    }
                    errorCollection = this._errors;
                }
                this._errors   = null;
                this._warnings = null;
            }
            else
            {
                if (!ignoreWarnings)
                {
                    errorCollection = this._warnings;
                }
                this._warnings = null;
            }
            if (errorCollection != null)
            {
                exception = SqlException.CreateException(errorCollection, this.ServerVersion);
            }
            return(exception);
        }
Ejemplo n.º 21
0
        internal void CleanMessages()
        {
            SmiEventSink_Default parent = (SmiEventSink_Default)_parent;

            if (null != parent)
            {
                parent.CleanMessages();
            }
            else
            {
                _errors   = null;
                _warnings = null;
            }
        }
Ejemplo n.º 22
0
        private static void ValidateCopyTo(Action <SqlErrorCollection, SqlError[], int> copyTo)
        {
            SqlErrorCollection c = CreateCollection();

            SqlError[] destination = new SqlError[5];

            copyTo(c, destination, 2);

            Assert.Null(destination[0]);
            Assert.Null(destination[1]);
            Assert.Same(c[0], destination[2]);
            Assert.Null(destination[3]);
            Assert.Null(destination[4]);
        }
Ejemplo n.º 23
0
        public static SqlException GetSqlException()
        {
            SqlErrorCollection collection = Construct <SqlErrorCollection>();
            SqlError           error      = Construct <SqlError>(-2, (byte)2, (byte)3, "server name", "error message", "proc", 100, (uint)1);

            typeof(SqlErrorCollection)
            .GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance)
            .Invoke(collection, new object[] { error });

            var e = typeof(SqlException)
                    .GetMethod("CreateException", BindingFlags.NonPublic | BindingFlags.Static, null, CallingConventions.ExplicitThis, new[] { typeof(SqlErrorCollection), typeof(string) }, new ParameterModifier[] { })
                    .Invoke(null, new object[] { collection, "11.0.0" }) as SqlException;

            return(e);
        }
Ejemplo n.º 24
0
        private static SqlErrorCollection GenerateFakeSqlErrorCollection(params SqlError[] errors)
        {
            Type type = typeof(SqlErrorCollection);

            SqlErrorCollection collection = (SqlErrorCollection)Activator.CreateInstance(type, true);

            MethodInfo method = type.GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (SqlError error in errors)
            {
                method.Invoke(collection, new object[] { error });
            }

            return(collection);
        }
    private static SqlErrorCollection GenerateFakeSqlErrorCollection(params SqlError[] errors)
    {
        Type type = typeof(SqlErrorCollection);

        SqlErrorCollection collection = (SqlErrorCollection)(Activator.CreateInstance(type, true) ?? throw new InvalidOperationException("Failed to create SqlErrorCollection."));

        MethodInfo method = type.GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance) !;

        foreach (SqlError error in errors)
        {
            method?.Invoke(collection, new object[] { error });
        }

        return(collection);
    }
Ejemplo n.º 26
0
        public static SqlException CreateSqlException(string errorMessage, int errorNumber)
        {
            SqlErrorCollection collection = Construct <SqlErrorCollection>();
            SqlError           error      = GenerateFakeSqlError(errorNumber, errorMessage);

            typeof(SqlErrorCollection)
            .GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance)
            .Invoke(collection, new object[] { error });

            var createException = typeof(SqlException)
                                  .GetMethod("CreateException", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(SqlErrorCollection), typeof(string) }, null);

            var e = createException.Invoke(null, new object[] { collection, "7.0.0" }) as SqlException;

            return(e);
        }
Ejemplo n.º 27
0
        internal static SqlException NewSqlException(string message, int number, int level, int state)
        {
            SqlErrorCollection collection = Construct <SqlErrorCollection>();
            SqlError           error      = Construct <SqlError>(number, (byte)state, (byte)level, "test server", message, "test procedure", state);

            typeof(SqlErrorCollection)
            .GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance)
            .Invoke(collection, new object[] { error });

            return(typeof(SqlException)
                   .GetMethod("CreateException", BindingFlags.NonPublic | BindingFlags.Static,
                              null,
                              CallingConventions.ExplicitThis,
                              new[] { typeof(SqlErrorCollection), typeof(string) },
                              new ParameterModifier[] { })
                   .Invoke(null, new object[] { collection, "7.0.0" }) as SqlException);
        }
Ejemplo n.º 28
0
        public static SqlException NewSqlException(int number = 1)
        {
            SqlErrorCollection collection = Construct <SqlErrorCollection>();
            SqlError           error      = Construct <SqlError>(number, (byte)2, (byte)3, "server name", "error message", "proc", 100);

            typeof(SqlErrorCollection)
            .GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance)
            .Invoke(collection, new object[] { error });


            return(typeof(SqlException)
                   .GetMethod("CreateException", BindingFlags.NonPublic | BindingFlags.Static,
                              null,
                              CallingConventions.ExplicitThis,
                              new[] { typeof(SqlErrorCollection), typeof(string) },
                              Array.Empty <ParameterModifier>())
                   .Invoke(null, new object[] { collection, "7.0.0" }) as SqlException);
        }
Ejemplo n.º 29
0
        public static SqlException CreateSqlException(string errorMessage, int errorNumber, int state = 0, int severity = 10,
                                                      int lineNumber = 0, string server = "ServiceVirt", string procedureName = "ServiceVirtUnknownProcName")
        {
            SqlErrorCollection collection = GetErrorCollection();
            SqlError           error      = GetError(errorNumber, errorMessage, state, severity, lineNumber, server, procedureName);
            MethodInfo         addMethod  = collection.GetType().GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance);

            addMethod.Invoke(collection, new object[] { error });

            Type[] types = new Type[] { typeof(string), typeof(SqlErrorCollection), typeof(Exception), typeof(Guid) };

            object[] parameters = new object[] { errorMessage, collection, null, Guid.NewGuid() };

            ConstructorInfo constructor = typeof(SqlException).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, types, null);
            SqlException    exception   = (SqlException)constructor.Invoke(parameters);

            return(exception);
        }
        public static string ToLogString(this SqlErrorCollection errors)
        {
            string message = null;

            if (errors != null)
            {
                var stringBuilder = new StringBuilder();
                foreach (SqlError error in errors)
                {
                    var s = error.ToLogString();
                    stringBuilder.AppendLine(s);
                }

                message = stringBuilder.ToString();
            }

            return(message);
        }