private void FillSaveParameters(RegisterAssociationCategoriesEntity registerAssociationCategories, IDbCommand sqlCommand)
        {
            IDbDataParameter parameter;

            parameter = dataAccess.GetNewDataParameter("@idCategory", DbType.Int32);

            parameter.Value = registerAssociationCategories.IdCategory;
            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@idRegisterAssociation", DbType.Int32);

            parameter.Value = registerAssociationCategories.IdRegisterAssociation;
            sqlCommand.Parameters.Add(parameter);
        }
Пример #2
0
        /// <summary>
        /// Registra una asociación entre registros de tablas de modelos de datos y categorías.
        /// </summary>
        /// <param name="associations">Listado de asociaciones.</param>
        /// <param name="sessionId">Identificador de sesión.</param>
        /// <returns>True si todas las asociaciones se guardaron exitosamente.</returns>
        public bool SaveAssociations(Collection <RegisterAssociationData> associations, string sessionId)
        {
            if (associations == null)
            {
                throw new ArgumentNullException("associations", "Associations must have at least one RegisterAssociation.");
            }
            if (sessionId == null)
            {
                throw new ArgumentNullException("sessionId", "SessionId must not be null.");
            }
            if (associations.Count == 0)
            {
                throw new ArgumentException("Associations list must have at least one RegisterAssociation.", "associations");
            }

            RegisterAssociationEntity           RAEntity;
            RegisterAssociationCategoriesEntity RACEntity;
            RegisterAssociation RAClient = new UtnEmall.Server.BusinessLogic.RegisterAssociation();
            bool result = true;

            // Retorna la tienda del usuario actual
            StoreEntity userStore = SessionManager.Instance.StoreFromUserSession(sessionId);

            // Recorre el listado de asociaciones
            foreach (RegisterAssociationData registerAssociation in associations)
            {
                TableEntity table = ObtainTableEntity(registerAssociation.TableName, userStore, sessionId);
                RAEntity = new RegisterAssociationEntity();

                RAEntity.Table      = table;
                RAEntity.IdRegister = registerAssociation.RegisterId;
                RAEntity.RegisterAssociationCategories = new Collection <RegisterAssociationCategoriesEntity>();

                foreach (int categoryId in registerAssociation.CategoriesId)
                {
                    RACEntity                     = new RegisterAssociationCategoriesEntity();
                    RACEntity.IdCategory          = categoryId;
                    RACEntity.RegisterAssociation = RAEntity;

                    RAEntity.RegisterAssociationCategories.Add(RACEntity);
                }

                // Si el valor de retorno no es null, ha ocurrido un error.
                if (RAClient.Save(RAEntity, sessionId) != null)
                {
                    result = false;
                }
            }

            return(result);
        }
Пример #3
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 SaveRegisterAssociationCategoriesCollection(RegisterAssociationCategoriesDataAccess collectionDataAccess, RegisterAssociationEntity parent, Collection <RegisterAssociationCategoriesEntity> 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].RegisterAssociation = 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 idRegisterAssociationCategories FROM [RegisterAssociationCategories] WHERE idRegisterAssociation = @idRegisterAssociation AND idRegisterAssociationCategories NOT IN (" + idList + ")";

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

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

                IDataReader reader = sqlCommand.ExecuteReader();
                Collection <RegisterAssociationCategoriesEntity> objectsToDelete = new Collection <RegisterAssociationCategoriesEntity>();
                // 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)
                {
                    RegisterAssociationCategoriesEntity 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++)
                {
                    RegisterAssociationCategoriesEntity item = collection[i];
                    if (!item.Changed && !item.IsNew)
                    {
                        // Create the command
                        string     sql = "SELECT timestamp FROM [RegisterAssociationCategories] WHERE idRegisterAssociationCategories = @idRegisterAssociationCategories";
                        IDbCommand sqlCommandTimestamp = dataAccess.GetNewCommand(sql, dbConnection, dbTransaction);
                        // Set the command's parameters values

                        IDbDataParameter sqlParameterIdPreference = dataAccess.GetNewDataParameter("@idRegisterAssociationCategories", 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 load a RegisterAssociationCategoriesEntity 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 RegisterAssociationCategoriesEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope)
        {
            // Build a key for internal scope object
            string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "RegisterAssociationCategories";

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

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

                scope.Add(scopeKey, registerAssociationCategories);
            }
            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 idRegisterAssociationCategories, idCategory, idRegisterAssociation, timestamp FROM [RegisterAssociationCategories] WHERE idRegisterAssociationCategories = @idRegisterAssociationCategories";
                    // Create the command

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

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

                    IDataReader reader = sqlCommand.ExecuteReader();
                    registerAssociationCategories = new RegisterAssociationCategoriesEntity();

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

                        registerAssociationCategories.IdCategory            = reader.GetInt32(1);
                        registerAssociationCategories.IdRegisterAssociation = reader.GetInt32(2);
                        // Add current object to the scope

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

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

                        registerAssociationCategories.Timestamp = reader.GetDateTime(3);
                        registerAssociationCategories.IsNew     = false;
                        registerAssociationCategories.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(registerAssociationCategories);
        }
        /// <summary>
        /// Function to Delete a RegisterAssociationCategoriesEntity from database.
        /// </summary>
        /// <param name="registerAssociationCategories">RegisterAssociationCategoriesEntity 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="registerAssociationCategories"/> is not a <c>RegisterAssociationCategoriesEntity</c>.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// If an DbException occurs in the try block while accessing the database.
        /// </exception>
        public void Delete(RegisterAssociationCategoriesEntity registerAssociationCategories, Dictionary <string, IEntity> scope)
        {
            if (registerAssociationCategories == 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

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

                IDbDataParameter parameterID = dataAccess.GetNewDataParameter("@idRegisterAssociationCategories", DbType.Int32);
                parameterID.Value = registerAssociationCategories.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(registerAssociationCategories.Id);
                // Remove entity from current internal scope

                if (scope != null)
                {
                    string scopeKey = registerAssociationCategories.Id.ToString(NumberFormatInfo.InvariantInfo) + "RegisterAssociationCategories";
                    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>
 /// Function to Delete a RegisterAssociationCategoriesEntity from database.
 /// </summary>
 /// <param name="registerAssociationCategories">RegisterAssociationCategoriesEntity to delete</param>
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="registerAssociationCategories"/> is not a <c>RegisterAssociationCategoriesEntity</c>.
 /// </exception>
 /// <exception cref="UtnEmallDataAccessException">
 /// If an DbException occurs in the try block while accessing the database.
 /// </exception>
 public void Delete(RegisterAssociationCategoriesEntity registerAssociationCategories)
 {
     Delete(registerAssociationCategories, null);
 }
        /// <summary>
        /// Function to Save a RegisterAssociationCategoriesEntity in the database.
        /// </summary>
        /// <param name="registerAssociationCategories">RegisterAssociationCategoriesEntity 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="registerAssociationCategories"/> is not a <c>RegisterAssociationCategoriesEntity</c>.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// If an DbException occurs in the try block while accessing the database.
        /// </exception>
        public void Save(RegisterAssociationCategoriesEntity registerAssociationCategories, Dictionary <string, IEntity> scope)
        {
            if (registerAssociationCategories == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            // Create a unique key to identify the object in the internal scope
            string scopeKey = registerAssociationCategories.Id.ToString(NumberFormatInfo.InvariantInfo) + "RegisterAssociationCategories";

            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 (registerAssociationCategories.IsNew || !DataAccessConnection.ExistsEntity(registerAssociationCategories.Id, "RegisterAssociationCategories", "idRegisterAssociationCategories", dbConnection, dbTransaction))
                {
                    commandName = "SaveRegisterAssociationCategories";
                }
                else
                {
                    isUpdate    = true;
                    commandName = "UpdateRegisterAssociationCategories";
                }
                // 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("@idRegisterAssociationCategories", DbType.Int32);
                    parameter.Value = registerAssociationCategories.Id;
                    sqlCommand.Parameters.Add(parameter);
                }

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

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

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

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

                registerAssociationCategories.IsNew   = false;
                registerAssociationCategories.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>
 /// Function to Save a RegisterAssociationCategoriesEntity in the database.
 /// </summary>
 /// <param name="registerAssociationCategories">RegisterAssociationCategoriesEntity to save</param>
 /// <exception cref="ArgumentNullException">
 /// if <paramref name="registerAssociationCategories"/> is not a <c>RegisterAssociationCategoriesEntity</c>.
 /// </exception>
 /// <exception cref="UtnEmallDataAccessException">
 /// If an DbException occurs in the try block while accessing the database.
 /// </exception>
 public void Save(RegisterAssociationCategoriesEntity registerAssociationCategories)
 {
     Save(registerAssociationCategories, null);
 }