DO NOT enter the method of an internal class c #

4

I am trying to understand why it does not execute a method from a non-static public class ( public class DatosHandler ), even a static method:

public class DatosHandler
{

    public static DataTable ConsultaFacturasAll()
    {

        //*** cadena de texto de consulta de las facturas detalle*** 
        string ConsultaEncabezado = "SELECT " +
                                    "facturaNumero, " +
                                    "DATE_FORMAT(facturaFecha, '%Y-%m-%d') as FacturaFecha, " +
                                    "DATE_FORMAT(facturaFechaVencimiento, '%Y-%m-%d') as FacturaFechaVencimiento, " +
                                    "facturaOrdenCompra, " +
                                    "clienteNombre, " +
                                    "clienteIdentificacion, " +
                                    "clienteTelefono, " +
                                    "clienteEmail, " +
                                    "FORMAT(facturaSubtotal, 2)  as facturaSubtotal, " +
                                    "FORMAT(facturaValorTotal, 2) as facturaValorTotal FROM Encabezados";

        return Conexion.EjecutarConsulta(ConsultaEncabezado, CommandType.Text); // ACA SALE EL ERROR

    }

The Class that invokes the ExecuteConsulta method is internal and Static methods as I put it in the box:

public static DataTable EjecutarConsulta(string cadenaComando, CommandType tipocomando)
    {
        MySqlDataAdapter adaptador = new MySqlDataAdapter();// aca he colocado punto de interrupcion pero no llega el debuger en este punto
        adaptador.SelectCommand = new MySqlCommand(cadenaComando, conexion);
        adaptador.SelectCommand.CommandType = tipocomando;

        DataSet resultado = new DataSet();
        adaptador.Fill(resultado);

        return resultado.Tables[0];
    }

The error that shows me is:

  

An exception occurred in the type initializer of 'co.InfraestructuraData.Conexion'

I have well-referenced dll to mysql, the query is fine (I tested)

but when debug return Conexion.EjecutarConsulta(ConsultaEncabezado, CommandType.Text); in this line, the exception occurs in the type initializer.

Could you explain to me why you do not enter the class call Connection run query ??? It is defined as static !

public static DataTable EjecutarConsulta

Both the class Conexión and DatosHandler are in the same project or namespace namespace co.InfraestructuraData

As much as possible explain with code Thank you! ;);)

Update

this is the code of the internal Conexion class, and they are in the same namespace namespace co.InfraestructuraData

internal class Conexion
{

    private static string cadenaConexion= ConfigurationManager.ConnectionStrings["sqlConexionApp"].ConnectionString;
    private static MySqlConnection conexion = new MySqlConnection(cadenaConexion);

    public static bool Conectar()
    {
        try
        {
            conexion.Open();
            return true;
        }
        catch (Exception)
        {

            return false;
        }
    }

    public static void Desconectar()
    {
        conexion.Close();
    }

    public static void EjecutarOperacion(string cadenaComando, List<MySqlParameter> listaparametros, CommandType tipoComando)
    {
        if (Conectar())
        {
            MySqlCommand comando = new MySqlCommand();
            comando.CommandText = cadenaComando;
            comando.CommandType = tipoComando;
            comando.Connection = conexion;

            foreach (MySqlParameter parametro in listaparametros)
            {
                comando.Parameters.Add(parametro);
            }
            comando.ExecuteNonQuery();
            Desconectar();
        }
        else
        {
            throw new Exception("No se pudo establecer conexion");
        }
    }

    public static DataTable EjecutarConsulta(string sentencia, List<MySqlParameter> listaparametro, CommandType tipocomando)
    {
        MySqlDataAdapter adaptador = new MySqlDataAdapter();
        adaptador.SelectCommand = new MySqlCommand(sentencia, conexion);
        adaptador.SelectCommand.CommandType = tipocomando;
        foreach (MySqlParameter parametro in listaparametro)
        {
            adaptador.SelectCommand.Parameters.Add(parametro);
        }
        DataSet resultado = new DataSet();
        adaptador.Fill(resultado);

        return resultado.Tables[0];
    }

    public static DataTable EjecutarConsulta(string cadenaComando, CommandType tipocomando)
    {
        MySqlDataAdapter adaptador = new MySqlDataAdapter();
        adaptador.SelectCommand = new MySqlCommand(cadenaComando, conexion);
        adaptador.SelectCommand.CommandType = tipocomando;

        DataSet resultado = new DataSet();
        adaptador.Fill(resultado);

        return resultado.Tables[0];
    }
}
    
asked by ger 09.10.2018 в 16:42
source

2 answers

2

When a call is made to a static method of a class, it must be taken into account that all static variables of the class are initialized.

In your case, you have two static variables in Conexion : cadenaConexion and conexion .

The error you describe is being thrown by the initialization of some of those variables. Either the key sqlConexionApp does not exist in your configuration file ( web.config or app.config ), or the connection string is not correct and the error is occurring in conexion = new MySqlConnection(cadenaConexion);

You must check both, and also in these cases normally the InnerException should give you more information about what the problem is.

    
answered by 09.10.2018 / 17:40
source
1

You must ensure that the version of your library is equal to the mysql database that you use, the versions are 5.1 and 5.2, etc; Even if you already have your library installed you should check that they are the same version.

I show you part of the connection class: to use the method just create an instance of the class

MySqlHelper mc = new MySqlHelper();
mc.EjecutarConsulta("SELECT * ...");

You can add the methods you want something like:

public DataTable EjecutarConsulta(string cadenaComando){
 try{
    var dbCon = Instance();
    if (!dbCon.IsConnect())
      throw new Exception("CP: No es posible establecer la conexión");
    MySqlCommand cmd = new MySqlCommand(cadenaComando, dbCon._connection);
    DataTable dt = new DataTable();
    dt.load(cmd.ExecuteReader());
    return dt;
 }catch (Exception ex) { throw ex; }
}

I leave the code:

    public class MySqlHelper
    {
        private MySqlHelper()
        {
        }


        private string _Host { get; set; } = "localhost";
        private string _databaseName { get; set; } = "BASE";
        private string _usid { get; set; } = "USER";
        private string _password { get; set; } = "***";

        public MySqlConnection _connection { get; set; } = null;

        private static MySqlHelper _instance = null;

        private static MySqlHelper Instance()
        {
            if (_instance == null)
                _instance = new MySqlHelper();
            return _instance;
        }

        private bool IsConnect()
        {
            if (_connection == null)
            {
                if (String.IsNullOrEmpty(_databaseName))
                    return false;
                string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3};charset=utf8", _Host, _databaseName, _usid, _password);
                _connection = new MySqlConnection(connstring);
                _connection.Open();
            }

            return true;
        }

        public void Close()
        {
            _connection.Close();
        }

    /// <summary>
    /// Pasa un sql Command de tipo Text
    /// </summary>
    /// <param name="cmd"></param>
    /// <param name="Timeout"></param>
    /// <returns></returns>
    public string ExecCommad(MySqlCommand cmd, int Timeout = 45)
    {
        var dbCon = Instance();
        try
        {
            if(cmd == null)
                throw new NullReferenceException("CP: No se mando ningun parametro o no puede ser null :(");

            if (!dbCon.IsConnect())
                throw new Exception("CP: No es posible establecer la conexión");

            cmd.CommandType = CommandType.Text;
            cmd.CommandTimeout = Timeout;//60 = 1 minutos
            cmd.Connection = dbCon._connection;
            cmd.ExecuteScalar();
            var getValue = cmd.ExecuteScalar();
            return (getValue == null) ? string.Empty : getValue.ToString();
        }
        catch (Exception ex) { throw ex; }
        finally { dbCon.Close(); cmd.Dispose(); }
    }

    /// <summary>
    /// Pasa un Sql command param de tipo proc
    /// </summary>
    /// <param name="cmd"></param>
    /// <param name="Timeout"></param>
    /// <returns></returns>
    public string ExecProc(MySqlCommand cmd, int Timeout = 45)
    {
        var dbCon = Instance();
        try
        {
            if(cmd==null)
                throw new NullReferenceException("CP: No se mando ningun parametro o no puede ser null :(");

            if (cmd.CommandType != CommandType.StoredProcedure)
                throw new ArgumentException("CP: Solo se pueden usar comandos tipos proc :(");

            if (!dbCon.IsConnect())
                throw new Exception("CP: No es posible establecer la conexión");


            cmd.Connection = dbCon._connection;
            cmd.CommandTimeout = Timeout;//60 = 1 minutos
            cmd.ExecuteScalar();
            var getValue = cmd.ExecuteScalar();
            return (getValue == null) ? string.Empty : getValue.ToString();
        }
        catch (Exception ex) { throw ex; }
        finally { dbCon.Close(); cmd.Dispose(); }
    }
}
    
answered by 09.10.2018 в 18:52