/// <summary>
        /// Inicializa una nueva instancia de
        /// <c>StoreDataAccess</c>.
        /// Chequea si la tabla y los procedimientos almacenados
        /// ya existen en la base de datos, si no, los crea
        /// Establece las propiedades que permite realizar consultas
        /// llamando los metodos LoadWhere.
        /// </summary>
        public StoreDataAccess()
        {
            dataAccess = DataAccessConnection.Instance;
            if (!dbChecked)
            {
                DbChecked();
            }

            if (properties == null)
            {
                SetProperties();
            }

            inMemoryEntities = new Dictionary <int, StoreEntity>();
        }
        /// <summary>
        /// Inicializa una nueva instancia de
        /// <c>UserActionClientDataDataAccess</c>.
        /// Chequea si la tabla y los procedimientos almacenados
        /// ya existen en la base de datos, si no, los crea
        /// Establece las propiedades que permite realizar consultas
        /// llamando los metodos LoadWhere.
        /// </summary>
        public UserActionClientDataDataAccess()
        {
            dataAccess = DataAccessConnection.Instance;
            if (!dbChecked)
            {
                DbChecked();
            }

            if (properties == null)
            {
                SetProperties();
            }

            inMemoryEntities = new Dictionary <int, UserActionClientDataEntity>();
        }
예제 #3
0
        /// <summary>
        /// Function to check and create table and stored procedures for this class.
        /// </summary>
        private static void DbChecked()
        {
            if (dbChecked)
            {
                return;
            }
            string[] fieldsName = new string[] { "idCustomer", "name", "surname", "address", "phoneNumber", "userName", "password", "birthday", "howManyChildren", "gender", "civilState" };
            Type[]   fieldsType = new Type[] { typeof(int), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(System.DateTime), typeof(int), typeof(int), typeof(int) };

            bool existsTable = DataAccessConnection.DBCheckedTable("Customer");

            if (!existsTable)
            {
                DataAccessConnection.CreateTable("Customer", fieldsName, false, fieldsType);
            }
            dbChecked = true;
        }
        /// <summary>
        /// Función que controla y crea la tabla y los procedimientos almacenados para esta clase.
        /// </summary>
        private static void DbChecked()
        {
            if (dbChecked)
            {
                return;
            }
            string[] fieldsName = new string[] { "idLastSync", "entityName", "lastTimestamp" };
            Type[]   fieldsType = new Type[] { typeof(int), typeof(string), typeof(System.DateTime) };

            bool existsTable = DataAccessConnection.DBCheckedTable("LastSync");

            if (!existsTable)
            {
                DataAccessConnection.CreateTable("LastSync", fieldsName, false, fieldsType);
            }
            dbChecked = true;
        }
        /// <summary>
        /// Función que controla y crea la tabla y los procedimientos almacenados para esta clase.
        /// </summary>
        private static void DbChecked()
        {
            if (dbChecked)
            {
                return;
            }
            string[] fieldsName = new string[] { "idStore", "name", "telephoneNumber", "internalPhoneNumber", "contactName", "ownerName", "email", "webAddress", "localNumber" };
            Type[]   fieldsType = new Type[] { typeof(int), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string) };

            bool existsTable = DataAccessConnection.DBCheckedTable("Store");

            if (!existsTable)
            {
                DataAccessConnection.CreateTable("Store", fieldsName, false, fieldsType);
            }
            dbChecked = true;
        }
        /// <summary>
        /// Función que controla y crea la tabla y los procedimientos almacenados para esta clase.
        /// </summary>
        private static void DbChecked()
        {
            if (dbChecked)
            {
                return;
            }
            string[] fieldsName = new string[] { "idUserActionClientData", "actionType", "start", "stop", "idTable", "idRegister", "idComponent", "idService" };
            Type[]   fieldsType = new Type[] { typeof(int), typeof(int), typeof(System.DateTime), typeof(System.DateTime), typeof(int), typeof(int), typeof(int), typeof(int) };

            bool existsTable = DataAccessConnection.DBCheckedTable("UserActionClientData");

            if (!existsTable)
            {
                DataAccessConnection.CreateTable("UserActionClientData", fieldsName, false, fieldsType);
            }
            dbChecked = true;
        }
예제 #7
0
        /// <summary>
        /// Función que controla y crea la tabla y los procedimientos almacenados para esta clase.
        /// </summary>
        private static void DbChecked()
        {
            if (dbChecked)
            {
                return;
            }
            string[] fieldsName = new string[] { "idCategory", "description", "name", "idParentCategory" };
            Type[]   fieldsType = new Type[] { typeof(int), typeof(string), typeof(string), typeof(int) };

            bool existsTable = DataAccessConnection.DBCheckedTable("Category");

            if (!existsTable)
            {
                DataAccessConnection.CreateTable("Category", fieldsName, false, fieldsType);
            }
            dbChecked = true;
        }
예제 #8
0
        /// <summary>
        /// Función que controla y crea la tabla y los procedimientos almacenados para esta clase.
        /// </summary>
        private static void DbChecked()
        {
            if (dbChecked)
            {
                return;
            }
            string[] fieldsName = new string[] { "idPreference", "active", "level", "idCustomer", "idCategory" };
            Type[]   fieldsType = new Type[] { typeof(int), typeof(bool), typeof(double), typeof(int), typeof(int) };

            bool existsTable = DataAccessConnection.DBCheckedTable("Preference");

            if (!existsTable)
            {
                DataAccessConnection.CreateTable("Preference", fieldsName, false, fieldsType);
            }
            dbChecked = true;
        }
        /// <summary>
        /// Función que controla y crea la tabla y los procedimientos almacenados para esta clase.
        /// </summary>
        private static void DbChecked()
        {
            if (dbChecked)
            {
                return;
            }
            string[] fieldsName = new string[] { "idService", "name", "description", "webAccess", "relativePathAssembly", "pathAssemblyServer", "active", "global", "image", "website", "deployed", "updated", "idStore", "startDate", "stopDate" };
            Type[]   fieldsType = new Type[] { typeof(int), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(bool), typeof(bool), typeof(string), typeof(string), typeof(bool), typeof(bool), typeof(int), typeof(System.DateTime), typeof(System.DateTime) };

            bool existsTable = DataAccessConnection.DBCheckedTable("Service");

            if (!existsTable)
            {
                DataAccessConnection.CreateTable("Service", fieldsName, false, fieldsType);
            }
            dbChecked = true;
        }
        /// <summary>
        /// Función que controla y crea la tabla y los procedimientos almacenados para esta clase.
        /// </summary>
        private static void DbChecked()
        {
            if (dbChecked)
            {
                return;
            }
            string[] fieldsName = new string[] { "idDeviceProfile", "deviceType", "deviceModel", "macAddress", "windowsMobileVersion", "idCustomer" };
            Type[]   fieldsType = new Type[] { typeof(int), typeof(string), typeof(string), typeof(string), typeof(string), typeof(int) };

            bool existsTable = DataAccessConnection.DBCheckedTable("DeviceProfile");

            if (!existsTable)
            {
                DataAccessConnection.CreateTable("DeviceProfile", fieldsName, false, fieldsType);
            }
            dbChecked = true;
        }
예제 #11
0
        /// <summary>
        /// Obtiene el siguiente Id para una tabla
        /// </summary>
        /// <param name="nameId">Nombre de la clave primaria</param>
        /// <param name="tableName">Nombre de la tabla</param>
        /// <param name="connection">conexión a usar</param>
        /// <param name="transaction">transacción a usar</param>
        /// <returns>El siguiente id</returns>
        public static int GetNextId(string nameId, string tableName, SqlCeConnection connection, SqlCeTransaction transaction)
        {
            DataAccessConnection dataAccess = DataAccessConnection.Instance;

            string       cmdText = "SELECT (MAX(" + nameId + ")+1) FROM [" + tableName + "]";
            SqlCeCommand command = dataAccess.GetNewCommand(cmdText, connection, transaction);

            try
            {
                object temp = command.ExecuteScalar();
                if (temp is int)
                {
                    return((int)temp);
                }
                else
                {
                    return(1);
                }
            }
            catch (InvalidCastException)
            {
                return(1);
            }
        }
        /// <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;
                }
            }
        }
        /// <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;
                }
            }
        }
예제 #14
0
        /// <summary>
        /// Crea una nueva tabla con indices para claves foraneas
        /// </summary>
        /// <param name="table">Nombre de la tabla a crear</param>
        /// <param name="fieldsName">Nombres de los campos</param>
        /// <param name="fieldsType">Tipos de los campos, en el mismo orden que los nombres de campo</param>
        /// <param name="indexColumns">columnas a indexar</param>
        /// <returns>True si tiene éxito</returns>
        public static bool CreateTable(string table, string[] fieldsName, bool isIdIdentity, Type[] fieldsType, string[] indexColumns)
        {
            if (fieldsName.Length == 0)
            {
                throw new ArgumentException("");
            }
            if (fieldsType.Length == 0)
            {
                throw new ArgumentException("");
            }

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

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

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

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

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

            dbConnection.Open();

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

            command.ExecuteNonQuery();

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

            dbConnection.Close();

            return(true);
        }
예제 #15
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;
                }
            }
        }
예제 #16
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;
                }
            }
        }
예제 #17
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 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;
                }
            }
        }
예제 #19
0
        /// <summary>
        /// Function to Load a CustomerEntity from database.
        /// </summary>
        /// <param name="propertyName">A string with the name of the field or a
        /// constant from the class that represent that field</param>
        /// <param name="expValue">The value that will be inserted on the where
        /// clause of the sql query</param>
        /// <param name="loadRelation">If is true load the relations</param>
        /// <returns>A list containing all the entities that match the where clause</returns>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="propertyName"/> is null or empty.
        /// If <paramref name="propertyName"/> is not a property of CustomerEntity class.
        /// If <paramref name="expValue"/> is null.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// If an DbException occurs in the try block while accessing the database.
        /// </exception>
        public Collection <CustomerEntity> LoadWhere(string propertyName, object expValue, bool loadRelation, OperatorType operatorType)
        {
            if (String.IsNullOrEmpty(propertyName) || expValue == null)
            {
                throw new ArgumentException("The argument can not be null or be empty", "propertyName");
            }
            if (!properties.ContainsKey(propertyName))
            {
                throw new ArgumentException("The property " + propertyName + " is not a property of this entity", "propertyName");
            }
            Collection <CustomerEntity> customerList;

            bool closeConnection = false;

            try
            {
                // Open a new connection with a database if necessary
                if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0)
                {
                    closeConnection = true;
                    dbConnection    = dataAccess.GetNewConnection();
                    dbConnection.Open();
                }

                string op = DataAccessConnection.GetOperatorString(operatorType);
                // Build the query string

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

                SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction);
                // Add parameters values to the command

                SqlCeParameter parameter = dataAccess.GetNewDataParameter();
                parameter.ParameterName = "@expValue";
                Type parameterType = properties[propertyName];
                parameter.DbType = DataAccessConnection.GetParameterDBType(parameterType);

                parameter.Value = expValue;
                sqlCommand.Parameters.Add(parameter);
                // Create a DataReader

                IDataReader reader = sqlCommand.ExecuteReader();
                customerList = new Collection <CustomerEntity>();
                CustomerEntity customer;
                List <int>     listId = new List <int>();
                // Add list of Ids to a list
                while (reader.Read())
                {
                    listId.Add(reader.GetInt32(0));
                }
                // Close the reader

                reader.Close();
                // Load the entities

                foreach (int id in listId)
                {
                    customer = Load(id, loadRelation, null);
                    customerList.Add(customer);
                }
            }
            catch (DbException dbException)
            {
                // Catch DbException and rethrow as custom exception
                throw new UtnEmallDataAccessException(dbException.Message, dbException);
            }
            finally
            {
                // Close connection if it was opened by myself
                if (closeConnection)
                {
                    dbConnection.Close();
                }
            }
            return(customerList);
        }
예제 #20
0
        /// <summary>
        /// Función para cargar un CategoryEntity desde la base de datos
        /// </summary>
        /// <param name="propertyName">Un string con el nombre del campo o una constante de la clase que representa ese campo</param>
        /// <param name="expValue">El valor que será insertado en la clausula where</param>
        /// <param name="loadRelation">Si es true carga la relacion</param>
        /// <returns>Una lista que contiene todas las entidades que concuerdan con la clausula where</returns>
        /// <exception cref="ArgumentNullException">
        /// Si <paramref name="propertyName"/> es null or vacio.
        /// Si <paramref name="propertyName"/> no es una propiedad de la clase CategoryEntity.
        /// Si <paramref name="expValue"/> es null.
        /// </exception>
        /// <exception cref="UtnEmallDataAccessException">
        /// Si una DbException ocurre cuando se accede a la base de datos
        /// </exception>
        public Collection <CategoryEntity> LoadWhere(string propertyName, object expValue, bool loadRelation, OperatorType operatorType)
        {
            if (String.IsNullOrEmpty(propertyName) || expValue == null)
            {
                throw new ArgumentException("The argument can not be null or be empty", "propertyName");
            }
            if (!properties.ContainsKey(propertyName))
            {
                throw new ArgumentException("The property " + propertyName + " is not a property of this entity", "propertyName");
            }
            Collection <CategoryEntity> categoryList;

            bool closeConnection = false;

            try
            {
                // Abrir una nueva conexión con la base de datos si es necesario
                if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0)
                {
                    closeConnection = true;
                    dbConnection    = dataAccess.GetNewConnection();
                    dbConnection.Open();
                }

                string op = DataAccessConnection.GetOperatorString(operatorType);
                // Construir la consulta

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

                SqlCeCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction);
                // Agrega los parametros al command

                SqlCeParameter parameter = dataAccess.GetNewDataParameter();
                parameter.ParameterName = "@expValue";
                Type parameterType = properties[propertyName];
                parameter.DbType = DataAccessConnection.GetParameterDBType(parameterType);

                parameter.Value = expValue;
                sqlCommand.Parameters.Add(parameter);
                // Crea un datareader

                IDataReader reader = sqlCommand.ExecuteReader();
                categoryList = new Collection <CategoryEntity>();
                CategoryEntity category;
                List <int>     listId = new List <int>();
                // Agrega los id a una lista de ids
                while (reader.Read())
                {
                    listId.Add(reader.GetInt32(0));
                }
                // Cerrar el Reader

                reader.Close();
                // Carga las entidades

                foreach (int id in listId)
                {
                    category = Load(id, loadRelation, null);
                    categoryList.Add(category);
                }
            }
            catch (DbException dbException)
            {
                // Relanza la excepcion como una excepcion personalizada
                throw new UtnEmallDataAccessException(dbException.Message, dbException);
            }
            finally
            {
                // Cierra la conexión si fue abierta dentro de la Función
                if (closeConnection)
                {
                    dbConnection.Close();
                }
            }
            return(categoryList);
        }
        /// <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;
                }
            }
        }