Exemplo n.º 1
0
 /// <summary>
 /// Cria a conexão.
 /// </summary>
 internal IDbConnection CreateConnection()
 {
     if (_currentConnection == null)
     {
         _currentConnection = _providerConfiguration.CreateConnection();
         GDAConnectionManager.NotifyConnectionCreated(_currentConnection);
         if (ConnectionCreated != null)
         {
             ConnectionCreated(this, new GDA.Provider.CreateConnectionEventArgs(_currentConnection));
         }
         if (_currentConnection.State != ConnectionState.Open)
         {
             _currentConnection.Open();
             GDAConnectionManager.NotifyConnectionOpened(_currentConnection);
         }
     }
     return(_currentConnection);
 }
Exemplo n.º 2
0
        /// <summary>
        /// Recupera os dados do objeto submetido com base na consulta fornecida.
        /// </summary>
        /// <param name="session">Sess�o utilizada para a execu��o do comando.</param>
        /// <param name="objData">Objeto onde os valores ser�o atribuidos.</param>
        /// <param name="sqlQuery">Consulta para a recupera��o dos dados.</param>
        /// <param name="parameters">Parametros utilizados na consulta.</param>
        /// <returns>Objecto com os valores da recupera��o j� atribu�dos.</returns>
        public Model RecoverData(GDASession session, Model objData, string sqlQuery, params GDAParameter[] parameters)
        {
            IDbConnection conn    = CreateConnection(session);
            IDbCommand    cmd     = CreateCommand(session, conn);
            string        newName = null;

            if (parameters != null)
            {
                for (int i = 0; i < parameters.Length; i++)
                {
                    try
                    {
                        newName = (parameters[i].ParameterName[0] != '?' ? parameters[i].ParameterName : UserProvider.ParameterPrefix + parameters[i].ParameterName.Substring(1) + UserProvider.ParameterSuffix);
                    }
                    catch (Exception ex)
                    {
                        throw new GDAException("Error on make parameter name '" + parameters[i].ParameterName + "'.", ex);
                    }
                    sqlQuery = sqlQuery.Replace(parameters[i].ParameterName, newName);
                    cmd.Parameters.Add(GDA.Helper.GDAHelper.ConvertGDAParameter(cmd, parameters[i], UserProvider));
                }
            }
            cmd.CommandText = sqlQuery;
            if (session == null && conn.State != ConnectionState.Open)
            {
                try
                {
                    conn.Open();
                }
                catch (Exception ex)
                {
                    throw new GDAException(ex);
                }
                GDAConnectionManager.NotifyConnectionOpened(conn);
            }
            IDataReader dReader = null;

            try
            {
                SendMessageDebugTrace("CommandText: " + cmd.CommandText);
                using (var executionHandler = Diagnostics.GDATrace.CreateExecutionHandler(cmd))
                    try
                    {
                        dReader = cmd.ExecuteReader();
                    }
                    catch (Exception ex)
                    {
                        ex = new GDAException(ex);
                        executionHandler.Fail(ex);
                        throw ex;
                    }
                if (dReader.Read())
                {
                    var mapping = new TranslatorDataInfoCollection(MappingManager.GetMappers <Model>(null, null));
                    mapping.ProcessFieldsPositions(dReader);
                    IDataRecord record = dReader;
                    RecoverValueOfResult(ref record, mapping, ref objData, false);
                }
                else
                {
                    throw new ItemNotFoundException("Item not found with submited parameters.");
                }
            }
            finally
            {
                if (dReader != null)
                {
                    dReader.Close();
                }
                if (session == null)
                {
                    try
                    {
                        conn.Close();
                        conn.Dispose();
                    }
                    catch
                    {
                        SendMessageDebugTrace("Error close connection.");
                    }
                }
            }
            return(objData);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Recupera os valores da propriedade que se encontra no resultado da consulta.
        /// </summary>
        /// <param name="session">Sess�o para execu��o do comando.</param>
        /// <param name="query">Comando da consulta que ser� executada.</param>
        /// <param name="propertyName">Nome da propriedade que ser� recuperada.</param>
        /// <returns>Valores da propriedade encontrada.</returns>
        public IEnumerable <GDAPropertyValue> GetValues(GDASession session, IQuery query, string propertyName)
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                throw new ArgumentNullException("propertyName");
            }
            if (query == null)
            {
                query = new Query();
            }
            query.ReturnTypeQuery = typeof(Model);
            QueryReturnInfo returnInfo = query.BuildResultInfo <Model>(this.Configuration);
            List <Mapper>   listAttr   = returnInfo.RecoverProperties;
            string          sqlQuery   = returnInfo.CommandText;
            IDbConnection   conn       = CreateConnection(session);
            IDbCommand      cmd        = CreateCommand(session, conn);

            cmd.CommandType = CommandType.Text;
            bool usingPaging = false;

            if (query.SkipCount > 0 || query.TakeCount > 0)
            {
                usingPaging = true;
            }
            if (listAttr.Count == 0)
            {
                throw new GDAException("Not found properties mappers to model {0}.", typeof(Model).FullName);
            }
            if (returnInfo.Parameters != null)
            {
                for (int i = 0; i < returnInfo.Parameters.Count; i++)
                {
                    try
                    {
                        string newName = (returnInfo.Parameters[i].ParameterName[0] != '?' ? returnInfo.Parameters[i].ParameterName : UserProvider.ParameterPrefix + returnInfo.Parameters[i].ParameterName.Substring(1) + UserProvider.ParameterSuffix);
                        sqlQuery = sqlQuery.Replace(returnInfo.Parameters[i].ParameterName, newName);
                    }
                    catch (Exception ex)
                    {
                        throw new GDAException("Error on make parameter name '" + returnInfo.Parameters[i].ParameterName + "'.", ex);
                    }
                    cmd.Parameters.Add(GDA.Helper.GDAHelper.ConvertGDAParameter(cmd, returnInfo.Parameters[i], UserProvider));
                }
            }
            if (usingPaging)
            {
                sqlQuery = UserProvider.SQLCommandLimit(listAttr, sqlQuery, query.SkipCount, query.TakeCount);
            }
            cmd.CommandText = sqlQuery;
            var property    = listAttr.Find(delegate(Mapper m) {
                return(m.PropertyMapperName == propertyName);
            });

            if (property == null)
            {
                throw new GDAException("Property {0} not found in {1}.", propertyName, typeof(Model).FullName);
            }
            IDataReader dReader = null;

            if (session == null)
            {
                try
                {
                    conn.Open();
                }
                catch (Exception ex)
                {
                    throw new GDAException(ex);
                }
                GDAConnectionManager.NotifyConnectionOpened(conn);
            }
            try
            {
                SendMessageDebugTrace("CommandText: " + cmd.CommandText);
                using (var executionHandler = Diagnostics.GDATrace.CreateExecutionHandler(cmd))
                    try
                    {
                        dReader = cmd.ExecuteReader();
                    }
                    catch (Exception ex)
                    {
                        ex = new GDAException(ex);
                        executionHandler.Fail(ex);
                        throw ex;
                    }
                if (dReader.FieldCount == 0)
                {
                    throw new GDAException("The query not return any field.");
                }
                var propertyExists = false;
                while (dReader.Read())
                {
                    var i = new GDADataRecord(dReader, null);
                    if (!propertyExists && i.GetOrdinal(property.Name) < 0)
                    {
                        yield break;
                    }
                    propertyExists = true;
                    yield return(new GDAPropertyValue(i.GetValue(property.Name), true));
                }
            }
            finally
            {
                if (session == null)
                {
                    try
                    {
                        conn.Close();
                    }
                    catch
                    {
                        SendMessageDebugTrace("Error close connection.");
                    }
                }
                if (dReader != null)
                {
                    dReader.Close();
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Executa uma consulta que retorna somente um campo.
        /// </summary>
        /// <param name="session">Sessão utilizada para a execução do comando.</param>
        /// <param name="sqlQuery">Consulta.</param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public object ExecuteScalar(GDASession session, CommandType commandType, int commandTimeout, string sqlQuery, params GDAParameter[] parameters)
        {
            object        returnValue;
            IDbConnection conn = CreateConnection(session);
            IDbCommand    cmd  = CreateCommand(session, conn);

            try
            {
                if (parameters != null)
                {
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        string newName = (parameters[i].ParameterName[0] != '?' ? parameters[i].ParameterName : UserProvider.ParameterPrefix + parameters[i].ParameterName.Substring(1) + UserProvider.ParameterSuffix);
                        sqlQuery = sqlQuery.Replace(parameters[i].ParameterName, newName);
                        cmd.Parameters.Add(GDA.Helper.GDAHelper.ConvertGDAParameter(cmd, parameters[i], UserProvider));
                    }
                }
                cmd.CommandText    = sqlQuery;
                cmd.CommandType    = commandType;
                cmd.CommandTimeout = commandTimeout;
                if (session == null && conn.State != ConnectionState.Open)
                {
                    try
                    {
                        conn.Open();
                    }
                    catch (Exception ex)
                    {
                        throw new GDAException(ex);
                    }
                    GDAConnectionManager.NotifyConnectionOpened(conn);
                }
                try
                {
                    SendMessageDebugTrace(cmd.CommandText);
                    using (var executionHandler = Diagnostics.GDATrace.CreateExecutionHandler(cmd))
                        try
                        {
                            returnValue = cmd.ExecuteScalar();
                        }
                        catch (Exception ex)
                        {
                            executionHandler.Fail(ex);
                            throw ex;
                        }
                    if (returnValue != DBNull.Value && returnValue != null)
                    {
                        SendMessageDebugTrace("Return: " + returnValue.ToString());
                    }
                    else
                    {
                        returnValue = null;
                        SendMessageDebugTrace("Return: null");
                    }
                }
                catch (Exception ex)
                {
                    throw new GDAException(ex);
                }
            }
            finally
            {
                try
                {
                    cmd.Dispose();
                    cmd = null;
                }
                finally
                {
                    if (session == null)
                    {
                        conn.Close();
                        conn.Dispose();
                    }
                }
            }
            return(returnValue);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Executa comandos sql.
        /// </summary>
        /// <param name="session">Sessão para execução do comando.</param>
        /// <param name="commandType">Tipo do comando a ser executado.</param>
        /// <param name="commandTimeout">commandTimeout</param>
        /// <param name="sqlQuery">Causa sql a ser executada.</param>
        /// <param name="parameters">Parametros a serem passados para o comando.</param>
        /// <returns>Número de linhas afetadas.</returns>
        /// <exception cref="ArgumentNullException">sqlQuery</exception>
        /// <exception cref="ArgumentException">sqlQuery cannot empty.</exception>
        public int ExecuteCommand(GDASession session, CommandType commandType, int commandTimeout, string sqlQuery, params GDAParameter[] parameters)
        {
            if (sqlQuery == null)
            {
                throw new ArgumentNullException("sqlQuery");
            }
            else if (sqlQuery == "")
            {
                throw new ArgumentException("sqlQuery cannot empty.");
            }
            int           valueReturn = 0;
            IDbConnection conn        = CreateConnection(session);
            IDbCommand    command     = CreateCommand(session, conn);

            try
            {
                SendMessageDebugTrace(sqlQuery);
                string newParameterName = null;
                if (parameters != null)
                {
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        newParameterName            = parameters[i].ParameterName.Replace("?", UserProvider.ParameterPrefix) + UserProvider.ParameterSuffix;
                        sqlQuery                    = sqlQuery.Replace(parameters[i].ParameterName, newParameterName);
                        parameters[i].ParameterName = newParameterName;
                        IDbDataParameter p = GDA.Helper.GDAHelper.ConvertGDAParameter(command, parameters[i], UserProvider);
                        command.Parameters.Add(p);
                    }
                }
                command.CommandText    = sqlQuery;
                command.CommandType    = commandType;
                command.CommandTimeout = commandTimeout;
                if (session == null && conn.State != ConnectionState.Open)
                {
                    try
                    {
                        conn.Open();
                    }
                    catch (Exception ex)
                    {
                        throw new GDAException(ex);
                    }
                    GDAConnectionManager.NotifyConnectionOpened(conn);
                }
                try
                {
                    SendMessageDebugTrace(command.CommandText);
                    using (var executionHandler = Diagnostics.GDATrace.CreateExecutionHandler(command))
                        try
                        {
                            executionHandler.RowsAffects = valueReturn = command.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            executionHandler.Fail(ex);
                            throw ex;
                        }
                    SendMessageDebugTrace("Return: " + valueReturn.ToString());
                }
                catch (Exception ex)
                {
                    throw new GDAException("SqlQuery: " + sqlQuery + "; --> " + ex.Message, ex);
                }
                for (int i = 0; i < command.Parameters.Count; i++)
                {
                    parameters[i].Value = ((IDbDataParameter)command.Parameters[i]).Value;
                }
            }
            finally
            {
                try
                {
                    command.Dispose();
                    command = null;
                }
                finally
                {
                    if (session == null)
                    {
                        conn.Close();
                        conn.Dispose();
                    }
                }
            }
            return(valueReturn);
        }
Exemplo n.º 6
0
        public object ExecuteScalar(GDASession session, GDAStoredProcedure procedure)
        {
            IDbConnection conn        = CreateConnection(session);
            IDbCommand    cmd         = CreateCommand(session, conn);
            object        valueReturn = null;

            try
            {
                procedure.Prepare(cmd, UserProvider);
                if (session == null && conn.State != ConnectionState.Open)
                {
                    try
                    {
                        conn.Open();
                    }
                    catch (Exception ex)
                    {
                        throw new GDAException(ex);
                    }
                    GDAConnectionManager.NotifyConnectionOpened(conn);
                }
                SendMessageDebugTrace(cmd.CommandText);
                try
                {
                    using (var executionHandler = Diagnostics.GDATrace.CreateExecutionHandler(cmd))
                        try
                        {
                            valueReturn = cmd.ExecuteScalar();
                        }
                        catch (Exception ex)
                        {
                            executionHandler.Fail(ex);
                            throw ex;
                        }
                }
                catch (Exception ex)
                {
                    throw new GDAException("StoredProcedure: " + cmd.CommandText + "; --> " + ex.Message, ex);
                }
                for (int i = 0; i < cmd.Parameters.Count; i++)
                {
                    procedure[i] = ((IDbDataParameter)cmd.Parameters[i]).Value;
                }
            }
            finally
            {
                try
                {
                    cmd.Dispose();
                    cmd = null;
                }
                finally
                {
                    if (session == null)
                    {
                        conn.Close();
                        conn.Dispose();
                    }
                }
            }
            return(valueReturn);
        }