Here are the examples of the csharp api System.Reflection.PropertyInfo.SetValue(object, object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
841 Examples
19
View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
{
if (t.IsPrimitive)
{
if (t == typeof(byte))
{
return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
}
if (t == typeof(sbyte))
{
return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
}
if (t == typeof(short))
{
return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
}
if (t == typeof(ushort))
{
return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
}
if (t == typeof(int))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
if (t == typeof(uint))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToUInt32(bytes, 0);
}
if (t == typeof(long))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToInt64(bytes, 0);
}
if (t == typeof(ulong))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToUInt64(bytes, 0);
}
if (t == typeof(float))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
var f = BitConverter.ToSingle(bytes, 0);
if (float.IsNaN(f))
f = (float)RandomValue<short>();
return f;
}
if (t == typeof(double))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
var d = BitConverter.ToDouble(bytes, 0);
if (double.IsNaN(d))
d = (double)RandomValue<short>();
return d;
}
if (t == typeof(char))
{
var roll = Rand.Next(ASCII.Length);
return ASCII[roll];
}
if (t == typeof(bool))
{
return (Rand.Next(2) == 1);
}
throw new InvalidOperationException();
}
if (t == typeof(decimal))
{
return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
}
if (t == typeof(string))
{
int start = stringValueAllowEmpty ? 0 : 1;
var len = Rand.Next(start, 28);
var c = new char[len];
for (var i = 0; i < c.Length; i++)
{
c[i] = (char)typeof(char).RandomValue();
}
return new string(c);
}
if (t == typeof(DateTime))
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var bytes = new byte[4];
Rand.NextBytes(bytes);
var secsOffset = BitConverter.ToInt32(bytes, 0);
var retDate = epoch.AddSeconds(secsOffset);
return retDate;
}
if (t == typeof(TimeSpan))
{
return new TimeSpan(RandomValue<DateTime>().Ticks);
}
if (t == typeof(DataTable))
{
DataTable dt = new DataTable();
int coluCount = Rand.Next(10, 30);
for (int i = 0; i < coluCount; i++)
{
dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
}
int rowCount = Rand.Next(20, 50);
for (int i = 0; i < rowCount; i++)
{
var row = new object[coluCount];
for (int zi = 0; zi < coluCount; zi++)
{
row[zi] = RandomHelper.RandomValue<object>();
}
dt.Rows.Add(row);
}
return dt;
}
if (t.IsNullable())
{
// leave it unset
if (Rand.Next(2) == 0)
{
// null!
return Activator.CreateInstance(t);
}
var underlying = Nullable.GetUnderlyingType(t);
var val = underlying.RandomValue(stringValueAllowEmpty);
var cons = t.GetConstructor(new[] { underlying });
return cons.Invoke(new object[] { val });
}
if (t.IsEnum)
{
var allValues = Enum.GetValues(t);
var ix = Rand.Next(allValues.Length);
return allValues.GetValue(ix);
}
if (t.IsArray)
{
var valType = t.GetElementType();
var len = Rand.Next(20, 50);
var ret = Array.CreateInstance(valType, len);
//var add = t.GetMethod("SetValue");
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
ret.SetValue(elem, i);
}
return ret;
}
if (t.IsGenericType)
{
var defind = t.GetGenericTypeDefinition();
if (defind == typeof(HashSet<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("Contains");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(Dictionary<,>))
{
var keyType = t.GetGenericArguments()[0];
var valType = t.GetGenericArguments()[1];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("ContainsKey");
var len = Rand.Next(20, 50);
if (keyType == typeof(Boolean))
len = 2;
for (var i = 0; i < len; i++)
{
var val = valType.RandomValue(stringValueAllowEmpty);
var key = keyType.RandomValue(stringValueAllowEmpty);
while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
key = keyType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { key, val });
}
return ret;
}
if (defind == typeof(List<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(ArraySegment<>))
{
var valType = t.GetGenericArguments()[0];
var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
var lenT = ary.GetType().GetProperty("Length");
var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
var len = (int)lenT.GetValue(ary) - offset;
return Activator.CreateInstance(t, ary, offset, len);
}
}
if (t == typeof(Guid))
return Guid.NewGuid();
if (t == typeof(object))
{
var code = Rand.Next(0, 9);
switch (code)
{
case 0:
return RandomValue<int>();
case 1:
return RandomValue<long>();
case 2:
return RandomValue<Char>();
case 3:
return RandomValue<DateTime>();
case 4:
return RandomValue<string>(stringValueAllowEmpty);
case 5:
return RandomValue<Guid>();
case 6:
return RandomValue<decimal>();
case 7:
return RandomValue<double>();
case 8:
return RandomValue<float>();
default:
return RandomValue<short>();
}
}
//model
var retObj = Activator.CreateInstance(t);
foreach (var p in t.GetFields())
{
//if (Rand.Next(5) == 0) continue;
var fieldType = p.FieldType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
foreach (var p in t.GetProperties())
{
//if (Rand.Next(5) == 0) continue;
if (p.CanWrite && p.CanRead)
{
var fieldType = p.PropertyType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
}
return retObj;
}
19
View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
{
if (t.IsPrimitive)
{
if (t == typeof(byte))
{
return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
}
if (t == typeof(sbyte))
{
return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
}
if (t == typeof(short))
{
return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
}
if (t == typeof(ushort))
{
return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
}
if (t == typeof(int))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
if (t == typeof(uint))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToUInt32(bytes, 0);
}
if (t == typeof(long))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToInt64(bytes, 0);
}
if (t == typeof(ulong))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToUInt64(bytes, 0);
}
if (t == typeof(float))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
var f = BitConverter.ToSingle(bytes, 0);
if (float.IsNaN(f))
f = (float)RandomValue<short>();
return f;
}
if (t == typeof(double))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
var d= BitConverter.ToDouble(bytes, 0);
if (double.IsNaN(d))
d = (double)RandomValue<short>();
return d;
}
if (t == typeof(char))
{
var roll = Rand.Next(ASCII.Length);
return ASCII[roll];
}
if (t == typeof(bool))
{
return (Rand.Next(2) == 1);
}
throw new InvalidOperationException();
}
if (t == typeof(decimal))
{
return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
}
if (t == typeof(string))
{
int start = stringValueAllowEmpty ? 0 : 1;
var len = Rand.Next(start, 40);
var c = new char[len];
for (var i = 0; i < c.Length; i++)
{
c[i] = (char)typeof(char).RandomValue();
}
return new string(c);
}
if (t == typeof(DateTime))
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var bytes = new byte[4];
Rand.NextBytes(bytes);
var secsOffset = BitConverter.ToInt32(bytes, 0);
var retDate = epoch.AddSeconds(secsOffset);
return retDate;
}
if (t == typeof(TimeSpan))
{
return new TimeSpan(RandomValue<DateTime>().Ticks);
}
if (t == typeof(DataTable))
{
DataTable dt = new DataTable();
int coluCount = Rand.Next(10, 30);
for (int i = 0; i < coluCount; i++)
{
string n = RandomHelper.RandomValue<string>(false);
while(dt.Columns.Contains(n))
n = RandomHelper.RandomValue<string>(false);
dt.Columns.Add(n, typeof(object));
}
int rowCount = Rand.Next(20, 50);
for (int i = 0; i < rowCount; i++)
{
var row = new object[coluCount];
for (int zi = 0; zi < coluCount; zi++)
{
row[zi] = RandomHelper.RandomValue<object>();
}
dt.Rows.Add(row);
}
return dt;
}
if (t.IsNullable())
{
// leave it unset
if (Rand.Next(2) == 0)
{
// null!
return Activator.CreateInstance(t);
}
var underlying = Nullable.GetUnderlyingType(t);
var val = underlying.RandomValue(stringValueAllowEmpty);
var cons = t.GetConstructor(new[] { underlying });
return cons.Invoke(new object[] { val });
}
if (t.IsEnum)
{
var allValues = Enum.GetValues(t);
var ix = Rand.Next(allValues.Length);
return allValues.GetValue(ix);
}
if (t.IsArray)
{
var valType = t.GetElementType();
var len = Rand.Next(20, 50);
var ret = Array.CreateInstance(valType, len);
//var add = t.GetMethod("SetValue");
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
ret.SetValue(elem, i);
}
return ret;
}
if (t.IsGenericType)
{
var defind = t.GetGenericTypeDefinition();
if (defind == typeof(HashSet<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("Contains");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(Dictionary<,>))
{
var keyType = t.GetGenericArguments()[0];
var valType = t.GetGenericArguments()[1];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("ContainsKey");
var len = Rand.Next(20, 50);
if (keyType == typeof(Boolean))
len = 2;
for (var i = 0; i < len; i++)
{
var val = valType.RandomValue(stringValueAllowEmpty);
var key = keyType.RandomValue(stringValueAllowEmpty);
while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
key = keyType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { key, val });
}
return ret;
}
if (defind == typeof(List<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(ArraySegment<>))
{
var valType = t.GetGenericArguments()[0];
var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
var lenT = ary.GetType().GetProperty("Length");
var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
var len = (int)lenT.GetValue(ary) - offset;
return Activator.CreateInstance(t, ary, offset, len);
}
}
if (t == typeof(Guid))
return Guid.NewGuid();
if (t == typeof(object))
{
var code = Rand.Next(0, 9);
switch (code)
{
case 0:
return RandomValue<int>();
case 1:
return RandomValue<long>();
case 2:
return RandomValue<Char>();
case 3:
return RandomValue<DateTime>();
case 4:
return RandomValue<string>(stringValueAllowEmpty);
case 5:
return RandomValue<Guid>();
case 6:
return RandomValue<decimal>();
case 7:
return RandomValue<double>();
case 8:
return RandomValue<float>();
default:
return RandomValue<short>();
}
}
//model
var retObj = Activator.CreateInstance(t);
foreach (var p in t.GetFields())
{
//if (Rand.Next(5) == 0) continue;
var fieldType = p.FieldType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
foreach (var p in t.GetProperties())
{
//if (Rand.Next(5) == 0) continue;
if (p.CanWrite && p.CanRead)
{
var fieldType = p.PropertyType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
}
return retObj;
}
19
View Source File : XmlHelper.cs
License : MIT License
Project Creator : 279328316
License : MIT License
Project Creator : 279328316
public T DeserializeNode<T>(XmlNode node = null) where T : clreplaced, new()
{
T model = new T();
XmlNode firstChild;
if (node == null)
{
node = root;
}
firstChild = node.FirstChild;
Dictionary<string, string> dict = new Dictionary<string, string>();
XmlAttributeCollection xmlAttribute = node.Attributes;
if (node.Attributes.Count > 0)
{
for (int i = 0; i < node.Attributes.Count; i++)
{
if (!dict.Keys.Contains(node.Attributes[i].Name))
{
dict.Add(node.Attributes[i].Name, node.Attributes[i].Value);
}
}
}
if (!dict.Keys.Contains(firstChild.Name))
{
dict.Add(firstChild.Name, firstChild.InnerText);
}
XmlNode next = firstChild.NextSibling;
while (next != null)
{
if (!dict.Keys.Contains(next.Name))
{
dict.Add(next.Name, next.InnerText);
}
else
{
throw new Exception($"重复的属性Key:{next.Name}");
}
next = next.NextSibling;
}
#region 为对象赋值
Type modelType = typeof(T);
List<PropertyInfo> piList = modelType.GetProperties().Where(pro => (pro.PropertyType.Equals(typeof(string)) || pro.PropertyType.IsValueType) && pro.CanRead && pro.CanWrite).ToList();
foreach (PropertyInfo pi in piList)
{
string dictKey = dict.Keys.FirstOrDefault(key => key.ToLower() == pi.Name.ToLower());
if (!string.IsNullOrEmpty(dictKey))
{
string value = dict[dictKey];
TypeConverter typeConverter = TypeDescriptor.GetConverter(pi.PropertyType);
if (typeConverter != null)
{
if (typeConverter.CanConvertFrom(typeof(string)))
pi.SetValue(model, typeConverter.ConvertFromString(value));
else
{
if (typeConverter.CanConvertTo(pi.PropertyType))
pi.SetValue(model, typeConverter.ConvertTo(value, pi.PropertyType));
}
}
}
}
#endregion
return model;
}
19
View Source File : TypeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
private T InstantiateAndFuzzViaPropertiesWhenTheyHaveSetters<T>(ConstructorInfo constructor, int recursionLevel,
Type genericType, object instance = null)
{
if (instance == null)
{
instance = constructor.Invoke(new object[0]);
}
var propertyInfos = genericType.GetProperties().Where(prop => prop.CanWrite);
foreach (var propertyInfo in propertyInfos)
{
var propertyType = propertyInfo.PropertyType;
var propertyValue = FuzzAnyDotNetType(Type.GetTypeCode(propertyType), propertyType, recursionLevel);
propertyInfo.SetValue(instance, propertyValue);
}
return (T)instance;
}
19
View Source File : CometaryExtensions.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public static T Construct<T>(this AttributeData attribute)
{
if (attribute == null)
throw new ArgumentNullException(nameof(attribute));
// Make args array
ImmutableArray<TypedConstant> constantArgs = attribute.ConstructorArguments;
object[] args = new object[constantArgs.Length];
for (int i = 0; i < constantArgs.Length; i++)
{
args[i] = constantArgs[i].GetValue();
}
// Find ctor, and invoke it
ConstructorInfo constructor = attribute.AttributeConstructor.GetCorrespondingMethod() as ConstructorInfo;
if (constructor == null)
throw new DiagnosticException($"Cannot find a constructor matching {attribute.AttributeConstructor}.", attribute.ApplicationSyntaxReference.ToLocation());
T result = (T)constructor.Invoke(args);
// Set named args
var namedArgs = attribute.NamedArguments;
if (namedArgs.Length == 0)
return result;
Type attrType = constructor.DeclaringType;
for (int i = 0; i < namedArgs.Length; i++)
{
var namedArg = namedArgs[i];
MemberInfo correspondingMember = attrType.GetMember(namedArg.Key, BindingFlags.Instance | BindingFlags.Public)[0];
switch (correspondingMember)
{
case PropertyInfo prop:
prop.SetValue(result, namedArg.Value.GetValue());
break;
case FieldInfo field:
field.SetValue(result, namedArg.Value.GetValue());
break;
}
}
// Return fully constructed attr
return result;
}
19
View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public bool TryGetVectorObject(Span<byte> buffer, out object value, out int consumed)
{
value = default;
consumed = default;
if (!DataIsType(buffer, Amf3Type.VectorObject))
{
return false;
}
buffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH);
int arrayConsumed = 0;
if (!ReadVectorHeader(ref buffer, ref value, ref arrayConsumed, out var itemCount, out var isFixedSize, out var isRef))
{
return false;
}
if (isRef)
{
consumed = arrayConsumed;
return true;
}
if (!ReadVectorTypeName(ref buffer, out var typeName, out var typeNameConsumed))
{
return false;
}
var arrayBodyBuffer = buffer;
object resultVector = null;
Type elementType = null;
Action<object> addAction = null;
if (typeName == "*")
{
elementType = typeof(object);
var v = new Vector<object>();
_objectReferenceTable.Add(v);
v.IsFixedSize = isFixedSize;
resultVector = v;
addAction = v.Add;
}
else
{
if (!_registeredTypedObejectStates.TryGetValue(typeName, out var state))
{
return false;
}
elementType = state.Type;
var vectorType = typeof(Vector<>).MakeGenericType(elementType);
resultVector = Activator.CreateInstance(vectorType);
_objectReferenceTable.Add(resultVector);
vectorType.GetProperty("IsFixedSize").SetValue(resultVector, isFixedSize);
var addMethod = vectorType.GetMethod("Add");
addAction = o => addMethod.Invoke(resultVector, new object[] { o });
}
for (int i = 0; i < itemCount; i++)
{
if (!TryGetValue(arrayBodyBuffer, out var item, out var itemConsumed))
{
return false;
}
addAction(item);
arrayBodyBuffer = arrayBodyBuffer.Slice(itemConsumed);
arrayConsumed += itemConsumed;
}
value = resultVector;
consumed = typeNameConsumed + arrayConsumed;
return true;
}
19
View Source File : BitfinexResultConverter.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (objectType == null) throw new ArgumentNullException(nameof(objectType));
var result = Activator.CreateInstance(objectType);
var arr = JArray.Load(reader);
foreach (var property in objectType.GetProperties())
{
var attribute =
(BitfinexPropertyAttribute) property.GetCustomAttribute(typeof(BitfinexPropertyAttribute));
if (attribute == null)
continue;
if (attribute.Index >= arr.Count)
continue;
object value;
var converterAttribute = (JsonConverterAttribute) property.GetCustomAttribute(typeof(JsonConverterAttribute));
if (converterAttribute != null)
value = arr[attribute.Index].ToObject(property.PropertyType, new JsonSerializer() { Converters = { (JsonConverter)Activator.CreateInstance(converterAttribute.ConverterType) } });
else
value = arr[attribute.Index];
if (property.PropertyType.IsreplacedignableFrom(value.GetType()))
property.SetValue(result, value);
else
property.SetValue(result, value == null ? null : Convert.ChangeType(value, property.PropertyType));
}
return result;
}
19
View Source File : ValueReference.cs
License : MIT License
Project Creator : Aaltuj
License : MIT License
Project Creator : Aaltuj
public static void SetValue(object model, string key, TValue value)
{
var modelType = model.GetType();
if (modelType == typeof(ExpandoObject))
{
var accessor = ((IDictionary<string, object>)model);
accessor[key] = value;
}
else
{
var propertyInfo = modelType.GetProperty(key);
propertyInfo.SetValue(model, value);
}
}
19
View Source File : ContextIsolatedTask.cs
License : Microsoft Public License
Project Creator : AArnott
License : Microsoft Public License
Project Creator : AArnott
private bool ExecuteInnerTask(ContextIsolatedTask innerTask, Type innerTaskType)
{
if (innerTask == null)
{
throw new ArgumentNullException(nameof(innerTask));
}
try
{
Type innerTaskBaseType = innerTaskType;
while (innerTaskBaseType.FullName != typeof(ContextIsolatedTask).FullName)
{
innerTaskBaseType = innerTaskBaseType.GetTypeInfo().BaseType;
if (innerTaskBaseType == null)
{
throw new ArgumentException($"Unable to find {nameof(ContextIsolatedTask)} in type hierarchy.");
}
}
var properties = this.GetType().GetRuntimeProperties()
.Where(property => property.GetMethod != null && property.SetMethod != null);
foreach (var property in properties)
{
object value = property.GetValue(this);
property.SetValue(innerTask, value);
}
// Forward any cancellation requests
using (this.CancellationToken.Register(innerTask.Cancel))
{
this.CancellationToken.ThrowIfCancellationRequested();
// Execute the inner task.
bool result = innerTask.ExecuteIsolated();
// Retrieve any output properties.
foreach (var property in properties)
{
object value = property.GetValue(innerTask);
property.SetValue(this, value);
}
return result;
}
}
catch (OperationCanceledException)
{
this.Log.LogMessage(MessageImportance.High, "Canceled.");
return false;
}
}
19
View Source File : ContextIsolatedTask.cs
License : Microsoft Public License
Project Creator : AArnott
License : Microsoft Public License
Project Creator : AArnott
private bool ExecuteInnerTask(object innerTask)
{
Type innerTaskType = innerTask.GetType();
Type innerTaskBaseType = innerTaskType;
while (innerTaskBaseType.FullName != typeof(ContextIsolatedTask).FullName)
{
innerTaskBaseType = innerTaskBaseType.GetTypeInfo().BaseType;
}
var outerProperties = this.GetType().GetRuntimeProperties().ToDictionary(i => i.Name);
var innerProperties = innerTaskType.GetRuntimeProperties().ToDictionary(i => i.Name);
var propertiesDiscovery = from outerProperty in outerProperties.Values
where outerProperty.SetMethod != null && outerProperty.GetMethod != null
let innerProperty = innerProperties[outerProperty.Name]
select new { outerProperty, innerProperty };
var propertiesMap = propertiesDiscovery.ToArray();
var outputPropertiesMap = propertiesMap.Where(pair => pair.outerProperty.GetCustomAttribute<OutputAttribute>() != null).ToArray();
foreach (var propertyPair in propertiesMap)
{
object outerPropertyValue = propertyPair.outerProperty.GetValue(this);
propertyPair.innerProperty.SetValue(innerTask, outerPropertyValue);
}
// Forward any cancellation requests
MethodInfo innerCancelMethod = innerTaskType.GetMethod(nameof(Cancel));
using (this.CancellationToken.Register(() => innerCancelMethod.Invoke(innerTask, new object[0])))
{
this.CancellationToken.ThrowIfCancellationRequested();
// Execute the inner task.
var executeInnerMethod = innerTaskType.GetMethod(nameof(ExecuteIsolated), BindingFlags.Instance | BindingFlags.NonPublic);
bool result = (bool)executeInnerMethod.Invoke(innerTask, new object[0]);
// Retrieve any output properties.
foreach (var propertyPair in outputPropertiesMap)
{
propertyPair.outerProperty.SetValue(this, propertyPair.innerProperty.GetValue(innerTask));
}
return result;
}
}
19
View Source File : InspectorGenericFields.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static void LoadSettings(T target, List<InspectorPropertySetting> settings)
{
Type myType = target.GetType();
List<PropertyInfo> propInfoList = new List<PropertyInfo>(myType.GetProperties());
for (int i = 0; i < propInfoList.Count; i++)
{
PropertyInfo propInfo = propInfoList[i];
var attrs = (InspectorField[])propInfo.GetCustomAttributes(typeof(InspectorField), false);
foreach (var attr in attrs)
{
object value = InspectorField.GetSettingValue(settings, propInfo.Name);
if (value != null)
{
propInfo.SetValue(target, value);
}
}
}
List<FieldInfo> fieldInfoList = new List<FieldInfo>(myType.GetFields());
for (int i = 0; i < fieldInfoList.Count; i++)
{
FieldInfo fieldInfo = fieldInfoList[i];
var attrs = (InspectorField[])fieldInfo.GetCustomAttributes(typeof(InspectorField), false);
foreach (var attr in attrs)
{
object value = InspectorField.GetSettingValue(settings, fieldInfo.Name);
if (value != null)
{
fieldInfo.SetValue(target, value);
}
}
}
}
19
View Source File : TypeExtensionMethods.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static void SetMemberValue(this Type type, string name, object obj, object value)
{
PropertyInfo propertyInfo = GetPublicInstancePropertyInfo(type, name);
if (propertyInfo != null)
{
if (!propertyInfo.SetMethod.IsPublic)
{
// this is here to match original behaviour before we switched to PCL version of code.
throw new ArgumentException("Property set method not public.");
}
propertyInfo.SetValue(obj, value);
}
else
{
FieldInfo fieldInfo = GetPublicInstanceFieldInfo(type, name);
if (fieldInfo != null)
{
fieldInfo.SetValue(obj, value);
}
}
}
19
View Source File : XmlSerializableDataContractExtensions.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public void SetValue(object @object, object value) => Property.SetValue(@object, value);
19
View Source File : ContractReferenceState.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private void InitializeProperties()
{
foreach (var kv in _methodReferenceProperties)
{
var name = kv.Key;
var propertyInfo = kv.Value;
var propertyType = kv.Value.PropertyType;
var instance = Activator.CreateInstance(propertyType, this, name);
propertyInfo.SetValue(this, instance);
}
}
19
View Source File : StructuredState.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private void InitializeProperties()
{
foreach (var kv in _propertyInfos)
{
var propertyInfo = kv.Value;
var type = propertyInfo.PropertyType;
var instance = Activator.CreateInstance(type);
propertyInfo.SetValue(this, instance);
}
}
19
View Source File : LazyNode.cs
License : GNU General Public License v3.0
Project Creator : agolaszewski
License : GNU General Public License v3.0
Project Creator : agolaszewski
public virtual void Bind(Expression<Func<TResult>> action)
{
if (((MemberExpression)action.Body).Member is PropertyInfo)
{
var propertyInfo = ((MemberExpression)action.Body).Member as PropertyInfo;
var body = action.Body as MemberExpression;
object projection = Expression.Lambda<Func<object>>(body.Expression).Compile()();
_then = answer => { propertyInfo.SetValue(projection, answer); };
}
if (((MemberExpression)action.Body).Member is FieldInfo)
{
var fieldInfo = ((MemberExpression)action.Body).Member as FieldInfo;
var body = action.Body as MemberExpression;
object projection = Expression.Lambda<Func<object>>(body.Expression).Compile()();
_then = answer => { fieldInfo.SetValue(projection, answer); };
}
}
19
View Source File : Node.cs
License : GNU General Public License v3.0
Project Creator : agolaszewski
License : GNU General Public License v3.0
Project Creator : agolaszewski
public virtual IThen Bind(Expression<Func<TResult>> action)
{
if (((MemberExpression)action.Body).Member is PropertyInfo)
{
var propertyInfo = ((MemberExpression)action.Body).Member as PropertyInfo;
var body = action.Body as MemberExpression;
object projection = Expression.Lambda<Func<object>>(body.Expression).Compile()();
_then = answer => { propertyInfo.SetValue(projection, answer); };
}
if (((MemberExpression)action.Body).Member is FieldInfo)
{
var fieldInfo = ((MemberExpression)action.Body).Member as FieldInfo;
var body = action.Body as MemberExpression;
object projection = Expression.Lambda<Func<object>>(body.Expression).Compile()();
_then = answer => { fieldInfo.SetValue(projection, answer); };
}
return new ThenComponent(this);
}
19
View Source File : Map.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
public static T FromDictionary<T>(Dictionary<string, object> dictionary) where T : new()
{
if (dictionary == null)
{
return default;
}
var user = new T();
var type = user.GetType();
foreach (var key in dictionary.Keys)
{
var property = type.GetProperty(key);
var value = dictionary[key];
var valueType = value?.GetType();
if (value != null && valueType != property.PropertyType)
{
if (valueType == typeof(Timestamp))
{
value = ConvertFromDate(property, value);
}
else
{
value = Convert.ChangeType(value, property.PropertyType);
}
}
property.SetValue(user, value);
}
return user;
}
19
View Source File : AdminStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
private async Task PopulateSubEnreplacediesAsync(string idName, string path, TEnreplacedy enreplacedy)
{
var property = _enreplacedyType.GetProperty(path);
var value = property.GetValue(enreplacedy);
if (value == null)
{
if (property.PropertyType.ImplementsGenericInterface(typeof(ICollection<>)))
{
value = Activator.CreateInstance(typeof(Collection<>).MakeGenericType(property.PropertyType.GetGenericArguments()));
}
else
{
value = Activator.CreateInstance(property.PropertyType);
}
property.SetValue(enreplacedy, value);
}
if (value is ICollection collection)
{
foreach (var v in collection)
{
await PopulateSubEnreplacedyAsync("Id", v).ConfigureAwait(false);
var idProperty = v.GetType().GetProperty(idName);
idProperty.SetValue(v, enreplacedy.Id);
}
return;
}
var parentIdProperty = _enreplacedyType.GetProperty($"{path}Id");
((IEnreplacedyId)value).Id = parentIdProperty.GetValue(enreplacedy) as string;
await PopulateSubEnreplacedyAsync("Id", value).ConfigureAwait(false);
parentIdProperty.SetValue(enreplacedy, ((IEnreplacedyId)value).Id);
}
19
View Source File : AdminStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
private static void CloneEnreplacedy(object enreplacedy, Type type, object loaded)
{
foreach (var property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
property.SetValue(enreplacedy, property.GetValue(loaded));
}
}
19
View Source File : ImportService.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
private static Dictionary<string, IEnumerable> GetSubEnreplacedies(T enreplacedy)
{
var collectionPropertyList = typeof(T).GetProperties().Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetInterface(typeof(IEnumerable<>).Name) != null);
var dictionary = new Dictionary<string, IEnumerable>(collectionPropertyList.Count());
foreach(var property in collectionPropertyList)
{
if (property.GetValue(enreplacedy) is not IEnumerable values)
{
continue;
}
dictionary[property.Name] = values;
property.SetValue(enreplacedy, null); // remove sub enreplacedies from enreplacedy object
}
return dictionary;
}
19
View Source File : AdminStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
private async Task PopulateSubEnreplacediesAsync(string path, TEnreplacedy enreplacedy)
{
var property = _enreplacedyType.GetProperty(path);
var propertyType = property.PropertyType;
if (propertyType.ImplementsGenericInterface(typeof(ICollection<>)))
{
var items = await GetSubItemsAsync(enreplacedy, propertyType).ConfigureAwait(false);
property.SetValue(enreplacedy, items);
return;
}
var navigationProperty = _enreplacedyType.GetProperty($"{path}Id");
var parentId = navigationProperty.GetValue(enreplacedy) as string;
var storeType = typeof(IAdminStore<>).MakeGenericType(propertyType);
var subStore = _provider.GetRequiredService(storeType);
var getMethod = storeType.GetMethod(nameof(IAdminStore<object>.GetAsync), new[] { typeof(string), typeof(GetRequest), typeof(CancellationToken) });
var task = getMethod.Invoke(subStore, new[]
{
parentId,
null,
null
});
await (task as Task).ConfigureAwait(false);
var response = task.GetType().GetProperty(nameof(Task<object>.Result)).GetValue(task);
property.SetValue(enreplacedy, response);
}
19
View Source File : ScrollBar.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
License : Mozilla Public License 2.0
Project Creator : ahyahy
public void ScrollBarManagedProperties()
{
if (ManagedProperties.Count > 0)
{
foreach (ClManagedProperty ClManagedProperty1 in ManagedProperties.Base_obj)
{
object obj1 = ClManagedProperty1.ManagedObject;
string prop1 = "";
float ratio1 = 1.0f;
if (ClManagedProperty1.Ratio == null)
{
}
else
{
ratio1 = Convert.ToSingle(ClManagedProperty1.Ratio.AsNumber());
}
System.Reflection.PropertyInfo[] myPropertyInfo;
myPropertyInfo = obj1.GetType().GetProperties();
for (int i = 0; i < myPropertyInfo.Length; i++)
{
System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData> CustomAttributeData1 =
myPropertyInfo[i].CustomAttributes;
foreach (System.Reflection.CustomAttributeData CustomAttribute1 in CustomAttributeData1)
{
string quote = "\"";
string text = CustomAttribute1.ToString();
if (text.Contains("[ScriptEngine.Machine.Contexts.ContextPropertyAttribute(" + quote))
{
text = text.Replace("[ScriptEngine.Machine.Contexts.ContextPropertyAttribute(" + quote, "");
text = text.Replace(quote + ", " + quote, " ");
text = text.Replace(quote + ")]", "");
string[] stringSeparators = new string[] { };
string[] result = text.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
if (ClManagedProperty1.ManagedProperty == result[0])
{
prop1 = result[1];
break;
}
}
}
}
System.Type Type1 = obj1.GetType();
float _Value = Convert.ToSingle(v_h_ScrollBar.Value);
int res = Convert.ToInt32(ratio1 * _Value);
if (Type1.GetProperty(prop1).PropertyType.ToString() != "System.String")
{
Type1.GetProperty(prop1).SetValue(obj1, res);
}
else
{
Type1.GetProperty(prop1).SetValue(obj1, res.ToString());
}
}
}
}
19
View Source File : TypeExtensions.cs
License : MIT License
Project Creator : ahydrax
License : MIT License
Project Creator : ahydrax
private static object CreateSampleInstanceInternal(this Type type, int currentDepth, int maxDepth)
{
if (currentDepth > maxDepth) return GetDefaultValue(type);
var instance = Activator.CreateInstance(type);
foreach (var property in type.GetProperties())
{
var propertyType = property.PropertyType;
if (propertyType.CanBeInstantiated())
{
type.GetProperty(property.Name).SetValue(instance,
propertyType.CreateSampleInstanceInternal(currentDepth + 1, SampleMaxDepth));
}
if (typeof(IEnumerable).IsreplacedignableFrom(propertyType)
&& propertyType != typeof(string))
{
var elementType = propertyType.IsArray
? propertyType.GetElementType()
: propertyType.GenericTypeArguments[0];
var array = Array.CreateInstance(elementType, 1);
array.SetValue(
elementType.CanBeInstantiated()
? elementType.CreateSampleInstanceInternal(currentDepth + 1, SampleMaxDepth)
: GetDefaultValue(elementType),
0);
type.GetProperty(property.Name).SetValue(instance, array);
}
}
return instance;
}
19
View Source File : CommandsNextUtilities.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
internal static object CreateInstance(this Type t, IServiceProvider services)
{
var ti = t.GetTypeInfo();
var constructors = ti.DeclaredConstructors
.Where(xci => xci.IsPublic)
.ToArray();
if (constructors.Length != 1)
throw new ArgumentException("Specified type does not contain a public constructor or contains more than one public constructor.");
var constructor = constructors[0];
var constructorArgs = constructor.GetParameters();
var args = new object[constructorArgs.Length];
if (constructorArgs.Length != 0 && services == null)
throw new InvalidOperationException("Dependency collection needs to be specified for parameterized constructors.");
// inject via constructor
if (constructorArgs.Length != 0)
for (var i = 0; i < args.Length; i++)
args[i] = services.GetRequiredService(constructorArgs[i].ParameterType);
var moduleInstance = Activator.CreateInstance(t, args);
// inject into properties
var props = t.GetRuntimeProperties().Where(xp => xp.CanWrite && xp.SetMethod != null && !xp.SetMethod.IsStatic && xp.SetMethod.IsPublic);
foreach (var prop in props)
{
if (prop.GetCustomAttribute<DontInjectAttribute>() != null)
continue;
var service = services.GetService(prop.PropertyType);
if (service == null)
continue;
prop.SetValue(moduleInstance, service);
}
// inject into fields
var fields = t.GetRuntimeFields().Where(xf => !xf.IsInitOnly && !xf.IsStatic && xf.IsPublic);
foreach (var field in fields)
{
if (field.GetCustomAttribute<DontInjectAttribute>() != null)
continue;
var service = services.GetService(field.FieldType);
if (service == null)
continue;
field.SetValue(moduleInstance, service);
}
return moduleInstance;
}
19
View Source File : InstranceMaker.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public static object Make(this Type type)
{
if (type == typeof(string))
{
return "an example string.";
}
else if (type == typeof(int) || type == typeof(int?))
{
return 0;
}
else if (type == typeof(DateTime) || type == typeof(DateTime?))
{
return DateTime.UtcNow;
}
else if (type == typeof(Guid) || type == typeof(Guid?))
{
return Guid.NewGuid();
}
else if (type == typeof(DateTimeOffset) || type == typeof(DateTimeOffset?))
{
return DateTimeOffset.UtcNow;
}
else if (type == typeof(TimeSpan) || type == typeof(TimeSpan?))
{
return TimeSpan.FromMinutes(37);
}
else if (type == typeof(bool) || type == typeof(bool?))
{
return true;
}
// List
else if (type.IsGenericType && type.GetGenericTypeDefinition().GetInterfaces().Any(t => t.IsreplacedignableFrom(typeof(IEnumerable))))
{
var itemType = type.GetGenericArguments()[0];
return GetArrayWithInstanceInherts(itemType);
}
// Array
else if (type.GetInterface(typeof(IEnumerable<>).FullName ?? string.Empty) != null)
{
var itemType = type.GetElementType();
var list = GetArrayWithInstanceInherts(itemType);
var array = Array.CreateInstance(itemType ?? typeof(string[]), list.Count);
list.CopyTo(array, 0);
return array;
}
else
{
var instance = GenerateWithConstructor(type);
if (instance != null)
{
foreach (var property in instance.GetType().GetProperties())
{
if (property.CustomAttributes.Any(t => t.AttributeType == typeof(JsonIgnoreAttribute)))
{
property.SetValue(instance, null);
}
else if (property.CustomAttributes.Any(t => t.AttributeType == typeof(InstanceMakerIgnore)))
{
property.SetValue(instance, null);
}
else if (property.SetMethod != null)
{
property.SetValue(instance, Make(property.PropertyType));
}
}
}
return instance;
}
}
19
View Source File : OffsetManager.cs
License : GNU Affero General Public License v3.0
Project Creator : akira0245
License : GNU Affero General Public License v3.0
Project Creator : akira0245
public static void Setup(SigScanner scanner)
{
var props = typeof(Offsets).GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
.Select(i => (prop: i, Attribute: i.GetCustomAttribute<SigAttribute>())).Where(i => i.Attribute != null);
List<Exception> exceptions = new List<Exception>(100);
foreach ((PropertyInfo propertyInfo, SigAttribute sigAttribute) in props)
{
try
{
var sig = sigAttribute.SigString;
sig = string.Join(' ', sig.Split(new[] { ' ' }, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
.Select(i => i == "?" ? "??" : i));
IntPtr address;
switch (sigAttribute)
{
case StaticAddressAttribute:
address = scanner.GetStaticAddressFromSig(sig);
break;
case FunctionAttribute:
address = scanner.ScanText(sig);
break;
case OffsetAttribute:
{
address = scanner.ScanText(sig);
address += sigAttribute.Offset;
var structure = Marshal.PtrToStructure(address, propertyInfo.PropertyType);
propertyInfo.SetValue(null, structure);
PluginLog.Information($"[{nameof(OffsetManager)}][{propertyInfo.Name}] {propertyInfo.PropertyType.FullName} {structure}");
continue;
}
default:
throw new ArgumentOutOfRangeException();
}
address += sigAttribute.Offset;
propertyInfo.SetValue(null, address);
PluginLog.Information($"[{nameof(OffsetManager)}][{propertyInfo.Name}] {address.ToInt64():X}");
}
catch (Exception e)
{
PluginLog.Error(e, $"[{nameof(OffsetManager)}][{propertyInfo?.Name}] failed to find sig : {sigAttribute?.SigString}");
exceptions.Add(e);
}
}
if (exceptions.Any())
{
throw new AggregateException(exceptions);
}
}
19
View Source File : Uncapsulator.cs
License : MIT License
Project Creator : albahari
License : MIT License
Project Creator : albahari
public void SetValue (object instance, object value)
{
if (MemberInfo is FieldInfo fi)
fi.SetValue (instance, value);
else
((PropertyInfo)MemberInfo).SetValue (instance, value);
}
19
View Source File : Parser.Internal.cs
License : MIT License
Project Creator : AlexGhiondea
License : MIT License
Project Creator : AlexGhiondea
private static TOptions InternalParse<TOptions>(string[] args, int offsetInArray, ArgumentGroupInfo arguments, ParserOptions parseOptions)
where TOptions : new()
{
TOptions options = new TOptions();
int currentLogicalPosition = 0;
// let's match them to actual required args, in positional
if (arguments.RequiredArguments.Count > 0)
{
ParseRequiredParameters(args, offsetInArray, arguments, options, ref currentLogicalPosition);
}
// we are going to keep track of any properties that have not been specified so that we can set their default value.
var unmatchedOptionalProperties = ParseOptionalParameters(args, offsetInArray, arguments, options, ref currentLogicalPosition);
// for all the remaining optional properties, set their default value.
foreach (var property in unmatchedOptionalProperties)
{
//get the default value..
var value = property.GetCustomAttribute<OptionalArgumentAttribute>();
object defaultValue = value.DefaultValue;
// If we want to read values from the environment, try to get the value
if (parseOptions.ReadFromEnvironment && !value.IsCollection && parseOptions.VariableNamePrefix != null)
{
var envVar = Environment.GetEnvironmentVariable($"{parseOptions.VariableNamePrefix}{value.Name}");
if (!string.IsNullOrEmpty(envVar))
{
defaultValue = PropertyHelpers.GetValueForProperty(envVar, property);
}
}
property.SetValue(options, Convert.ChangeType(defaultValue, property.PropertyType));
}
return options;
}
19
View Source File : Parser.Internal.cs
License : MIT License
Project Creator : AlexGhiondea
License : MIT License
Project Creator : AlexGhiondea
private static void ParseRequiredParameters<TOptions>(string[] args, int offsetInArray, ArgumentGroupInfo TypeArgumentInfo, TOptions options, ref int currentLogicalPosition) where TOptions : new()
{
if (args.Length == 0)
{
throw new ArgumentException("Required parameters have not been specified");
}
int matchedRequiredParameters = 0;
do
{
//set the required property
PropertyInfo propInfo;
if (!TypeArgumentInfo.RequiredArguments.TryGetValue(currentLogicalPosition, out propInfo))
{
break;
}
//make sure that we don't run out of array
if (offsetInArray + currentLogicalPosition >= args.Length)
{
throw new ArgumentException("Required parameters have not been specified");
}
object value = PropertyHelpers.GetValueFromArgsArray(args, offsetInArray, ref currentLogicalPosition, propInfo);
propInfo.SetValue(options, value);
matchedRequiredParameters++;
} while (offsetInArray + currentLogicalPosition < args.Length);
// no more? do we have any properties that we have not yet set?
if (TypeArgumentInfo.RequiredArguments.Count != matchedRequiredParameters)
{
throw new ArgumentException("Not all required arguments have been specified");
}
}
19
View Source File : SelectableTextBlock.cs
License : GNU General Public License v3.0
Project Creator : alexdillon
License : GNU General Public License v3.0
Project Creator : alexdillon
public static TextEditorWrapper CreateFor(TextBlock tb)
{
var textContainer = TextContainerProp.GetValue(tb);
var editor = new TextEditorWrapper(textContainer, tb, false);
IsReadOnlyProp.SetValue(editor.editor, true);
TextViewProp.SetValue(editor.editor, TextContainerTextViewProp.GetValue(textContainer));
return editor;
}
19
View Source File : PayloadExtensions.cs
License : Apache License 2.0
Project Creator : alexz76
License : Apache License 2.0
Project Creator : alexz76
internal static object ToFinalPayload(this object originalModel, IList<object> links)
{
if (originalModel == null)
{
throw new InvalidOperationException("It must be a non-nullable instance.");
}
if (!links.Any())
{
return originalModel;
}
var originalType = originalModel.GetType();
replacedemblyBuilder replacedemblyBuilder = replacedemblyBuilder.DefineDynamicreplacedembly(new replacedemblyName("Sciensoft.Hateoas.Links"), replacedemblyBuilderAccess.RunAndCollect);
ModuleBuilder moduleBuilder = replacedemblyBuilder.DefineDynamicModule("DynamicLinkModule");
TypeBuilder typeBuilder = moduleBuilder.DefineType("LinkModel", TypeAttributes.Public | TypeAttributes.Clreplaced | TypeAttributes.AutoClreplaced, null); // itemType
var originalValues = new Dictionary<string, object>();
foreach (var property in originalType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy))
{
CreateProperty(typeBuilder, property.Name, property.PropertyType);
originalValues.TryAdd(property.Name, property.GetValue(originalModel));
}
CreateProperty(typeBuilder, "Links", links.GetType());
var payloadType = typeBuilder.CreateType();
var payloadInstance = Activator.CreateInstance(payloadType);
foreach (var pv in originalValues)
{
payloadType.GetProperty(pv.Key).SetValue(payloadInstance, pv.Value);
}
payloadType.GetProperty("Links").SetValue(payloadInstance, links);
return payloadInstance;
}
19
View Source File : YellowTeleportationPortal.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
private void SetProperties(BlueTeleportationPortal a)
{
foreach (var p in properties)
p.SetValue(this, p.GetValue(a));
Y = a.Y + a.YellowTeleportationPortalDistance;
Rotation = a.Rotation;
}
19
View Source File : PropertySynchronizer.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
public void Invoke( object obj, bool propertyGetToSet )
{
if ( !IsValid )
return;
if ( propertyGetToSet )
m_property.SetValue( obj, m_property.GetValue( obj ) );
else
m_property.SetValue( obj, m_field.GetValue( obj ) );
}
19
View Source File : PropertySynchronizer.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
public void Invoke( object source, object destination, bool onlyValueTypes )
{
if ( !IsValid )
return;
if ( m_field.FieldType.IsValueType )
m_property.SetValue( destination, m_property.GetValue( source ) );
else if ( !onlyValueTypes && m_property.GetSetMethod() != null && m_property.GetSetMethod().IsPublic )
m_property.SetValue( destination, m_property.GetValue( source ) );
}
19
View Source File : Pool.cs
License : MIT License
Project Creator : AliakseiFutryn
License : MIT License
Project Creator : AliakseiFutryn
private static void CleanUp(TValue item)
{
// Sets default values to all properties.
item.GetType()
.GetProperties(BindingFlags.Public)
.ToList()
.ForEach(propertyInfo => propertyInfo.SetValue(item, GetDefaultValue(propertyInfo.PropertyType)));
// Sets default values to all fields.
item.GetType()
.GetFields(BindingFlags.Public)
.ToList()
.ForEach(fieldInfo => fieldInfo.SetValue(item, GetDefaultValue(fieldInfo.FieldType)));
}
19
View Source File : ConsoleApp.cs
License : MIT License
Project Creator : allisterb
License : MIT License
Project Creator : allisterb
internal static void SetPropFromDict(Type t, object o, Dictionary<string, object> p)
{
foreach (PropertyInfo prop in t.GetProperties())
{
if (p.ContainsKey(prop.Name) && prop.PropertyType == p[prop.Name].GetType())
{
prop.SetValue(o, p[prop.Name]);
}
}
}
19
View Source File : FieldPropertyListInfo.cs
License : MIT License
Project Creator : allenwp
License : MIT License
Project Creator : allenwp
public void SetValue(object value)
{
if (fieldInfo != null)
{
fieldInfo.SetValue(obj, value);
}
else if (propertyInfo != null)
{
propertyInfo.SetValue(obj, value);
}
else if (list != null)
{
list[listIndex] = value;
}
else
{
throw new NotImplementedException();
}
}
19
View Source File : Stage.cs
License : MIT License
Project Creator : allisterb
License : MIT License
Project Creator : allisterb
protected static void SetPropFromDict(Type t, object o, Dictionary<string, object> p)
{
foreach (PropertyInfo prop in t.GetProperties())
{
if (p.ContainsKey(prop.Name) && prop.PropertyType == p[prop.Name].GetType())
{
prop.SetValue(o, p[prop.Name]);
}
}
}
19
View Source File : DataHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
private static void ResetDataField(string[] keys, object data, int index = 0)
{
string key = keys[index];
Type current = data.GetType();
bool isLastKey = (keys.Length - 1) == index;
PropertyInfo property = current.GetProperty(
key,
BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (property == null)
{
return;
}
object propertyValue = property.GetValue(data, null);
if (propertyValue == null)
{
return;
}
if (isLastKey)
{
object defaultValue = property.PropertyType.IsValueType ? Activator.CreateInstance(property.PropertyType) : null;
property.SetValue(data, defaultValue);
return;
}
ResetDataField(keys, property.GetValue(data, null), index + 1);
}
19
View Source File : Program.cs
License : MIT License
Project Creator : anastasios-stamoulis
License : MIT License
Project Creator : anastasios-stamoulis
static void Main(string[] args) {
// make sure that the hard-coded values have been set up correctly
if ( System.IO.Directory.Exists(PYTHON_HOME_)==false ) {
throw new NotSupportedException("Please set PYTHON_HOME_ properly");
}
if ( System.IO.File.Exists(PYTHONNET_DLL_)==false ) {
throw new NotSupportedException("Probably you have not pip-installed pythonnet");
}
if ( System.IO.Directory.Exists(KERAS_PORTED_CODE_)==false ) {
throw new NotSupportedException("Need to initialize KERAS_PORTED_CODE_");
}
System.Console.replacedle = "Ch_08_Deep_Dream";
// set model_path, and image_path
var vgg16_model_path = DeepLearningWithCNTK.VGG16.download_model_if_needed();
var image_path = DeepLearningWithCNTK.Util.get_the_path_of_the_elephant_image();
// modify the environment variables
var to_be_added_to_path = PYTHON_HOME_ + ";" + KERAS_PORTED_CODE_;
var path = Environment.GetEnvironmentVariable("PATH");
path = to_be_added_to_path + ";" + path;
Environment.SetEnvironmentVariable("PATH", path);
Environment.SetEnvironmentVariable("PYTHONPATH", path);
// load the Python.NET dll, and start the (embedded) Python engine
var dll = System.Reflection.replacedembly.LoadFile(PYTHONNET_DLL_);
var PythonEngine = dll.GetType("Python.Runtime.PythonEngine");
// to be on the safe side, update the PythonPath of the local engine
var PythonPathProperty = PythonEngine.GetProperty("PythonPath");
var pythonPath = (string)PythonPathProperty.GetValue(null);
pythonPath += ";" + KERAS_PORTED_CODE_;
pythonPath += ";" + PYTHON_HOME_ + "\\Lib\\site-packages";
PythonPathProperty.SetValue(null, pythonPath);
// let's start executing some python code
dynamic Py = dll.GetType("Python.Runtime.Py");
dynamic GIL = Py.GetMethod("GIL").Invoke(null, null);
// import "ch8-2.py"
dynamic ch8_2 = Py.GetMethod("Import").Invoke(null, new object[] { "ch8-2" });
// response = ch8_2.get_response("Hi From C#")
var response = ch8_2.get_response("Hi From C#");
Console.WriteLine("C# received: "+response);
Console.WriteLine("\n\n");
// let's call the run_cntk function from the Python script
var img = ch8_2.run_cntk(image_path, vgg16_model_path);
// convert the python numpy array to byte[]
byte[] img_data = convert_uint8_numpy_array_to_byte_array(img);
// display the image with OpenCV
var mat = new OpenCvSharp.Mat(224, 224, OpenCvSharp.MatType.CV_8UC3, img_data, 3 * 224);
OpenCvSharp.Cv2.ImShow("The Dream", mat);
// Show also the original image
OpenCvSharp.Cv2.ImShow("Original", OpenCvSharp.Cv2.ImRead(image_path).Resize(new OpenCvSharp.Size(224, 224)));
OpenCvSharp.Cv2.WaitKey(0);
GIL.Dispose();
}
19
View Source File : HotReloader.cs
License : MIT License
Project Creator : AndreiMisiukevich
License : MIT License
Project Creator : AndreiMisiukevich
private Exception RebuildElement(object obj, XmlDoreplacedent xmlDoc)
{
try
{
switch (obj)
{
case MultiPage<Page> multiPage:
multiPage.Children.Clear();
break;
case ContentPage contentPage:
contentPage.Content = null;
break;
case ContentView contentView:
contentView.Content = null;
break;
case ScrollView scrollView:
scrollView.Content = null;
break;
case Layout<View> layout:
layout.Children.Clear();
break;
case Application app:
app.Resources.Clear();
break;
}
if (IsSubclreplacedOfShell(obj))
{
var shellType = obj.GetType();
shellType.GetProperty("FlyoutHeaderTemplate", BindingFlags.Instance | BindingFlags.Public).SetValue(obj, null);
shellType.GetProperty("FlyoutHeader", BindingFlags.Instance | BindingFlags.Public).SetValue(obj, null);
var items = shellType.GetProperty("Items", BindingFlags.Instance | BindingFlags.Public).GetValue(obj, null);
items.GetType().GetMethod("Clear", BindingFlags.Instance | BindingFlags.Public).Invoke(items, null);
}
if (obj is Grid grid)
{
grid.RowDefinitions.Clear();
grid.ColumnDefinitions.Clear();
}
if (obj is View view)
{
ClearView(view, xmlDoc);
}
if (obj is Page page)
{
page.ToolbarItems.Clear();
}
if (obj is ViewCell cell)
{
return UpdateViewCell(cell, xmlDoc.InnerXml);
}
LoadFromXaml(obj, xmlDoc);
return null;
}
catch (Exception ex)
{
return ex;
}
}
19
View Source File : ExpressionHelpers.cs
License : MIT License
Project Creator : angelsix
License : MIT License
Project Creator : angelsix
public static void SetPropertyValue<T>(this Expression<Func<T>> lambda, T value)
{
// Converts a lambda () => some.Property, to some.Property
var expression = (lambda as LambdaExpression).Body as MemberExpression;
// Get the property information so we can set it
var propertyInfo = (PropertyInfo)expression.Member;
var target = Expression.Lambda(expression.Expression).Compile().DynamicInvoke();
// Set the property value
propertyInfo.SetValue(target, value);
}
19
View Source File : ExpressionHelpers.cs
License : MIT License
Project Creator : angelsix
License : MIT License
Project Creator : angelsix
public static void SetPropertyValue<In, T>(this Expression<Func<In, T>> lambda, T value, In input)
{
// Converts a lambda () => some.Property, to some.Property
var expression = (lambda as LambdaExpression).Body as MemberExpression;
// Get the property information so we can set it
var propertyInfo = (PropertyInfo)expression.Member;
// Set the property value
propertyInfo.SetValue(input, value);
}
19
View Source File : ExpressionHelpers.cs
License : MIT License
Project Creator : angelsix
License : MIT License
Project Creator : angelsix
public static void SetPropertyValue<T>(this Expression<Func<T>> lambda, object value)
{
// Get the member expression
var expression = GetMemberExpression(lambda);
// Get the property info from the member
var propertyInfo = (PropertyInfo)expression.Member;
// Create a target value to set the property
var target = Expression.Lambda(expression.Expression).Compile().DynamicInvoke();
// Reflect to set the property value
propertyInfo.SetValue(target, value);
}
19
View Source File : ModifyObjectPropertiesOperation.cs
License : MIT License
Project Creator : AnnoDesigner
License : MIT License
Project Creator : AnnoDesigner
protected override void UndoOperation()
{
foreach (var (obj, oldValue, _) in ObjectPropertyValues)
{
propertyInfo.SetValue(obj, oldValue);
}
}
19
View Source File : ModifyObjectPropertiesOperation.cs
License : MIT License
Project Creator : AnnoDesigner
License : MIT License
Project Creator : AnnoDesigner
protected override void RedoOperation()
{
foreach (var (obj, _, newValue) in ObjectPropertyValues)
{
propertyInfo.SetValue(obj, newValue);
}
}
19
View Source File : Settings.Defaults.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
public void Reset()
{
lock (this.locker)
{
var pis = this.GetType().GetProperties();
foreach (var pi in pis)
{
try
{
var defaultValue =
DefaultValues.ContainsKey(pi.Name) ?
DefaultValues[pi.Name] :
null;
if (defaultValue != null)
{
pi.SetValue(this, defaultValue);
}
}
catch
{
Debug.WriteLine($"Settings Reset Error: {pi.Name}");
}
}
}
}
19
View Source File : ITrigger.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
public static async void ImportProperties(
this ITrigger t,
ITrigger source)
{
if (source == null ||
t == null)
{
return;
}
var properties = source.GetType().GetProperties(
BindingFlags.Public |
BindingFlags.Instance)
.Where(x =>
x.CanRead &&
x.CanWrite);
await WPFHelper.InvokeAsync(() =>
{
foreach (var pi in properties)
{
if (t.GetType().GetProperty(pi.Name) == null ||
ImportIgnoreProperties.Contains(pi.Name))
{
continue;
}
var attrs = pi.GetCustomAttributes(true);
if (attrs.Any(a => a is XmlIgnoreAttribute))
{
continue;
}
pi.SetValue(t, pi.GetValue(source));
Thread.Yield();
(t as TreeItemBase)?.ExecuteRaisePropertyChanged(pi.Name);
Thread.Yield();
}
switch (t)
{
case Spell spell:
spell.Enabled = true;
break;
case Ticker ticker:
ticker.Enabled = true;
break;
}
});
}
19
View Source File : Settings.Defaults.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
public void Reset()
{
lock (locker)
{
var pis = this.GetType().GetProperties();
foreach (var pi in pis)
{
try
{
var defaultValue =
DefaultValues.ContainsKey(pi.Name) ?
DefaultValues[pi.Name] :
null;
if (defaultValue != null)
{
pi.SetValue(this, defaultValue);
}
}
catch
{
Debug.WriteLine($"Settings Reset Error: {pi.Name}");
}
}
}
}
See More Examples