/// <summary> /// Permet de définir directement la structure de la table pour ce datarow, création d'une nouvelle si elle existe pas /// Ne fonctionnera /// </summary> /// <param name="nameTable"></param> /// <param name="ColsKeys"></param> public static void DefineSchemaPO(DataPO po, string nameTable, System.Data.DataColumn[] Cols, System.Data.DataColumn[] ColsKeys) { System.Data.DataTable table = null; table = DataSetTools.DefineDataTable(nameTable, Cols, ColsKeys); DefineSchemaPO(po, table); // itemcc.ReadOnly = false; // pas de readonly dans les bulles, sinon on ne peut plus modifier }
public static Dictionary <string, object> GetChangedValues(this DataPO po) { bool refreshflow = (po.flows != null && po.flows.Count(f => f.IsChanges()) > 0); System.Data.DataRow row = po.GetRow(refreshflow); return(DataSetTools.GetChangedValues(row)); }
private void button1_Click(object sender, EventArgs e) { try { DataSetTools changes = (DataSetTools)dataSetTools.GetChanges(); if (changes == null) { return; } DataTable dt = changes.tblTools.GetChanges(); DataRow[] badRows = dt.GetErrors(); if (badRows.Length > 0) { string errorMsg = ""; foreach (DataRow row in badRows) { foreach (DataColumn col in row.GetColumnsInError()) { errorMsg = errorMsg + row.GetColumnsInError() + "\n"; } } MessageBox.Show("Errors in data: " + errorMsg, "Please fix", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } int numRows = tblToolsTableAdapter.Update(changes); MessageBox.Show("Updated " + numRows + " rows", "Success"); dataSetTools.AcceptChanges(); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message, "Erros", MessageBoxButtons.OK, MessageBoxIcon.Error); dataSetTools.RejectChanges(); } }
/// <summary> /// Obtientir les données du DataPO /// </summary> /// <returns></returns> public static Dictionary <string, object> GetValues(this DataPO po, bool returnKeys, bool returnValues) { System.Data.DataRow row = po.GetRow(returnValues);// Si les valeurs sont demandé on refresh les flow if (returnKeys && !IsDefinedSchema(po)) { DefineSchemaPO(po); // Si l'objet est pas définis il faut le daire } return(DataSetTools.GetValues(row, returnKeys, returnValues)); }
/// <summary> /// Obtientir les données du DataPO /// </summary> /// <returns></returns> public static Dictionary <string, object> GetValues(this DataPO po, params string[] ColNames) { if (ColNames == null || ColNames.Length == 0) { return(new Dictionary <string, object>()); } bool refreshflow = false; if (po.flows != null && po.flows.Count > 0) { refreshflow = po.flows.Select(f => f.GetFieldName()).Where(fn => !string.IsNullOrWhiteSpace(fn)).Any(fn => ColNames.Any(eq => fn.Equals(eq, StringComparison.OrdinalIgnoreCase))); } System.Data.DataRow row = po.GetRow(refreshflow); return(DataSetTools.GetValues(row, ColNames)); }
//绑定类别列表 private void DoInitialDataBind() { currentRole = new Role(Convert.ToInt32(lblRoleID.Text)); RoleLabel.Text = currentRole.Description; this.TxtNewname.Text = currentRole.Description; DataSet allCategories = AccountsTool.GetAllCategories(); if (!DataSetTools.DataSetIsNull(allCategories)) { CategoryDownList.DataSource = allCategories.Tables[0]; CategoryDownList.DataTextField = "Description"; CategoryDownList.DataValueField = "CategoryID"; CategoryDownList.DataBind(); } }
private void GetRolePermissionlist() { DataSet ds = currentRole.Permissions; if (!DataSetTools.DataSetIsNull(ds)) { rolePermissionlist = new List <int>(); DataTable dt = ds.Tables["Permissions"]; if (!DataTableTools.DataTableIsNull(dt)) { foreach (DataRow dr in dt.Rows) { rolePermissionlist.Add(Convert.ToInt32(dr["PermissionID"])); } } } }
//填充非权限列表 public void FillCategoryList(int categoryId) { currentRole = new Role(Convert.ToInt32(lblRoleID.Text)); GetRolePermissionlist(); DataSet ds = AccountsTool.GetPermissionsByCategory(categoryId); if (!DataSetTools.DataSetIsNull(ds)) { DataView dv = ds.Tables[0].DefaultView; if (!UserPrincipal.HasPermissionID(GetPermidByActID(Act_ShowReservedPerm))) { dv.RowFilter = "PermissionID not in (" + ReservedPermIDs + ")"; } chkPermissions.DataSource = dv; chkPermissions.DataValueField = "PermissionID"; chkPermissions.DataTextField = "Description"; chkPermissions.DataBind(); } }
/// <summary> /// Permet de clonner les données des datarow en une seule datatable /// </summary> /// <param name="datas"></param> /// <returns></returns> public static System.Data.DataTable CloneDataTable(params DATAPO.DataPO[] datas) { try { List <System.Data.DataTable> alltables = datas.Select(dt => dt.GetRow().Table).Distinct().ToList(); System.Data.DataTable tabinsert = DataSetTools.DataTableMergeSchemas(alltables.ToArray()); DataSetTools.DataTableRemoveConstraints(tabinsert); foreach (var itemdata in datas) { System.Data.DataRow newrow = tabinsert.NewRow(); System.Data.DataRow oldrow = itemdata.GetRow(true); oldrow.CopyRow(newrow); tabinsert.Rows.Add(newrow); } return(tabinsert); } catch (Exception ex) { throw new Exception("CloneDataTable " + ex.Message); } }
/// <summary> /// Insertion table (Insert Optimsé en insertion multirows) /// </summary> /// <param name="connector"></param> /// <param name="dataTable"></param> /// <param name="SpecialTimeOut"></param> /// <param name="AutoIncrementColumn"></param> /// <returns></returns> public async Task <List <long> > InsertTableAsync(System.Data.DataTable dataTable, int SpecialTimeOut = 600, string AutoIncrementColumn = null) { List <System.Data.DataTable> tablesSpliteds = DataSetTools.DataTableSplit(dataTable, 50); // Découpe 50 lignes par 50 lignes bool UseTransaction = true; List <long> retourIncremented = new List <long>(); try { UseTransaction = this.BeginTransaction("t1"); int count = 0; foreach (System.Data.DataTable tabl in tablesSpliteds) // list { List <long> retourIncrementedSub = this.InsertTableSub(tabl, SpecialTimeOut, AutoIncrementColumn); retourIncremented.AddRange(retourIncrementedSub); count += tabl.Rows.Count; tabl.Dispose(); } if (UseTransaction) { this.CommitTransaction(); } return(retourIncremented); } catch (Exception ex) { //Console.WriteLine("Exeption " + ex.Message); if (UseTransaction) { this.RollBackTransaction(); } throw ex; } finally { } }
private static System.Data.DataTable CreateSchemaWithAttributes(Type potype) { System.Data.DataTable table = null; try { System.Attribute tableAttribute = APP.CODE.AttributesTools.FindObjectAttribute(potype, DataAnnotationsFactory.TableAttributeType); if (tableAttribute == null) { return(null); } string tableName = APP.CODE.PropertiesTools.GetStringReflexion(tableAttribute, "Name"); List <System.Data.DataColumn> Cols = new List <System.Data.DataColumn>(); List <System.Data.DataColumn> ColKeys = new List <System.Data.DataColumn>(); table = new DataTable(); table.TableName = tableName; // Parcours des propriétés (cols) List <PropertyInfo> props = APP.CODE.PropertiesTools.GetProperties(potype); foreach (PropertyInfo prop in props) { System.Data.DataColumn col = null; //clef if (DataAnnotationsFactory.AnnotationExist(prop, DataAnnotationsFactory.KeyAttributeType)) { if (col == null) { col = new DataColumn(); col.ColumnName = prop.Name.ToLower(); if (prop.PropertyType == typeof(Nglib.DATA.PARAMVALUES.ParamValuesPOFlux)) // les flux seront consiédéré comme des string { col.DataType = typeof(string); } else { col.DataType = prop.PropertyType; } } ColKeys.Add(col); } // Création des colones if (DataAnnotationsFactory.AnnotationExist(prop, DataAnnotationsFactory.ColumnAttributeType)) { if (col == null) { col = new DataColumn(); col.ColumnName = prop.Name.ToLower(); if (prop.PropertyType == typeof(Nglib.DATA.PARAMVALUES.ParamValuesPOFlux)) // les flux seront consiédéré comme des string { col.DataType = typeof(string); } else { col.DataType = prop.PropertyType; } } string RealColumnName = DataAnnotationsFactory.AnnotationGetString(prop, DataAnnotationsFactory.ColumnAttributeType, "Name"); if (!string.IsNullOrWhiteSpace(RealColumnName)) { col.ColumnName = RealColumnName; } //if (!string.IsNullOrWhiteSpace(columnAttribute.TypeName)) // ; } string DatabaseGeneratedOption = DataAnnotationsFactory.AnnotationGetString(prop, DataAnnotationsFactory.DatabaseGeneratedAttributeType, "DatabaseGeneratedOption"); if (!string.IsNullOrEmpty(DatabaseGeneratedOption) && !DatabaseGeneratedOption.Equals("None", StringComparison.OrdinalIgnoreCase)) { if (col != null) { col.AutoIncrement = true; } } //System.ComponentModel.DataAnnotations.Schema.ForeignKeyAttribute foreignKeyAttribute = propAttributes.FirstOrDefault(at => (at is ForeignKeyAttribute)) as ForeignKeyAttribute; //System.ComponentModel.DataAnnotations.DataTypeAttribute dataTypeAttribute = propAttributes.FirstOrDefault(at => (at is DataTypeAttribute)) as DataTypeAttribute; //System.ComponentModel.DataAnnotations.DisplayColumnAttribute displayColumnAttribute = propAttributes.FirstOrDefault(at => (at is DisplayColumnAttribute)) as DisplayColumnAttribute; //System.ComponentModel.DataAnnotations.EditableAttribute editableAttribute = propAttributes.FirstOrDefault(at => (at is EditableAttribute)) as EditableAttribute; //System.ComponentModel.DataAnnotations.RequiredAttribute requiredAttribute = propAttributes.FirstOrDefault(at => (at is RequiredAttribute)) as RequiredAttribute; // Objets lié //System.ComponentModel.DataAnnotations.AssociationAttribute associationAttribute = propAttributes.FirstOrDefault(at => (at is AssociationAttribute)) as AssociationAttribute; if (col != null) { Cols.Add(col); } } // défini les colonnes sur la table DataSetTools.SetColumns(table, Cols.ToArray()); DataSetTools.SetPrimaryKeys(table, ColKeys.ToArray()); return(table); } catch (Exception ex) { throw new Exception("DefineRowWithAttributes" + ex.Message); } }
/// <summary> /// Défini un objet /// </summary> /// <returns></returns> public bool SetData(string nameValue, object obj, DataAccessorOptionEnum AccesOptions) { try { if (string.IsNullOrWhiteSpace(nameValue)) { return(false); } nameValue = nameValue.Trim(); if (nameValue.Contains(":")) { // Obtenir la valeur dans un datapo join à celui-ci throw new Exception("DataPo In SubObject non géré"); } else if (nameValue.StartsWith("/")) { // Obtenir la valeur dans le flux nosql lié string fieldName = nameValue.Split('/')[1]; // le nom du champ est équivalent au nom du root IDataPOFlow flow = this.GetFlow(fieldName); if (flow == null) { return(false); } //bool iset = flow.SetObject(nameValue, obj, AccesOptions); //if (iset) this.localRow.SetModified(); //return iset; //!!!!!!!!!!!! return(false); } else { // Obtien la valeur normalement dans le datarow local if (this.localRow == null) { this.DefineSchemaPO(); // si pas de datarow, on l'initialiser (identique à GetRow()) } System.Data.DataColumn realColumn = this.localRow.Table.Columns[nameValue]; if (realColumn == null) { if (AccesOptions.HasFlag(DataAccessorOptionEnum.NotCreateColumn)) // création de la colonne interdite { if (AccesOptions.HasFlag(DataAccessorOptionEnum.Safe)) { return(false); } else { throw new Exception("Colonne Introuvable dans le DataRow (NotCreateColumn = true)"); } } else if (obj == null || obj == DBNull.Value) // si la valeur est null et que la valeur existe pas c'est pas la peine de créer une colone { return(false); //if (AccesOptions.HasFlag(DataAccessorOptionEnum.Safe)) return false; //else throw new Exception("Colonne Introuvable dans le DataRow (Impossible de déterminer le type à partir d'un null pour créer la colonne)"); } // Création de la colone Type typetocreate = obj.GetType(); realColumn = this.localRow.Table.CreateColumn(nameValue.ToLower(), typetocreate); // Création d'une nouvelle colonne dans la table pour stoker la valeur (toujours en minuscule) } object orgnobj = this.localRow[realColumn]; if (obj == null && orgnobj == null) { return(false); // inutile si pas modifié } if (obj != null && obj.Equals(orgnobj)) { return(false); // inutile si pas modifié } if (AccesOptions.HasFlag(DataAccessorOptionEnum.IgnoreChange)) // il faut tromper le datarow pour lui faire croire que la donnée n'a pas été modifié { Dictionary <string, object> prechanged = DataSetTools.GetChangedValues(this.localRow); // on obtien les changements précédents if (prechanged.Count > 0) { this.localRow.RejectChanges(); // on les rejetents pour les remettre après } this.localRow[realColumn] = obj; // on met à jours la données this.localRow.AcceptChanges(); // on approuve la mise à jours if (prechanged.Count > 0) { prechanged.Keys.ToList().ForEach(k => this.localRow[k] = prechanged[k]); // on remet les anciennes modifications } } else { this.localRow[realColumn] = obj; // on met à jours la données dans le datarow , l'objet passera au statut modified } return(true); } } catch (Exception ex) { if (AccesOptions.HasFlag(DataAccessorOptionEnum.Safe)) { return(false); } else { throw new Exception("SetObject DataRow " + nameValue + " : " + ex.Message, ex); } } finally { } }
/// <summary> /// Obtient un Objet (du datarow, fluxxml ou des objets liés) /// méthode principale /// </summary> /// <returns></returns> public object GetData(string nameValue, DataAccessorOptionEnum AccesOptions) { if (this.localRow == null) { return(null); // vraiement innutile, y'a aucune données } try { if (string.IsNullOrWhiteSpace(nameValue)) { return(null); } nameValue = nameValue.Trim(); // ----------------------------- if (nameValue.Contains(":")) // Il s'agit d'un champ provenant d'un autre datapo incorporé { string[] fieldsPO = nameValue.Split(':'); if (fieldsPO.Length < 2 || string.IsNullOrWhiteSpace(fieldsPO[0]) || string.IsNullOrWhiteSpace(fieldsPO[1])) { return(null); } System.Reflection.PropertyInfo pi = this.GetType().GetProperty(fieldsPO[0]); if (pi == null || !pi.CanRead) { return(null); } object ObjfieldIn = pi.GetValue(this, null); if (ObjfieldIn == null) { return(null); } if (ObjfieldIn is DATAPO.DataPO) { DATAPO.DataPO dpo = (DATAPO.DataPO)ObjfieldIn; return(dpo.GetObject(fieldsPO[1], AccesOptions)); } else if (pi.PropertyType.IsClass) { System.Reflection.PropertyInfo subpi = pi.PropertyType.GetProperty(fieldsPO[1]); if (subpi == null) { return(null); } else { return(subpi.GetValue(ObjfieldIn, null)); } // !!! ajouter la recherche dans une liste ou dictionary : 'documents[monchamp="valeur",monchamp2="valeur"]:monchamp3' } } // ----------------------------- else if (nameValue.StartsWith("/")) // Il s'agit du flux de données nosql { //string fieldName = nameValue.Split('/')[1]; // le nom du champ est équivalent au nom du root //IDataPOFlow flow = this.GetFlow(fieldName); //// IDataAccessor flowdata = this.GetFlow(fieldName) as IDataAccessor; // On converti le //if (flow == null ||) return null; //return flow.GetObject(nameValue, AccesOptions); //!!!!!!!!! } // ----------------------------- else // sinon c'est un champdu datarow { System.Data.DataColumn realColumn = DataSetTools.GetColumn(this.localRow.Table, nameValue); if (realColumn != null) { return(this.localRow[realColumn]); } } return(null); } catch (Exception) { return(null); } }