Esempio n. 1
0
        /// <summary>
        /// Controla que los artefactos de base de datos para una tabla determinada existan, sino existen los crea.
        /// </summary>
        /// <param name="tableName">Tabla a controlar</param>
        /// <returns>True si es verdadero</returns>
        public static bool DBCheckedTable(string tableName)
        {
            bool result = false;

            DataAccessConnection dataAccess   = DataAccessConnection.Instance;
            SqlCeConnection      dbConnection = dataAccess.GetNewConnection();

            dbConnection.Open();

            string           cmdText = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @tablename";
            SqlCeCommand     command = dataAccess.GetNewCommand(cmdText, dbConnection, null);
            IDbDataParameter param   = dataAccess.GetNewDataParameter();

            param.ParameterName = "@tablename";
            param.DbType        = DbType.String;
            param.Size          = tableName.Length;
            param.Value         = tableName;
            command.Parameters.Add(param);

            IDataReader dataReader = command.ExecuteReader();

            if (dataReader.Read())
            {
                result = true;
            }
            dataReader.Close();
            dbConnection.Close();

            return(result);
        }
Esempio n. 2
0
        /// <summary>
        /// Función para cargar un CategoryEntity desde la base de datos.
        /// </summary>
        /// <param name="id">El id del registro a cargar</param>
        /// <param name="loadRelation">Si es true carga las relaciones</param>
        /// <param name="scope">Estructura interna usada para evitar la referencia circular, debe ser proveida si es llamada desde otro data access</param>
        /// <returns>La instancia de la entidad</returns>
        /// <exception cref="UtnEmallDataAccessException">
        /// Si una DbException ocurre mientras se accede a la base de datos
        /// </exception>
        public CategoryEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope)
        {
            // Crea una clave para el objeto de scope interno
            string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "Category";

            if (scope != null)
            {
                // Si el scope contiene el objeto, este ya fue cargado
                // retorna el objeto situado en el scope para evitar referencias circulares
                if (scope.ContainsKey(scopeKey))
                {
                    return((CategoryEntity)scope[scopeKey]);
                }
            }
            else
            {
                // Si no existe un scope, crear uno
                scope = new Dictionary <string, IEntity>();
            }

            CategoryEntity category = null;

            // Chequear si la entidad fue ya cargada por el data access actual
            // y retornar si fue ya cargada

            if (inMemoryEntities.ContainsKey(id))
            {
                category = inMemoryEntities[id];
                // Agregar el objeto actual al scope

                scope.Add(scopeKey, category);
            }
            else
            {
                bool closeConnection = false;
                try
                {
                    // Abrir una nueva conexión si no es una transaccion
                    if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0)
                    {
                        closeConnection = true;
                        dbConnection    = dataAccess.GetNewConnection();
                        dbConnection.Open();
                    }

                    string cmdText = "SELECT idCategory, description, name, idParentCategory, timestamp FROM [Category] WHERE idCategory = @idCategory";
                    // Crea el command

                    SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction);
                    // Crear el parametro id para la consulta

                    SqlCeParameter parameter = dataAccess.GetNewDataParameter("@idCategory", DbType.Int32);
                    parameter.Value = id;
                    sqlCommand.Parameters.Add(parameter);
                    // Usar el datareader para cargar desde la base de datos

                    IDataReader reader = sqlCommand.ExecuteReader();
                    category = new CategoryEntity();

                    if (reader.Read())
                    {
                        // Cargar las filas de la entidad
                        category.Id = reader.GetInt32(0);

                        if (!reader.IsDBNull(1))
                        {
                            category.Description = reader.GetString(1);
                        }
                        if (!reader.IsDBNull(2))
                        {
                            category.Name = reader.GetString(2);
                        }

                        category.IdParentCategory = reader.GetInt32(3);
                        // Agregar el objeto actual al scope

                        scope.Add(scopeKey, category);
                        // Agregar el objeto a la cahce de entidades cargadas

                        inMemoryEntities.Add(category.Id, category);
                        // Lee el timestamp y establece las propiedades nuevo y cambiado

                        category.Timestamp = reader.GetDateTime(4);
                        category.IsNew     = false;
                        category.Changed   = false;
                        // Cerrar el Reader

                        reader.Close();
                        // Carga los objetos relacionadoss if required

                        if (loadRelation)
                        {
                            LoadRelationChilds(category, scope);
                            LoadRelationParentCategory(category, scope);
                        }
                    }
                    else
                    {
                        reader.Close();
                    }
                }
                catch (DbException dbException)
                {
                    // Relanza la excepcion como una excepcion personalizada
                    throw new UtnEmallDataAccessException(dbException.Message, dbException);
                }
                finally
                {
                    // Cierra la conexión si fue creada dentro de la Función
                    if (closeConnection)
                    {
                        dbConnection.Close();
                    }
                }
            }
            // Retorna la entidad cargada
            return(category);
        }
        /// <summary>
        /// Función para cargar un ServiceEntity desde la base de datos.
        /// </summary>
        /// <param name="id">El id del registro a cargar</param>
        /// <param name="loadRelation">Si es true carga las relaciones</param>
        /// <param name="scope">Estructura interna usada para evitar la referencia circular, debe ser proveida si es llamada desde otro data access</param>
        /// <returns>La instancia de la entidad</returns>
        /// <exception cref="UtnEmallDataAccessException">
        /// Si una DbException ocurre mientras se accede a la base de datos
        /// </exception>
        public ServiceEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope)
        {
            // Crea una clave para el objeto de scope interno
            string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "Service";

            if (scope != null)
            {
                // Si el scope contiene el objeto, este ya fue cargado
                // retorna el objeto situado en el scope para evitar referencias circulares
                if (scope.ContainsKey(scopeKey))
                {
                    return((ServiceEntity)scope[scopeKey]);
                }
            }
            else
            {
                // Si no existe un scope, crear uno
                scope = new Dictionary <string, IEntity>();
            }

            ServiceEntity service = null;

            // Chequear si la entidad fue ya cargada por el data access actual
            // y retornar si fue ya cargada

            if (inMemoryEntities.ContainsKey(id))
            {
                service = inMemoryEntities[id];
                // Agregar el objeto actual al scope

                scope.Add(scopeKey, service);
            }
            else
            {
                bool closeConnection = false;
                try
                {
                    // Abrir una nueva conexión si no es una transaccion
                    if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0)
                    {
                        closeConnection = true;
                        dbConnection    = dataAccess.GetNewConnection();
                        dbConnection.Open();
                    }

                    string cmdText = "SELECT idService, name, description, webAccess, relativePathAssembly, pathAssemblyServer, active, global, image, website, deployed, updated, idStore, startDate, stopDate, timestamp FROM [Service] WHERE idService = @idService";
                    // Crea el command

                    SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction);
                    // Crear el parametro id para la consulta

                    SqlCeParameter parameter = dataAccess.GetNewDataParameter("@idService", DbType.Int32);
                    parameter.Value = id;
                    sqlCommand.Parameters.Add(parameter);
                    // Usar el datareader para cargar desde la base de datos

                    IDataReader reader = sqlCommand.ExecuteReader();
                    service = new ServiceEntity();

                    if (reader.Read())
                    {
                        // Cargar las filas de la entidad
                        service.Id = reader.GetInt32(0);

                        if (!reader.IsDBNull(1))
                        {
                            service.Name = reader.GetString(1);
                        }
                        if (!reader.IsDBNull(2))
                        {
                            service.Description = reader.GetString(2);
                        }
                        if (!reader.IsDBNull(3))
                        {
                            service.WebAccess = reader.GetString(3);
                        }
                        if (!reader.IsDBNull(4))
                        {
                            service.RelativePathAssembly = reader.GetString(4);
                        }
                        if (!reader.IsDBNull(5))
                        {
                            service.PathAssemblyServer = reader.GetString(5);
                        }

                        service.Active = reader.GetBoolean(6);
                        service.Global = reader.GetBoolean(7);
                        if (!reader.IsDBNull(8))
                        {
                            service.Image = reader.GetString(8);
                        }
                        if (!reader.IsDBNull(9))
                        {
                            service.Website = reader.GetString(9);
                        }

                        service.Deployed  = reader.GetBoolean(10);
                        service.Updated   = reader.GetBoolean(11);
                        service.IdStore   = reader.GetInt32(12);
                        service.StartDate = reader.GetDateTime(13);
                        service.StopDate  = reader.GetDateTime(14);
                        // Agregar el objeto actual al scope

                        scope.Add(scopeKey, service);
                        // Agregar el objeto a la cahce de entidades cargadas

                        inMemoryEntities.Add(service.Id, service);
                        // Lee el timestamp y establece las propiedades nuevo y cambiado

                        service.Timestamp = reader.GetDateTime(15);
                        service.IsNew     = false;
                        service.Changed   = false;
                        // Cerrar el Reader

                        reader.Close();
                        // Carga los objetos relacionadoss if required

                        if (loadRelation)
                        {
                            LoadRelationServiceCategory(service, scope);
                        }
                    }
                    else
                    {
                        reader.Close();
                    }
                }
                catch (DbException dbException)
                {
                    // Relanza la excepcion como una excepcion personalizada
                    throw new UtnEmallDataAccessException(dbException.Message, dbException);
                }
                finally
                {
                    // Cierra la conexión si fue creada dentro de la Función
                    if (closeConnection)
                    {
                        dbConnection.Close();
                    }
                }
            }
            // Retorna la entidad cargada
            return(service);
        }
Esempio n. 4
0
        /// <summary>
        /// Crea una nueva tabla con indices para claves foraneas
        /// </summary>
        /// <param name="table">Nombre de la tabla a crear</param>
        /// <param name="fieldsName">Nombres de los campos</param>
        /// <param name="fieldsType">Tipos de los campos, en el mismo orden que los nombres de campo</param>
        /// <param name="indexColumns">columnas a indexar</param>
        /// <returns>True si tiene éxito</returns>
        public static bool CreateTable(string table, string[] fieldsName, bool isIdIdentity, Type[] fieldsType, string[] indexColumns)
        {
            if (fieldsName.Length == 0)
            {
                throw new ArgumentException("");
            }
            if (fieldsType.Length == 0)
            {
                throw new ArgumentException("");
            }

            // Agrega el campo de timestamp
            string[] fields = new string[fieldsName.Length + 1];
            fieldsName.CopyTo(fields, 0);
            fields[fields.Length - 1] = "timestamp";
            fieldsName = fields;

            Type[] fieldsNewTypes = new Type[fieldsType.Length + 1];
            fieldsType.CopyTo(fieldsNewTypes, 0);
            fieldsNewTypes[fieldsNewTypes.Length - 1] = Type.GetType("System.DateTime");
            fieldsType = fieldsNewTypes;

            string cmdText = "CREATE TABLE [" + table + "] (";

            cmdText += "" + fieldsName[0] + " " + GetSQLTypeName(fieldsType[0]) + " PRIMARY KEY";
            if (isIdIdentity)
            {
                cmdText += " IDENTITY";
            }
            for (int i = 1; i < fieldsName.Length; i++)
            {
                cmdText += "," + fieldsName[i] + " " + GetSQLTypeName(fieldsType[i]);
            }
            cmdText += ")";

            DataAccessConnection dataAccess   = DataAccessConnection.Instance;
            SqlCeConnection      dbConnection = dataAccess.GetNewConnection();

            dbConnection.Open();

            SqlCeCommand command = dataAccess.GetNewCommand(cmdText, dbConnection, null);

            command.ExecuteNonQuery();

            // Crea los indices
            if (indexColumns != null && indexColumns.Length > 0)
            {
                string cmdIndex;
                for (int i = 0; i < indexColumns.Length; i++)
                {
                    cmdIndex = "CREATE INDEX IDX_" + table + "_" + indexColumns[i] +
                               " ON [" + table + "] (" + indexColumns[i] + ");";
                    command.CommandText = cmdIndex;
                    command.ExecuteNonQuery();
                }
            }

            dbConnection.Close();

            return(true);
        }
        /// <summary>
        /// Función para cargar un UserActionClientDataEntity desde la base de datos.
        /// </summary>
        /// <param name="id">El id del registro a cargar</param>
        /// <param name="loadRelation">Si es true carga las relaciones</param>
        /// <param name="scope">Estructura interna usada para evitar la referencia circular, debe ser proveida si es llamada desde otro data access</param>
        /// <returns>La instancia de la entidad</returns>
        /// <exception cref="UtnEmallDataAccessException">
        /// Si una DbException ocurre mientras se accede a la base de datos
        /// </exception>
        public UserActionClientDataEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope)
        {
            // Crea una clave para el objeto de scope interno
            string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "UserActionClientData";

            if (scope != null)
            {
                // Si el scope contiene el objeto, este ya fue cargado
                // retorna el objeto situado en el scope para evitar referencias circulares
                if (scope.ContainsKey(scopeKey))
                {
                    return((UserActionClientDataEntity)scope[scopeKey]);
                }
            }
            else
            {
                // Si no existe un scope, crear uno
                scope = new Dictionary <string, IEntity>();
            }

            UserActionClientDataEntity userActionClientData = null;

            // Chequear si la entidad fue ya cargada por el data access actual
            // y retornar si fue ya cargada

            if (inMemoryEntities.ContainsKey(id))
            {
                userActionClientData = inMemoryEntities[id];
                // Agregar el objeto actual al scope

                scope.Add(scopeKey, userActionClientData);
            }
            else
            {
                bool closeConnection = false;
                try
                {
                    // Abrir una nueva conexión si no es una transaccion
                    if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0)
                    {
                        closeConnection = true;
                        dbConnection    = dataAccess.GetNewConnection();
                        dbConnection.Open();
                    }

                    string cmdText = "SELECT idUserActionClientData, actionType, start, stop, idTable, idRegister, idComponent, idService, timestamp FROM [UserActionClientData] WHERE idUserActionClientData = @idUserActionClientData";
                    // Crea el command

                    SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction);
                    // Crear el parametro id para la consulta

                    SqlCeParameter parameter = dataAccess.GetNewDataParameter("@idUserActionClientData", DbType.Int32);
                    parameter.Value = id;
                    sqlCommand.Parameters.Add(parameter);
                    // Usar el datareader para cargar desde la base de datos

                    IDataReader reader = sqlCommand.ExecuteReader();
                    userActionClientData = new UserActionClientDataEntity();

                    if (reader.Read())
                    {
                        // Cargar las filas de la entidad
                        userActionClientData.Id = reader.GetInt32(0);

                        userActionClientData.ActionType  = reader.GetInt32(1);
                        userActionClientData.Start       = reader.GetDateTime(2);
                        userActionClientData.Stop        = reader.GetDateTime(3);
                        userActionClientData.IdTable     = reader.GetInt32(4);
                        userActionClientData.IdRegister  = reader.GetInt32(5);
                        userActionClientData.IdComponent = reader.GetInt32(6);
                        userActionClientData.IdService   = reader.GetInt32(7);
                        // Agregar el objeto actual al scope

                        scope.Add(scopeKey, userActionClientData);
                        // Agregar el objeto a la cahce de entidades cargadas

                        inMemoryEntities.Add(userActionClientData.Id, userActionClientData);
                        // Lee el timestamp y establece las propiedades nuevo y cambiado

                        userActionClientData.Timestamp = reader.GetDateTime(8);
                        userActionClientData.IsNew     = false;
                        userActionClientData.Changed   = false;
                        // Cerrar el Reader

                        reader.Close();
                        // Carga los objetos relacionadoss if required

                        if (loadRelation)
                        {
                        }
                    }
                    else
                    {
                        reader.Close();
                    }
                }
                catch (DbException dbException)
                {
                    // Relanza la excepcion como una excepcion personalizada
                    throw new UtnEmallDataAccessException(dbException.Message, dbException);
                }
                finally
                {
                    // Cierra la conexión si fue creada dentro de la Función
                    if (closeConnection)
                    {
                        dbConnection.Close();
                    }
                }
            }
            // Retorna la entidad cargada
            return(userActionClientData);
        }
Esempio n. 6
0
        /// <summary>
        /// Function to load a CustomerEntity from database.
        /// </summary>
        /// <param name="id">The ID of the record to load</param>
        /// <param name="loadRelation">if is true load the relation</param>
        /// <param name="scope">Internal structure used to avoid circular reference locks, must be provided if calling from other data access object</param>
        /// <returns>The entity instance</returns>
        /// <exception cref="UtnEmallDataAccessException">
        /// If a DbException occurs while accessing the database.
        /// </exception>
        public CustomerEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope)
        {
            // Build a key for internal scope object
            string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "Customer";

            if (scope != null)
            {
                // If scope contains the object it was already loaded,
                // return it to avoid circular references
                if (scope.ContainsKey(scopeKey))
                {
                    return((CustomerEntity)scope[scopeKey]);
                }
            }
            else
            {
                // If there isn't a current scope create one
                scope = new Dictionary <string, IEntity>();
            }

            CustomerEntity customer = null;

            // Check if the entity was already loaded by current data access object
            // and return it if that is the case

            if (inMemoryEntities.ContainsKey(id))
            {
                customer = inMemoryEntities[id];
                // Add current object to current load scope

                scope.Add(scopeKey, customer);
            }
            else
            {
                bool closeConnection = false;
                try
                {
                    // Open a new connection if it isn't on a transaction
                    if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0)
                    {
                        closeConnection = true;
                        dbConnection    = dataAccess.GetNewConnection();
                        dbConnection.Open();
                    }

                    string cmdText = "SELECT idCustomer, name, surname, address, phoneNumber, userName, password, birthday, howManyChildren, gender, civilState, timestamp FROM [Customer] WHERE idCustomer = @idCustomer";
                    // Create the command

                    SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction);
                    // Create the Id parameter for the query

                    SqlCeParameter parameter = dataAccess.GetNewDataParameter("@idCustomer", DbType.Int32);
                    parameter.Value = id;
                    sqlCommand.Parameters.Add(parameter);
                    // Use a DataReader to get data from db

                    IDataReader reader = sqlCommand.ExecuteReader();
                    customer = new CustomerEntity();

                    if (reader.Read())
                    {
                        // Load fields of entity
                        customer.Id = reader.GetInt32(0);

                        if (!reader.IsDBNull(1))
                        {
                            customer.Name = reader.GetString(1);
                        }
                        if (!reader.IsDBNull(2))
                        {
                            customer.Surname = reader.GetString(2);
                        }
                        if (!reader.IsDBNull(3))
                        {
                            customer.Address = reader.GetString(3);
                        }
                        if (!reader.IsDBNull(4))
                        {
                            customer.PhoneNumber = reader.GetString(4);
                        }
                        if (!reader.IsDBNull(5))
                        {
                            customer.UserName = reader.GetString(5);
                        }
                        if (!reader.IsDBNull(6))
                        {
                            customer.Password = reader.GetString(6);
                        }

                        customer.Birthday        = reader.GetDateTime(7);
                        customer.HowManyChildren = reader.GetInt32(8);
                        customer.Gender          = reader.GetInt32(9);
                        customer.CivilState      = reader.GetInt32(10);
                        // Add current object to the scope

                        scope.Add(scopeKey, customer);
                        // Add current object to cache of loaded entities

                        inMemoryEntities.Add(customer.Id, customer);
                        // Read the timestamp and set new and changed properties

                        customer.Timestamp = reader.GetDateTime(11);
                        customer.IsNew     = false;
                        customer.Changed   = false;
                        // Close the reader

                        reader.Close();
                        // Load related objects if required

                        if (loadRelation)
                        {
                            LoadRelationPreferences(customer, scope);
                            LoadRelationDeviceProfile(customer, scope);
                        }
                    }
                    else
                    {
                        reader.Close();
                    }
                }
                catch (DbException dbException)
                {
                    // Catch DBException and rethrow as custom exception
                    throw new UtnEmallDataAccessException(dbException.Message, dbException);
                }
                finally
                {
                    // Close connection if it was opened by ourself
                    if (closeConnection)
                    {
                        dbConnection.Close();
                    }
                }
            }
            // Return the loaded entity
            return(customer);
        }