/// <summary> /// Applique le tri et le filtrage à la liste. /// </summary> /// <typeparam name="TSource">Type source.</typeparam> /// <param name="list">Liste source.</param> /// <returns>Liste triée.</returns> public ICollection <TSource> Apply <TSource>(ICollection <TSource> list) { if (list == null) { throw new ArgumentNullException("list"); } if (_sortList.Count != 1) { throw new NotImplementedException(); } if (this.InlineCount) { QueryContext.InlineCount = list.Count; } string sortColumn = _sortList[0]; SortOrder sortOrder = _mapSort[sortColumn]; BeanDefinition beanDef = BeanDescriptor.GetDefinition(typeof(TSource)); BeanPropertyDescriptor propertyDescriptor = beanDef.Properties[FirstToUpper(sortColumn)]; if (sortOrder == SortOrder.Asc) { list = list.OrderBy(x => propertyDescriptor.GetValue(x)).ToList(); } else { list = list.OrderByDescending(x => propertyDescriptor.GetValue(x)).ToList(); } // If this.Limit == 0 we disable pagination. return(list.Skip(this.Offset).Take(this.Limit > 0 ? this.Limit : list.Count).ToList()); }
public string GetReferenceValueByPrimaryKey(Type referenceType, object primaryKey, object dataSource, string defaultPropertyName = null) { BeanDefinition definition = BeanDescriptor.GetDefinition(referenceType); BeanPropertyDescriptor primaryKeyProperty = definition.PrimaryKey; BeanPropertyDescriptor valueProperty = string.IsNullOrEmpty(defaultPropertyName) ? definition.DefaultProperty : definition.Properties[defaultPropertyName]; ICollection dataSourceColl = (ICollection)dataSource; if (dataSourceColl == null) { throw new NotSupportedException("DataSource must be an ICollection."); } object candidate = null; foreach (object item in dataSourceColl) { if (primaryKeyProperty.GetValue(item).Equals(primaryKey)) { candidate = item; break; } } if (candidate == null) { throw new NotSupportedException("The datasource does not contain an object with this primary key."); } return(valueProperty.ConvertToString(valueProperty.GetValue(candidate))); }
/// <summary> /// Crée un dictionnaire { nom de la propriété => valeur } pour un item à insérer. /// </summary> /// <param name="modelClass">Modele de la classe.</param> /// <param name="initItem">Item a insérer.</param> /// <param name="isPrimaryKeyIncluded">True si le script d'insert doit comporter la clef primaire.</param> /// <returns>Dictionnaire contenant { nom de la propriété => valeur }.</returns> protected override Dictionary <string, string> CreatePropertyValueDictionary(ModelClass modelClass, ItemInit initItem, bool isPrimaryKeyIncluded) { Dictionary <string, string> nameValueDict = new Dictionary <string, string>(); BeanDefinition definition = BeanDescriptor.GetDefinition(initItem.Bean); foreach (ModelProperty property in modelClass.PersistentPropertyList) { if (!property.DataDescription.IsPrimaryKey || isPrimaryKeyIncluded) { BeanPropertyDescriptor propertyDescriptor = definition.Properties[property.Name]; object propertyValue = propertyDescriptor.GetValue(initItem.Bean); string propertyValueStr = propertyValue == null ? string.Empty : propertyValue.ToString(); if (property.DataType == "byte[]") { nameValueDict[property.DataMember.Name] = GetBulkColumn(propertyValueStr); } else if (propertyDescriptor.PrimitiveType == typeof(string)) { nameValueDict[property.DataMember.Name] = "'" + propertyValueStr.Replace("'", "''") + "'"; } else { nameValueDict[property.DataMember.Name] = propertyValueStr; } } } return(nameValueDict); }
/// <summary> /// Prend en charge l'alimentation de la classe pour les valeurs d'initialisation. /// </summary> /// <param name="classe">Classe concernée.</param> /// <param name="item">Bean d'initialisation.</param> protected void HandleCorrectInit(ModelClass classe, TableInit item) { if (!DictionaryItemInit.ContainsKey(classe)) { DictionaryItemInit.Add(classe, item); } foreach (ItemInit itemInit in item.ItemInitList) { BeanDefinition definition = BeanDescriptor.GetDefinition(itemInit.Bean); BeanPropertyDescriptor propertyDescriptor = GetReferenceKeyDescriptor(classe, definition); object propertyValue = propertyDescriptor.GetValue(itemInit.Bean); if (propertyDescriptor.PrimitiveType == typeof(string)) { propertyValue = "\"" + propertyValue + "\""; } BeanPropertyDescriptor libelleDescriptor = GetLibelleDescriptor(classe, definition); string libelle = null; if (libelleDescriptor != null) { libelle = (string)libelleDescriptor.GetValue(itemInit.Bean); } else { libelle = itemInit.VarName; } classe.ConstValues.Add(itemInit.VarName, new StaticListElement() { Code = propertyValue, Libelle = libelle, CodeType = propertyDescriptor.PrimitiveType.ToString() }); } }
/// <summary> /// Retourne la valeur d'une liste de référence à partir /// de son identifiant. /// </summary> /// <param name="referenceType">Type de la liste de référence.</param> /// <param name="primaryKey">Identifiant de la liste de référence.</param> /// <param name="defaultPropertyName">Nom de la propriété par défaut à utiliser. Null pour utiliser la valeur définie au niveau de l'objet.</param> /// <returns>Libellé de la liste de référence.</returns> public string GetReferenceValueByPrimaryKey(Type referenceType, object primaryKey, string defaultPropertyName = null) { object reference = GetReferenceObjectByPrimaryKey(referenceType, primaryKey); BeanDefinition definition = BeanDescriptor.GetDefinition(reference); BeanPropertyDescriptor property = string.IsNullOrEmpty(defaultPropertyName) ? definition.DefaultProperty : definition.Properties[defaultPropertyName]; return(property.ConvertToString(property.GetValue(reference))); }
/// <summary> /// Appelle le PrimaryKeyAccessor pour le type donné avec la valeur de PK donnée. /// </summary> /// <param name="type">Type concerné.</param> /// <param name="primaryKey">Clef primaire.</param> /// <param name="propertyName">Propriété évaluée.</param> /// <returns>Libellé par défaut.</returns> private string InvokePrimaryKeyAccessor(Type type, object primaryKey, string propertyName = null) { object o = GetBeanByPrimaryKey(type, primaryKey); Accessor accessor = _primaryKeyAccessors[type.FullName]; BeanDefinition definition = BeanDescriptor.GetDefinition(accessor.ReturnType); BeanPropertyDescriptor property = string.IsNullOrEmpty(propertyName) ? definition.DefaultProperty : definition.Properties[propertyName]; return(property.ConvertToString(property.GetValue(o))); }
/// <summary> /// Insère un nouvel enregistrement. /// </summary> /// <param name="commandName">Nom de la commande.</param> /// <param name="bean">Bean à insérer.</param> /// <param name="beanDefinition">Définition du bean.</param> /// <param name="primaryKey">Définition de la clef primaire.</param> /// <returns>Bean inséré.</returns> protected override IDataReader Insert(string commandName, T bean, BeanDefinition beanDefinition, BeanPropertyDescriptor primaryKey, ColumnSelector columnSelector) { BeanDefinition definition = BeanDescriptor.GetDefinition(typeof(Bean)); Assert.AreEqual(definition, beanDefinition); Assert.AreEqual(definition.PrimaryKey, primaryKey); Assert.IsNull(primaryKey.GetValue(bean)); return(new TestDataReader(1, 1)); }
/// <summary> /// Renvoie la valeur de la propriété. /// </summary> /// <param name="item">Item.</param> /// <param name="property">Descrition de l'item.</param> /// <returns>Valeur.</returns> private static object GetPropertyValue(T item, BeanPropertyDescriptor property) { object value = property.GetValue(item); ExtendedValue v = value as ExtendedValue; if (v != null) { value = v.Value; } return(value); }
/// <summary> /// Met à jour un bean. /// </summary> /// <param name="commandName">Nom de la commande.</param> /// <param name="bean">Bean à mettre à jour.</param> /// <param name="beanDefinition">Définition du bean.</param> /// <param name="primaryKey">Définition de la clef primaire.</param> /// <param name="primaryKeyValue">Valeur de la clef primaire.</param> /// <param name="columnSelector">Selecteur de colonnes à mettre à jour ou à ignorer.</param> /// <returns>Bean mise à jour.</returns> protected override IDataReader Update(string commandName, T bean, BeanDefinition beanDefinition, BeanPropertyDescriptor primaryKey, object primaryKeyValue, ColumnSelector columnSelector) { BeanDefinition definition = BeanDescriptor.GetDefinition(typeof(Bean)); Assert.AreEqual(definition, beanDefinition); Assert.AreEqual(definition.PrimaryKey, primaryKey); Assert.IsNotNull(primaryKey.GetValue(bean)); Assert.IsNotNull(primaryKeyValue); Assert.AreEqual(primaryKeyValue, primaryKey.GetValue(bean)); int id = (int)primaryKeyValue; int rowAffected = 1; if (id == 6) { rowAffected = 0; } else if (id == 7) { rowAffected = 2; } return(new TestDataReader(id, rowAffected)); }
/// <summary> /// Crée la chaîne liée à la clause Where. /// </summary> /// <param name="bean">Bean à mettre à jour.</param> /// <param name="sbUpdateWhere">Clause Where.</param> /// <param name="property">Propriété courante.</param> /// <param name="rule">Règle à appliquer.</param> protected void BuildUpdateWhere(T bean, StringBuilder sbUpdateWhere, BeanPropertyDescriptor property, IStoreRule rule) { if (sbUpdateWhere == null) { throw new ArgumentNullException("sbUpdateWhere"); } if (property == null) { throw new ArgumentNullException("property"); } if (rule == null) { return; } object value = property.GetValue(bean); if (value != null) { ExtendedValue extValue = value as ExtendedValue; if (extValue != null) { value = extValue.Value; } } ValueRule valueRule = rule.GetWhereClause(value); if (valueRule == null) { return; } switch (valueRule.Action) { case ActionRule.Check: sbUpdateWhere.Append(" and ").Append(property.MemberName).Append(" = "); sbUpdateWhere.Append(VariablePrefix).Append("RU_").Append( property.MemberName); break; case ActionRule.DoNothing: break; default: throw new NotSupportedException(); } }
/// <summary> /// Sauvegarde l'ensemble des éléments d'une association n-n. /// </summary> /// <param name="values">Les valeurs à ajouter via associations.</param> /// <param name="columnSelector">Sélecteur de colonnes à mettre à jour.</param> /// <exception cref="ArgumentException">Si la collection n'est pas composée d'objets implémentant l'interface IBeanState.</exception> public virtual void SaveAll(ICollection <T> values, ColumnSelector columnSelector = null) { if (values == null) { throw new ArgumentNullException("values"); } BeanPropertyDescriptor primaryKey = BeanDescriptor.GetDefinition(typeof(T), true).PrimaryKey; using (ServiceScope tx = new ServiceScope(TransactionScopeOption.Required)) { if (typeof(IBeanState).IsAssignableFrom(typeof(T))) { foreach (T value in values) { switch (((IBeanState)value).State) { case ChangeAction.Insert: case ChangeAction.Update: _store.Put(value, columnSelector); break; case ChangeAction.Delete: _store.Remove(primaryKey.GetValue(value)); break; default: break; } } } else { foreach (T value in values) { _store.Put(value, columnSelector); } } tx.Complete(); } if (_hasCache) { FlushCache(); } }
/// <summary> /// Obtient un reader du résultat d'enregistrement. /// </summary> /// <param name="bean">Bean à saugevarder.</param> /// <param name="beanDefinition">Definition.</param> /// <param name="primaryKey">Clef primaire.</param> /// <param name="primaryKeyValue">Valeur de la clef primaire.</param> /// <param name="columnSelector">Selecteur de colonnes à mettre à jour ou à ignorer.</param> /// <returns>DataReader contenant le bean sauvegardé.</returns> private IDataReader ExecutePutReader(T bean, BeanDefinition beanDefinition, BeanPropertyDescriptor primaryKey, object primaryKeyValue, ColumnSelector columnSelector) { if (primaryKey.GetValue(bean) != null) { string commandName = ServiceUpdate + "_" + beanDefinition.ContractName; return(this.Update(commandName, bean, beanDefinition, primaryKey, primaryKeyValue, columnSelector)); } if (primaryKeyValue == null) { string commandName = ServiceInsert + "_" + beanDefinition.ContractName; return(this.Insert(commandName, bean, beanDefinition, primaryKey, columnSelector)); } else { string commandName = ServiceInsert + "_" + beanDefinition.ContractName; return(this.Insert(commandName, bean, beanDefinition, primaryKey, columnSelector, primaryKeyValue)); } }
/// <summary> /// Prend en charge l'alimentation de la classe pour les valeurs d'initialisation. /// </summary> /// <param name="classe">Classe concernée.</param> /// <param name="item">Bean d'initialisation.</param> protected void HandleCorrectInit(ModelClass classe, TableInit item) { if (!DictionaryItemInit.ContainsKey(classe)) { DictionaryItemInit.Add(classe, item); } foreach (ItemInit itemInit in item.ItemInitList) { BeanDefinition definition = BeanDescriptor.GetDefinition(itemInit.Bean); BeanPropertyDescriptor propertyDescriptor = GetReferenceKeyDescriptor(classe, definition); object propertyValue = propertyDescriptor.GetValue(itemInit.Bean); if (propertyDescriptor.PrimitiveType == typeof(string)) { propertyValue = "\"" + propertyValue + "\""; } classe.ConstValues.Add(itemInit.VarName, propertyValue.ToString()); } }
/// <summary> /// Crée un dictionnaire { nom de la propriété => valeur } pour un item à insérer. /// </summary> /// <param name="modelClass">Modele de la classe.</param> /// <param name="initItem">Item a insérer.</param> /// <param name="isPrimaryKeyIncluded">True si le script d'insert doit comporter la clef primaire.</param> /// <returns>Dictionnaire contenant { nom de la propriété => valeur }.</returns> protected override Dictionary <string, string> CreatePropertyValueDictionary(ModelClass modelClass, ItemInit initItem, bool isPrimaryKeyIncluded) { Dictionary <string, string> nameValueDict = new Dictionary <string, string>(); BeanDefinition definition = BeanDescriptor.GetDefinition(initItem.Bean); foreach (ModelProperty property in modelClass.PersistentPropertyList) { if (!property.DataDescription.IsPrimaryKey || isPrimaryKeyIncluded) { BeanPropertyDescriptor propertyDescriptor = definition.Properties[property.Name]; object propertyValue = propertyDescriptor.GetValue(initItem.Bean); string propertyValueStr = propertyValue == null ? string.Empty : propertyValue.ToString(); if (property.DataType.Equals("bool")) { // gestion d'un booléen sous Oracle: number appartenant à {0,1} nameValueDict[property.DataMember.Name] = propertyValueStr.Equals("true") ? "1" : "0"; } else if (propertyDescriptor.PrimitiveType == typeof(string)) { nameValueDict[property.DataMember.Name] = "'" + propertyValueStr.Replace("'", "''") + "'"; } else if (propertyDescriptor.PrimitiveType == typeof(DateTime)) { nameValueDict[property.DataMember.Name] = "to_date('" + string.Format("{0:MM/dd/yy}", (DateTime)propertyValue) + "', 'DD/MM/YY')"; } else { nameValueDict[property.DataMember.Name] = propertyValueStr; } } else { // cas de la clé primaire non spécifiée sous Oracle: on utilise une séquence pour auto incrémenter la valeur de la clé nameValueDict[property.DataMember.Name] = GetSequenceName(modelClass) + ".nextval"; } } return(nameValueDict); }
/// <summary> /// Retourne la ligne d'insert. /// </summary> /// <param name="modelClass">Modele de la classe.</param> /// <param name="initItem">Item a insérer.</param> /// <param name="siPrimaryKeyIncluded">True si le script d'insert doit comporter la clef primaire.</param> /// <returns>Requête.</returns> private static string GetInsertLine(ModelClass modelClass, ItemInit initItem, bool siPrimaryKeyIncluded) { // Remplissage d'un dictionnaire nom de colonne => valeur. BeanDefinition definition = BeanDescriptor.GetDefinition(initItem.Bean); Dictionary <string, string> nameValueDict = new Dictionary <string, string>(); foreach (ModelProperty property in modelClass.PersistentPropertyList) { if (!property.DataDescription.IsPrimaryKey || siPrimaryKeyIncluded || property.DataDescription.Domain.Code == "DO_CD") { BeanPropertyDescriptor propertyDescriptor = definition.Properties[property.Name]; object propertyValue = propertyDescriptor.GetValue(initItem.Bean); string propertyValueStr = propertyValue == null ? "NULL" : propertyValue.ToString(); if (property.DataType == "byte[]") { nameValueDict[property.DataMember.Name] = propertyValueStr; } else if (propertyDescriptor.PrimitiveType == typeof(string)) { nameValueDict[property.DataMember.Name] = propertyValue == null ? "NULL" : "N'" + ScriptUtils.PrepareDataToSqlDisplay(propertyValueStr) + "'"; } else { nameValueDict[property.DataMember.Name] = propertyValue == null ? "NULL" : propertyValueStr; } } } // Création de la requête. StringBuilder sb = new StringBuilder(); sb.Append("\tINSERT INTO " + modelClass.DataContract.Name + "("); bool isFirst = true; foreach (string columnName in nameValueDict.Keys) { if (!isFirst) { sb.Append(", "); } isFirst = false; sb.Append(columnName); } sb.Append(") VALUES("); isFirst = true; foreach (string value in nameValueDict.Values) { if (!isFirst) { sb.Append(", "); } isFirst = false; sb.Append(value); } sb.Append(");"); return(sb.ToString()); }
/// <summary> /// Création d'un document CSV à partir d'une collection et de ses colonnes à exporter. /// </summary> /// <param name="colonnes">Colonnes à exporter.</param> /// <param name="dataSourceList">Liste des données à exporter.</param> /// <param name="headers">Liste des headers(si null alors on utilise les colonnes).</param> /// <param name="showHeader">Affiche ou pas un header.</param> /// <returns>Fichier binaire.</returns> private static byte[] CreateCsvFile(IList <string> colonnes, object dataSourceList, IList <string> headers, bool showHeader = true) { if (dataSourceList == null) { throw new ArgumentNullException("dataSourceList"); } if (colonnes == null) { throw new ArgumentNullException("colonnes"); } StringBuilder sb = new StringBuilder(); BeanDefinition beanDefinition = BeanDescriptor.GetCollectionDefinition(dataSourceList); BeanPropertyDescriptorCollection properties = beanDefinition.Properties; if (showHeader) { bool first = true; if (headers == null) { foreach (string colonne in colonnes) { BeanPropertyDescriptor descriptor = properties[colonne]; if (!first) { sb.Append(';'); } sb.Append(descriptor.Description); first = false; } } else { if (headers.Count != colonnes.Count) { throw new ArgumentException("colonnes et headers n'ont pas la même taille"); } foreach (string header in headers) { if (!first) { sb.Append(';'); } sb.Append(header); first = false; } } sb.Append("\r\n"); } foreach (object valeur in (ICollection)dataSourceList) { bool first = true; foreach (string colonne in colonnes) { BeanPropertyDescriptor descriptor = properties[colonne]; if (!first) { sb.Append(';'); } sb.Append(descriptor.GetValue(valeur)); first = false; } sb.Append("\r\n"); } return(Encoding.Default.GetBytes(sb.ToString())); }
/// <summary> /// Recursive get property value. /// </summary> /// <param name="dataSource">Source de données courante.</param> /// <param name="fieldName">Nom du Field.</param> /// <param name="isXmlData">Si la source en xml.</param> /// <returns>Value.</returns> protected object GetPropertyValue(object dataSource, string fieldName, bool isXmlData) { if (fieldName.Contains(".")) { string firstFieldName = fieldName.Substring(0, fieldName.IndexOf('.')); string lastFieldName = fieldName.Substring(fieldName.IndexOf('.') + 1); PropertyDescriptor property = TypeDescriptor.GetProperties(dataSource)[firstFieldName]; object newDataSource = property.GetValue(dataSource); return(GetPropertyValue(newDataSource, lastFieldName, isXmlData)); } else { if (isXmlData) { PropertyDescriptor property = TypeDescriptor.GetProperties(dataSource)[fieldName]; if (property != null) { return(property.GetValue(dataSource)); } else { throw new KeyNotFoundException("The tag " + this.TagName + " has no attribute named " + fieldName); } } else { BeanDefinition beanDefinition = BeanDescriptor.GetDefinition(dataSource); BeanPropertyDescriptor descriptor = beanDefinition.Properties[fieldName]; if (descriptor != null) { object propertyValue = descriptor.GetValue(dataSource); if (propertyValue == null) { return(null); } else { ICollection collection = propertyValue as ICollection; if (collection != null) { if (collection.Count == 0) { return(null); } else { return(propertyValue); } } else if (descriptor.PrimitiveType == typeof(byte[])) { return(propertyValue); } else if (propertyValue.GetType() == typeof(DateTime)) { if (descriptor.DomainName == "DO_JOUR_MOIS") { return(((DateTime)propertyValue).ToString("dd/MM", DateTimeFormatInfo.CurrentInfo)); } else { return(descriptor.ConvertToString(propertyValue)); } } else if (propertyValue.GetType() == typeof(bool)) { return(Convert.ToString(propertyValue, CultureInfo.InvariantCulture)); } else { return(descriptor.ConvertToString(propertyValue)); } } } else { throw new KeyNotFoundException("The tag " + this.TagName + " has no attribute named " + fieldName); } } } }
/// <summary> /// Crée une nouvelle entrée pour le type. /// </summary> /// <param name="referenceList">Liste de référence.</param> /// <param name="resourceList">Liste des resources disponible.</param> void IReferenceEntry.Initialize(ICollection referenceList, ICollection <ReferenceResource> resourceList) { BeanDefinition definition = BeanDescriptor.GetDefinition(typeof(T)); BeanPropertyDescriptor primaryKey = definition.PrimaryKey; if (primaryKey == null) { throw new NotSupportedException("Reference type " + typeof(T).FullName + " doesn't have a primary key defined. Use the ColumnAttribute to set the primary key property."); } BeanPropertyDescriptor propertyIsActif = null; if (definition.Properties.Contains(PropertyIsActif)) { propertyIsActif = definition.Properties[PropertyIsActif]; } ICollection <T> initialList = (ICollection <T>)referenceList; ICollection <T> activeList = (propertyIsActif == null) ? initialList : new List <T>(); foreach (T reference in initialList) { _resourceMap.Add(DefaultLocale + primaryKey.GetValue(reference), reference); if (propertyIsActif != null) { bool?isActif = (bool?)propertyIsActif.GetValue(reference); if (isActif.HasValue && isActif.Value) { activeList.Add(reference); } } } _localizedList.Add(DefaultLocale, activeList); if (resourceList == null) { return; } BeanFactory <T> factory = new BeanFactory <T>(); foreach (ReferenceResource resource in resourceList) { T reference; string locale = resource.Locale.Trim(); if (!_localizedList.ContainsKey(locale)) { // Construction des entrées pour la locale. List <T> list = new List <T>(); foreach (T initialReference in initialList) { reference = factory.CloneBean(initialReference); _resourceMap.Add(locale + primaryKey.GetValue(reference), reference); if (propertyIsActif != null) { bool?isActif = (bool?)propertyIsActif.GetValue(reference); if (isActif.HasValue && isActif.Value) { list.Add(reference); } } else { list.Add(reference); } } _localizedList.Add(locale, list); } reference = _resourceMap[locale + resource.Id]; definition.Properties[resource.PropertyName].SetValue(reference, resource.Label); } }