コード例 #1
0
 /// <summary>
 /// Contructor.
 /// </summary>
 /// <param name="deviceProfile">
 /// the customer' device to edit
 /// </param>
 public DeviceProfileForm(DeviceProfileEntity deviceProfile)
 {
     if (deviceProfile == null)
     {
         this.Dispose();
         return;
     }
     else
     {
         deviceProfileCustomer = deviceProfile;
     }
     InitializeComponent();
 }
コード例 #2
0
        public CustomerEntity llenarPerfil()
        {
            Customer customerBusiness = new Customer();

            CustomerEntity customer = new CustomerEntity();

            PreferenceEntity preference = new PreferenceEntity();
            CategoryEntity   category   = new CategoryEntity();

            category.Description = "Sport";
            preference.Category  = category;
            preference.Active    = true;

            PreferenceEntity preference2 = new PreferenceEntity();
            CategoryEntity   category2   = new CategoryEntity();

            category2.Description = "Food";
            preference2.Category  = category2;
            preference2.Active    = true;

            customer.Preferences = new ArrayList();
            customer.Preferences.Add(preference);
            customer.Preferences.Add(preference2);

            DeviceProfileEntity device = new DeviceProfileEntity();

            device.DeviceType           = "Smartphone";
            device.DeviceModel          = "5.5";
            device.MacAddress           = "8F-6A-88-F0-AA-10";
            device.WindowsMobileVersion = "6.0";

            customer.Id          = 1;
            customer.Name        = "Javier";
            customer.Surname     = "Dall' Amore";
            customer.Phonenumber = "4871419";
            customer.Address     = "Facundo Quiroga 2525";
            customer.UserName    = "******";
            customer.Password    = "******";
            customer.IdMall      = 1;

            customer.DeviceProfile = device;

            customerBusiness.Delete(customer, "");
            customerBusiness.Save(customer, "");
            return(customer);
        }
コード例 #3
0
        private void FillSaveParameters(DeviceProfileEntity deviceProfile, SqlCeCommand sqlCommand)
        {
            SqlCeParameter parameter;

            parameter = dataAccess.GetNewDataParameter("@deviceType", DbType.String);

            parameter.Value = deviceProfile.DeviceType;
            if (String.IsNullOrEmpty(deviceProfile.DeviceType))
            {
                parameter.Value = DBNull.Value;
            }

            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@deviceModel", DbType.String);

            parameter.Value = deviceProfile.DeviceModel;
            if (String.IsNullOrEmpty(deviceProfile.DeviceModel))
            {
                parameter.Value = DBNull.Value;
            }

            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@macAddress", DbType.String);

            parameter.Value = deviceProfile.MacAddress;
            if (String.IsNullOrEmpty(deviceProfile.MacAddress))
            {
                parameter.Value = DBNull.Value;
            }

            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@windowsMobileVersion", DbType.String);

            parameter.Value = deviceProfile.WindowsMobileVersion;
            if (String.IsNullOrEmpty(deviceProfile.WindowsMobileVersion))
            {
                parameter.Value = DBNull.Value;
            }

            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@idCustomer", DbType.Int32);

            parameter.Value = deviceProfile.IdCustomer;
            sqlCommand.Parameters.Add(parameter);
        }
コード例 #4
0
        /// <summary>
        /// Función para cargar un DeviceProfileEntity 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 DeviceProfileEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope)
        {
            // Crea una clave para el objeto de scope interno
            string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "DeviceProfile";

            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((DeviceProfileEntity)scope[scopeKey]);
                }
            }
            else
            {
                // Si no existe un scope, crear uno
                scope = new Dictionary <string, IEntity>();
            }

            DeviceProfileEntity deviceProfile = null;

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

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

                scope.Add(scopeKey, deviceProfile);
            }
            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 idDeviceProfile, deviceType, deviceModel, macAddress, windowsMobileVersion, idCustomer, timestamp FROM [DeviceProfile] WHERE idDeviceProfile = @idDeviceProfile";
                    // Crea el command

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

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

                    IDataReader reader = sqlCommand.ExecuteReader();
                    deviceProfile = new DeviceProfileEntity();

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

                        if (!reader.IsDBNull(1))
                        {
                            deviceProfile.DeviceType = reader.GetString(1);
                        }
                        if (!reader.IsDBNull(2))
                        {
                            deviceProfile.DeviceModel = reader.GetString(2);
                        }
                        if (!reader.IsDBNull(3))
                        {
                            deviceProfile.MacAddress = reader.GetString(3);
                        }
                        if (!reader.IsDBNull(4))
                        {
                            deviceProfile.WindowsMobileVersion = reader.GetString(4);
                        }

                        deviceProfile.IdCustomer = reader.GetInt32(5);
                        // Agregar el objeto actual al scope

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

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

                        deviceProfile.Timestamp = reader.GetDateTime(6);
                        deviceProfile.IsNew     = false;
                        deviceProfile.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(deviceProfile);
        }
コード例 #5
0
        /// <summary>
        /// Función que elimina un DeviceProfileEntity de la base de datos.
        /// </summary>
        /// <param name="deviceProfile">DeviceProfileEntity a eliminar</param>
        /// <param name="scope">Estructura interna para evitar problemas de referencia circular.</param>
        /// <exception cref="ArgumentNullException">
        /// Si <paramref name="deviceProfile"/> no es un <c>DeviceProfileEntity</c>.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// Si una DbException ocurre cuando se accede a la base de datos
        /// </exception>
        public void Delete(DeviceProfileEntity deviceProfile, Dictionary <string, IEntity> scope)
        {
            if (deviceProfile == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            try
            {
                // Abrir una nueva conexión e inicializar una transacción si es necesario
                if (!isGlobalTransaction)
                {
                    dbConnection = dataAccess.GetNewConnection();
                    dbConnection.Open();
                    dbTransaction = dbConnection.BeginTransaction();
                }
                // Carga la entidad para garantizar eliminar todos los datos antiguos.

                deviceProfile = this.Load(deviceProfile.Id, true);
                if (deviceProfile == null)
                {
                    throw new UtnEmallDataAccessException("Error al recuperar datos al intentar eliminar.");
                }
                // Crea un nuevo command para eliminar
                string       cmdText    = "DELETE FROM [DeviceProfile] WHERE idDeviceProfile = @idDeviceProfile";
                SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction);
                // Agrega los valores de los parametros
                SqlCeParameter parameterID = dataAccess.GetNewDataParameter("@idDeviceProfile", DbType.Int32);
                parameterID.Value = deviceProfile.Id;
                sqlCommand.Parameters.Add(parameterID);
                // Ejecuta el comando

                sqlCommand.ExecuteNonQuery();
                // Elimina los objetos relacionados
                // Confirma la transacción si se inicio dentro de la función
                if (!isGlobalTransaction)
                {
                    dbTransaction.Commit();
                }
                // Eliminamos la entidad de la lista de entidades cargadas en memoria

                inMemoryEntities.Remove(deviceProfile.Id);
                // Eliminamos la entidad del scope

                if (scope != null)
                {
                    string scopeKey = deviceProfile.Id.ToString(NumberFormatInfo.InvariantInfo) + "DeviceProfile";
                    scope.Remove(scopeKey);
                }
            }
            catch (DbException dbException)
            {
                // Anula la transaccion
                if (!isGlobalTransaction)
                {
                    dbTransaction.Rollback();
                }
                // Relanza una excepcion personalizada
                throw new UtnEmallDataAccessException(dbException.Message, dbException);
            }
            finally
            {
                // Cierra la conexión si fue abierta dentro de la Función
                if (!isGlobalTransaction)
                {
                    dbConnection.Close();
                    dbConnection  = null;
                    dbTransaction = null;
                }
            }
        }
コード例 #6
0
 /// <summary>
 /// Función que elimina un DeviceProfileEntity de la base de datos.
 /// </summary>
 /// <param name="deviceProfile">DeviceProfileEntity a eliminar</param>
 /// <exception cref="ArgumentNullException">
 /// Si <paramref name="deviceProfile"/> no es un <c>DeviceProfileEntity</c>.
 /// </exception>
 /// <exception cref="UtnEmallDataAccessException">
 /// Si una DbException ocurre cuando se accede a la base de datos
 /// </exception>
 public void Delete(DeviceProfileEntity deviceProfile)
 {
     Delete(deviceProfile, null);
 }
コード例 #7
0
        /// <summary>
        /// Función que guarda un DeviceProfileEntity en la base de datos.
        /// </summary>
        /// <param name="deviceProfile">DeviceProfileEntity a guardar</param>
        /// <param name="scope">Estructura interna para evitar problemas con referencias circulares</param>
        /// <exception cref="ArgumentNullException">
        /// Si <paramref name="deviceProfile"/> no es un <c>DeviceProfileEntity</c>.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// Si una DbException ocurre cuando se accede a la base de datos
        /// </exception>
        public void Save(DeviceProfileEntity deviceProfile, Dictionary <string, IEntity> scope)
        {
            if (deviceProfile == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            // Crear una clave unica para identificar el objeto dentro del scope interno
            string scopeKey = deviceProfile.Id.ToString(NumberFormatInfo.InvariantInfo) + "DeviceProfile";

            if (scope != null)
            {
                // Si se encuentra dentro del scope lo retornamos
                if (scope.ContainsKey(scopeKey))
                {
                    return;
                }
            }
            else
            {
                // Crea un nuevo scope si este no fue enviado
                scope = new Dictionary <string, IEntity>();
            }

            try
            {
                // Crea una nueva conexion y una nueva transaccion si no hay una a nivel superior
                if (!isGlobalTransaction)
                {
                    dbConnection = dataAccess.GetNewConnection();
                    dbConnection.Open();
                    dbTransaction = dbConnection.BeginTransaction();
                }

                string commandName = "";
                bool   isUpdate    = false;
                // Verifica si se debe hacer una actualización o una inserción

                if (deviceProfile.IsNew || !DataAccessConnection.ExistsEntity(deviceProfile.Id, "DeviceProfile", "idDeviceProfile", dbConnection, dbTransaction))
                {
                    commandName = "INSERT INTO [DeviceProfile] (idDeviceProfile, DEVICETYPE, DEVICEMODEL, MACADDRESS, WINDOWSMOBILEVERSION, IDCUSTOMER, [TIMESTAMP] ) VALUES( @idDeviceProfile,  @deviceType,@deviceModel,@macAddress,@windowsMobileVersion,@idCustomer, GETDATE()); ";
                }
                else
                {
                    isUpdate    = true;
                    commandName = "UPDATE [DeviceProfile] SET deviceType = @deviceType, deviceModel = @deviceModel, macAddress = @macAddress, windowsMobileVersion = @windowsMobileVersion, idCustomer = @idCustomer , timestamp=GETDATE() WHERE idDeviceProfile = @idDeviceProfile";
                }
                // Se crea un command
                SqlCeCommand sqlCommand = dataAccess.GetNewCommand(commandName, dbConnection, dbTransaction);
                // Agregar los parametros del command .
                SqlCeParameter parameter;
                if (!isUpdate && deviceProfile.Id == 0)
                {
                    deviceProfile.Id = DataAccessConnection.GetNextId("idDeviceProfile", "DeviceProfile", dbConnection, dbTransaction);
                }

                parameter       = dataAccess.GetNewDataParameter("@idDeviceProfile", DbType.Int32);
                parameter.Value = deviceProfile.Id;
                sqlCommand.Parameters.Add(parameter);

                FillSaveParameters(deviceProfile, sqlCommand);
                // Ejecutar el command
                sqlCommand.ExecuteNonQuery();

                scopeKey = deviceProfile.Id.ToString(NumberFormatInfo.InvariantInfo) + "DeviceProfile";
                // Agregar la entidad al scope actual

                scope.Add(scopeKey, deviceProfile);
                // Guarda las colecciones de objetos relacionados.
                // Guardar objetos relacionados con la entidad actual
                // Actualizar
                // Cierra la conexión si fue abierta en la función
                if (!isGlobalTransaction)
                {
                    dbTransaction.Commit();
                }
                // Actualizar los campos new y changed

                deviceProfile.IsNew   = false;
                deviceProfile.Changed = false;
            }
            catch (DbException dbException)
            {
                // Anula la transaccion
                if (!isGlobalTransaction)
                {
                    dbTransaction.Rollback();
                }
                // Relanza una excepcion personalizada
                throw new UtnEmallDataAccessException(dbException.Message, dbException);
            }
            finally
            {
                // Cierra la conexión si fue inicializada
                if (!isGlobalTransaction)
                {
                    dbConnection.Close();
                    dbConnection  = null;
                    dbTransaction = null;
                }
            }
        }
コード例 #8
0
 /// <summary>
 /// Función que guarda un DeviceProfileEntity en la base de datos.
 /// </summary>
 /// <param name="deviceProfile">DeviceProfileEntity a guardar</param>
 /// <exception cref="ArgumentNullException">
 /// Si <paramref name="deviceProfile"/> no es un <c>DeviceProfileEntity</c>.
 /// </exception>
 /// <exception cref="UtnEmallDataAccessException">
 /// Si una DbException ocurre cuando se accede a la base de datos
 /// </exception>
 public void Save(DeviceProfileEntity deviceProfile)
 {
     Save(deviceProfile, null);
 }
コード例 #9
0
        /// <summary>
        /// Function to load a DeviceProfileEntity 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 DeviceProfileEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope)
        {
            // Build a key for internal scope object
            string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "DeviceProfile";

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

            DeviceProfileEntity deviceProfile = 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))
            {
                deviceProfile = inMemoryEntities[id];
                // Add current object to current load scope

                scope.Add(scopeKey, deviceProfile);
            }
            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 idDeviceProfile, deviceType, deviceModel, macAddress, windowsMobileVersion, idCustomer, timestamp FROM [DeviceProfile] WHERE idDeviceProfile = @idDeviceProfile";
                    // Create the command

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

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

                    IDataReader reader = sqlCommand.ExecuteReader();
                    deviceProfile = new DeviceProfileEntity();

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

                        if (!reader.IsDBNull(1))
                        {
                            deviceProfile.DeviceType = reader.GetString(1);
                        }
                        if (!reader.IsDBNull(2))
                        {
                            deviceProfile.DeviceModel = reader.GetString(2);
                        }
                        if (!reader.IsDBNull(3))
                        {
                            deviceProfile.MacAddress = reader.GetString(3);
                        }
                        if (!reader.IsDBNull(4))
                        {
                            deviceProfile.WindowsMobileVersion = reader.GetString(4);
                        }

                        deviceProfile.IdCustomer = reader.GetInt32(5);
                        // Add current object to the scope

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

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

                        deviceProfile.Timestamp = reader.GetDateTime(6);
                        deviceProfile.IsNew     = false;
                        deviceProfile.Changed   = false;
                        // Close the reader

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

                        if (loadRelation)
                        {
                        }
                    }
                    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(deviceProfile);
        }
コード例 #10
0
        /// <summary>
        /// Function to Delete a DeviceProfileEntity from database.
        /// </summary>
        /// <param name="deviceProfile">DeviceProfileEntity to delete</param>
        /// <param name="scope">Internal structure to avoid circular reference locks. Must provide an instance while calling from other data access object.</param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="deviceProfile"/> is not a <c>DeviceProfileEntity</c>.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// If an DbException occurs in the try block while accessing the database.
        /// </exception>
        public void Delete(DeviceProfileEntity deviceProfile, Dictionary <string, IEntity> scope)
        {
            if (deviceProfile == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            try
            {
                // Open connection and initialize a transaction if needed
                if (!isGlobalTransaction)
                {
                    dbConnection = dataAccess.GetNewConnection();
                    dbConnection.Open();
                    dbTransaction = dbConnection.BeginTransaction();
                }
                // Reload the entity to ensure deletion of older data

                deviceProfile = this.Load(deviceProfile.Id, true);
                if (deviceProfile == null)
                {
                    throw new UtnEmallDataAccessException("Error retrieving data while trying to delete.");
                }
                // Create a command for delete
                string     cmdText    = "DeleteDeviceProfile";
                IDbCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction);
                sqlCommand.CommandType = CommandType.StoredProcedure;
                // Add values to parameters

                IDbDataParameter parameterID = dataAccess.GetNewDataParameter("@idDeviceProfile", DbType.Int32);
                parameterID.Value = deviceProfile.Id;
                sqlCommand.Parameters.Add(parameterID);
                // Execute the command

                sqlCommand.ExecuteNonQuery();
                // Delete related objects
                // Commit transaction if is mine
                if (!isGlobalTransaction)
                {
                    dbTransaction.Commit();
                }
                // Remove entity from loaded objects

                inMemoryEntities.Remove(deviceProfile.Id);
                // Remove entity from current internal scope

                if (scope != null)
                {
                    string scopeKey = deviceProfile.Id.ToString(NumberFormatInfo.InvariantInfo) + "DeviceProfile";
                    scope.Remove(scopeKey);
                }
            }
            catch (DbException dbException)
            {
                // Rollback transaction
                if (!isGlobalTransaction)
                {
                    dbTransaction.Rollback();
                }
                // Rethrow as custom exception
                throw new UtnEmallDataAccessException(dbException.Message, dbException);
            }
            finally
            {
                // Close connection if it was initiated by this instance
                if (!isGlobalTransaction)
                {
                    dbConnection.Close();
                    dbConnection  = null;
                    dbTransaction = null;
                }
            }
        }
コード例 #11
0
        /// <summary>
        /// Function to Save a DeviceProfileEntity in the database.
        /// </summary>
        /// <param name="deviceProfile">DeviceProfileEntity to save</param>
        /// <param name="scope">Interna structure to avoid circular reference locks. Provide an instance when calling from other data access object.</param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="deviceProfile"/> is not a <c>DeviceProfileEntity</c>.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// If an DbException occurs in the try block while accessing the database.
        /// </exception>
        public void Save(DeviceProfileEntity deviceProfile, Dictionary <string, IEntity> scope)
        {
            if (deviceProfile == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            // Create a unique key to identify the object in the internal scope
            string scopeKey = deviceProfile.Id.ToString(NumberFormatInfo.InvariantInfo) + "DeviceProfile";

            if (scope != null)
            {
                // If it's on the scope return it, don't save again
                if (scope.ContainsKey(scopeKey))
                {
                    return;
                }
            }
            else
            {
                // Create a new scope if it's not provided
                scope = new Dictionary <string, IEntity>();
            }

            try
            {
                // Open a DbConnection and a new transaction if it isn't on a higher level one
                if (!isGlobalTransaction)
                {
                    dbConnection = dataAccess.GetNewConnection();
                    dbConnection.Open();
                    dbTransaction = dbConnection.BeginTransaction();
                }

                string commandName = "";
                bool   isUpdate    = false;
                // Check if it is an insert or update command

                if (deviceProfile.IsNew || !DataAccessConnection.ExistsEntity(deviceProfile.Id, "DeviceProfile", "idDeviceProfile", dbConnection, dbTransaction))
                {
                    commandName = "SaveDeviceProfile";
                }
                else
                {
                    isUpdate    = true;
                    commandName = "UpdateDeviceProfile";
                }
                // Create a db command
                IDbCommand sqlCommand = dataAccess.GetNewCommand(commandName, dbConnection, dbTransaction);
                sqlCommand.CommandType = CommandType.StoredProcedure;
                // Add parameters values to current command

                IDbDataParameter parameter;
                if (isUpdate)
                {
                    parameter       = dataAccess.GetNewDataParameter("@idDeviceProfile", DbType.Int32);
                    parameter.Value = deviceProfile.Id;
                    sqlCommand.Parameters.Add(parameter);
                }

                FillSaveParameters(deviceProfile, sqlCommand);
                // Execute the command
                if (isUpdate)
                {
                    sqlCommand.ExecuteNonQuery();
                }
                else
                {
                    IDbDataParameter parameterIdOutput = dataAccess.GetNewDataParameter("@idDeviceProfile", DbType.Int32);
                    parameterIdOutput.Direction = ParameterDirection.ReturnValue;
                    sqlCommand.Parameters.Add(parameterIdOutput);

                    sqlCommand.ExecuteNonQuery();
                    deviceProfile.Id = Convert.ToInt32(parameterIdOutput.Value, NumberFormatInfo.InvariantInfo);
                }

                scopeKey = deviceProfile.Id.ToString(NumberFormatInfo.InvariantInfo) + "DeviceProfile";
                // Add entity to current internal scope

                scope.Add(scopeKey, deviceProfile);
                // Save collections of related objects to current entity
                // Save objects related to current entity
                // Update
                // Close transaction if initiated by me
                if (!isGlobalTransaction)
                {
                    dbTransaction.Commit();
                }
                // Update new and changed flags

                deviceProfile.IsNew   = false;
                deviceProfile.Changed = false;
            }
            catch (DbException dbException)
            {
                // Rollback transaction
                if (!isGlobalTransaction)
                {
                    dbTransaction.Rollback();
                }
                // Rethrow as custom exception
                throw new UtnEmallDataAccessException(dbException.Message, dbException);
            }
            finally
            {
                // Close connection if initiated by me
                if (!isGlobalTransaction)
                {
                    dbConnection.Close();
                    dbConnection  = null;
                    dbTransaction = null;
                }
            }
        }
コード例 #12
0
        /// <summary>
        /// Updates the database to reflect the current state of the list.
        /// </summary>
        /// <param name="collectionDataAccess">the IDataAccess of the relation</param>
        /// <param name="parent">the parent of the object</param>
        /// <param name="collection">a collection of items</param>
        /// <param name="isNewParent">if the parent is a new object</param>
        /// <param name="scope">internal data structure to aviod problems with circular referencies on entities</param>
        /// <exception cref="UtnEmallDataAccessException">
        /// If an DbException occurs in the try block while accessing the database.
        /// </exception>
        private void SaveDeviceProfileCollection(DeviceProfileDataAccess collectionDataAccess, CustomerEntity parent, Collection <DeviceProfileEntity> collection, bool isNewParent, Dictionary <string, IEntity> scope)
        {
            if (collection == null)
            {
                return;
            }
            // Set connection objects on collection data access
            collectionDataAccess.SetConnectionObjects(dbConnection, dbTransaction);
            // Set the child/parent relation

            for (int i = 0; i < collection.Count; i++)
            {
                bool changed = collection[i].Changed;
                collection[i].Customer = parent;
                collection[i].Changed  = changed;
            }
            // If the parent is new save all childs, else check diferencies with db

            if (isNewParent)
            {
                for (int i = 0; i < collection.Count; i++)
                {
                    collectionDataAccess.Save(collection[i], scope);
                }
            }
            else
            {
                // Check the childs that are not part of the parent any more
                string idList = "0";
                if (collection.Count > 0)
                {
                    idList = "" + collection[0].Id;
                }

                for (int i = 1; i < collection.Count; i++)
                {
                    idList += ", " + collection[i].Id;
                }
                // Returns the ids that doesn't exists in the current collection

                string command = "SELECT idDeviceProfile FROM [DeviceProfile] WHERE idCustomer = @idCustomer AND idDeviceProfile NOT IN (" + idList + ")";

                SqlCeCommand sqlCommand = dataAccess.GetNewCommand(command, dbConnection, dbTransaction);

                SqlCeParameter sqlParameterId = dataAccess.GetNewDataParameter("@idCustomer", DbType.Int32);
                sqlParameterId.Value = parent.Id;
                sqlCommand.Parameters.Add(sqlParameterId);

                IDataReader reader = sqlCommand.ExecuteReader();
                Collection <DeviceProfileEntity> objectsToDelete = new Collection <DeviceProfileEntity>();
                // Insert Ids on a list

                List <int> listId = new List <int>();
                while (reader.Read())
                {
                    listId.Add(reader.GetInt32(0));
                }

                reader.Close();
                // Load items to be removed

                foreach (int id in listId)
                {
                    DeviceProfileEntity entityToDelete = collectionDataAccess.Load(id, scope);
                    objectsToDelete.Add(entityToDelete);
                }
                // Have to do this because the reader must be closed before
                // deletion of entities

                for (int i = 0; i < objectsToDelete.Count; i++)
                {
                    collectionDataAccess.Delete(objectsToDelete[i], scope);
                }

                System.DateTime timestamp;
                // Check all the properties of the collection items
                // to see if they have changed (timestamp)

                for (int i = 0; i < collection.Count; i++)
                {
                    DeviceProfileEntity item = collection[i];
                    if (!item.Changed && !item.IsNew)
                    {
                        // Create the command
                        string       sql = "SELECT timestamp FROM [DeviceProfile] WHERE idDeviceProfile = @idDeviceProfile";
                        SqlCeCommand sqlCommandTimestamp = dataAccess.GetNewCommand(sql, dbConnection, dbTransaction);
                        // Set the command's parameters values

                        SqlCeParameter sqlParameterIdPreference = dataAccess.GetNewDataParameter("@idDeviceProfile", DbType.Int32);
                        sqlParameterIdPreference.Value = item.Id;
                        sqlCommandTimestamp.Parameters.Add(sqlParameterIdPreference);

                        timestamp = ((System.DateTime)sqlCommandTimestamp.ExecuteScalar());
                        if (item.Timestamp != timestamp)
                        {
                            item.Changed = true;
                        }
                    }
                    // Save the item if it changed or is new

                    if (item.Changed || item.IsNew)
                    {
                        collectionDataAccess.Save(item);
                    }
                }
            }
        }