//----------------------------------------------------------
        public override CResultAErreur BeforeSave(CContexteSauvegardeObjetsDonnees contexte, IDataAdapter adapter, DataRowState etatsAPrendreEnCompte)
        {
            CResultAErreur result = base.BeforeSave(contexte, adapter, etatsAPrendreEnCompte);

            if (!result)
            {
                return(result);
            }
            if (IdVersionDeTravail == null || (etatsAPrendreEnCompte & DataRowState.Added) != DataRowState.Added)
            {
                return(result);
            }

            //Si on affecte un champ dans une version, il faut qu'il soit affecté dans le référentiel,
            //sinon, on n'a pas d'id original pour le CRelationElementAChamp_ChampCustom
            DataTable table = contexte.ContexteDonnee.Tables[GetNomTable()];

            if (table == null)
            {
                return(result);
            }

            Dictionary <DataRow, DataRow> mapRowToRowOriginale = new Dictionary <DataRow, DataRow>();

            ArrayList lstRows = new ArrayList(table.Rows);

            foreach (DataRow row in lstRows)
            {
                if (row.RowState == DataRowState.Added && row[CSc2iDataConst.c_champIdVersion] != DBNull.Value)
                {
                    if (row[CSc2iDataConst.c_champOriginalId] == DBNull.Value)
                    {
                        //Le champ n'a pas de valeur dans le référentiel, lui affecte la valeur
                        //par défault, sauf si l'élément parent n'appartient pas au référentiel,
                        //il faut trouver à quelle version appartient l'élément parent
                        int?nIdVersionCreationDuParent           = null;
                        CRelationElementAChamp_ChampCustom rel   = (CRelationElementAChamp_ChampCustom)contexte.ContexteDonnee.GetNewObjetForRow(row);
                        CObjetDonneeAIdNumerique           objet = (CObjetDonneeAIdNumerique)rel.ElementAChamps;
                        nIdVersionCreationDuParent = (int?)objet.Row[CSc2iDataConst.c_champIdVersion, true];
                        if ((int)row[CSc2iDataConst.c_champIdVersion] != nIdVersionCreationDuParent)
                        {
                            CRelationElementAChamp_ChampCustom newRel = (CRelationElementAChamp_ChampCustom)Activator.CreateInstance(GetTypeObjets(), contexte.ContexteDonnee);
                            newRel.CreateNewInCurrentContexte();
                            newRel.ElementAChamps             = rel.ElementAChamps;
                            newRel.ChampCustom                = rel.ChampCustom;
                            newRel.Valeur                     = rel.ChampCustom.ValeurParDefaut;
                            newRel.IdVersionDatabase          = nIdVersionCreationDuParent;
                            mapRowToRowOriginale[rel.Row.Row] = newRel.Row.Row;
                        }
                    }
                }
            }
            //Stocke le mapRow dans le contexte, pour s'en resservir après update
            contexte.ContexteDonnee.ExtendedProperties[GetType().ToString() + "_MAPORG"] = mapRowToRowOriginale;
            return(result);
        }
        //-------------------------------------------------------------------
        public override CResultAErreur VerifieDonnees(CObjetDonnee objet)
        {
            CResultAErreur result = CResultAErreur.True;

            try
            {
                CRelationElementAChamp_ChampCustom relation = (CRelationElementAChamp_ChampCustom)objet;
                result = VerifieDonneesRelation(relation);
            }
            catch (Exception e)
            {
                result.EmpileErreur(new CErreurException(e));
            }
            return(result);
        }
        //-------------------------------------------------------------------
        public static CResultAErreur VerifieDonneesRelation(CRelationElementAChamp_ChampCustom relation)
        {
            CResultAErreur result = CResultAErreur.True;

            if (relation.ChampCustom == null)
            {
                result.EmpileErreur(I.T("The field cannot be null|136"));
            }
            if (!result)
            {
                return(result);
            }
            result = relation.ChampCustom.IsCorrectValue(relation.Valeur);
            if (!result)
            {
                result.EmpileErreur(I.T("The field value '@1' is incorrect|137", relation.ChampCustom.Nom));
            }
            return(result);
        }
示例#4
0
        public static CResultAErreur DoTraitementExterneAvantSauvegarde(CContexteDonnee contexte, Hashtable tableData)
        {
            CResultAErreur result = CResultAErreur.True;
            Type           tp;

            ArrayList lst = new ArrayList(contexte.Tables);

            foreach (DataTable table in lst)
            {
                tp = null;
                ArrayList listeChampsDate = (ArrayList)m_tableChampsDate[table.TableName];
                #region récupération des champs date
                if (listeChampsDate == null)
                {
                    listeChampsDate = new ArrayList();
                    //Premier passage, cherche les champs date
                    foreach (DataColumn col in table.Columns)
                    {
                        if (col.DataType == typeof(DateTime) ||
                            col.DataType == typeof(CDateTimeEx) ||
                            col.DataType == typeof(DateTime?))
                        {
                            listeChampsDate.Add(col.ColumnName);
                        }
                    }
                    m_tableChampsDate[table.TableName] = listeChampsDate;
                }
                #endregion

                if (listeChampsDate.Count > 0 && table.PrimaryKey.Length == 1)
                {
                    Hashtable tablesQuiOntChange = new Hashtable();
                    //NomChamp->Méthode set associée
                    Hashtable tableChampToMethode = new Hashtable();
                    string    strCle  = table.PrimaryKey[0].ColumnName;
                    ArrayList lstRows = new ArrayList(table.Rows);

                    if (tp == null)
                    {
                        tp = CContexteDonnee.GetTypeForTable(table.TableName);
                    }

                    //Travaille par paquets de 500
                    for (int nRowLot = 0; nRowLot < lstRows.Count; nRowLot += 500)
                    {
                        int           nMin = Math.Min(lstRows.Count, nRowLot + 500);
                        StringBuilder bl   = new StringBuilder();
                        for (int nRow = nRowLot; nRow < nMin; nRow++)
                        {
                            DataRow rowTest = (DataRow)lstRows[nRow];
                            if (rowTest.RowState == DataRowState.Modified)
                            {
                                bl.Append(rowTest[strCle]);
                                bl.Append(",");
                            }
                        }
                        string strIds = bl.ToString();
                        if (strIds.Length > 0)
                        {
                            Type typeMainElementAChamp = null;
                            if (typeof(CRelationElementAChamp_ChampCustom).IsAssignableFrom(tp))
                            {
                                CRelationElementAChamp_ChampCustom relation = (CRelationElementAChamp_ChampCustom)Activator.CreateInstance(tp, new object[] { contexte });
                                typeMainElementAChamp = relation.GetTypeElementAChamps();
                            }
                            strIds = strIds.Substring(0, strIds.Length - 1);
                            CFiltreData filtrePrinc = new CFiltreData(
                                CSynchronismeDonnees.c_champIdSource + " in (" + strIds + ") and " +
                                CSynchronismeDonnees.c_champTypeSource + "=@1",
                                typeMainElementAChamp == null?tp.ToString():typeMainElementAChamp.ToString());
                            CListeObjetsDonnees listeSynchro = new CListeObjetsDonnees(contexte, typeof(CSynchronismeDonnees), filtrePrinc);
                            listeSynchro.AssureLectureFaite();
                            listeSynchro.InterditLectureInDB = true;

                            CFiltreData filtreChercheMesSynchros = new CFiltreData(
                                CSynchronismeDonnees.c_champIdSource + "=@1", 0);

                            CFiltreData filtreChercheMesSynchrosChamp = new CFiltreData(
                                CSynchronismeDonnees.c_champIdSource + "=@1 and " +
                                CSynchronismeDonnees.c_champChampSource + "=@2",
                                0, "");

                            if (listeSynchro.Count > 0)
                            {
                                foreach (DataRow row in lstRows)
                                {
                                    if (row.RowState == DataRowState.Modified)
                                    {
                                        int nCleElement = (int)row[strCle];
                                        filtreChercheMesSynchros.Parametres[0] = nCleElement;
                                        listeSynchro.Filtre = filtreChercheMesSynchros;
                                        if (listeSynchro.Count > 0)
                                        {
                                            foreach (string strChamp in listeChampsDate)
                                            {
                                                if (row[strChamp, DataRowVersion.Original] != DBNull.Value &&
                                                    row[strChamp, DataRowVersion.Current] != DBNull.Value)
                                                {
                                                    string   strIdChampSynchronisme = strChamp;
                                                    DateTime dtOrg, dtNew;
                                                    dtOrg = (DateTime)row[strChamp, DataRowVersion.Original];
                                                    dtNew = (DateTime)row[strChamp, DataRowVersion.Current];
                                                    if (!dtNew.Equals(dtOrg))
                                                    {
                                                        //La colonne a change. Cherche tous les synchronismes liés à cet élément


                                                        //Si c'est un champ custom, on cherche un synchro sur le type
                                                        //contenant le champ custom
                                                        if (typeof(CRelationElementAChamp_ChampCustom).IsAssignableFrom(tp))
                                                        {
                                                            CRelationElementAChamp_ChampCustom relation = (CRelationElementAChamp_ChampCustom)contexte.GetNewObjetForRow(row);
                                                            strIdChampSynchronisme = CSynchronismeDonnees.c_idChampCustom + row[CChampCustom.c_champId];
                                                            nCleElement            = relation.ElementAChamps.Id;
                                                        }
                                                        if (tp != null && tp.IsSubclassOf(typeof(CObjetDonneeAIdNumerique)))
                                                        {
                                                            filtreChercheMesSynchrosChamp.Parametres[0] = nCleElement;
                                                            filtreChercheMesSynchrosChamp.Parametres[1] = strIdChampSynchronisme;
                                                            listeSynchro.Filtre = filtreChercheMesSynchrosChamp;
                                                            if (listeSynchro.Count > 0)
                                                            {
                                                                TimeSpan sp = (DateTime)row[strChamp, DataRowVersion.Current] -
                                                                              (DateTime)row[strChamp, DataRowVersion.Original];
                                                                foreach (CSynchronismeDonnees synchro in listeSynchro)
                                                                {
                                                                    CObjetDonneeAIdNumerique objetDest = synchro.ObjetDest;
                                                                    if (objetDest != null)
                                                                    {
                                                                        string strChampDest = synchro.ChampDest;
                                                                        //La donnée n'est synchronisée que si elle est
                                                                        //égale à sa valeur d'origine
                                                                        if (synchro.ChampDest.IndexOf(CSynchronismeDonnees.c_idChampCustom) == 0)
                                                                        {
                                                                            //C'est un champ custom.
                                                                            if (objetDest is IElementAChamps)
                                                                            {
                                                                                CListeObjetsDonnees listeRels = ((IElementAChamps)objetDest).RelationsChampsCustom;
                                                                                int nIdChamp = Int32.Parse(synchro.ChampDest.Substring(
                                                                                                               CSynchronismeDonnees.c_idChampCustom.Length));
                                                                                listeRels.Filtre = new CFiltreData(CChampCustom.c_champId + "=@1",
                                                                                                                   nIdChamp);
                                                                                if (listeRels.Count != 0)
                                                                                {
                                                                                    objetDest    = (CObjetDonneeAIdNumerique)listeRels[0];
                                                                                    strChampDest = CRelationElementAChamp_ChampCustom.c_champValeurDate;
                                                                                }
                                                                                else
                                                                                {
                                                                                    objetDest = null;
                                                                                }
                                                                            }
                                                                            else
                                                                            {
                                                                                objetDest = null;
                                                                            }
                                                                        }
                                                                        if (objetDest != null && objetDest.Row[strChampDest] != DBNull.Value)
                                                                        {
                                                                            object valeurOld      = null;
                                                                            object valeurCourante = objetDest.Row[strChampDest, DataRowVersion.Current];
                                                                            if (objetDest.Row.HasVersion(DataRowVersion.Original))
                                                                            {
                                                                                valeurOld = objetDest.Row[strChampDest, DataRowVersion.Original];
                                                                            }
                                                                            if (objetDest.Row.RowState != DataRowState.Deleted &&
                                                                                (objetDest.Row.RowState != DataRowState.Modified ||
                                                                                 valeurCourante.Equals(valeurOld)))
                                                                            {
                                                                                MethodInfo method = (MethodInfo)tableChampToMethode[strChampDest];
                                                                                if (method == null)
                                                                                ///Cherche la méthode associée au champ
                                                                                {
                                                                                    CStructureTable structure = CStructureTable.GetStructure(objetDest.GetType());
                                                                                    foreach (CInfoChampTable champ in structure.Champs)
                                                                                    {
                                                                                        if (champ.NomChamp == strChampDest)
                                                                                        {
                                                                                            PropertyInfo prop = objetDest.GetType().GetProperty(champ.Propriete);
                                                                                            if (prop != null)
                                                                                            {
                                                                                                method = prop.GetSetMethod(true);
                                                                                                tableChampToMethode[strChampDest] = method;
                                                                                            }
                                                                                            break;
                                                                                        }
                                                                                    }
                                                                                }
                                                                                DateTime dt = (DateTime)objetDest.Row[strChampDest];
                                                                                dt = dt.Add(sp);
                                                                                if (method == null)
                                                                                {
                                                                                    objetDest.Row[strChampDest] = dt;
                                                                                }
                                                                                else
                                                                                {
                                                                                    method.Invoke(objetDest, new object[] { dt });
                                                                                }
                                                                                tablesQuiOntChange[objetDest.GetNomTable()] = true;
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    foreach (string strNomTable in tablesQuiOntChange.Keys)
                    {
                        result += contexte.GetTableLoader(strNomTable).TraitementAvantSauvegarde(contexte);
                        if (!result)
                        {
                            break;
                        }
                    }
                }
            }
            return(result);
        }
        /// <summary>
        /// /////////////////////////////////////////////////////////////////////////////////
        /// </summary>
        /// <param name="table"></param>
        /// <param name="result"></param>
        ///
        private static CResultAErreur TraitementAvantSauvegardeExterne(CContexteDonnee contexte, Hashtable tableData)
        {
            CResultAErreur result = CResultAErreur.True;

            ///Stef 22/07/08 : l'appel à shouldDeclenche peut
            ///nécessiter GetValeurChamp (si conditions sur des champs). Or, si un élément n'a pas
            ///de valeur pour un champ, l'appli va aller chercher la valeur par défaut de ce
            ///champ, si le champ n'est pas chargé, l'appli va le lire. Comme on est souvent
            ///dans un contexte sans gestion par tables complètes, on est mal, parce que
            ///ça va génerer une requête par champ.
            ///Donc, on lit tous les champs custom avant de commencer
            CListeObjetsDonnees listeChamps = new CListeObjetsDonnees(contexte, typeof(CChampCustom));

            listeChamps.PreserveChanges = true;            //Pour ne pas modifier les champs modifiés
            listeChamps.AssureLectureFaite();

            DateTime dt = DateTime.Now;
            CTraitementApresSauvegarde traitement = new CTraitementApresSauvegarde( );

            ArrayList lstTables = CContexteDonnee.GetTablesOrderInsert(contexte);

            //Pour empêcher de regarder deux fois les évenements d'un même objet
            //Type->Dictionnaire des ids vus
            Dictionary <Type, Dictionary <int, bool> > elementsVus = new Dictionary <Type, Dictionary <int, bool> >();

            DataRowChangeEventHandler handlerRedo = new DataRowChangeEventHandler(table_RowChanged);

            Dictionary <string, Dictionary <int, bool> > listeElementsARepasser = null;

            if (!m_listeElementsARepasser.TryGetValue(contexte, out listeElementsARepasser))
            {
                listeElementsARepasser             = new Dictionary <string, Dictionary <int, bool> >();
                m_listeElementsARepasser[contexte] = listeElementsARepasser;
            }

            bool bFirstPasse     = true;
            int  nLimiteurPasses = 0;

            while ((bFirstPasse | listeElementsARepasser.Count > 0) && nLimiteurPasses < 5)
            {
                nLimiteurPasses++;

                foreach (DataTable table in lstTables)
                {
                    if (table.Rows.Count > 0 && table.PrimaryKey.Length == 1)
                    {
                        string strChampCle = table.PrimaryKey[0].ColumnName;

                        Type tpObjets = CContexteDonnee.GetTypeForTable(table.TableName);
                        if (!typeof(CObjetDonneeAIdNumerique).IsAssignableFrom(tpObjets))
                        {
                            continue;
                        }

                        Type typeOriginal = tpObjets;

                        //Lors de la modif de champs custom, l'élement parent n'est pas forcement modifié
                        //Mais le champ peut l'être
                        if (tpObjets.IsSubclassOf(typeof(CRelationElementAChamp_ChampCustom)))
                        {
                            int  nLigne = 0;
                            bool bGoOut = false;
                            while (table.Rows.Count > nLigne && !bGoOut)
                            {
                                if (table.Rows[nLigne].RowState != DataRowState.Deleted)
                                {
                                    CRelationElementAChamp_ChampCustom rel = (CRelationElementAChamp_ChampCustom)contexte.GetNewObjetForRow(table.Rows[nLigne]);
                                    tpObjets    = rel.ElementAChamps.GetType();
                                    strChampCle = ((CObjetDonnee)rel.ElementAChamps).GetChampsId()[0];
                                    bGoOut      = true;
                                }
                                nLigne++;
                            }
                        }

                        //Les objets qui n'ont pas de relationTypeId ne peuvent pas avoir d'évenements
                        if (tpObjets.GetCustomAttributes(typeof(NoRelationTypeIdAttribute), true).Length > 0)
                        {
                            continue;
                        }

                        ArrayList lstEvenements = GetListeEvenementsAutoSur(tpObjets, contexte.IdVersionDeTravail);

                        //Id des éléments modifiés
                        List <int> listeIdsElementsAVerifierHandlers = new List <int>();
                        string     strPrimaryKey = "";
                        if (table.PrimaryKey.Length == 1 &&
                            table.PrimaryKey[0].DataType == typeof(int))
                        {
                            strPrimaryKey = table.PrimaryKey[0].ColumnName;
                        }

                        Dictionary <int, bool> tableIdsVues = null;
                        if (!elementsVus.TryGetValue(tpObjets, out tableIdsVues))
                        {
                            tableIdsVues          = new Dictionary <int, bool>();
                            elementsVus[tpObjets] = tableIdsVues;
                        }

                        Dictionary <int, bool> listeARepasserPourTable = null;
                        if (!listeElementsARepasser.TryGetValue(table.TableName, out listeARepasserPourTable))
                        {
                            listeARepasserPourTable = null;
                        }

                        List <CObjetDonnee> lstObjetsAvecEvenementsSpecifiques = new List <CObjetDonnee>();

                        //Stef 16/11/2012 :
                        //Si c'est un élément à champs, il est consideré comme modifié
                        //si un de ses champs custom est modifiés
                        //Ca a été fait parce que les handlers d'évenement n'étaient
                        //Pas pris en compte sur modif de champ custom
                        //On n'enlève pas pour autant l'ancienne méthode qui consiste
                        //à considérer l'élément modifié losrqu'on passe sur la table des
                        //valeurs de champs custom
                        if (typeof(IObjetDonneeAChamps).IsAssignableFrom(typeOriginal) && table.Rows.Count > 0)
                        {
                            //Regarde s'il y a des relations
                            IObjetDonneeAChamps objAChamp = contexte.GetNewObjetForRow(table.Rows[0]) as IObjetDonneeAChamps;
                            string strTableChamps         = objAChamp.GetNomTableRelationToChamps();
                            //Trouve la relation à la table
                            DataTable tableChamps = contexte.Tables[strTableChamps];
                            if (tableChamps != null)//Si la table champs n'est pas là, c'est
                            //qu'elle n'a pas été modifiée !! c'est logique çà
                            {
                                DataRelation rel = null;
                                foreach (DataRelation relTest in tableChamps.ParentRelations)
                                {
                                    if (relTest.ParentTable.TableName == table.TableName)
                                    {
                                        rel = relTest;
                                        break;
                                    }
                                }
                                if (rel != null)//On peut vérifier !
                                {
                                    foreach (DataRow row in new ArrayList(table.Rows))
                                    {
                                        if (row.RowState == DataRowState.Unchanged)//sinon, ce n'est pas la peine
                                        {
                                            DataRow[] rowsChamps = row.GetChildRows(rel);
                                            foreach (DataRow rowChamp in rowsChamps)
                                            {
                                                if (rowChamp.RowState != DataRowState.Unchanged)
                                                {
                                                    //Aloue l'objet pour s'assurer que la ligne est bien pleine
                                                    CObjetDonnee objTmp = contexte.GetNewObjetForRow(row);
                                                    objTmp.AssureData();
                                                    row.SetModified();
                                                    string strOldContexte = (string)row[CObjetDonnee.c_champContexteModification];
                                                    if (strOldContexte.Length == 0)
                                                    {
                                                        row[CObjetDonnee.c_champContexteModification] = rowChamp[CObjetDonnee.c_champContexteModification,
                                                                                                                 rowChamp.RowState == DataRowState.Deleted ? DataRowVersion.Original : DataRowVersion.Current] as string;
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        foreach (DataRow row in new ArrayList(table.Rows))
                        {
                            CObjetDonneeAIdNumerique objet = null;
                            if (lstEvenements.Count > 0)
                            {
                                if (row.RowState == DataRowState.Added ||
                                    row.RowState == DataRowState.Modified ||
                                    row.RowState == DataRowState.Deleted)
                                {
                                    objet = (CObjetDonneeAIdNumerique)((CContexteDonnee)table.DataSet).GetNewObjetForRow(row);
                                    if (objet.Row.RowState == DataRowState.Deleted)
                                    {
                                        objet.VersionToReturn = DataRowVersion.Original;
                                    }
                                    if (objet.Row.RowState != DataRowState.Deleted && EvenementAttribute.HasEventsSpecifiques(objet))
                                    {
                                        lstObjetsAvecEvenementsSpecifiques.Add(objet);
                                    }

                                    if (typeof(CRelationElementAChamp_ChampCustom).IsAssignableFrom(typeOriginal))
                                    {
                                        CRelationElementAChamp_ChampCustom rel = objet as CRelationElementAChamp_ChampCustom;
                                        objet = (CObjetDonneeAIdNumerique)((CRelationElementAChamp_ChampCustom)objet).ElementAChamps;
                                        if (objet.Row.RowState == DataRowState.Unchanged)
                                        {
                                            objet.Row.Row.SetModified();
                                        }
                                        if (objet.Row.RowState == DataRowState.Deleted)
                                        {
                                            objet.VersionToReturn = DataRowVersion.Original;
                                        }
                                        if (rel.ContexteDeModification.Length != 0 &&
                                            objet.ContexteDeModification.Length == 0)
                                        {
                                            objet.ContexteDeModification = rel.ContexteDeModification;
                                        }
                                    }
                                    if (!tableIdsVues.ContainsKey(objet.Id) || (
                                            listeARepasserPourTable != null && listeARepasserPourTable.ContainsKey(objet.Id)))
                                    {
                                        tableIdsVues[objet.Id] = true;
                                        foreach (CEvenement evt in lstEvenements)
                                        {
                                            if (!traitement.ContainsCouple(evt, (CObjetDonneeAIdNumerique)objet))
                                            {
                                                //Attention, si c'est une valeur de champ custom, envoie la valeur,
                                                //c'est elle qui sera testée.
                                                CInfoDeclencheurProcess infoDeclencheur = null;
                                                if (evt.ShouldDeclenche((CObjetDonneeAIdNumerique)objet, ref infoDeclencheur))
                                                {
                                                    infoDeclencheur.DbKeyEvenementDeclencheur = evt.DbKey;
                                                    infoDeclencheur.Info = evt.Libelle;
                                                    traitement.AddCoupleEvenementObjet(evt, (CObjetDonneeAIdNumerique)objet, infoDeclencheur);
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            //Regarde les handle d'évenement sur l'objet
                            if (strPrimaryKey != "" && (row.RowState == DataRowState.Modified))
                            {
                                listeIdsElementsAVerifierHandlers.Add((int)row[strPrimaryKey]);
                            }
                        }
                        if (listeARepasserPourTable != null)
                        {
                            listeARepasserPourTable.Clear();
                        }

                        if (listeIdsElementsAVerifierHandlers.Count > 0 && bFirstPasse)
                        {
                            //traitement par paquet de 500
                            for (int nIndexLot = 0; nIndexLot < listeIdsElementsAVerifierHandlers.Count; nIndexLot += 500)
                            {
                                int           nMin = Math.Min(nIndexLot + 500, listeIdsElementsAVerifierHandlers.Count);
                                StringBuilder bl   = new StringBuilder();
                                for (int nIndex = nIndexLot; nIndex < nMin; nIndex++)
                                {
                                    bl.Append(listeIdsElementsAVerifierHandlers[nIndex].ToString());
                                    bl.Append(",");
                                }
                                string strIdsElementsAVerifierHandlers = bl.ToString().Substring(0, bl.ToString().Length - 1);
                                //Recherche tous les handlers d'évenement pour les objets concernés
                                CListeObjetsDonnees listeHandler = new CListeObjetsDonnees(contexte, typeof(CHandlerEvenement));
                                listeHandler.Filtre = new CFiltreData(
                                    CHandlerEvenement.c_champIdCible + " in (" + strIdsElementsAVerifierHandlers + ") and " +
                                    CHandlerEvenement.c_champTypeCible + "=@1 and " +
                                    CHandlerEvenement.c_champTypeEvenement + "=@2",
                                    tpObjets.ToString(),
                                    (int)TypeEvenement.Modification);
                                listeHandler.PreserveChanges = true;
                                foreach (CHandlerEvenement handler in listeHandler)
                                {
                                    if (handler.Row.RowState != DataRowState.Deleted)
                                    {
                                        CObjetDonneeAIdNumerique objetTmp = (CObjetDonneeAIdNumerique)Activator.CreateInstance(tpObjets, new object[] { contexte });
                                        if (objetTmp.ReadIfExists(handler.IdElementCible))
                                        {
                                            CInfoDeclencheurProcess infoDeclencheur = null;
                                            if (handler.ShoulDeclenche(objetTmp, ref infoDeclencheur))
                                            {
                                                if (infoDeclencheur != null && handler.EvenementLie != null)
                                                {
                                                    infoDeclencheur.Info = handler.EvenementLie.Libelle;
                                                }
                                                traitement.AddCoupleHandlerObjet(handler, (CObjetDonneeAIdNumerique)objetTmp, infoDeclencheur);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //Annule les évenements spécifiques, ils ont été traités !
                        foreach (CObjetDonnee objet in lstObjetsAvecEvenementsSpecifiques)
                        {
                            EvenementAttribute.ClearEvenements(objet);
                        }
                    }
                }

                //Execute ce qui peut être executé tout de suite
                foreach (DataTable table in contexte.Tables)
                {
                    table.RowChanged += handlerRedo;
                }
                listeElementsARepasser.Clear();
                foreach (CTraitementApresSauvegarde.CCoupleDeclencheurObjet couple in traitement.CouplesEvenementOuHandlerObjet)
                {
                    if (couple.Objet is CObjetDonneeAIdNumerique &&
                        couple.PeutEtreExecuteSurLePosteClient)
                    {
                        result = couple.OnDeclencheSurClient();
                        if (!result)
                        {
                            return(result);
                        }
                    }
                }
                foreach (DataTable table in contexte.Tables)
                {
                    table.RowChanged -= handlerRedo;
                }
                bFirstPasse = false;
            }

            if (traitement.CouplesEvenementOuHandlerObjet.Count != 0)
            {
                tableData[c_cleDonneeListeTraitements] = traitement;
            }
            m_listeElementsARepasser.Remove(contexte);
            return(result);
        }
        //--------------------------------------------------------------------------------------------------------
        private void FillListeRésumée()
        {
            //Note les rows comme modifiées si des champs custom ont été modifiés
            foreach (DataTable table in m_contexteDonnee.Tables)
            {
                if (table.Rows.Count > 0)
                {
                    Type tp = CContexteDonnee.GetTypeForTable(table.TableName);
                    if (typeof(CRelationElementAChamp_ChampCustom).IsAssignableFrom(tp))
                    {
                        foreach (DataRow row in table.Rows)
                        {
                            CRelationElementAChamp_ChampCustom rel = m_contexteDonnee.GetNewObjetForRow(row) as CRelationElementAChamp_ChampCustom;
                            if (row.RowState != DataRowState.Unchanged)
                            {
                                if (rel.ElementAChamps != null && rel.ElementAChamps.Row.RowState == DataRowState.Unchanged)
                                {
                                    rel.ElementAChamps.Row.Row.SetModified();
                                }
                            }
                        }
                    }
                }
            }
            m_wndListeResumée.BeginUpdate();
            m_wndListeResumée.Items.Clear();
            List <DataTable> lst = new List <DataTable>();

            foreach (DataTable table in m_contexteDonnee.Tables)
            {
                lst.Add(table);
            }
            lst.Sort((x, y) => DynamicClassAttribute.GetNomConvivial(CContexteDonnee.GetTypeForTable(x.TableName))
                     .CompareTo(DynamicClassAttribute.GetNomConvivial(CContexteDonnee.GetTypeForTable(y.TableName))));
            foreach (DataTable table in lst)
            {
                if (table.Rows.Count > 0)
                {
                    StringBuilder bl = new StringBuilder();
                    bl.Append(DynamicClassAttribute.GetNomConvivial(CContexteDonnee.GetTypeForTable(table.TableName)));
                    bl.Append(" (");
                    bl.Append(table.Rows.Count);
                    bl.Append(" / ");
                    int nNbModified = 0;
                    int nNbAdded    = 0;
                    foreach (DataRow row in table.Rows)
                    {
                        if (row.RowState == DataRowState.Modified)
                        {
                            nNbModified++;
                        }
                        if (row.RowState == DataRowState.Added)
                        {
                            nNbAdded++;
                        }
                    }
                    bl.Append(nNbModified);
                    bl.Append(" / ");
                    bl.Append(nNbAdded);
                    bl.Append(")");
                    ListViewItem item = new ListViewItem(bl.ToString());
                    item.Tag = table;
                    m_wndListeResumée.Items.Add(item);
                }
            }
            m_wndListeResumée.EndUpdate();
        }
        ///////////////////////////////////////////////////
        public override CResultAErreur TraitementAvantSauvegarde(CContexteDonnee contexte)
        {
            CResultAErreur result = base.TraitementAvantSauvegarde(contexte);

            CSessionClient session = CSessionClient.GetSessionForIdSession(IdSession);
            //Annule les modifications sur les champs interdits en modification
            DataTable table = contexte.Tables[GetNomTable()];
            //Objet témoin pour vérifier les valeurs non affectées
            CRelationElementAChamp_ChampCustom relTemoin = null;

            if (IdVersionDeTravail != null)            //Dans les versions, on ne stocke pas les créations de valeurs nulles
            {
                relTemoin = (CRelationElementAChamp_ChampCustom)contexte.GetNewObjetForTable(table);
                relTemoin.CreateNewInCurrentContexte();
            }
            if (table != null && session != null)
            {
                IInfoUtilisateur user = session.GetInfoUtilisateur();
                if (user != null)
                {
                    ArrayList       lst     = new ArrayList(table.Rows);
                    IElementAChamps lastElt = null;
                    CRestrictionUtilisateurSurType restDeBase    = null;
                    CRestrictionUtilisateurSurType restAppliquee = null;
                    foreach (DataRow row in lst)
                    {
                        CRelationElementAChamp_ChampCustom rel = (CRelationElementAChamp_ChampCustom)contexte.GetNewObjetForRow(row);
                        if (row.RowState == DataRowState.Added && relTemoin != null)
                        {
                            if (relTemoin.Valeur != null && relTemoin.Valeur.Equals(rel.Valeur) ||
                                relTemoin.Valeur == null && relTemoin.Valeur == null)
                            {
                                rel.CancelCreate();
                            }
                        }


                        if (row.RowState == DataRowState.Modified || row.RowState == DataRowState.Added)
                        {
                            if (restDeBase == null)
                            {
                                Type tp = rel.ElementAChamps.GetType();
                                restDeBase = user.GetRestrictionsSur(tp, contexte.IdVersionDeTravail);
                            }
                            if (restDeBase != null && rel.ElementAChamps.Equals(lastElt))
                            {
                                restAppliquee = restDeBase.Clone() as CRestrictionUtilisateurSurType;
                            }
                            //Vérifie qu'on a le droit
                            if (!rel.ElementAChamps.Equals(lastElt) && restAppliquee != null)
                            {
                                restAppliquee.ApplyToObjet(rel.ElementAChamps);
                            }
                            lastElt = rel.ElementAChamps;
                            if (restAppliquee != null)
                            {
                                ERestriction restChamp = restAppliquee.GetRestriction(rel.ChampCustom.CleRestriction);
                                if ((restChamp & ERestriction.ReadOnly) == ERestriction.ReadOnly)
                                {
                                    row.RejectChanges();
                                }
                            }
                        }
                    }
                }
            }
            if (relTemoin != null)
            {
                relTemoin.CancelCreate();
            }
            return(result);
        }
示例#8
0
        /// /////////////////////////////////////////////////////////
        public static object GetValeur(CObjetDonnee objet, CDefinitionProprieteDynamique prop, DataRowVersion version)
        {
            if (prop is CDefinitionProprieteDynamiqueChampCustom)
            {
                //Evaluation d'un champ custom
                if (objet is CRelationElementAChamp_ChampCustom)
                {
                    CRelationElementAChamp_ChampCustom rel = (CRelationElementAChamp_ChampCustom)objet;
                    return(rel.GetValeur(version));
                }
                if (objet is IElementAChamps)
                {
                    return(((IElementAChamps)objet).GetValeurChamp(((CDefinitionProprieteDynamiqueChampCustom)prop).DbKeyChamp, version));
                }
            }
            else
            {
                #region Evaluation d'un champ
                PropertyInfo info    = objet.GetType().GetProperty(prop.NomProprieteSansCleTypeChamp);
                object[]     attribs = info.GetCustomAttributes(typeof(TableFieldPropertyAttribute), true);
                if (attribs.Length != 0)
                {
                    TableFieldPropertyAttribute attrTable = (TableFieldPropertyAttribute)attribs[0];
                    try
                    {
                        object val = objet.Row[attrTable.NomChamp, version];
                        if (val == DBNull.Value)
                        {
                            val = null;
                        }
                        return(val);
                    }
                    catch
                    {
                        return(null);
                    }
                }
                else
                {
                    attribs = info.GetCustomAttributes(typeof(RelationAttribute), true);
                    if (attribs.Length != 0)
                    {
                        RelationAttribute attrRel = (RelationAttribute)attribs[0];
                        try
                        {
                            object val = objet.Row[attrRel.ChampsFils[0], version];
                            if (val == DBNull.Value)
                            {
                                val = null;
                            }
                            return(val);
                        }
                        catch
                        {
                            return(null);
                        }
                    }
                }
                #endregion
            }

            return(null);
        }
示例#9
0
        /// <summary>
        /// Indique si l'évenement doit se déclencher
        /// </summary>
        /// <param name="objet"></param>
        /// <param name="bModeAvecInterface">
        /// si vrai, les évenements de type Manuel ou Ouverture retournent vrai,
        /// sinon, ils retournent systématiquement faux
        /// </param>
        /// <param name="bModeStatique">
        /// Si vrai, les évenements de création sont vrai et les évenements
        /// de modif sans valeur initiale retournent vrai si la valeur de fin est verifiée
        /// </param>
        /// <returns></returns>
        public bool ShouldDeclenche(CObjetDonneeAIdNumerique objet, bool bModeAvecInterface, bool bModeStatique, ref CInfoDeclencheurProcess infoDeclencheur)
        {
            CResultAErreur result = CResultAErreur.True;

            if (ContextesException.Contains(objet.ContexteDeModification))
            {
                return(false);
            }
            //CObjetDonneeAIdNumeriqueAuto objetToEval = objet;
            CDefinitionProprieteDynamique defPropriete = ProprieteASurveiller;

            if (objet is CRelationElementAChamp_ChampCustom)
            {
                if (!(defPropriete is CDefinitionProprieteDynamiqueChampCustom))
                {
                    return(false);
                }
                CRelationElementAChamp_ChampCustom rel = (CRelationElementAChamp_ChampCustom)objet;
                if (rel.ChampCustom.DbKey != ((CDefinitionProprieteDynamiqueChampCustom)defPropriete).DbKeyChamp)
                {
                    return(false);
                }
            }
            CObjetDonneeAIdNumerique objetToTest = GetObjetToRun(objet);

            if (objetToTest == null)
            {
                return(false);
            }
            DataRowVersion versionToReturnOriginal = objetToTest.VersionToReturn;

            try
            {
                if (objetToTest.Row.RowState == DataRowState.Deleted)
                {
                    objetToTest.VersionToReturn = DataRowVersion.Original;
                }
                CContexteEvaluationExpression contexteEval = new CContexteEvaluationExpression(objetToTest);
                object valeurAvant;
                object valeurApres;
                infoDeclencheur = new CInfoDeclencheurProcess();
                infoDeclencheur.TypeDeclencheur = TypeEvenement;
                switch (TypeEvenement)
                {
                case TypeEvenement.Manuel:
                    if (!bModeAvecInterface)
                    {
                        return(false);
                    }
                    break;

                case TypeEvenement.Creation:
                    if (objet.Row.RowState != DataRowState.Added && !bModeStatique)
                    {
                        return(false);
                    }
                    break;

                case TypeEvenement.Date:
                    //Vérifie si la date a changé
                    if (defPropriete != null)
                    {
                        if (!bModeStatique)
                        {
                            valeurAvant = GetValeur(objet, defPropriete, DataRowVersion.Original);
                            valeurApres = GetValeur(objet, defPropriete, DataRowVersion.Current);
                            if (TestEgalite(valeurApres, valeurAvant))
                            {
                                return(false);
                            }
                        }
                    }
                    break;

                case TypeEvenement.Modification:
                    if (objet.Row.RowState == DataRowState.Modified || objet.Row.RowState == DataRowState.Added || bModeStatique)
                    {
                        if (defPropriete != null)
                        {
                            try
                            {
                                valeurAvant = null;
                                if (objet.Row.RowState == DataRowState.Modified)
                                {
                                    valeurAvant = GetValeur(objet, defPropriete, DataRowVersion.Original);
                                }
                                valeurApres = GetValeur(objet, defPropriete, DataRowVersion.Current);
                                if (objet.Row.RowState == DataRowState.Modified && TestEgalite(valeurApres, valeurAvant))
                                {
                                    return(false);
                                }
                                if (FormuleValeurAvant != null)
                                {
                                    if (bModeStatique)
                                    {
                                        return(false);
                                    }
                                    result = FormuleValeurAvant.Eval(contexteEval);
                                    if (!result)
                                    {
                                        return(false);
                                    }
                                    if (!TestEgalite(result.Data, valeurAvant))
                                    {
                                        return(false);
                                    }
                                }
                                if (FormuleValeurApres != null)
                                {
                                    result = FormuleValeurApres.Eval(contexteEval);
                                    if (!result)
                                    {
                                        return(false);
                                    }
                                    if (!TestEgalite(result.Data, valeurApres))
                                    {
                                        return(false);
                                    }
                                }
                                infoDeclencheur.ValeurOrigine = valeurAvant;
                            }
                            catch
                            {
                                return(false);
                            }
                        }
                    }
                    else
                    {
                        return(false);
                    }
                    break;

                case TypeEvenement.Specifique:
                    if (objet.Table.Columns.Contains(EvenementAttribute.c_champEvenements))
                    {
                        if (!EvenementAttribute.HasEvent(objet, IdEvenementSpecifique))
                        {
                            return(false);
                        }
                    }
                    //Stef 110309 : Si on annule l'évenement là, et qu'il y a d'autres
                    //Hanlder sur cet évenement, les autres handler ne se déclencheront pas
                    //il faut donc annuler l'evenement quand on a parcouru tous les évenements
                    //Donc, dans le CGestionnaireEvenements
                    //EvenementAttribute.AnnuleEvenement(objet, IdEvenementSpecifique);
                    break;

                case TypeEvenement.Suppression:
                    if (objet.Row.RowState != DataRowState.Deleted)
                    {
                        return(false);
                    }
                    break;
                }
                //Evalue la condition
                if (FormuleConditionDeclenchement != null)
                {
                    result = FormuleConditionDeclenchement.Eval(contexteEval);
                    if (!result)
                    {
                        return(result);
                    }
                    if (result.Data is bool)
                    {
                        if (!(bool)result.Data)
                        {
                            return(false);
                        }
                    }
                    else if (result.Data.ToString() == "" || result.Data.ToString() == "0")
                    {
                        return(false);
                    }
                }
            }
            catch
            {
            }
            finally
            {
                objetToTest.VersionToReturn = versionToReturnOriginal;
            }
            return(true);
        }
示例#10
0
        //-----------------------------------------------------------------------
        //Si idsChampsAMettreAJour est vide, il faut tout mettre à jour
        public CResultAErreur SendToSnmp(bool bOnlyModifiés, params int[] idsChampsAMettreAJour)
        {
            CResultAErreur result = CResultAErreur.True;

            if (TypeEntiteSnmp == null)
            {
                return(result);
            }
            if (TypeEntiteSnmp.ReadOnly)
            {
                result.EmpileErreur(I.T("This is a readonly entity|20127"));
                return(result);
            }
            IEnumerable <CChampEntiteFromQueryToChampCustom> lstChamps = TypeEntiteSnmp.ChampsFromQuery;
            Dictionary <string, object>            lstValeurs          = new Dictionary <string, object>();
            CResultAErreurType <IObjetDeEasyQuery> resObj = TypeEntiteSnmp.FindSourceObjetInQuery( );

            if (!resObj || resObj.DataType == null)
            {
                result.EmpileErreur(resObj.Erreur);
                return(result);
            }

            IObjetDeEasyQuery objetSource = resObj.DataType;
            CEasyQuery        query       = objetSource.Query;

            Dictionary <string, string> dicOIDStringToChamp = new Dictionary <string, string>();
            CEntiteSnmpPourSupervision  ettPourSup          = null;

            foreach (CChampEntiteFromQueryToChampCustom champ in lstChamps)
            {
                if (champ.IdChampCustom != null && (idsChampsAMettreAJour.Length == 0 ||
                                                    idsChampsAMettreAJour.Contains(champ.IdChampCustom.Value)))
                {
                    CRelationElementAChamp_ChampCustom rel = CUtilElementAChamps.GetRelationToChamp(this, champ.IdChampCustom.Value);
                    if (rel != null && (bOnlyModifiés && (rel.Row.RowState == DataRowState.Added || rel.Row.RowState == DataRowState.Modified) ||
                                        !bOnlyModifiés))
                    {
                        object valeur = rel.Valeur;

                        ITableDefinition  table = null;
                        IColumnDefinition col   = null;
                        if (query.FindSource(champ.Champ.ColonneSource, objetSource,
                                             out table,
                                             out col))
                        {
                            CColumnDefinitionSNMP colSnmp = col as CColumnDefinitionSNMP;

                            if (colSnmp != null && !champ.Champ.IsReadOnly)
                            {
                                ISnmpData snmpVal = AbstractTypeAssignment.GetSnmpFromDotNet(colSnmp.SnmpType, valeur);
                                if (snmpVal == null && valeur != null)
                                {
                                    snmpVal = new OctetString(valeur.ToString());
                                }
                                if (snmpVal != null)
                                {
                                    string strIndex = Index;
                                    if (champ.Champ.FormuleIndex != null)
                                    {
                                        if (ettPourSup == null)
                                        {
                                            ettPourSup = GetEntitePourSupervision(TypeEntiteSnmp.GetTypeEntitePourSupervision(null, false));
                                        }
                                        CContexteEvaluationExpression ctx = new CContexteEvaluationExpression(ettPourSup);
                                        CResultAErreur restTmp            = champ.Champ.FormuleIndex.Eval(ctx);
                                        if (restTmp && restTmp.Data != null)
                                        {
                                            strIndex = restTmp.Data.ToString();
                                        }
                                    }
                                    if (!strIndex.StartsWith("."))
                                    {
                                        strIndex = "." + strIndex;
                                    }
                                    lstValeurs[colSnmp.OIDString + strIndex]          = snmpVal;
                                    dicOIDStringToChamp[colSnmp.OIDString + strIndex] = champ.ChampCustom.Nom;
                                }
                            }
                        }
                    }
                }
            }
            if (lstValeurs.Count > 0)
            {
                CInterrogateurSnmp agent = new CInterrogateurSnmp();
                agent.Connexion.Version  = AgentSnmp.SnmpVersion;
                agent.ConnexionIp        = AgentSnmp.SnmpIp;
                agent.ConnexionPort      = AgentSnmp.SnmpPort;
                agent.ConnexionCommunity = AgentSnmp.SnmpCommunaute;
                foreach (KeyValuePair <string, object> kv in lstValeurs)
                {
                    try
                    {
                        CResultAErreur resTmp = agent.Set(kv.Key, kv.Value);

                        if (!resTmp)
                        {
                            string strChamp = null;
                            if (dicOIDStringToChamp.TryGetValue(kv.Key, out strChamp))
                            {
                                result.EmpileErreur(new CErreurValidation(I.T("Entity @1 (@2), Field @3 : |20105", Libelle, Index, strChamp) + resTmp.Erreur.ToString(), resTmp.IsAvertissement));
                            }
                            else
                            {
                                result.EmpileErreur(resTmp.Erreur);
                            }
                            if (!result.IsAvertissement)
                            {
                                return(result);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        result.EmpileErreur(new CErreurException(e));
                    }
                }
            }
            return(result);
        }