17 using System.Collections.Generic;
19 using System.Reflection;
29 [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
35 public const BindingFlags BindingFlags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance;
40 public string Name {
get;
private set; }
58 public static void ApplyAttributes(Dictionary<string, string> parameters,
object instance)
60 if (instance ==
null)
throw new ArgumentNullException(nameof(instance));
62 var type = instance.GetType();
66 foreach (var memberInfo
in members)
68 var fieldInfo = memberInfo as FieldInfo;
69 var propertyInfo = memberInfo as PropertyInfo;
72 if (fieldInfo ==
null && propertyInfo ==
null)
74 throw new InvalidOperationException(
"Resolved member that is neither FieldInfo or PropertyInfo");
79 if (attribute ==
null)
continue;
82 var parameterName = attribute.
Name ?? memberInfo.Name;
85 string parameterValue;
86 if (!parameters.TryGetValue(parameterName, out parameterValue))
continue;
88 if (
string.IsNullOrEmpty(parameterValue))
90 Log.
Error($
"ParameterAttribute.ApplyAttributes(): parameter '{parameterName}' provided value is null/empty, skipping");
95 if (propertyInfo !=
null && !propertyInfo.CanWrite)
97 var message = $
"The specified property is read only: {propertyInfo.DeclaringType}.{propertyInfo.Name}";
98 throw new InvalidOperationException(message);
102 var memberType = fieldInfo !=
null ? fieldInfo.FieldType : propertyInfo.PropertyType;
105 var value = parameterValue.ConvertTo(memberType);
108 if (fieldInfo !=
null)
110 fieldInfo.SetValue(instance, value);
114 propertyInfo.SetValue(instance, value);
126 var parameters =
new Dictionary<string, string>();
127 foreach (var type
in assembly.GetTypes())
131 parameters[kvp.Key] = kvp.Value;
147 if (attribute !=
null)
149 var parameterName = attribute.
Name ?? field.Name;
150 yield
return new KeyValuePair<string, string>(parameterName, field.FieldType.GetBetterTypeName());
154 foreach (var property
in type.GetProperties(
BindingFlags))
157 if (!property.CanWrite)
continue;
159 if (attribute !=
null)
161 var parameterName = attribute.
Name ??
property.Name;
162 yield
return new KeyValuePair<string, string>(parameterName, property.PropertyType.GetBetterTypeName());