/// <summary>
        /// Función que guarda un ServiceEntity en la base de datos.
        /// </summary>
        /// <param name="service">ServiceEntity a guardar</param>
        /// <param name="scope">Estructura interna para evitar problemas con referencias circulares</param>
        /// <exception cref="ArgumentNullException">
        /// Si <paramref name="service"/> no es un <c>ServiceEntity</c>.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// Si una DbException ocurre cuando se accede a la base de datos
        /// </exception>
        public void Save(ServiceEntity service, Dictionary <string, IEntity> scope)
        {
            if (service == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            // Crear una clave unica para identificar el objeto dentro del scope interno
            string scopeKey = service.Id.ToString(NumberFormatInfo.InvariantInfo) + "Service";

            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 (service.IsNew || !DataAccessConnection.ExistsEntity(service.Id, "Service", "idService", dbConnection, dbTransaction))
                {
                    commandName = "INSERT INTO [Service] (idService, NAME, DESCRIPTION, WEBACCESS, RELATIVEPATHASSEMBLY, PATHASSEMBLYSERVER, ACTIVE, GLOBAL, IMAGE, WEBSITE, DEPLOYED, UPDATED, IDSTORE, STARTDATE, STOPDATE, [TIMESTAMP] ) VALUES( @idService,  @name,@description,@webAccess,@relativePathAssembly,@pathAssemblyServer,@active,@global,@image,@website,@deployed,@updated,@idStore,@startDate,@stopDate, GETDATE()); ";
                }
                else
                {
                    isUpdate    = true;
                    commandName = "UPDATE [Service] SET name = @name, description = @description, webAccess = @webAccess, relativePathAssembly = @relativePathAssembly, pathAssemblyServer = @pathAssemblyServer, active = @active, global = @global, image = @image, website = @website, deployed = @deployed, updated = @updated, idStore = @idStore, startDate = @startDate, stopDate = @stopDate , timestamp=GETDATE() WHERE idService = @idService";
                }
                // Se crea un command
                SqlCeCommand sqlCommand = dataAccess.GetNewCommand(commandName, dbConnection, dbTransaction);
                // Agregar los parametros del command .
                SqlCeParameter parameter;
                if (!isUpdate && service.Id == 0)
                {
                    service.Id = DataAccessConnection.GetNextId("idService", "Service", dbConnection, dbTransaction);
                }

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

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

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

                scope.Add(scopeKey, service);
                // Guarda las colecciones de objetos relacionados.
                if (service.ServiceCategory != null)
                {
                    this.SaveServiceCategoryCollection(new ServiceCategoryDataAccess(), service, service.ServiceCategory, service.IsNew, scope);
                }
                // 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

                service.IsNew   = false;
                service.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;
                }
            }
        }
Beispiel #2
0
        /// <summary>
        /// Función que guarda un CategoryEntity en la base de datos.
        /// </summary>
        /// <param name="category">CategoryEntity a guardar</param>
        /// <param name="scope">Estructura interna para evitar problemas con referencias circulares</param>
        /// <exception cref="ArgumentNullException">
        /// Si <paramref name="category"/> no es un <c>CategoryEntity</c>.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// Si una DbException ocurre cuando se accede a la base de datos
        /// </exception>
        public void Save(CategoryEntity category, Dictionary <string, IEntity> scope)
        {
            if (category == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            // Crear una clave unica para identificar el objeto dentro del scope interno
            string scopeKey = category.Id.ToString(NumberFormatInfo.InvariantInfo) + "Category";

            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 (category.IsNew || !DataAccessConnection.ExistsEntity(category.Id, "Category", "idCategory", dbConnection, dbTransaction))
                {
                    commandName = "INSERT INTO [Category] (idCategory, DESCRIPTION, NAME, IDPARENTCATEGORY, [TIMESTAMP] ) VALUES( @idCategory,  @description,@name,@idParentCategory, GETDATE()); ";
                }
                else
                {
                    isUpdate    = true;
                    commandName = "UPDATE [Category] SET description = @description, name = @name, idParentCategory = @idParentCategory , timestamp=GETDATE() WHERE idCategory = @idCategory";
                }
                // Se crea un command
                SqlCeCommand sqlCommand = dataAccess.GetNewCommand(commandName, dbConnection, dbTransaction);
                // Agregar los parametros del command .
                SqlCeParameter parameter;
                if (!isUpdate && category.Id == 0)
                {
                    category.Id = DataAccessConnection.GetNextId("idCategory", "Category", dbConnection, dbTransaction);
                }

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

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

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

                scope.Add(scopeKey, category);
                // Guarda las colecciones de objetos relacionados.
                if (category.Childs != null)
                {
                    this.SaveCategoryCollection(new CategoryDataAccess(), category, category.Childs, category.IsNew, scope);
                }
                // 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

                category.IsNew   = false;
                category.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;
                }
            }
        }
        /// <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;
                }
            }
        }
        /// <summary>
        /// Función que guarda un UserActionClientDataEntity en la base de datos.
        /// </summary>
        /// <param name="userActionClientData">UserActionClientDataEntity a guardar</param>
        /// <param name="scope">Estructura interna para evitar problemas con referencias circulares</param>
        /// <exception cref="ArgumentNullException">
        /// Si <paramref name="userActionClientData"/> no es un <c>UserActionClientDataEntity</c>.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// Si una DbException ocurre cuando se accede a la base de datos
        /// </exception>
        public void Save(UserActionClientDataEntity userActionClientData, Dictionary <string, IEntity> scope)
        {
            if (userActionClientData == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            // Crear una clave unica para identificar el objeto dentro del scope interno
            string scopeKey = userActionClientData.Id.ToString(NumberFormatInfo.InvariantInfo) + "UserActionClientData";

            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 (userActionClientData.IsNew || !DataAccessConnection.ExistsEntity(userActionClientData.Id, "UserActionClientData", "idUserActionClientData", dbConnection, dbTransaction))
                {
                    commandName = "INSERT INTO [UserActionClientData] (idUserActionClientData, ACTIONTYPE, START, STOP, IDTABLE, IDREGISTER, IDCOMPONENT, IDSERVICE, [TIMESTAMP] ) VALUES( @idUserActionClientData,  @actionType,@start,@stop,@idTable,@idRegister,@idComponent,@idService, GETDATE()); ";
                }
                else
                {
                    isUpdate    = true;
                    commandName = "UPDATE [UserActionClientData] SET actionType = @actionType, start = @start, stop = @stop, idTable = @idTable, idRegister = @idRegister, idComponent = @idComponent, idService = @idService , timestamp=GETDATE() WHERE idUserActionClientData = @idUserActionClientData";
                }
                // Se crea un command
                SqlCeCommand sqlCommand = dataAccess.GetNewCommand(commandName, dbConnection, dbTransaction);
                // Agregar los parametros del command .
                SqlCeParameter parameter;
                if (!isUpdate && userActionClientData.Id == 0)
                {
                    userActionClientData.Id = DataAccessConnection.GetNextId("idUserActionClientData", "UserActionClientData", dbConnection, dbTransaction);
                }

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

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

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

                scope.Add(scopeKey, userActionClientData);
                // 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

                userActionClientData.IsNew   = false;
                userActionClientData.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;
                }
            }
        }
        /// <summary>
        /// Función que guarda un StoreEntity en la base de datos.
        /// </summary>
        /// <param name="store">StoreEntity a guardar</param>
        /// <param name="scope">Estructura interna para evitar problemas con referencias circulares</param>
        /// <exception cref="ArgumentNullException">
        /// Si <paramref name="store"/> no es un <c>StoreEntity</c>.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// Si una DbException ocurre cuando se accede a la base de datos
        /// </exception>
        public void Save(StoreEntity store, Dictionary <string, IEntity> scope)
        {
            if (store == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            // Crear una clave unica para identificar el objeto dentro del scope interno
            string scopeKey = store.Id.ToString(NumberFormatInfo.InvariantInfo) + "Store";

            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 (store.IsNew || !DataAccessConnection.ExistsEntity(store.Id, "Store", "idStore", dbConnection, dbTransaction))
                {
                    commandName = "INSERT INTO [Store] (idStore, NAME, TELEPHONENUMBER, INTERNALPHONENUMBER, CONTACTNAME, OWNERNAME, EMAIL, WEBADDRESS, LOCALNUMBER, [TIMESTAMP] ) VALUES( @idStore,  @name,@telephoneNumber,@internalPhoneNumber,@contactName,@ownerName,@email,@webAddress,@localNumber, GETDATE()); ";
                }
                else
                {
                    isUpdate    = true;
                    commandName = "UPDATE [Store] SET name = @name, telephoneNumber = @telephoneNumber, internalPhoneNumber = @internalPhoneNumber, contactName = @contactName, ownerName = @ownerName, email = @email, webAddress = @webAddress, localNumber = @localNumber , timestamp=GETDATE() WHERE idStore = @idStore";
                }
                // Se crea un command
                SqlCeCommand sqlCommand = dataAccess.GetNewCommand(commandName, dbConnection, dbTransaction);
                // Agregar los parametros del command .
                SqlCeParameter parameter;
                if (!isUpdate && store.Id == 0)
                {
                    store.Id = DataAccessConnection.GetNextId("idStore", "Store", dbConnection, dbTransaction);
                }

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

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

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

                scope.Add(scopeKey, store);
                // Guarda las colecciones de objetos relacionados.
                if (store.StoreCategory != null)
                {
                    this.SaveStoreCategoryCollection(new StoreCategoryDataAccess(), store, store.StoreCategory, store.IsNew, scope);
                }
                // 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

                store.IsNew   = false;
                store.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;
                }
            }
        }
Beispiel #6
0
        /// <summary>
        /// Function to Save a CustomerEntity in the database.
        /// </summary>
        /// <param name="customer">CustomerEntity 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="customer"/> is not a <c>CustomerEntity</c>.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// If an DbException occurs in the try block while accessing the database.
        /// </exception>
        public void Save(CustomerEntity customer, Dictionary <string, IEntity> scope)
        {
            if (customer == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            // Create a unique key to identify the object in the internal scope
            string scopeKey = customer.Id.ToString(NumberFormatInfo.InvariantInfo) + "Customer";

            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 (customer.IsNew || !DataAccessConnection.ExistsEntity(customer.Id, "Customer", "idCustomer", dbConnection, dbTransaction))
                {
                    commandName = "INSERT INTO [Customer] (idCustomer, NAME, SURNAME, ADDRESS, PHONENUMBER, USERNAME, PASSWORD, BIRTHDAY, HOWMANYCHILDREN, GENDER, CIVILSTATE, [TIMESTAMP] ) VALUES( @idCustomer,  @name,@surname,@address,@phoneNumber,@userName,@password,@birthday,@howManyChildren,@gender,@civilState, GETDATE()); ";
                }
                else
                {
                    isUpdate    = true;
                    commandName = "UPDATE [Customer] SET name = @name, surname = @surname, address = @address, phoneNumber = @phoneNumber, userName = @userName, password = @password, birthday = @birthday, howManyChildren = @howManyChildren, gender = @gender, civilState = @civilState , timestamp=GETDATE() WHERE idCustomer = @idCustomer";
                }
                // Create a db command
                SqlCeCommand sqlCommand = dataAccess.GetNewCommand(commandName, dbConnection, dbTransaction);
                // Add parameters values to current command
                SqlCeParameter parameter;
                if (!isUpdate && customer.Id == 0)
                {
                    customer.Id = DataAccessConnection.GetNextId("idCustomer", "Customer", dbConnection, dbTransaction);
                }

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

                FillSaveParameters(customer, sqlCommand);
                // Execute the command
                sqlCommand.ExecuteNonQuery();

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

                scope.Add(scopeKey, customer);
                // Save collections of related objects to current entity
                if (customer.Preferences != null)
                {
                    this.SavePreferenceCollection(new PreferenceDataAccess(), customer, customer.Preferences, customer.IsNew, scope);
                }
                if (customer.DeviceProfile != null)
                {
                    this.SaveDeviceProfileCollection(new DeviceProfileDataAccess(), customer, customer.DeviceProfile, customer.IsNew, scope);
                }
                // Save objects related to current entity
                // Update
                // Close transaction if initiated by me
                if (!isGlobalTransaction)
                {
                    dbTransaction.Commit();
                }
                // Update new and changed flags

                customer.IsNew   = false;
                customer.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;
                }
            }
        }
Beispiel #7
0
        /// <summary>
        /// Función que guarda un PreferenceEntity en la base de datos.
        /// </summary>
        /// <param name="preference">PreferenceEntity a guardar</param>
        /// <param name="scope">Estructura interna para evitar problemas con referencias circulares</param>
        /// <exception cref="ArgumentNullException">
        /// Si <paramref name="preference"/> no es un <c>PreferenceEntity</c>.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// Si una DbException ocurre cuando se accede a la base de datos
        /// </exception>
        public void Save(PreferenceEntity preference, Dictionary <string, IEntity> scope)
        {
            if (preference == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            // Crear una clave unica para identificar el objeto dentro del scope interno
            string scopeKey = preference.Id.ToString(NumberFormatInfo.InvariantInfo) + "Preference";

            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 (preference.IsNew || !DataAccessConnection.ExistsEntity(preference.Id, "Preference", "idPreference", dbConnection, dbTransaction))
                {
                    commandName = "INSERT INTO [Preference] (idPreference, ACTIVE, LEVEL, IDCUSTOMER, IDCATEGORY, [TIMESTAMP] ) VALUES( @idPreference,  @active,@level,@idCustomer,@idCategory, GETDATE()); ";
                }
                else
                {
                    isUpdate    = true;
                    commandName = "UPDATE [Preference] SET active = @active, level = @level, idCustomer = @idCustomer, idCategory = @idCategory , timestamp=GETDATE() WHERE idPreference = @idPreference";
                }
                // Se crea un command
                SqlCeCommand sqlCommand = dataAccess.GetNewCommand(commandName, dbConnection, dbTransaction);
                // Agregar los parametros del command .
                SqlCeParameter parameter;
                if (!isUpdate && preference.Id == 0)
                {
                    preference.Id = DataAccessConnection.GetNextId("idPreference", "Preference", dbConnection, dbTransaction);
                }

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

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

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

                scope.Add(scopeKey, preference);
                // Guarda las colecciones de objetos relacionados.
                // Guardar objetos relacionados con la entidad actual
                if (preference.Category != null)
                {
                    CategoryDataAccess categoryDataAccess = new CategoryDataAccess();
                    categoryDataAccess.SetConnectionObjects(dbConnection, dbTransaction);
                    categoryDataAccess.Save(preference.Category, scope);
                }
                // Actualizar
                Update(preference);
                // Cierra la conexión si fue abierta en la función

                if (!isGlobalTransaction)
                {
                    dbTransaction.Commit();
                }
                // Actualizar los campos new y changed

                preference.IsNew   = false;
                preference.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;
                }
            }
        }