/// <summary>
        /// Store or update user action entity in table storage.
        /// </summary>
        /// <param name="userAction">Represents user action entity used for storage and retrieval.</param>
        /// <returns>that represents user action entity is saved or updated.</returns>
        public Task UpsertUserActionAsync(UserActionEntity userAction)
        {
            userAction.PartitionKey = PartitionKey;
            userAction.RowKey       = userAction.UserActionId;

            return(this.StoreOrUpdateFeedbackEntityAsync(userAction));
        }
        /// <summary>
        /// Function to delete a UserActionEntity from database.
        /// </summary>
        /// <param name="userActionEntity">UserActionEntity to delete</param>
        /// <param name="session">User's session identifier.</param>
        /// <returns>null if the UserActionEntity was deleted successfully, the same UserActionEntity otherwise</returns>
        /// <exception cref="ArgumentNullException">
        /// if <paramref name="userActionEntity"/> is null.
        /// </exception>
        /// <exception cref="UtnEmallBusinessLogicException">
        /// If an UtnEmallDataAccessException occurs in DataModel.
        /// </exception>
        public UserActionEntity Delete(UserActionEntity userActionEntity, string session)
        {
            bool permited = ValidationService.Instance.ValidatePermission(session, "delete", "UserAction");

            if (!permited)
            {
                ExceptionDetail detail = new ExceptionDetail(new UtnEmall.Server.BusinessLogic.UtnEmallPermissionException("The user hasn't permissions to delete an entity"));
                throw new FaultException <ExceptionDetail>(detail);
            }

            if (userActionEntity == null)
            {
                throw new ArgumentException("The argument can not be null or be empty");
            }
            try
            {
                // Delete userActionEntity using data access object
                useractionDataAccess.Delete(userActionEntity);
                return(null);
            }
            catch (UtnEmallDataAccessException utnEmallDataAccessException)
            {
                throw new UtnEmall.Server.BusinessLogic.UtnEmallBusinessLogicException(utnEmallDataAccessException.Message, utnEmallDataAccessException);
            }
        }
        void loadOperation_UserActionCompleted(object sender, EventArgs e)
        {
            LoadOperation loadOperation = sender as LoadOperation;

            foreach (ProductManager.Web.Model.user_action user_action in loadOperation.Entities)
            {
                UserActionEntity userActionEntity = new UserActionEntity();
                userActionEntity.UserAction = user_action;
                userActionEntity.Update();
                ActionAndUserActionEntity actionAndUserActionEntity;
                if (ActionAndUserActionEntityDictionary.TryGetValue(userActionEntity.ActionID, out actionAndUserActionEntity))
                {
                    actionAndUserActionEntity.UserActionEntity = userActionEntity;
                }
            }

            RootActionAndUserActionEntity.ChildList.Clear();
            foreach (KeyValuePair <int, ActionAndUserActionEntity> actionAndUserActionEntityPair in ActionAndUserActionEntityDictionary)
            {
                actionAndUserActionEntityPair.Value.CurrentSelectUserEntity = SelectUserEntity;
                int supperActionID = actionAndUserActionEntityPair.Value.ActionEntity.SupperActionID;
                if (supperActionID == 0)
                {
                    RootActionAndUserActionEntity.ChildList.Add(actionAndUserActionEntityPair.Value);
                }
            }
            UpdateChanged("RootActionAndUserActionEntity");

            IsBusy = false;
        }
        /// <summary>
        /// Function to save a UserActionEntity to the database.
        /// </summary>
        /// <param name="userActionEntity">UserActionEntity to save</param>
        /// <param name="session">User's session identifier.</param>
        /// <returns>null if the UserActionEntity was saved successfully, the same UserActionEntity otherwise</returns>
        /// <exception cref="ArgumentNullException">
        /// if <paramref name="userActionEntity"/> is null.
        /// </exception>
        /// <exception cref="UtnEmallBusinessLogicException">
        /// If an UtnEmallDataAccessException occurs in DataModel.
        /// </exception>
        public UserActionEntity Save(UserActionEntity userActionEntity, string session)
        {
            bool permited = ValidationService.Instance.ValidatePermission(session, "save", "UserAction");

            if (!permited)
            {
                ExceptionDetail detail = new ExceptionDetail(new UtnEmall.Server.BusinessLogic.UtnEmallPermissionException("The user hasn't permissions to save an entity"));
                throw new FaultException <ExceptionDetail>(detail);
            }

            if (!Validate(userActionEntity))
            {
                return(userActionEntity);
            }
            try
            {
                // Save userActionEntity using data access object
                useractionDataAccess.Save(userActionEntity);
                return(null);
            }
            catch (UtnEmallDataAccessException utnEmallDataAccessException)
            {
                throw new UtnEmall.Server.BusinessLogic.UtnEmallBusinessLogicException(utnEmallDataAccessException.Message, utnEmallDataAccessException);
            }
        }
        /// <summary>
        /// Store or update user action entity in table storage.
        /// </summary>
        /// <param name="entity">Represents user action entity used for storage and retrieval.</param>
        /// <returns><see cref="Task"/> that represents configuration entity is saved or updated.</returns>
        private async Task <TableResult> StoreOrUpdateFeedbackEntityAsync(UserActionEntity entity)
        {
            await this.EnsureInitializedAsync().ConfigureAwait(false);

            TableOperation addOrUpdateOperation = TableOperation.InsertOrReplace(entity);

            return(await this.userActionCloudTable.ExecuteAsync(addOrUpdateOperation).ConfigureAwait(false));
        }
        private static bool TransformAndSave(UserActionClientDataEntity userActionClientData, string sessionId)
        {
            UserAction       businessUAClient = new UserAction();
            UserActionEntity action           = new UserActionEntity();

            action.ActionType  = userActionClientData.ActionType;
            action.Customer    = SessionManager.Instance.GetCustomerFromSession(sessionId);
            action.IdComponent = userActionClientData.IdComponent;
            action.IdRegister  = userActionClientData.IdRegister;
            action.IdService   = userActionClientData.IdService;
            action.IdTable     = userActionClientData.IdTable;
            action.Start       = userActionClientData.Start;
            action.Stop        = userActionClientData.Stop;
            action.Timestamp   = userActionClientData.Timestamp;

            return(businessUAClient.Save(action, sessionId) == null);
        }
        /// <summary>
        /// Function to validate a UserActionEntity before it's saved.
        /// </summary>
        /// <param name="userActionEntity">UserActionEntity to validate</param>
        /// <param name="session">User's session identifier.</param>
        /// <returns>null if the UserActionEntity was deleted successfully, the same UserActionEntity otherwise</returns>
        /// <exception cref="ArgumentNullException">
        /// if <paramref name="userActionEntity"/> is null.
        /// </exception>
        /// <exception cref="UtnEmallBusinessLogicException">
        /// If an UtnEmallDataAccessException occurs in DataModel.
        /// </exception>
        public bool Validate(UserActionEntity userAction)
        {
            bool result = true;

            if (userAction == null)
            {
                throw new ArgumentException("The argument can not be null or be empty");
            }
            // Check entity data
            if (userAction.ActionType < 0)
            {
                userAction.Errors.Add(new Error("ActionType", "ActionType", "El tipo de acción no puede ser negativo"));
                result = false;
            }
            if (userAction.Start == null)
            {
                userAction.Errors.Add(new Error("Start", "Start", "El inicio no puede ser nulo"));
                result = false;
            }

            if (userAction.Stop < userAction.Start)
            {
                userAction.Errors.Add(new Error("Stop", "Stop", "La fecha de finalización no puede ser menor a la fecha de inicio"));
                result = false;
            }
            if (userAction.Stop == null)
            {
                userAction.Errors.Add(new Error("Stop", "Stop", "La fecha de finalización no puede ser nula"));
                result = false;
            }
            // Rules::PropertyGreaterThanZero(IdTable, "IdTable can't be negative");
            // Rules::PropertyGreaterThanZero(IdRegister, "IdRegister can't be negative");
            // Rules::PropertyGreaterThanZero(IdComponent, "IdComponent can't be negative");

            if (userAction.IdService < 0)
            {
                userAction.Errors.Add(new Error("IdService", "IdService", "El id de servicio no puede ser negativo"));
                result = false;
            }
            return(result);
        }
        private void FillSaveParameters(UserActionEntity userAction, IDbCommand sqlCommand)
        {
            IDbDataParameter parameter;

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

            parameter.Value = userAction.ActionType;
            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@start", DbType.DateTime);

            parameter.Value = userAction.Start;
            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@stop", DbType.DateTime);

            parameter.Value = userAction.Stop;
            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@idTable", DbType.Int32);

            parameter.Value = userAction.IdTable;
            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@idRegister", DbType.Int32);

            parameter.Value = userAction.IdRegister;
            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@idComponent", DbType.Int32);

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

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

            parameter.Value = userAction.IdCustomer;
            sqlCommand.Parameters.Add(parameter);
        }
        /// <summary>
        /// Function to load a UserActionEntity 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 UserActionEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope)
        {
            // Build a key for internal scope object
            string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "UserAction";

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

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

                scope.Add(scopeKey, userAction);
            }
            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 idUserAction, actionType, start, stop, idTable, idRegister, idComponent, idService, idCustomer, timestamp FROM [UserAction] WHERE idUserAction = @idUserAction";
                    // Create the command

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

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

                    IDataReader reader = sqlCommand.ExecuteReader();
                    userAction = new UserActionEntity();

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

                        userAction.ActionType  = reader.GetInt32(1);
                        userAction.Start       = reader.GetDateTime(2);
                        userAction.Stop        = reader.GetDateTime(3);
                        userAction.IdTable     = reader.GetInt32(4);
                        userAction.IdRegister  = reader.GetInt32(5);
                        userAction.IdComponent = reader.GetInt32(6);
                        userAction.IdService   = reader.GetInt32(7);
                        userAction.IdCustomer  = reader.GetInt32(8);
                        // Add current object to the scope

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

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

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

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

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

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

            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 (userAction.IsNew || !DataAccessConnection.ExistsEntity(userAction.Id, "UserAction", "idUserAction", dbConnection, dbTransaction))
                {
                    commandName = "SaveUserAction";
                }
                else
                {
                    isUpdate    = true;
                    commandName = "UpdateUserAction";
                }
                // 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("@idUserAction", DbType.Int32);
                    parameter.Value = userAction.Id;
                    sqlCommand.Parameters.Add(parameter);
                }

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

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

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

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

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