/// <summary> /// 子要素とセッターのペアを列挙します。 /// </summary> /// <returns> 子要素 </returns> public virtual IEnumerable <ElementReference> ElementReferences() { return(PropertyInfos.Select( p => ElementReference.Create( () => (UnifiedElement)p.GetValue(this, null), e => p.SetValue(this, e, null)))); }
//C# 任意类型数据转JSON格式 #region Json 格式示例 /* * * {"total":28, "rows":[ * {"productid":"FI-SW-01","productname":"Koi","unitcost":10.00,"status":"P","listprice":36.50,"attr1":"Large","itemid":"EST-1"}, * {"productid":"K9-DL-01","productname":"Dalmation","unitcost":12.00,"status":"P","listprice":18.50,"attr1":"Spotted Adult Female","itemid":"EST-10"}, * {"productid":"RP-SN-01","productname":"Rattlesnake","unitcost":12.00,"status":"P","listprice":38.50,"attr1":"Venomless","itemid":"EST-11"}, * {"productid":"RP-SN-01","productname":"Rattlesnake","unitcost":12.00,"status":"P","listprice":26.50,"attr1":"Rattleless","itemid":"EST-12"}, * {"productid":"RP-LI-02","productname":"Iguana","unitcost":12.00,"status":"P","listprice":35.50,"attr1":"Green Adult","itemid":"EST-13"}, * {"productid":"FL-DSH-01","productname":"Manx","unitcost":12.00,"status":"P","listprice":158.50,"attr1":"Tailless","itemid":"EST-14"}, * {"productid":"FL-DSH-01","productname":"Manx","unitcost":12.00,"status":"P","listprice":83.50,"attr1":"With tail","itemid":"EST-15"}, * {"productid":"FL-DLH-02","productname":"Persian","unitcost":12.00,"status":"P","listprice":23.50,"attr1":"Adult Female","itemid":"EST-16"}, * {"productid":"FL-DLH-02","productname":"Persian","unitcost":12.00,"status":"P","listprice":89.50,"attr1":"Adult Male","itemid":"EST-17"}, * {"productid":"AV-CB-01","productname":"Amazon Parrot","unitcost":92.00,"status":"P","listprice":63.50,"attr1":"Adult Male","itemid":"EST-18"} * ] * } * */ #region JsonModel /* * * * {"total":"28","rows":[ {"itemid":"EST-1","productid":"FI-SW-01","listprice":"16.50","unitcost":"10.00","status":"P","attr1":"Large"}, * {"itemid":"EST-10","productid":"K9-DL-01","listprice":"18.50","unitcost":"12.00","status":"P","attr1":"Spotted Adult Female"}, * {"itemid":"EST-11","productid":"RP-SN-01","listprice":"18.50","unitcost":"12.00","status":"P","attr1":"Venomless"}, * {"itemid":"EST-12","productid":"RP-SN-01","listprice":"18.50","unitcost":"12.00","status":"P","attr1":"Rattleless"}, * {"itemid":"EST-13","productid":"RP-LI-02","listprice":"18.50","unitcost":"12.00","status":"P","attr1":"Green Adult"}, * {"itemid":"EST-14","productid":"FL-DSH-01","listprice":"58.50","unitcost":"12.00","status":"P","attr1":"Tailless"}, * {"itemid":"EST-15","productid":"FL-DSH-01","listprice":"23.50","unitcost":"12.00","status":"P","attr1":"With tail"}, * {"itemid":"EST-16","productid":"FL-DLH-02","listprice":"93.50","unitcost":"12.00","status":"P","attr1":"Adult Female"}, * {"itemid":"EST-17","productid":"FL-DLH-02","listprice":"93.50","unitcost":"12.00","status":"P","attr1":"Adult Male"}, * {"itemid":"EST-18","productid":"AV-CB-01","listprice":"193.50","unitcost":"92.00","status":"P","attr1":"Adult Male"} * ] * } * * */ #endregion #endregion #region 获取实体Attributes /// <summary> /// 获取实体Attributes /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static IList GetAttribute <T>() { List <string> AttributeLst = new List <string>(); #region 查看其是否Attributes Type mType = typeof(T); PropertyInfo[] mTypePro = mType.GetProperties(); foreach (PropertyInfo PropertyInfos in mTypePro) { //查看其是否Attributes object[] objAttributes = PropertyInfos.GetCustomAttributes(typeof(Attribute), true); if (objAttributes.Length > 0) { string Joson = string.Empty; Attribute JosonAttribute = objAttributes[0] as Attribute; if (JosonAttribute != null) { Joson = JosonAttribute.GetType().Name.ToStrings(); AttributeLst.Add(Joson); } } } return(AttributeLst); #endregion }
private void SetDictionary() { var properties = typeof(T).GetRuntimeProperties(); foreach (var property in properties) { var element = (BinaryElement)property.GetCustomAttribute(typeof(BinaryElement)); if (element != null) { if (element.Direction == DirectionEnum.Reverse) { if (_bytes == null) { element.FieldOffset = 1000; } else { element.FieldOffset = _bytes.Length - element.Length - element.FieldOffset; } } var el = new SerializeInfoElement() { Element = element, Info = property }; InfoElements.Add(property.Name, el); } PropertyInfos.Add(property); } InfoElementOrderedList.AddRange(InfoElements.Select(e => e.Value).OrderBy(e => e.Element.FieldOffset)); }
/// <summary> /// Is called by the indexer to collect all errors and not only the one for a special field. /// </summary> /// <remarks> /// Because <see cref="HasErrors" /> depends on the <see cref="Errors" /> dictionary this /// ensures that controls like buttons can switch their state accordingly. /// </remarks> private void CollectErrors() { Errors.Clear(); PropertyInfos.ForEach( prop => { var currentValue = prop.GetValue(this); var requiredAttr = prop.GetCustomAttribute <RequiredAttribute>(); var maxLenAttr = prop.GetCustomAttribute <MaxLengthAttribute>(); if (requiredAttr != null) { if (string.IsNullOrEmpty(currentValue?.ToString() ?? string.Empty)) { Errors.Add(prop.Name, requiredAttr.ErrorMessage); } } if (maxLenAttr != null) { if ((currentValue?.ToString() ?? string.Empty).Length > maxLenAttr.Length) { Errors.Add(prop.Name, maxLenAttr.ErrorMessage); } } // TODO further attributes }); // we have to this because the Dictionary does not implement INotifyPropertyChanged OnPropertyChanged(nameof(HasErrors)); OnPropertyChanged(nameof(IsOk)); // commands do not recognize property changes automatically OnErrorsCollected(); }
protected override object GetValue(string key) { if (PropertyInfos.ContainsKey(key.ToLower())) { return(PropertyInfos[key.ToLower()].GetValue(ObjectWithLazyProperty, null)); } return(base.GetValue(key)); }
public AttributeGetter(Type type) { type = type ?? throw new ArgumentNullException("type"); foreach (PropertyInfo propInfo in type.GetProperties()) { PropertyInfos.Add(propInfo.Name, propInfo); } }
public string this[string propertyName] { get { var propertyInfo = this.GetType().GetRuntimeProperty(propertyName); PropertyInfos.Add(propertyInfo); return(string.Empty); } }
private List <MethodCtorMatch> MatchMethodsToProperties(DecodedEntityClass entityInfo) { var nonReadOnlyPropertyInfo = PropertyInfos.Where(y => y.PropertyType != DtoPropertyTypes.ReadOnly) .Select(x => x.PropertyInfo).ToList(); _allPossibleSetterMatches = _matcher.GradeAllMethods(entityInfo.PublicSetterMethods, nonReadOnlyPropertyInfo, HowTheyWereAskedFor.DefaultMatchToProperties).ToList(); return(_allPossibleSetterMatches.Where(x => x.PropertiesMatch.Score >= PropertyMatch.PerfectMatchValue).ToList()); }
public override bool Contains(object key) { var dicKey = key.ToString().ToLower(); if (PropertyInfos.ContainsKey(dicKey)) { return(true); } return(base.Contains(key)); }
public static void Postfix(ViewModel __instance) { DebugLogger.Print("Created: {0}", __instance.GetType().Name); // Check if property exists in DialogHolders if (!PropertyInfos.ContainsKey(__instance.GetType())) { return; } PropertyInfos[__instance.GetType()].SetValue(null, __instance); }
public List <TEntity> Set <TEntity>() where TEntity : class { var propertyInfo = PropertyInfos.FirstOrDefault(p => p.PropertyType == typeof(List <TEntity>)); if (propertyInfo != null) { // Get the List<T> from 'this' Context instance var x = propertyInfo.GetValue(this, null) as List <TEntity>; return(x); } throw new Exception("Type collection not found"); }
/// <summary> /// 通过反射设置属性值 /// </summary> /// <param name="key">属性名</param> /// <param name="value">值</param> void SetPropertyValue(string key, string value) { try { PropertyInfo propertyInfo = PropertyInfos.Where(x => x.Name.ToLower() == key.ToLower()).FirstOrDefault(); //获取指定名称的属性 if (propertyInfo != null) { propertyInfo.SetValue(request, value, null); } } catch { throw; } }
public void DeletePropertyInfos(ICollection <int> aPropertyInfoIdCollection) { if (PropertyInfos != null && PropertyInfos.Count > 0) { if (aPropertyInfoIdCollection != null && aPropertyInfoIdCollection.Count > 0) { foreach (var item in aPropertyInfoIdCollection) { var removeItem = PropertyInfos.FirstOrDefault(p => p.UId == item); if (removeItem != null) { PropertyInfos.Remove(removeItem); } } } } }
public void AddOrUpdatePropertyInfos(ICollection <PropertyInfo> aPropertyInfoCollection) { if (aPropertyInfoCollection != null && aPropertyInfoCollection.Count > 0) { foreach (var item in aPropertyInfoCollection) { var existItem = PropertyInfos.FirstOrDefault(p => p.UId == item.UId); if (existItem == null) { PropertyInfos.Add(item); } else { existItem.Update(item.PropertyId, item.PropertyValueIds); } } } }
/// <summary> /// Is called by the indexer to collect all errors and not only the one for a special field. /// </summary> /// <remarks> /// Because <see cref="HasErrors" /> depends on the <see cref="Errors" /> dictionary this /// ensures that controls like buttons can switch their state accordingly. /// </remarks> private void CollectErrors() { Errors.Clear(); PropertyInfos.ForEach( prop => { //Validate generically var errors = new List <string>(); var isValid = TryValidateProperty(prop, errors); if (!isValid) { Errors.Add(prop.Name, errors.FirstOrDefault()); } }); // we have to this because the Dictionary does not implement INotifyPropertyChanged OnPropertyChanged(nameof(HasErrors)); OnPropertyChanged(nameof(IsOk)); // commands do not recognize property changes automatically OnErrorsCollected(); }
private string GetFields(FieldTypes fieldType) { string returnValue = null; switch (fieldType) { case FieldTypes.Fields: // Concatenated fields for SELECT command returnValue = string.Join(", ", PropertyInfos.Select(p => string.Format("[{0}]", p.Name)).ToArray()); break; case FieldTypes.Values: // Concatenated fields for INSERT command returnValue = string.Join(", ", PropertyInfos.Select(p => string.Format("@{0}", p.Name)).ToArray()); break; case FieldTypes.Updates: // Concatenated fields for UPDATE command returnValue = string.Join(", ", PropertyInfos.Where(p => p.Name != this.IdField).Select(p => string.Format("[{0}] = @{1}", p.Name, p.Name)).ToArray()); break; } return(returnValue); }
public DecodedDto(Type dtoType, DecodedEntityClass entityInfo, IGenericServicesConfig publicConfig, PerDtoConfig perDtoConfig) { DtoType = dtoType ?? throw new ArgumentNullException(nameof(dtoType)); _matcher = new MethodCtorMatcher(publicConfig.NameMatcher); _perDtoConfig = perDtoConfig; //can be null LinkedEntityInfo = entityInfo; if (entityInfo.EntityStyle == EntityStyles.OwnedType) { throw new InvalidOperationException($"{DtoType.Name}: You cannot use ILinkToEntity<T> with an EF Core Owned Type."); } if (entityInfo.EntityStyle == EntityStyles.HasNoKey) { //If HasNoKey or is OwnedType then exit immediately as properties etc return; } PropertyInfos = dtoType.GetProperties() .Select(x => new DecodedDtoProperty(x, BestPropertyMatch.FindMatch(x, entityInfo.PrimaryKeyProperties).Score >= PropertyMatch.PerfectMatchValue)) .ToImmutableList(); if (!PropertyInfos.Any()) { throw new InvalidOperationException($"The {DtoType.Name} class inherits ILinkToEntity<T> but has no properties in it!"); } if (entityInfo.CanBeUpdatedViaMethods) { _matchedSetterMethods = PreloadPossibleMethodCtorMatches(MatchMethodsToProperties(entityInfo), new DecodeName(_perDtoConfig?.UpdateMethod), null); } if (entityInfo.CanBeCreatedByCtorOrStaticMethod) { _matchedCtorsAndStaticMethods = PreloadPossibleMethodCtorMatches(MatchCtorsAndStaticMethodsToProperties(entityInfo), new DecodeName(_perDtoConfig?.UpdateMethod), null); } }
public GenericStructSerializationInfo(TypeDefinition definition, CustomFormatterTypeInfo customFormatter, MethodDefinition serializationConstructorDefinition, GenericInstanceType[] definitionVariations) #endif { Definition = definition; CustomFormatter = customFormatter; FieldInfos = Array.Empty <FieldSerializationInfo>(); PropertyInfos = Array.Empty <PropertySerializationInfo>(); StringKeyValuePairs = Array.Empty <StringKeySerializationInfoTuple>(); MinIntKey = 0; MaxIntKey = 0; SerializationConstructor = serializationConstructorDefinition; DefinitionGenericInstanceVariations = definitionVariations; AreAllMessagePackPrimitive = FieldInfos.All(x => x.IsMessagePackPrimitive) && PropertyInfos.All(x => x.IsMessagePackPrimitive); PublicAccessible = PublicTypeTestUtility.IsPublicType(definition) && FieldInfos.All(x => x.PublicAccessible) && PropertyInfos.All(x => x.PublicAccessible); }
IEnumerable <MemberDeclarationSyntax> GetInterfaceMembers() { return(PropertyInfos.SelectMany(x => x.Declarations) .Concat(VirtualMethodInfos.SelectMany(x => x.Declarations))); }
internal static List <IPatchBase> ReadPatchDocumentProperties <T>(JsonReader reader, string path, BindAttribute bindAttribute = null, Action <JsonReader> patchTypeAction = null, Action <IPatchPrimitive> keyAction = null) { if (reader == null) { return(null); } var modelTypeAssemblyName = typeof(T).AssemblyQualifiedName; bool cacheProperties; const string patchTypeKey = PatchArrayDocument <object> .PatchTypeKey; // ReSharper disable once AssignmentInConditionalExpression var modelProperties = (cacheProperties = PropertyInfos.All(x => x.Key.Key1 != modelTypeAssemblyName)) ? typeof(T).GetTypeInfo().GetProperties() : PropertyInfos.Where(x => x.Key.Key1 == modelTypeAssemblyName).Select(x => x.Value).ToArray(); var values = new List <IPatchBase>(); var startPath = reader.Path; bindAttribute = bindAttribute ?? typeof(T).GetAttribute <BindAttribute>(); path = string.IsNullOrWhiteSpace(path) ? string.Empty : path + "."; var keys = new List <IPatchPrimitive>(); while (reader.Read()) { if (reader.Path == startPath) { break; } if (reader.TokenType != JsonToken.PropertyName) { while (reader.Read()) { if (reader.Path == startPath) { return(null); } } } var readerValueAsName = (string)reader.Value; if (readerValueAsName == patchTypeKey) { if (patchTypeAction != null) { patchTypeAction(reader); } else { reader.Skip(); } continue; } var propertyInfo = modelProperties.FirstOrDefault(x => { var jsonPropertyNameAttribute = x.GetCustomAttribute <JsonPropertyAttribute>(); if (jsonPropertyNameAttribute != null) { return(string.Equals(jsonPropertyNameAttribute.PropertyName, readerValueAsName)); } return(readerValueAsName.Equals(new CamelCaseNamingStrategy().GetPropertyName(x.Name, false)) || readerValueAsName.Equals(x.Name) || readerValueAsName.Equals(new SnakeCaseNamingStrategy().GetPropertyName(x.Name, false))); }); // If property not found, we should report an error with it. if (propertyInfo == null) { values.Add(new PatchPrimitive <object> { Errors = new List <Error> { new Error { ErrorType = typeof(InvalidCastException), JsonName = readerValueAsName, JsonPath = reader.Path, Message = string.Format(Resources.UnknownProperty, readerValueAsName), Name = readerValueAsName, Path = reader.Path } }, Found = true, JsonName = readerValueAsName, JsonPath = reader.Path, Name = readerValueAsName, Path = reader.Path, Value = null }); // Since this is an unknown property, we should not parse it. reader.Skip(); continue; } var propertyName = propertyInfo.Name; var isKey = propertyInfo.GetCustomAttribute <KeyAttribute>() != null; var isBindable = IsBindable(bindAttribute, propertyName); if (!isBindable && (!isKey || keyAction == null)) { reader.Skip(); continue; } var value = (IPatchBase)SelectStrategyMethodInfo.MakeGenericMethod(propertyInfo.PropertyType) .Invoke(null, new object[] { reader, propertyName, path + propertyName, propertyInfo }); value.IgnoreApply = propertyInfo.GetCustomAttribute <IgnorePatchAttribute>() != null; if (isKey && keyAction != null) { keys.Add((IPatchPrimitive)value); } if (isBindable) { values.Add(value); } } foreach (var propertyInfo in modelProperties) { if (cacheProperties) { PropertyInfos.Add(modelTypeAssemblyName, propertyInfo.Name, propertyInfo); } if (values.Any(x => x.Name == propertyInfo.Name)) { continue; } var propertyName = propertyInfo.Name; var isKey = propertyInfo.GetCustomAttribute <KeyAttribute>() != null; var isBindable = IsBindable(bindAttribute, propertyName); if (!isBindable && (!isKey || keyAction == null)) { continue; } var value = (IPatchBase)SelectStrategyMethodInfo.MakeGenericMethod(propertyInfo.PropertyType) .Invoke(null, new object[] { null, propertyName, path + propertyName, propertyInfo }); value.IgnoreApply = propertyInfo.GetCustomAttribute <IgnorePatchAttribute>() != null; if (isKey && keyAction != null && keys.All(x => x.Name != value.Name)) { keys.Add((IPatchPrimitive)value); } if (isBindable) { values.Add(value); } } if (keys.Any()) { foreach (var key in keys) { // ReSharper disable once PossibleNullReferenceException keyAction.Invoke(key); } } return(values); }
private PropertyInfo GetPropertyInfoForOrderedList(string colunmName) { PropertyInfo propertyInfo; return(AttributeToPropInfoMapping.TryGetValue(colunmName, out propertyInfo) ? propertyInfo : PropertyInfos.FirstOrDefault(info => String.Equals(info.Name, NamingConvention.ProcessDbNamesToObjectNames(colunmName), StringComparison.CurrentCultureIgnoreCase))); }
private string[] GetProperties() { // Create array of property names for DirectorySearcher.PropertiesToLoad.AddRange(string[]) return(PropertyInfos.Select(p => p.Name).ToArray()); }