コード例 #1
0
    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);
    }
コード例 #2
0
ファイル: Batch.cs プロジェクト: mattmasson/sqltoolsservice
        /// <summary>
        /// Called when a message came from SqlClient
        /// </summary>
        /// <remarks>
        /// Additionally, it's being used to notify the user that the script execution
        /// has been finished.
        /// </remarks>
        /// <param name="detailedMessage"></param>
        /// <param name="message"></param>
        private void RaiseBatchMessage(string detailedMessage, string message, SqlError error)
        {
            EventHandler <BatchMessageEventArgs> cache = BatchMessage;

            if (cache != null)
            {
                BatchMessageEventArgs args = new BatchMessageEventArgs(detailedMessage, message, error);
                cache(this, args);
            }
        }
コード例 #3
0
        private static string Format(SqlError error)
        {
            const string NonProcedureLocationName = "(batch)";

            var procedure
                = error.Procedure.NullIfEmpty()
                  ?? NonProcedureLocationName;

            return($"{procedure}:{error.LineNumber}: E{error.Class}: {error.Message}");
        }
コード例 #4
0
ファイル: Error.cs プロジェクト: 24/source_04
        private static string _GetErrorMessage(Exception ex, string sErrHeader, bool bAddClassName)
        {
            //string sErr;
            //OleDbException exOleDb;
            //SqlException exSql;
            //SqlError errSql;
            string sErr = "Error";

#if OleDb
            //if (exOleDb != null)
            if (ex is OleDbException)
            {
                OleDbException exOleDb = ex as OleDbException;
                for (int i = exOleDb.Errors.Count - 1; i >= 0; i--)
                {
                    //sErr += string.Format("{0} : {1} (Msg {2})\r\n", sErrHeader, exOleDb.Errors[i].Message, exOleDb.Errors[i].NativeError);
                    sErr += string.Format("{0}{1} (Msg {2})\r\n", sErrHeader, exOleDb.Errors[i].Message, exOleDb.Errors[i].NativeError);
                }
                return(sErr);
            }
#endif
#if SqlClient
            //else if (exSql != null)
            if (ex is SqlException)
            {
                SqlException exSql = ex as SqlException;
                for (int i = 0; i < exSql.Errors.Count; i++)
                {
                    SqlError errSql = exSql.Errors[i];
                    //sErr += string.Format("{0} : Msg {1}, State {2}, Procedure {3}, Line {4} : {5}\r\n", sErrHeader, errSql.Number, errSql.State, errSql.Procedure,
                    //    errSql.LineNumber, errSql.Message);
                    sErr += string.Format("{0}Msg {1}, State {2}, Procedure {3}, Line {4} : {5}\r\n", sErrHeader, errSql.Number, errSql.State, errSql.Procedure,
                                          errSql.LineNumber, errSql.Message);
                }
                return(sErr);
            }
#endif
            //else
            //{
            //sErr = sErrHeader;
            //if (bAddClassName ) sErr += " " + ex.GetType().FullName;
            //sErr += " : " + ex.Message;
            sErr = "";
            if (sErrHeader != null)
            {
                sErr = sErrHeader;
            }
            sErr += ex.Message;
            if (bAddClassName)
            {
                sErr += " (" + ex.GetType().FullName + ")";
            }
            //}
            return(sErr);
        }
コード例 #5
0
        private static string ReportSqlError(SqlError e)
        {
            string errorProcedure = !string.IsNullOrEmpty(e.Procedure)
                ? $", Procedure {e.Procedure}"
                : "";
            string errorMetadata = e.Class > 0
                ? $"Msg {e.Number}, Level {e.Class}, State {e.State}{errorProcedure}, Line {e.LineNumber}: "
                : "";

            return(errorMetadata + e.Message);
        }
コード例 #6
0
        private void bt_buscar_Click(object sender, EventArgs e)
        {
            if (MayorFacturacion.Checked == false && PorcentajeDescuento.Checked == false)
            {
                MessageBox.Show("Seleccione un tipo de Listado.", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return;
            }
            else if (rbt_primer_semestre.Checked == false && rbt_segundo_semestre.Checked == false)
            {
                MessageBox.Show("Seleccione un semestre.", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return;
            }

            conexionBD conexion = conexionBD.getConexion();

            SqlConnection conn = new SqlConnection(conexion.get_cadena());

            conn.Open();

            try
            {
                if (PorcentajeDescuento.Checked == true)
                {
                    string query = crear_query_PorcentajeDescuentos();

                    SqlDataAdapter adapter = new SqlDataAdapter(query, conn);


                    DataTable tabla_proveedores = new DataTable();

                    adapter.Fill(tabla_proveedores);

                    contenedor_proveedores.DataSource = tabla_proveedores;
                }
                if (MayorFacturacion.Checked == true)
                {
                    string query = crear_query_MayorFacturacion();


                    SqlDataAdapter adapter = new SqlDataAdapter(query, conn);


                    DataTable tabla_proveedores = new DataTable();

                    adapter.Fill(tabla_proveedores);

                    contenedor_proveedores.DataSource = tabla_proveedores;
                }
            }
            catch (SqlException exepcion)
            {
                SqlError errores = exepcion.Errors[0];
                MessageBox.Show(errores.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            conn.Close();
        }
コード例 #7
0
        public static void LogSqlError(SqlError e)
        {
            if (e != null)
            {
                Logger logger       = LogManager.GetLogger(e.Procedure + "@" + e.Server);
                var    logMessage   = e.Message;
                var    logException = new Exception("Exception at Line: " + e.LineNumber);

                switch (e.Class)
                {
                case 0:
                case 1:     // Trace: RAISERROR('Trace Message', 1,  1) WITH NOWAIT;
                    logger.Trace(logException, logMessage);
                    break;

                case 2:     // Debug: RAISERROR('Debug Message', 2,  1) WITH NOWAIT;
                    logger.Debug(logException, logMessage);
                    break;

                case 3:
                case 4:
                case 5:
                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
                    logger.Info(logException, logMessage);
                    break;

                case 11:
                case 12:
                case 13:
                case 14:
                case 15:
                case 16:     // Error RAISERROR('Error Message', 16,  1) WITH NOWAIT;
                case 17:
                case 18:
                case 19:     // Error that users can't RAISE
                    logger.Error(logException, logMessage);
                    break;

                case 20:     // from here the connection is forcefull closed
                case 21:
                case 22:
                case 23:
                case 24:
                case 25:
                default:     // from 17 to 24 or unknown
                    logger.Fatal(logException, logMessage);
                    break;
                }
            }
        }
コード例 #8
0
        private void bt_publicar_Click(object sender, EventArgs e)
        {
            if (this.verificar_txts_vacios())
            {
                MessageBox.Show("Todos los campos son obligatorios", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            //verificar fecha, precio de oferta rebajado al de lista

            if (this.verificar_datos())
            {
                return;
            }

            conn.Open();

            SqlCommand command = new SqlCommand("ZTS_DB.confeccion_oferta", conn);

            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.AddWithValue("@descripcion", SqlDbType.Char).Value                  = Descripcion.Text;
            command.Parameters.AddWithValue("@fecha_publicacion", SqlDbType.Date).Value            = FechaPublicacion.Value;
            command.Parameters.AddWithValue("@fecha_vencimiento", SqlDbType.Date).Value            = FechaVencimiento.Value;
            command.Parameters.AddWithValue("@precio_oferta", SqlDbType.Float).Value               = Convert.ToDecimal(PrecioOferta.Text);
            command.Parameters.AddWithValue("@precio_lista", SqlDbType.Float).Value                = Convert.ToDecimal(PrecioLista.Text);
            command.Parameters.AddWithValue("@cantidad_disponible", SqlDbType.Float).Value         = Int32.Parse(Cantidad.Value.ToString());
            command.Parameters.AddWithValue("@cantidad_maxima_por_usuario", SqlDbType.Float).Value = Int32.Parse(CantMax.Value.ToString());
            command.Parameters.AddWithValue("@codigo", SqlDbType.Char).Value = this.crear_codigo(10);

            if (this.bit_admin)
            {
                command.Parameters.AddWithValue("@proveedor_referenciado", SqlDbType.Char).Value = cbo_proveedores.Text;
            }
            else
            {
                command.Parameters.AddWithValue("@proveedor_referenciado", SqlDbType.Char).Value = sesion.get_username();
            }



            try
            {
                command.ExecuteNonQuery();
                MessageBox.Show("Oferta Publicada", "Publicacion de Ofertas", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.limpiar_datos();
            }
            catch (SqlException exepcion)
            {
                SqlError errores = exepcion.Errors[0];
                MessageBox.Show(errores.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            conn.Close();
        }
コード例 #9
0
    public void TestDecodeThrottlingReasonCode()
    {
        SqlError            err       = FakeSqlExceptionGenerator.GenerateFakeSqlError(ThrottlingCondition.ThrottlingErrorNumber, Resources.SampleThrottlingErrorMsg);
        ThrottlingCondition condition = ThrottlingCondition.FromError(err);

        Assert.AreEqual(ThrottlingMode.RejectAll, condition.ThrottlingMode, "Unexpected throttling mode.");

        ThrottlingType throttlingType = condition.ThrottledResources.Where(x => x.Item1 == ThrottledResourceType.Cpu).Select(x => x.Item2).FirstOrDefault();

        Assert.AreEqual(ThrottlingType.Hard, throttlingType, "Unexpected throttling type.");
    }
コード例 #10
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);
        }
コード例 #11
0
        public static ThrottlingCondition FromError(SqlError error)
        {
            if (error == null)
            {
                return(Unknown);
            }

            int capturedReasonCode;
            var match = SqlErrorCodeRegEx.Match(error.Message);

            return(match.Success && int.TryParse(match.Groups[1].Value, out capturedReasonCode) ? FromReasonCode(capturedReasonCode) : Unknown);
        }
    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.")));
    }
コード例 #13
0
 /// <summary>
 /// The local Searches are located in the "ea program files"\scripts (so usually C:\Program Files (x86)\Sparx Systems\EA\Scripts or C:\Program Files\Sparx Systems\EA\Scripts)
 /// The contents of the local scripts is loaded into the Searches.
 /// </summary>
 static void LoadLocalSearches(EA.Repository rep)
 {
     try
     {
         string searchFolder = SqlError.GetEaSqlErrorPath() + @"\Search Data";
         LoadSearchFromFolder(rep, searchFolder);
     }
     catch (Exception e)
     {
         MessageBox.Show($@"{e.Message}", @"Error in load Local Searches");
     }
 }
コード例 #14
0
 /// <summary>
 /// Determines the throttling conditions from the specified SQL error.
 ///
 /// </summary>
 /// <param name="error">The <see cref="T:System.Data.SqlClient.SqlError"/> object that contains information relevant to a warning or error returned by SQL Server.</param>
 /// <returns>
 /// An instance of the object that holds the decoded reason codes returned from SQL Database when throttling conditions were encountered.
 /// </returns>
 public static ThrottlingCondition FromError(SqlError error)
 {
     if (error != null)
     {
         Match match = sqlErrorCodeRegEx.Match(error.Message);
         if (match.Success && int.TryParse(match.Groups[1].Value, out var result))
         {
             return(FromReasonCode(result));
         }
     }
     return(Unknown);
 }
        private void bt_guardar_Click(object sender, EventArgs e)
        {
            if (txt_nombre.ReadOnly == true)
            {
                MessageBox.Show("Primero Inicie alguna Modificacion", "Modificacion de Clientes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (this.verificar_txts_vacios())
            {
                MessageBox.Show("Todos los campos son obligatorios menos la localidad, el codigo postal, el numero de piso y el departamento", "Modificacion de Clientes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (this.verificar_parametros())
            {
                return;
            }



            conexion_sql.Open();
            try
            {
                SqlCommand command = new SqlCommand("ZTS_DB.actualizar_cliente", conexion_sql);
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.AddWithValue("@username", SqlDbType.Char).Value = (txt_username.Text);
                command.Parameters.AddWithValue("@nombre", SqlDbType.Char).Value   = (txt_nombre.Text);
                command.Parameters.AddWithValue("@apellido", SqlDbType.Char).Value = (txt_apellido.Text);
                command.Parameters.AddWithValue("@DNI", SqlDbType.Int).Value       = Int32.Parse(txt_dni.Text);
                command.Parameters.AddWithValue("@telefono", SqlDbType.Int).Value  = Int64.Parse(txt_telefono.Text);
                command.Parameters.AddWithValue("@mail", SqlDbType.Char).Value     = (txt_email.Text);
                command.Parameters.AddWithValue("@fecha", SqlDbType.Char).Value    = (date_fecha_nacimiento.Value);

                command.Parameters.AddWithValue("@direccion", SqlDbType.Char).Value = (txt_direccion.Text);
                command.Parameters.AddWithValue("@ciudad", SqlDbType.Char).Value    = (txt_ciudad.Text);

                commonQueries_instance.filtrar_nulos(command, txt_codigopostal.Text, txt_localidad.Text, txt_piso.Text, txt_depto.Text);

                command.ExecuteNonQuery();


                MessageBox.Show("Cliente Modificado", "Modificacion de Clientes", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (SqlException exepcion)
            {
                SqlError errores = exepcion.Errors[0];
                MessageBox.Show(errores.Message.ToString(), "Modificacion de Clientes", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            conexion_sql.Close();
        }
コード例 #16
0
        private bool ConstraintResolve(Match match, SqlException exception, SqlError error, Action <string> addErrorMessage, long id, string originalTableName)
        {
            var tableName      = match.Groups[TableGroup].Value;
            var constraintName = match.Groups[ConstraintGroup].Value;
            var resolverRow    = db.SYS_ReferencesConflictResolvers.FirstOrDefault(r => r.ConstraintName == constraintName && r.TableName == tableName);

            if (resolverRow == null)
            {
                return(false);
            }

            return(RowResolve(resolverRow, match, exception, error, addErrorMessage, id, originalTableName));
        }
コード例 #17
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]);
        }
コード例 #18
0
        /// <summary>
        ///     Set sql exception and errors
        /// </summary>
        /// <param name="exception"></param>
        public void SetException(SqlException exception)
        {
            IsSuccess    = false;
            SqlException = exception;
            var errors = new SqlError[exception.Errors.Count];

            for (var i = 0; i < errors.Length; i++)
            {
                errors[i] = exception.Errors[i];
            }

            Errors = errors;
        }
コード例 #19
0
        private void bt_buscar_Click(object sender, EventArgs e)
        {
            conexionBD    conexion     = conexionBD.getConexion();
            SqlConnection conexion_sql = new SqlConnection(conexion.get_cadena());



            SqlCommand command = new SqlCommand("ZTS_DB.comprar_oferta", conexion_sql);

            command.CommandType = CommandType.StoredProcedure;


            command.Parameters.AddWithValue("@precioLista", SqlDbType.Float).Value      = (precio_lista2);
            command.Parameters.AddWithValue("@precio_oferta", SqlDbType.Float).Value    = (precio_oferta2);
            command.Parameters.AddWithValue("@clienteUsuario", SqlDbType.Char).Value    = (username);
            command.Parameters.AddWithValue("@cantidadDisponible", SqlDbType.Int).Value = (cantidadDispo2);
            command.Parameters.AddWithValue("@cantidadCompra", SqlDbType.Int).Value     = (Cantidad.Value);
            command.Parameters.AddWithValue("@cantidadMaxUsuario", SqlDbType.Int).Value = (cantMaxUser2);
            command.Parameters.AddWithValue("@codigoOferta", SqlDbType.Int).Value       = (codigo_oferta);
            command.Parameters.AddWithValue("@fecha", SqlDbType.DateTime).Value         = (fecha);

            conexion_sql.Open();


            try
            {
                command.ExecuteNonQuery();


                string     cmd      = "SELECT top 1 codigo_cupon FROM ZTS_DB.CUPONES  WHERE Codigo_oferta = '" + codigo_oferta + "' order by 1 desc ";
                SqlCommand command1 = new SqlCommand(cmd, conexion_sql);

                SqlDataReader reader = command1.ExecuteReader();

                while (reader.Read())
                {
                    string codigoCupon = (reader[0].ToString());
                    MessageBox.Show("Compra realizada con Éxito. Su código de cupón es: " + codigoCupon, "Compra de Ofertas", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (SqlException excepcion1)
            {
                SqlError errores = excepcion1.Errors[0];
                MessageBox.Show(errores.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                conexion_sql.Close();
                return;
            }

            conexion_sql.Close();
            bt_volver.PerformClick();
        }
コード例 #20
0
					public static SqlError FromBaseObject(BaseObject baseObj)
					{
						if (baseObj == null || baseObj.NativeObject == IntPtr.Zero)
							return null;
						SqlError obj = baseObj as  SqlError;
						if (object.Equals(obj, null))
						{
							obj = new SqlError(CreatedWhenConstruct.CWC_NotToCreate);
							obj.BindNativeObject(baseObj.NativeObject, "CSqlError");
							obj.IncreaseCast();
						}

						return obj;
					}
コード例 #21
0
        internal BatchErrorEventArgs(string message, SqlError error, TextSpan textSpan, Exception ex)
        {
            string desc = error != null ? error.Message : null;

            if (error.Number == 7202)
            {
                desc += " " + Environment.NewLine + SR.TroubleshootingAssistanceMessage;
            }

            int lineNumber = error != null ? error.LineNumber : -1;

            Init(message, desc, lineNumber, textSpan, ex);
            this.error = error;
        }
コード例 #22
0
        private void bt_guardar_Click(object sender, EventArgs e)
        {
            if (txt_RazonSoc.ReadOnly == true)
            {
                MessageBox.Show("Modifique algun parametro", "Modificacion de Proveedores", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (this.verificar_txts_vacios())
            {
                MessageBox.Show("Todos los campos son obligatorios menos el nombre de contacto, la localidad, el piso, el codigo postal y el departamento", "Modificacion de Proveedores", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (this.verificar_parametro())
            {
                return;
            }

            conexion_sql.Open();
            try
            {
                SqlCommand command = new SqlCommand("ZTS_DB.actualizar_proveedor", conexion_sql);
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.AddWithValue("@username", SqlDbType.Char).Value    = (txt_username.Text);
                command.Parameters.AddWithValue("@razonSocial", SqlDbType.Char).Value = (txt_RazonSoc.Text);
                command.Parameters.AddWithValue("@rubro", SqlDbType.Char).Value       = (cb_rubros.SelectedItem.ToString());
                command.Parameters.AddWithValue("@CUIT", SqlDbType.Char).Value        = txt_CUIT.Text;
                command.Parameters.AddWithValue("@telefono", SqlDbType.Float).Value   = Int64.Parse(txt_telefono.Text);
                command.Parameters.AddWithValue("@mail", SqlDbType.Char).Value        = (txt_email.Text);
                command.Parameters.AddWithValue("@direccion", SqlDbType.Char).Value   = (txt_direccion.Text);
                command.Parameters.AddWithValue("@ciudad", SqlDbType.Char).Value      = (txt_ciudad.Text);

                commonQueries_instance.filtrar_nulos(command, txt_codigopostal.Text, txt_localidad.Text, txt_piso.Text, txt_depto.Text);

                if (!string.IsNullOrEmpty(txt_Contacto.Text.Trim()))
                {
                    command.Parameters.AddWithValue("@contacto", SqlDbType.Char).Value = (txt_Contacto.Text);
                }

                command.ExecuteNonQuery();

                MessageBox.Show("Proveedor Modificado", "Modificacion de Proveedores", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (SqlException exepcion)
            {
                SqlError errores = exepcion.Errors[0];
                MessageBox.Show(errores.Message.ToString(), "Modificacion de Proveedores", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            conexion_sql.Close();
        }
コード例 #23
0
                protected override bool ShouldRetryOn(Exception exception)
                {
                    if (exception is SqlException sqlException)
                    {
                        SqlError error = sqlException.Errors.Cast <SqlError>().FirstOrDefault(n => _errorsToRetry.Contains(n.Number));
                        if (error != null)
                        {
                            LogWarn($"Retrying database operation on {sqlException.Server} after error {error.Number}.", exception);
                            return(true);
                        }
                    }

                    return(false);
                }
コード例 #24
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]);
        }
コード例 #25
0
ファイル: ServerConnect.cs プロジェクト: ramnaresh/SMO
        private void OnServerMessage(object sender,
                                     ServerMessageEventArgs args)
        {
            SqlError err = args.Error;

            ExceptionMessageBox emb = new ExceptionMessageBox();

            emb.Text = String.Format(
                System.Globalization.CultureInfo.InvariantCulture,
                Properties.Resources.SqlError,
                err.Source, err.Class, err.State, err.Number, err.LineNumber,
                err.Procedure, err.Server, err.Message);
            emb.Show(this);
        }
コード例 #26
0
        // 是否包含了指定的错误号?
        // 错误码表:ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.SQL.v2000.en/trblsql/tr_syserrors2_93i1.htm
        // 15007    The login '%s' does not exist.
        static bool IsSqlErrorNo(SqlException ex,
                                 int nNumber)
        {
            for (int i = 0; i < ex.Errors.Count; i++)
            {
                SqlError error = ex.Errors[i];

                if (error.Number == nNumber)
                {
                    return(true);
                }
            }
            return(false);
        }
コード例 #27
0
        private void bt_finalizar_Click(object sender, EventArgs e)
        {
            if (list_rol.Items.Count == 0)
            {
                MessageBox.Show("Agregue al menos una funcion", "Alta de Roles", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (string.IsNullOrEmpty(txt_nombre_rol.Text.Trim()))
            {
                MessageBox.Show("Introduzca el nombre del nuevo Rol", "Alta de Roles", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }


            conn.Open();
            //Esta no puede tirar error, por eso la saco del try
            this.carga_logica_funciones_nuevas(conn);
            conn.Close();

            conn.Open();
            try
            {
                //Primero inserto el rol nuevo, si tira error significa qu ya existe ese rol por lo que me sale al primer catch
                this.insert_into_roles(txt_nombre_rol.Text.ToString(), conn);

                //Si paso esa parte, meto todas las funciones que seleccione
                try
                {
                    for (int i = 0; i < Id_Funciones.Count; i++)
                    {
                        commonQueries_instance.insert_funciones_por_rol(txt_nombre_rol.Text.ToString(), Id_Funciones[i].ToString(), conn);
                    }
                }
                catch (SqlException exepcion)
                {
                    SqlError errores = exepcion.Errors[0];
                    MessageBox.Show(errores.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                MessageBox.Show("Creacion del Rol Finalizada", "Alta de Roles", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (SqlException exepcion)
            {
                SqlError errores = exepcion.Errors[0];
                MessageBox.Show(errores.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            conn.Close();
            Id_Funciones.Clear();
        }
コード例 #28
0
        static int callTestProc(string badgeNo, string msg, SqlConnection conn)
        {
            const string PN_BADGE = "@badge_number";
            const string PN_MSG = "@message";
            int          ret, rc;

            ret = -1;
            try {
                using (SqlCommand cmd = new SqlCommand("my_test_proc", conn)) {
                    cmd.CommandType = CommandType.StoredProcedure;
                    if (string.IsNullOrEmpty(badgeNo))
                    {
                        cmd.Parameters.AddWithValue(PN_BADGE, DBNull.Value);
                    }
                    else
                    {
                        cmd.Parameters.AddWithValue(PN_BADGE, badgeNo);
                    }
                    cmd.Parameters.AddWithValue(PN_MSG, msg);
                    Logger.logMethod(MethodBase.GetCurrentMethod());
                    if ((rc = cmd.ExecuteNonQuery()) > 0)
                    {
                        ret = rc;
                        tryToReceiveData(cmd);
                    }
                }
            } catch (SqlException sex) {
                // seems like this SqlException has the print-messages in it.  I only wanna see
                // the raise-error message.

                if (sex.Errors.Count > 0)
                {
                    SqlError e = sex.Errors[0];
                    Logger.logMethod(MethodBase.GetCurrentMethod(), Environment.NewLine +
                                     "Server " + e.Server +
                                     ", Error " + e.Number +
                                     ", class " + e.Class +
                                     " in procedure '" + e.Procedure + "', line " + e.LineNumber + Environment.NewLine +
                                     "error-message: " + e.Message + Environment.NewLine);
                }
                else
                {
                    Logger.logMethod(MethodBase.GetCurrentMethod(), sex);
                }
            } catch (Exception ex) {
                Logger.logMethod(MethodBase.GetCurrentMethod(), ex);
            }
            return(ret);
        }
コード例 #29
0
        public static string Translate(this SqlException ex)
        {
            int i             = 0;
            var errorMessages = new StringBuilder();

            for (i = 0; i <= ex.Errors.Count - 1; i++)
            {
                SqlError sqlError        = ex.Errors[i];
                string   filteredMessage = string.Empty;
                if (sqlError.Class == 16)
                {
                    if (sqlError.Number == 2812)
                    {
                        filteredMessage = "找不到存储过程";
                    }
                    else if (sqlError.Number == 208)
                    {
                        filteredMessage = "对象名无效";
                    }
                }
                switch (sqlError.Number)
                {
                case 17:
                case 53:
                    filteredMessage = "未找到或无法访问服务器";
                    break;

                case 4060:
                    filteredMessage = "无效的数据库";
                    break;

                case 18456:
                    filteredMessage = "数据库无法登陆";
                    break;

                case 1205:
                    filteredMessage = "sql 死锁";
                    break;

                default:
                    filteredMessage = ex.ToString();
                    break;
                }

                errorMessages.Append("<b>Index #:</b> " + i + "<br/>" + "<b>Source:</b> " + sqlError.Source + "<br/>" + "<b>Class:</b> " + sqlError.Class + "<br/>" + "<b>Number:</b> " +
                                     sqlError.Number + "<br/>" + "<b>Procedure:</b> " + sqlError.Procedure + "<br/>" + "<b>Message:</b> " + filteredMessage + "<br/>");
            }
            return(errorMessages.ToString());
        }
コード例 #30
0
ファイル: Form1.cs プロジェクト: AvitalKamil/BoxTarget
        private void button1_Click(object sender, EventArgs e)
        {
            UpdatedV.Clear();
            SqlError.Clear();
            SqlDataReader dataReader;

            sql = $"SELECT  * FROM [DC_PreProd_Box_Validation].[dbo].[tblBox] where BoxID = {TxtBoxID.Text} ";
            try
            {
                SqlConnection sqlConnection = new SqlConnection(connection);
                sqlConnection.Open();
                command    = new SqlCommand(sql, sqlConnection);
                dataReader = command.ExecuteReader();
                while (dataReader.Read())
                {
                    if (TxtTarget.Text == LastTarget)
                    {
                        LastTarget     = (string)dataReader.GetValue(5);
                        TxtTarget.Text = (string)dataReader.GetValue(5);
                    }
                    else
                    {
                        var IsYes = MessageBox.Show($"Do you want to change the target to: {TxtTarget.Text} ?", "Changing target", MessageBoxButtons.YesNo);
                        if (IsYes == DialogResult.Yes)
                        {
                            Update_Target();
                            LastTarget = TxtTarget.Text;
                        }
                        else
                        {
                            TxtTarget.Text = (string)dataReader.GetValue(5);
                        }
                    }
                }
                if (!dataReader.HasRows)
                {
                    LastTarget = "";
                    TxtTarget.Clear();
                    SqlError.SetError(TxtBoxID, "Box not found");
                }
                dataReader.Close();
                command.Dispose();
                sqlConnection.Close();
            }
            catch (Exception ex)
            {
                SqlError.SetError(TxtBoxID, ex.Message);
            }
        }
コード例 #31
0
            /// <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 ThrottlingReason FromError(SqlError error)
            {
                if (error != null)
                {
                    var match      = sqlErrorCodeRegEx.Match(error.Message);
                    int reasonCode = 0;

                    if (match.Success && Int32.TryParse(match.Groups[1].Value, out reasonCode))
                    {
                        return(FromReasonCode(reasonCode));
                    }
                }

                return(Unknown);
            }
コード例 #32
0
 // Called for messages and errors (ERROR and INFO tokens)
 internal override void MessagePosted ( int number, byte state, byte errorClass, string server, string message, string procedure, int lineNumber ) {
     if (null == _parent) {
         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, 
                         (null != server) ? server : "<null>", 
                         (null != message) ? message : "<null>", 
                         (null != procedure) ? procedure : "<null>", 
                         lineNumber
                         );
         }
         SqlError error = new SqlError ( number, state, errorClass, server, message, procedure, lineNumber );
         
         if ( error.Class < TdsEnums.MIN_ERROR_CLASS ) {
             Warnings.Add( error );
         }
         else {
             Errors.Add( error );
         }
     }
     else {
         _parent.MessagePosted( number, state, errorClass, server, message, procedure, lineNumber );
     }
 }
コード例 #33
0
 private void FireInfoMessageEvent(SqlConnection connection, TdsParserStateObject stateObj, SqlError error)
 {
     string serverVersion = null;
     if (this._state == TdsParserState.OpenLoggedIn)
     {
         serverVersion = this._connHandler.ServerVersion;
     }
     SqlErrorCollection errorCollection = new SqlErrorCollection();
     errorCollection.Add(error);
     SqlException exception = SqlException.CreateException(errorCollection, serverVersion);
     connection.OnInfoMessage(new SqlInfoMessageEventArgs(exception));
 }
コード例 #34
0
		public abstract void Send (SqlError x);
コード例 #35
0
        // 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;
        }
コード例 #36
0
ファイル: TdsParserStateObject.cs プロジェクト: mind0n/hive
        /// <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 [....] once we see a warning
            _syncOverAsync = true;

            lock (_errorAndWarningsLock){
                _hasErrorOrWarning = true;
                if (_warnings == null) {
                    _warnings = new SqlErrorCollection();
                }
                _warnings.Add(error);
            }
        }
コード例 #37
0
        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;

            // MDAC bug #49307 - server sometimes does not send over server field! In those cases
            // we will use our 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;
        }