/// <summary> /// Function to Load the relation Category from database. /// </summary> /// <param name="preference">PreferenceEntity parent</param> /// <exception cref="ArgumentNullException"> /// if <paramref name="preference"/> is not a <c>PreferenceEntity</c>. /// </exception> public void LoadRelationCategory(PreferenceEntity preference, Dictionary <string, IEntity> scope) { if (preference == null) { throw new ArgumentException("The argument can't be null"); } bool closeConnection = false; try { // Create a new connection if needed if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0) { closeConnection = true; dbConnection = dataAccess.GetNewConnection(); dbConnection.Open(); } // Create a command string cmdText = "SELECT idCategory FROM [Preference] WHERE idPreference = @idPreference"; IDbCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); IDbDataParameter parameter = dataAccess.GetNewDataParameter("@idPreference", DbType.Int32); // Set command parameters values parameter.Value = preference.Id; sqlCommand.Parameters.Add(parameter); // Execute commands object idRelation = sqlCommand.ExecuteScalar(); if (idRelation != null && ((int)idRelation) > 0) { // Create data access objects and set connection objects CategoryDataAccess categoryDataAccess = new CategoryDataAccess(); categoryDataAccess.SetConnectionObjects(dbConnection, dbTransaction); // Load related object preference.Category = categoryDataAccess.Load(((int)idRelation), false, scope); } } catch (DbException dbException) { // Catch and rethrow as custom exception throw new UtnEmallDataAccessException(dbException.Message, dbException); } finally { // Close connection if initiated by me if (closeConnection) { dbConnection.Close(); } } }
/// <summary> /// Función que carga la relacion Category desde la base de datos /// </summary> /// <param name="preference">Padre: PreferenceEntity</param> /// <exception cref="ArgumentNullException"> /// Si <paramref name="preference"/> no es un <c>PreferenceEntity</c>. /// </exception> public void LoadRelationCategory(PreferenceEntity preference, Dictionary <string, IEntity> scope) { if (preference == null) { throw new ArgumentException("The argument can't be null"); } bool closeConnection = false; try { // Crea una nueva conexión si es necesario if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0) { closeConnection = true; dbConnection = dataAccess.GetNewConnection(); dbConnection.Open(); } // Crea un nuevo command string cmdText = "SELECT idCategory FROM [Preference] WHERE idPreference = @idPreference"; SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); SqlCeParameter parameter = dataAccess.GetNewDataParameter("@idPreference", DbType.Int32); // Establece los valores a los parametros del command parameter.Value = preference.Id; sqlCommand.Parameters.Add(parameter); // Execute commands object idRelation = sqlCommand.ExecuteScalar(); if (idRelation != null && ((int)idRelation) > 0) { // Create data access objects and set connection objects CategoryDataAccess categoryDataAccess = new CategoryDataAccess(); categoryDataAccess.SetConnectionObjects(dbConnection, dbTransaction); // Carga los objetos relacionados preference.Category = categoryDataAccess.Load(((int)idRelation), true, scope); } } catch (DbException dbException) { // Relanza una excepcion personalizada throw new UtnEmallDataAccessException(dbException.Message, dbException); } finally { // Cierra la conexión si fue inicializada if (closeConnection) { dbConnection.Close(); } } }
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); }
public static void AddNewPreferencesDueToNewCategory(CategoryEntity category) { // Add the preferences to all the clients. CustomerDataAccess customerDataAccess = new CustomerDataAccess(); PreferenceDataAccess preferenceDataAccess = new PreferenceDataAccess(); foreach (CustomerEntity customer in customerDataAccess.LoadAll(false)) { PreferenceEntity preference = new PreferenceEntity(); preference.Active = true; preference.Level = 0; preference.Category = category; preference.IdCustomer = customer.Id; preference.IsNew = true; preferenceDataAccess.Save(preference); } }
/// <summary> /// Metodo llamado cuando se preciona "Guardar". /// Actualiza las preferencias del cliente. /// </summary> /// <param name="sender"> /// El objeto que genero el evento /// </param> /// <param name="e"> /// Un objeto que contiene información sobre el evento /// </param> private void menuItemSave_Click(object sender, EventArgs e) { foreach (KeyValuePair <CheckBox, PreferenceEntity> keyvalue in list) { PreferenceEntity preference = keyvalue.Value; // Si la categoria se encuentra seleccinada marcar como activa en las preferencias del cliente if (keyvalue.Key.Checked) { preference.Active = true; } else { preference.Active = false; } } // Cerrar el formulario this.Close(); }
public static void AddNewPreferencesDueToNewCustomer(CustomerEntity customer) { // Add all the categories as preferences. CustomerDataAccess customerDataAccess = new CustomerDataAccess(); CategoryDataAccess categoryDataAccess = new CategoryDataAccess(); foreach (CategoryEntity category in categoryDataAccess.LoadAll(false)) { PreferenceEntity preference = new PreferenceEntity(); preference.Active = true; preference.Level = 0; preference.Category = category; preference.IdCustomer = customer.Id; preference.IsNew = true; customer.Preferences.Add(preference); } customerDataAccess.Save(customer); }
public ActionResult AddPreference(string name, int id, bool like) { try { LoginHelper.CheckAccess(Session); } catch (Exception) { return(RedirectToAction("Login", "Login")); } var handler = new PreferenceHandler(); int prefId = id; //new preference => add it to preferences table if (id == 0) { var entity = new PreferenceEntity { Name = name.First().ToString().ToUpper() + name.Substring(1) }; var prefResponse = handler.Add(entity); if (!prefResponse.CompletedRequest) { return(RedirectToAction("Index", "Error", new { errorMessage = prefResponse.ErrorMessage.Replace(' ', '-') })); } prefId = prefResponse.Entity.Id; } //add to user's preferences int userProfileId = (int)Session["userProfileId"]; var response = handler.AddForUser(prefId, userProfileId, like); if (!response.CompletedRequest) { return(RedirectToAction("Index", "Error", new { errorMessage = response.ErrorMessage.Replace(' ', '-') })); } return(Content(prefId.ToString())); }
private void FillSaveParameters(PreferenceEntity preference, IDbCommand sqlCommand) { IDbDataParameter parameter; parameter = dataAccess.GetNewDataParameter("@active", DbType.Boolean); parameter.Value = preference.Active; sqlCommand.Parameters.Add(parameter); parameter = dataAccess.GetNewDataParameter("@level", DbType.Decimal); parameter.Value = preference.Level; sqlCommand.Parameters.Add(parameter); parameter = dataAccess.GetNewDataParameter("@idCustomer", DbType.Int32); parameter.Value = preference.IdCustomer; sqlCommand.Parameters.Add(parameter); parameter = dataAccess.GetNewDataParameter("@idCategory", DbType.Int32); parameter.Value = preference.IdCategory; sqlCommand.Parameters.Add(parameter); }
public ActionResult Create(PreferencesModel model) { var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity; ViewBag.Name = userClaims?.FindFirst("name")?.Value; if (model.DietaryRestrictions == null) { model.DietaryRestrictions = new List <EdamamService.Health>(); } PreferenceEntity preferences = new PreferenceEntity(userClaims?.FindFirst(System.IdentityModel.Claims.ClaimTypes.Name)?.Value, userClaims?.FindFirst(System.IdentityModel.Claims.ClaimTypes.Name)?.Value) { dietPreference = model.Diet.ToString(), healthPreference = string.Join(",", model.DietaryRestrictions.Select(x => x.ToString())) }; TableActions.AddRow("PreferenceTable", (TableEntity)preferences); return(View("Index", model)); }
/// <summary> /// Función que actualiza un PreferenceEntity en la base de datos. /// </summary> /// <param name="preference">PreferenceEntity a actualizar</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> private void Update(PreferenceEntity preference) { if (preference == null) { throw new ArgumentException("The argument can't be null", "preference"); } // Construir un comando para actualizar string commandName = "UPDATE [Preference] SET active = @active, level = @level, idCustomer = @idCustomer, idCategory = @idCategory , timestamp=GETDATE() WHERE idPreference = @idPreference"; SqlCeCommand sqlCommand = dataAccess.GetNewCommand(commandName, dbConnection, dbTransaction); // Establece los parametros de actualización SqlCeParameter parameter = dataAccess.GetNewDataParameter("@idPreference", DbType.Int32); parameter.Value = preference.Id; sqlCommand.Parameters.Add(parameter); parameter = dataAccess.GetNewDataParameter("@active", DbType.Boolean); parameter.Value = preference.Active; sqlCommand.Parameters.Add(parameter); parameter = dataAccess.GetNewDataParameter("@level", DbType.Decimal); parameter.Value = preference.Level; sqlCommand.Parameters.Add(parameter); parameter = dataAccess.GetNewDataParameter("@idCustomer", DbType.Int32); parameter.Value = preference.IdCustomer; sqlCommand.Parameters.Add(parameter); parameter = dataAccess.GetNewDataParameter("@idCategory", DbType.Int32); parameter.Value = preference.IdCategory; sqlCommand.Parameters.Add(parameter); // Ejecuta la actualización sqlCommand.ExecuteNonQuery(); // Actualizar los campos new y changed preference.IsNew = false; preference.Changed = false; }
/// <summary> /// Function to Save a PreferenceEntity in the database. /// </summary> /// <param name="preference">PreferenceEntity 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="preference"/> is not a <c>PreferenceEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// If an DbException occurs in the try block while accessing the database. /// </exception> public void Save(PreferenceEntity preference, Dictionary <string, IEntity> scope) { if (preference == null) { throw new ArgumentException("The argument can't be null"); } // Create a unique key to identify the object in the internal scope string scopeKey = preference.Id.ToString(NumberFormatInfo.InvariantInfo) + "Preference"; 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 (preference.IsNew || !DataAccessConnection.ExistsEntity(preference.Id, "Preference", "idPreference", dbConnection, dbTransaction)) { commandName = "SavePreference"; } else { isUpdate = true; commandName = "UpdatePreference"; } // 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("@idPreference", DbType.Int32); parameter.Value = preference.Id; sqlCommand.Parameters.Add(parameter); } FillSaveParameters(preference, sqlCommand); // Execute the command if (isUpdate) { sqlCommand.ExecuteNonQuery(); } else { IDbDataParameter parameterIdOutput = dataAccess.GetNewDataParameter("@idPreference", DbType.Int32); parameterIdOutput.Direction = ParameterDirection.ReturnValue; sqlCommand.Parameters.Add(parameterIdOutput); sqlCommand.ExecuteNonQuery(); preference.Id = Convert.ToInt32(parameterIdOutput.Value, NumberFormatInfo.InvariantInfo); } scopeKey = preference.Id.ToString(NumberFormatInfo.InvariantInfo) + "Preference"; // Add entity to current internal scope scope.Add(scopeKey, preference); // 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 preference.IsNew = false; preference.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; } } }
/// <summary> /// Función para cargar un PreferenceEntity 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 PreferenceEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope) { // Crea una clave para el objeto de scope interno string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "Preference"; 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((PreferenceEntity)scope[scopeKey]); } } else { // Si no existe un scope, crear uno scope = new Dictionary <string, IEntity>(); } PreferenceEntity preference = null; // Chequear si la entidad fue ya cargada por el data access actual // y retornar si fue ya cargada if (inMemoryEntities.ContainsKey(id)) { preference = inMemoryEntities[id]; // Agregar el objeto actual al scope scope.Add(scopeKey, preference); } 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 idPreference, active, level, idCustomer, idCategory, timestamp FROM [Preference] WHERE idPreference = @idPreference"; // Crea el command SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); // Crear el parametro id para la consulta SqlCeParameter parameter = dataAccess.GetNewDataParameter("@idPreference", DbType.Int32); parameter.Value = id; sqlCommand.Parameters.Add(parameter); // Usar el datareader para cargar desde la base de datos IDataReader reader = sqlCommand.ExecuteReader(); preference = new PreferenceEntity(); if (reader.Read()) { // Cargar las filas de la entidad preference.Id = reader.GetInt32(0); preference.Active = reader.GetBoolean(1); preference.Level = Convert.ToDouble(reader.GetDecimal(2)); preference.IdCustomer = reader.GetInt32(3); preference.IdCategory = reader.GetInt32(4); // Agregar el objeto actual al scope scope.Add(scopeKey, preference); // Agregar el objeto a la cahce de entidades cargadas inMemoryEntities.Add(preference.Id, preference); // Lee el timestamp y establece las propiedades nuevo y cambiado preference.Timestamp = reader.GetDateTime(5); preference.IsNew = false; preference.Changed = false; // Cerrar el Reader reader.Close(); // Carga los objetos relacionadoss if required if (loadRelation) { LoadRelationCategory(preference, 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(preference); }
/// <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 SavePreferenceCollection(PreferenceDataAccess collectionDataAccess, CustomerEntity parent, Collection <PreferenceEntity> 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 idPreference FROM [Preference] WHERE idCustomer = @idCustomer AND idPreference 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 <PreferenceEntity> objectsToDelete = new Collection <PreferenceEntity>(); // 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) { PreferenceEntity 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++) { PreferenceEntity item = collection[i]; if (!item.Changed && !item.IsNew) { // Create the command string sql = "SELECT timestamp FROM [Preference] WHERE idPreference = @idPreference"; SqlCeCommand sqlCommandTimestamp = dataAccess.GetNewCommand(sql, dbConnection, dbTransaction); // Set the command's parameters values SqlCeParameter sqlParameterIdPreference = dataAccess.GetNewDataParameter("@idPreference", 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); } } } }
/// <summary> /// Function to Save a PreferenceEntity in the database. /// </summary> /// <param name="preference">PreferenceEntity to save</param> /// <exception cref="ArgumentNullException"> /// if <paramref name="preference"/> is not a <c>PreferenceEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// If an DbException occurs in the try block while accessing the database. /// </exception> public void Save(PreferenceEntity preference) { Save(preference, null); }
/// <summary> /// Function to load a PreferenceEntity 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 PreferenceEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope) { // Build a key for internal scope object string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "Preference"; if (scope != null) { // If scope contains the object it was already loaded, // return it to avoid circular references if (scope.ContainsKey(scopeKey)) { return((PreferenceEntity)scope[scopeKey]); } } else { // If there isn't a current scope create one scope = new Dictionary <string, IEntity>(); } PreferenceEntity preference = 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)) { preference = inMemoryEntities[id]; // Add current object to current load scope scope.Add(scopeKey, preference); } 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 idPreference, active, level, idCustomer, idCategory, timestamp FROM [Preference] WHERE idPreference = @idPreference"; // Create the command IDbCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); // Create the Id parameter for the query IDbDataParameter parameter = dataAccess.GetNewDataParameter("@idPreference", DbType.Int32); parameter.Value = id; sqlCommand.Parameters.Add(parameter); // Use a DataReader to get data from db IDataReader reader = sqlCommand.ExecuteReader(); preference = new PreferenceEntity(); if (reader.Read()) { // Load fields of entity preference.Id = reader.GetInt32(0); preference.Active = reader.GetBoolean(1); preference.Level = Convert.ToDouble(reader.GetDecimal(2)); preference.IdCustomer = reader.GetInt32(3); preference.IdCategory = reader.GetInt32(4); // Add current object to the scope scope.Add(scopeKey, preference); // Add current object to cache of loaded entities inMemoryEntities.Add(preference.Id, preference); // Read the timestamp and set new and changed properties preference.Timestamp = reader.GetDateTime(5); preference.IsNew = false; preference.Changed = false; // Close the reader reader.Close(); // Load related objects if required if (loadRelation) { LoadRelationCategory(preference, 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(preference); }
/// <summary> /// Function to Delete a PreferenceEntity from database. /// </summary> /// <param name="preference">PreferenceEntity 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="preference"/> is not a <c>PreferenceEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// If an DbException occurs in the try block while accessing the database. /// </exception> public void Delete(PreferenceEntity preference, Dictionary <string, IEntity> scope) { if (preference == 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 preference = this.Load(preference.Id, true); if (preference == null) { throw new UtnEmallDataAccessException("Error retrieving data while trying to delete."); } // Create a command for delete string cmdText = "DeletePreference"; IDbCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); sqlCommand.CommandType = CommandType.StoredProcedure; // Add values to parameters IDbDataParameter parameterID = dataAccess.GetNewDataParameter("@idPreference", DbType.Int32); parameterID.Value = preference.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(preference.Id); // Remove entity from current internal scope if (scope != null) { string scopeKey = preference.Id.ToString(NumberFormatInfo.InvariantInfo) + "Preference"; 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; } } }
/// <summary> /// Función que elimina un PreferenceEntity de la base de datos. /// </summary> /// <param name="preference">PreferenceEntity a eliminar</param> /// <param name="scope">Estructura interna para evitar problemas de referencia circular.</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 Delete(PreferenceEntity preference, Dictionary <string, IEntity> scope) { if (preference == 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. preference = this.Load(preference.Id, true); if (preference == null) { throw new UtnEmallDataAccessException("Error al recuperar datos al intentar eliminar."); } // Crea un nuevo command para eliminar string cmdText = "DELETE FROM [Preference] WHERE idPreference = @idPreference"; SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); // Agrega los valores de los parametros SqlCeParameter parameterID = dataAccess.GetNewDataParameter("@idPreference", DbType.Int32); parameterID.Value = preference.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(preference.Id); // Eliminamos la entidad del scope if (scope != null) { string scopeKey = preference.Id.ToString(NumberFormatInfo.InvariantInfo) + "Preference"; 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; } } }
/// <summary> /// Function to Delete a PreferenceEntity from database. /// </summary> /// <param name="preference">PreferenceEntity to delete</param> /// <exception cref="ArgumentNullException"> /// If <paramref name="preference"/> is not a <c>PreferenceEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// If an DbException occurs in the try block while accessing the database. /// </exception> public void Delete(PreferenceEntity preference) { Delete(preference, null); }
/// <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; } } }