System.Reflection.PropertyInfo.GetValue(object)

Here are the examples of the csharp api System.Reflection.PropertyInfo.GetValue(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2117 Examples 7

19 Source : ScAllColumnTypes.cs
with MIT License
from 0x1000000

public async Task Exec(IScenarioContext context)
        {
            bool isPostgres = context.Dialect == SqlDialect.PgSql;
            var table = new TableItAllColumnTypes(isPostgres);
            await context.Database.Statement(table.Script.DropAndCreate());

            var testData = GetTestData(isPostgres);

            await InsertDataInto(table, testData)
                .MapData(Mapping)
                .Exec(context.Database);

            var mapper = new Mapper(new MapperConfiguration(cfg =>
            {
                cfg.AddDataReaderMapping();
                var map = cfg.CreateMap<IDataRecord, AllColumnTypesDto>();

                map
                    .ForMember(nameof(table.ColByteArraySmall), c => c.Ignore())
                    .ForMember(nameof(table.ColByteArrayBig), c => c.Ignore())
                    .ForMember(nameof(table.ColNullableByteArraySmall), c => c.Ignore())
                    .ForMember(nameof(table.ColNullableByteArrayBig), c => c.Ignore())
                    .ForMember(nameof(table.ColNullableFixedSizeByteArray), c => c.Ignore())
                    .ForMember(nameof(table.ColFixedSizeByteArray), c => c.Ignore());

                if (isPostgres)
                {
                    map
                        .ForMember(nameof(table.ColByte), c => c.Ignore())
                        .ForMember(nameof(table.ColNullableByte), c => c.Ignore());
                }
                if (context.Dialect == SqlDialect.MySql)
                {
                    map
                        .ForMember(nameof(table.ColBoolean), c => c.MapFrom((r, dto) => r.GetBoolean(r.GetOrdinal(nameof(table.ColBoolean)))))
                        .ForMember(nameof(table.ColNullableBoolean), c => c.MapFrom((r, dto) => r.IsDBNull(r.GetOrdinal(nameof(table.ColNullableBoolean))) ? (bool?)null : r.GetBoolean(r.GetOrdinal(nameof(table.ColNullableBoolean)))))
                        .ForMember(nameof(table.ColGuid), c => c.MapFrom((r, dto) => r.GetGuid(r.GetOrdinal(nameof(table.ColGuid)))))
                        .ForMember(nameof(table.ColNullableGuid), c=>c.MapFrom((r, dto) => r.IsDBNull(r.GetOrdinal(nameof(table.ColNullableGuid)))? (Guid?)null : r.GetGuid(r.GetOrdinal(nameof(table.ColNullableGuid)))));
                }
            }));

            var expr = Select(table.Columns)
                .From(table).Done();

            context.WriteLine(PgSqlExporter.Default.ToSql(expr));

            var result = await expr
                .QueryList(context.Database, r =>
                {
                    var allColumnTypesDto = mapper.Map<IDataRecord, AllColumnTypesDto>(r);

                    allColumnTypesDto.ColByteArrayBig = StreamToByteArray(table.ColByteArrayBig.GetStream(r));
                    allColumnTypesDto.ColByteArraySmall = table.ColByteArraySmall.Read(r);
                    allColumnTypesDto.ColNullableByteArrayBig = table.ColNullableByteArrayBig.Read(r);
                    allColumnTypesDto.ColNullableByteArraySmall = table.ColNullableByteArraySmall.Read(r);
                    allColumnTypesDto.ColFixedSizeByteArray = table.ColFixedSizeByteArray.Read(r);
                    allColumnTypesDto.ColNullableFixedSizeByteArray = table.ColNullableFixedSizeByteArray.Read(r);

                    return allColumnTypesDto;
                });

            static byte[] StreamToByteArray(Stream stream)
            {
                var buffer = new byte[stream.Length];

                using MemoryStream ms = new MemoryStream(buffer);

                stream.CopyTo(ms);

                var result = buffer;

                stream.Dispose();

                return result;
            }

            for (int i = 0; i < testData.Length; i++)
            {
                if (!Equals(testData[i], result[i]))
                {
                    var props = typeof(AllColumnTypesDto).GetProperties();
                    foreach (var propertyInfo in props)
                    {
                        context.WriteLine($"{propertyInfo.Name}: {propertyInfo.GetValue(testData[i])} - {propertyInfo.GetValue(result[i])}");
                    }

                    throw new Exception("Input and output are not identical!");
                }
            }

            if (context.Dialect == SqlDialect.TSql)
            {
                var data = await Select(AllTypes.GetColumns(table))
                    .From(table)
                    .QueryList(context.Database, (r) => AllTypes.Read(r, table));

                if (data.Count != 2)
                {
                    throw new Exception("Incorrect reading using models");
                }

                await InsertDataInto(table, data).MapData(AllTypes.GetMapping).Exec(context.Database);
            }


            Console.WriteLine("'All Column Type Test' is preplaceded");
        }

19 Source : DefaultCacheKeyBuilder.cs
with MIT License
from 1100100

public string Generate(string sql, object param, string customKey, int? pageIndex = default, int? pageSize = default)
        {
            if (!string.IsNullOrWhiteSpace(customKey))
                return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{customKey}";

            if (string.IsNullOrWhiteSpace(sql))
                throw new ArgumentNullException(nameof(sql));

            var builder = new StringBuilder();
            builder.AppendFormat("{0}:", sql);

            if (param == null)
                return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{HashCacheKey(builder.ToString().TrimEnd(':'))}";

            var prop = GetProperties(param);
            foreach (var item in prop)
            {
                builder.AppendFormat("{0}={1}&", item.Name, item.GetValue(param));
            }
            if (pageIndex.HasValue)
            {
                builder.AppendFormat("pageindex={0}&", pageIndex.Value);
            }
            if (pageSize.HasValue)
            {
                builder.AppendFormat("pagesize={0}&", pageSize.Value);
            }
            return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{HashCacheKey(builder.ToString().TrimEnd('&'))}";
        }

19 Source : ExpressionResovle.cs
with Apache License 2.0
from 1448376744

public object VisitConstantValue(Expression expression)
        {
            var names = new Stack<string>();
            var exps = new Stack<Expression>();
            var mifs = new Stack<MemberInfo>();
            if (expression is ConstantExpression constant)
                return constant.Value;
            else if (expression is MemberExpression)
            {
                var temp = expression;
                object value = null;
                while (temp is MemberExpression memberExpression)
                {
                    names.Push(memberExpression.Member.Name);
                    exps.Push(memberExpression.Expression);
                    mifs.Push(memberExpression.Member);
                    temp = memberExpression.Expression;
                }
                foreach (var name in names)
                {
                    var exp = exps.Pop();
                    var mif = mifs.Pop();
                    if (exp is ConstantExpression cex)
                        value = cex.Value;
                    if (mif is PropertyInfo pif)
                        value = pif.GetValue(value);
                    else if (mif is FieldInfo fif)
                        value = fif.GetValue(value);
                }
                return value;
            }
            else
            {
                return Expression.Lambda(expression).Compile().DynamicInvoke();
            }
        }

19 Source : TypeUtils.cs
with MIT License
from 1996v

public static IEnumerable<KeyValuePair<string, object>> GetPublicMembersWithDynamicObject(this object value)
        {
            DEBUG.replacedert(value != null);
            Type t = value.GetType();
            foreach (FieldInfo p in t.GetFields(BindingFlags.Public | BindingFlags.Instance))
            {
                yield return new KeyValuePair<string, object>(p.Name, p.GetValue(value));
            }
            foreach (PropertyInfo p in t.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (p.GetIndexParameters().Length == 0 && p.CanRead && p.CanWrite)
                {
                    yield return new KeyValuePair<string, object>(p.Name, p.GetValue(value));
                }
            }
        }

19 Source : BuildInFormatters.cs
with MIT License
from 1996v

public void Serialize(ref BssomWriter writer, ref BssomSerializeContext context, T value)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }
            PropertyInfo[] properties = typeof(T).GetProperties();
            MapFormatterHelper.Serialize(ref writer, ref context, properties.Select(e => new KeyValuePair<string, object>(e.Name, e.GetValue(value))), properties.Length);
        }

19 Source : BuildInFormatters.cs
with MIT License
from 1996v

public int Size(ref BssomSizeContext context, T value)
        {
            if (value == null)
            {
                return BssomBinaryPrimitives.NullSize;
            }

            PropertyInfo[] properties = typeof(T).GetProperties();
            return MapFormatterHelper.Size(ref context, properties.Select(e => new KeyValuePair<string, object>(e.Name, e.GetValue(value))), properties.Length);
        }

19 Source : RandomHelper.cs
with MIT License
from 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 Source : RandomHelper.cs
with MIT License
from 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 Source : SegmentedControlOption.cs
with MIT License
from 1iveowl

private void SetTextFromItemProperty()
        {
            if (Item != null && TextPropertyName != null)
                Text = Item.GetType().GetProperty(TextPropertyName)?.GetValue(Item)?.ToString();
        }

19 Source : XmlHelper.cs
with MIT License
from 279328316

public static void Serialize<T>(T dto, string xmlPathName) where T : clreplaced, new()
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            Type modelType = typeof(T);
            XmlDeclaration declaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
            xmlDoc.AppendChild(declaration);
            XmlElement root = xmlDoc.CreateElement(modelType.Name);
            xmlDoc.AppendChild(root);

            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)
            {
                object value = pi.GetValue(dto);
                if (value != null)
                {
                    var propertyNode = xmlDoc.CreateNode(XmlNodeType.Element, pi.Name, "");
                    propertyNode.InnerText = value.ToString();
                    root.AppendChild(propertyNode);
                }
            }
            xmlDoc.Save(xmlPathName);
        }

19 Source : XmlHelper.cs
with MIT License
from 279328316

public static void SerializeCollection<T>(IEnumerable<T> list, string filePath) where T : clreplaced, new()
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            Type modelType = typeof(T);
            XmlDeclaration declaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
            xmlDoc.AppendChild(declaration);
            XmlElement root = xmlDoc.CreateElement(string.Format("{0}List", modelType.Name));
            xmlDoc.AppendChild(root);

            List<PropertyInfo> piList = modelType.GetProperties().Where(pro => (pro.PropertyType.Equals(typeof(string)) || pro.PropertyType.IsValueType) && pro.CanRead && pro.CanWrite).ToList();
            foreach (T item in list)
            {
                XmlNode xmlNode = xmlDoc.CreateNode(XmlNodeType.Element, modelType.Name, "");
                root.AppendChild(xmlNode);

                foreach (PropertyInfo pi in piList)
                {
                    object value = pi.GetValue(item);
                    if (value != null)
                    {
                        var propertyNode = xmlDoc.CreateNode(XmlNodeType.Element, pi.Name, "");
                        propertyNode.InnerText = value.ToString();
                        xmlNode.AppendChild(propertyNode);
                    }
                }
            }
            xmlDoc.Save(filePath);
        }

19 Source : NotchSolutionDebugger.cs
with MIT License
from 5argon

void Update()
    {
        sb.Clear();
        ClearRects();

        switch (menu)
        {
            case Menu.Home:
                export.gameObject.SetActive(true);
                sb.AppendLine($"<b>-- PLEASE ROTATE THE DEVICE TO GET BOTH ORIENTATION'S DETAILS! --</b>\n");

                var safeArea = RelativeToReal(NotchSolutionUtility.ShouldUseNotchSimulatorValue ? storedSimulatedSafeAreaRelative : NotchSolutionUtility.ScreenSafeAreaRelative);

                PlaceRect(safeArea, Color.red);
                if (Screen.orientation != NotchSolutionUtility.GetCurrentOrientation())
                    safeArea.Set(Screen.width - safeArea.x, Screen.height - safeArea.y, safeArea.width, safeArea.height);
                sb.AppendLine($"Safe area : {safeArea}\n");

#if UNITY_2019_2_OR_NEWER
#if UNITY_EDITOR
                var relativeCutouts = NotchSolutionUtility.ShouldUseNotchSimulatorValue ? storedSimulatedCutoutsRelative : NotchSolutionUtility.ScreenCutoutsRelative;
                List<Rect> rectCutouts = new List<Rect>();
                foreach (Rect rect in relativeCutouts) rectCutouts.Add(RelativeToReal(rect));
                var cutouts = rectCutouts.ToArray();
#else
                var cutouts = Screen.cutouts;
#endif
                foreach (Rect r in cutouts) PlaceRect(r, Color.blue);

                if (Screen.orientation != NotchSolutionUtility.GetCurrentOrientation())
                {
                    foreach (Rect rect in cutouts) rect.Set(Screen.width - rect.x, Screen.height - rect.y, rect.width, rect.height);
                }
                sb.AppendLine($"Cutouts : {string.Join(" / ", cutouts.Select(x => x.ToString()))} \n");
#endif

                sb.AppendLine($"Current resolution : {Screen.currentResolution}\n");
                sb.AppendLine($"All Resolutions : {string.Join(" / ", Screen.resolutions.Select(x => x.ToString()))}\n");
                sb.AppendLine($"DPI : {Screen.dpi} WxH : {Screen.width}x{Screen.height} Orientation : {Screen.orientation}\n");
                var joinedProps = string.Join(" / ", typeof(SystemInfo).GetProperties(BindingFlags.Public | BindingFlags.Static).Select(x => $"{x.Name} : {x.GetValue(null)}"));
                sb.AppendLine(joinedProps);

                break;
            case Menu.Extracting:
                var screen = device.Screens.FirstOrDefault();
                export.gameObject.SetActive(false);

                if (screen.orientations.Count == 4)
                {
                    string path = Application.persistentDataPath + "/" + device.Meta.friendlyName + ".device.json";
                    System.IO.File.WriteAllText(path, JsonUtility.ToJson(device));
                    sb.AppendLine("<b>Done</b>");
                    sb.AppendLine("");
                    sb.AppendLine($"File saved at <i>{path}</i>");
                    StartCoroutine(exportDone());
                }
                else sb.AppendLine("Extracting...");

                break;
        }
        debugText.text = sb.ToString();
    }

19 Source : NotchSolutionDebugger.cs
with MIT License
from 5argon

public void Export()
    {
        device = new SimulationDevice();

        device.Meta = new MetaData();
        device.Meta.friendlyName = export.GetComponentInChildren<InputField>().text;

        device.SystemInfo = new SystemInfoData() { GraphicsDependentData = new GraphicsDependentSystemInfoData[1] { new GraphicsDependentSystemInfoData() } };
        foreach (var property in typeof(SystemInfo).GetProperties(BindingFlags.Public | BindingFlags.Static))
        {
            var prop = typeof(SystemInfoData).GetField(property.Name);
            if (prop != null) prop.SetValue(device.SystemInfo, property.GetValue(null));
            else
            {
                prop = typeof(GraphicsDependentSystemInfoData).GetField(property.Name);
                if (prop != null) prop.SetValue(device.SystemInfo.GraphicsDependentData[0], property.GetValue(null));
            }
        }

        device.Screens = new ScreenData[1];
        for (int i = 0; i < device.Screens.Length; i++)
        {
            var screen = new ScreenData();
            screen.width = Screen.width;
            screen.height = Screen.height;
            //screen.navigationBarHeight = 0;
            screen.orientations = new Dictionary<ScreenOrientation, OrientationDependentData>();
            screen.dpi = Screen.dpi;
            device.Screens[i] = screen;
            StartCoroutine(screenData(screen));
        }

        menu = Menu.Extracting;
    }

19 Source : MetaprogrammingTests.cs
with MIT License
from 71

[Fact]
        public void ShouldRunSelfModifyingEditor()
        {
            typeof(MetaprogrammingTests).GetProperty("Answer").GetValue(null).ShouldBe(42);
        }

19 Source : RtmpSession.cs
with MIT License
from a1q123456

internal void CommandHandler(RtmpController controller, CommandMessage command)
        {
            MethodInfo method = null;
            object[] arguments = null;
            try
            {
                _rpcService.PrepareMethod(controller, command, out method, out arguments);
                var result = method.Invoke(controller, arguments);
                if (result != null)
                {
                    var resType = method.ReturnType;
                    if (resType.IsGenericType && resType.GetGenericTypeDefinition() == typeof(Task<>))
                    {
                        var tsk = result as Task;
                        tsk.ContinueWith(t =>
                        {
                            var taskResult = resType.GetProperty("Result").GetValue(result);
                            var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
                            retCommand.IsSuccess = true;
                            retCommand.TranscationID = command.TranscationID;
                            retCommand.CommandObject = null;
                            retCommand.ReturnValue = taskResult;
                            _ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
                        }, TaskContinuationOptions.OnlyOnRanToCompletion);
                        tsk.ContinueWith(t =>
                        {
                            var exception = tsk.Exception;
                            var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
                            retCommand.IsSuccess = false;
                            retCommand.TranscationID = command.TranscationID;
                            retCommand.CommandObject = null;
                            retCommand.ReturnValue = exception.Message;
                            _ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
                        }, TaskContinuationOptions.OnlyOnFaulted);
                    }
                    else if (resType == typeof(Task))
                    {
                        var tsk = result as Task;
                        tsk.ContinueWith(t =>
                        {
                            var exception = tsk.Exception;
                            var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
                            retCommand.IsSuccess = false;
                            retCommand.TranscationID = command.TranscationID;
                            retCommand.CommandObject = null;
                            retCommand.ReturnValue = exception.Message;
                            _ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
                        }, TaskContinuationOptions.OnlyOnFaulted);
                    }
                    else if (resType != typeof(void))
                    {
                        var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
                        retCommand.IsSuccess = true;
                        retCommand.TranscationID = command.TranscationID;
                        retCommand.CommandObject = null;
                        retCommand.ReturnValue = result;
                        _ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
                    }
                }
            }
            catch (Exception e)
            {
                var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
                retCommand.IsSuccess = false;
                retCommand.TranscationID = command.TranscationID;
                retCommand.CommandObject = null;
                retCommand.ReturnValue = e.Message;
                _ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
                return;
            }
        }

19 Source : Amf0Writer.cs
with MIT License
from a1q123456

public void WriteTypedBytes(object value, SerializationContext context)
        {
            if (value == null)
            {
                WriteNullBytes(context);
                return;
            }
            var refIndex = context.ReferenceTable.IndexOf(value);

            if (refIndex >= 0)
            {
                WriteReferenceIndexBytes((ushort)refIndex, context);
                return;
            }
            context.Buffer.WriteToBuffer((byte)Amf0Type.TypedObject);
            context.ReferenceTable.Add(value);

            var valueType = value.GetType();
            var clreplacedName = valueType.Name;

            var clsAttr = (TypedObjectAttribute)Attribute.GetCustomAttribute(valueType, typeof(TypedObjectAttribute));
            if (clsAttr != null && clsAttr.Name != null)
            {
                clreplacedName = clsAttr.Name;
            }

            WriteStringBytesImpl(clreplacedName, context, out _);

            var props = valueType.GetProperties();

            foreach (var prop in props)
            {
                var attr = (ClreplacedFieldAttribute)Attribute.GetCustomAttribute(prop, typeof(ClreplacedFieldAttribute));
                if (attr != null)
                {
                    WriteStringBytesImpl(attr.Name ?? prop.Name, context, out _);
                    WriteValueBytes(prop.GetValue(value), context);
                }
            }

            WriteStringBytesImpl("", context, out _);
            WriteObjectEndBytes(context);
        }

19 Source : Amf3Writer.cs
with MIT License
from a1q123456

public void WriteBytes(object value, SerializationContext context)
        {
            uint header = 0;
            if (value == null)
            {
                context.Buffer.WriteToBuffer((byte)Amf3Type.Null);
                return;
            }
            else
            {
                context.Buffer.WriteToBuffer((byte)Amf3Type.Object);
            }

            var refIndex = context.ObjectReferenceTable.IndexOf(value);
            if (refIndex >= 0)
            {
                header = (uint)refIndex << 1;
                WriteU29BytesImpl(header, context);
                return;
            }

            var objType = value.GetType();
            string attrTypeName = null;
            var clreplacedAttr = objType.GetCustomAttribute<TypedObjectAttribute>();
            if (clreplacedAttr != null)
            {
                attrTypeName = clreplacedAttr.Name;
            }
            var traits = new Amf3ClreplacedTraits();
            var memberValues = new List<object>();
            if (value is AmfObject amf3Object)
            {
                if (amf3Object.IsAnonymous)
                {
                    traits.ClreplacedName = "";
                    traits.ClreplacedType = Amf3ClreplacedType.Anonymous;
                }
                else
                {
                    traits.ClreplacedName = attrTypeName ?? objType.Name;
                    traits.ClreplacedType = Amf3ClreplacedType.Typed;
                }
                traits.IsDynamic = amf3Object.IsDynamic;
                traits.Members = new List<string>(amf3Object.Fields.Keys);
                memberValues = new List<object>(amf3Object.Fields.Keys.Select(k => amf3Object.Fields[k]));
            }
            else if (value is IExternalizable)
            {
                traits.ClreplacedName = attrTypeName ?? objType.Name;
                traits.ClreplacedType = Amf3ClreplacedType.Externalizable;
            }
            else
            {
                traits.ClreplacedName = attrTypeName ?? objType.Name;
                traits.ClreplacedType = Amf3ClreplacedType.Typed;
                var props = objType.GetProperties();
                foreach (var prop in props)
                {
                    var attr = (ClreplacedFieldAttribute)Attribute.GetCustomAttribute(prop, typeof(ClreplacedFieldAttribute));
                    if (attr != null)
                    {
                        traits.Members.Add(attr.Name ?? prop.Name);
                        memberValues.Add(prop.GetValue(value));
                    }
                }
                traits.IsDynamic = value is IDynamicObject;
            }
            context.ObjectReferenceTable.Add(value);


            var traitRefIndex = context.ObjectTraitsReferenceTable.IndexOf(traits);
            if (traitRefIndex >= 0)
            {
                header = ((uint)traitRefIndex << 2) | 0x01;
                WriteU29BytesImpl(header, context);
            }
            else
            {
                if (traits.ClreplacedType == Amf3ClreplacedType.Externalizable)
                {
                    header = 0x07;
                    WriteU29BytesImpl(header, context);
                    WriteStringBytesImpl(traits.ClreplacedName, context, context.StringReferenceTable);
                    var extObj = value as IExternalizable;
                    extObj.TryEncodeData(context.Buffer);
                    return;
                }
                else
                {
                    header = 0x03;
                    if (traits.IsDynamic)
                    {
                        header |= 0x08;
                    }
                    var memberCount = (uint)traits.Members.Count;
                    header |= memberCount << 4;
                    WriteU29BytesImpl(header, context);
                    WriteStringBytesImpl(traits.ClreplacedName, context, context.StringReferenceTable);

                    foreach (var memberName in traits.Members)
                    {
                        WriteStringBytesImpl(memberName, context, context.StringReferenceTable);
                    }
                }
                context.ObjectTraitsReferenceTable.Add(traits);
            }


            foreach (var memberValue in memberValues)
            {
                WriteValueBytes(memberValue, context);
            }

            if (traits.IsDynamic)
            {
                var amf3Obj = value as IDynamicObject;
                foreach ((var key, var item) in amf3Obj.DynamicFields)
                {
                    WriteStringBytesImpl(key, context, context.StringReferenceTable);
                    WriteValueBytes(item, context);
                }
                WriteStringBytesImpl("", context, context.StringReferenceTable);
            }
        }

19 Source : ReaderCache.cs
with Apache License 2.0
from aadreja

private static Type GetTypeOfDynamicProperty(PropertyInfo property, object dynamicObject)
        {
            //dynamic property will always return System.Object as property type. Get Type from the value

            Type type = property.PropertyType;

            if (type == typeof(object))
                type = property.GetValue(dynamicObject)?.GetType() ?? typeof(object);
            else
            {
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    type = Nullable.GetUnderlyingType(property.PropertyType);
                else
                    type = property.PropertyType;
            }

            return type;
        }

19 Source : ReaderCache.cs
with Apache License 2.0
from aadreja

internal static void AddParameters(object param, IDbCommand cmd)
        {
            if (param == null)
                return;

            Type pType = param.GetType();
            foreach (PropertyInfo property in pType.GetProperties())
            {
                Type type = GetTypeOfDynamicProperty(property, param);
                if (type.IsEnum) type = Enum.GetUnderlyingType(type);
                if (!TypeCache.TypeToDbType.TryGetValue(type, out DbType dbType))
                    dbType = DbType.String; //TODO: fix when unkown type

                cmd.AddInParameter(property.Name, dbType, property.GetValue(param));
            }
        }

19 Source : VxFormColumnBase.cs
with MIT License
from Aaltuj

private void CreateFormElementReferencePoco<TValue>(object model, PropertyInfo propertyInfo,
            RenderTreeBuilder builder, Layout.VxFormElementDefinition formColumnDefinition)
        {
            var valueChanged = Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck(
                        EventCallback.Factory.Create<TValue>(
                            this, EventCallback.Factory.
                            CreateInferred(this, __value => propertyInfo.SetValue(model, __value),

                            (TValue)propertyInfo.GetValue(model))));
            // Create an expression to set the ValueExpression-attribute.
            var constant = Expression.Constant(model, model.GetType());
            var exp = Expression.Property(constant, propertyInfo.Name);
            var lamb = Expression.Lambda<Func<TValue>>(exp);

            var formElementReference = new FormElementReference<TValue>()
            {
                Value = (TValue)propertyInfo.GetValue(model),
                ValueChanged = valueChanged,
                ValueExpression = lamb,
                FormColumnDefinition = formColumnDefinition
            };

            var elementType = typeof(VxFormElementLoader<TValue>);

            builder.OpenComponent(0, elementType);
            builder.AddAttribute(1, nameof(VxFormElementLoader<TValue>.ValueReference), formElementReference);
            builder.CloseComponent();
        }

19 Source : ValueReference.cs
with MIT License
from Aaltuj

public static TValue GetValue(object model, string key)
        {
            var modelType = model.GetType();

            if (modelType == typeof(ExpandoObject))
            {
                var accessor = ((IDictionary<string, object>)model);
                return (TValue)accessor[key];
            }
            else
            {
                var propertyInfo = modelType.GetProperty(key);
                return (TValue) propertyInfo.GetValue(model);
            }

        }

19 Source : ContextIsolatedTask.cs
with Microsoft Public License
from 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 Source : ContextIsolatedTask.cs
with Microsoft Public License
from 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 Source : PropertyObserverNode.cs
with MIT License
from Accelerider

private void GenerateNextNode()
        {
            var propertyInfo = _inpcObject.GetType().GetRuntimeProperty(PropertyName); // TODO: To cache, if the step consume significant performance. Note: The type of _inpcObject may become its base type or derived type.
            var nextProperty = propertyInfo.GetValue(_inpcObject);
            if (nextProperty == null) return;
            if (!(nextProperty is INotifyPropertyChanged nextInpcObject))
                throw new InvalidOperationException($"Trying to subscribe PropertyChanged listener in object that " +
                                                    $"owns '{Next.PropertyName}' property, " +
                                                    $"but the object does not implements INotifyPropertyChanged.");

            Next.SubscribeListenerFor(nextInpcObject);
        }

19 Source : TypeExtensionMethods.cs
with MIT License
from actions

public static object GetMemberValue(this Type type, string name, object obj)
        {
            PropertyInfo propertyInfo = GetPublicInstancePropertyInfo(type, name);
            if (propertyInfo != null)
            {
                return propertyInfo.GetValue(obj);
            }
            else
            {
                FieldInfo fieldInfo = GetPublicInstanceFieldInfo(type, name);
                if (fieldInfo != null)
                {
                    return fieldInfo.GetValue(obj);
                }
            }
            return null;
        }

19 Source : WrappedException.cs
with MIT License
from actions

private void TryWrapCustomProperties(Exception exception)
        {
            var customPropertiesWithDataMemberAttribute = GetCustomPropertiesInfo();

            if (customPropertiesWithDataMemberAttribute.Any())
            {
                this.CustomProperties = new Dictionary<string, object>();
            }

            foreach (var customProperty in customPropertiesWithDataMemberAttribute)
            {
                try
                {
                    this.CustomProperties.Add(customProperty.Name, customProperty.GetValue(exception));
                }
                catch
                {
                    // skip this property
                }
            }
        }

19 Source : XmlSerializableDataContractExtensions.cs
with MIT License
from actions

public object GetValue(object @object) => Property.GetValue(@object);

19 Source : ReflectionUtils.cs
with GNU General Public License v3.0
from Acumatica

public static T GetValue<T>(this PropertyInfo propertyInfo, object instance) => (T)propertyInfo.GetValue(instance);

19 Source : RoslynDiagnosticService.cs
with GNU General Public License v3.0
from Acumatica

public async Task<List<DiagnosticData>> GetCurrentDiagnosticForDoreplacedentSpanAsync(Doreplacedent doreplacedent, TextSpan caretSpan,
																						 CancellationToken cancellationToken = default)
		{					
			try
			{
				object dataTask = _getDiagnosticOnTextSpanMethod.Invoke(_roslynreplacedyzersService, 
																new object[] { doreplacedent, caretSpan, null, false, cancellationToken });
				if (!(dataTask is Task task))
					return new List<DiagnosticData>();

				await task;
				object rawResult = _taskResultPropertyInfo.GetValue(dataTask);

				if (!(rawResult is IEnumerable<object> diagnosticsRaw) || diagnosticsRaw.IsNullOrEmpty())
					return new List<DiagnosticData>();

				return diagnosticsRaw.Select(rawData => DiagnosticData.Create(rawData))
									 .Where(diagnosticData => diagnosticData != null)
									 .ToList(capacity: 1);
			}
			catch (Exception e)
			{
				return new List<DiagnosticData>();
			}
		}

19 Source : RoslynDiagnosticService.cs
with GNU General Public License v3.0
from Acumatica

public async Task<List<DiagnosticData>> GetCurrentAreplacedinatorDiagnosticForDoreplacedentSpanAsync(Doreplacedent doreplacedent, TextSpan caretSpan,
																								   CancellationToken cancellationToken = default)
		{
			var componentModelType = _componentModel.GetType();

			try
			{
				object dataTask = _getDiagnosticOnTextSpanMethod.Invoke(_roslynreplacedyzersService,
																new object[] { doreplacedent, caretSpan, null, false, cancellationToken });
				if (!(dataTask is Task task))
					return new List<DiagnosticData>();

				await task;
				object rawResult = _taskResultPropertyInfo.GetValue(dataTask);

				if (!(rawResult is IEnumerable<object> diagnosticsRaw) || diagnosticsRaw.IsNullOrEmpty())
					return new List<DiagnosticData>();

				return diagnosticsRaw.Select(rawData => DiagnosticData.Create(rawData))
									 .Where(diagnosticData => diagnosticData != null && IsAreplacedinatorDiagnostic(diagnosticData))
									 .ToList(capacity: 1);
			}
			catch (Exception e)
			{
				return new List<DiagnosticData>();
			}
		}

19 Source : ObjectExtenders.cs
with MIT License
from adoconnection

public static ExpandoObject ToExpando(this object obj)
        {
            ExpandoObject expando = new ExpandoObject();
            IDictionary<string, object> dictionary = expando;

            foreach (PropertyInfo property in obj.GetType().GetProperties())
            {
                dictionary.Add(property.Name, property.GetValue(obj));
            }

            return expando;
        }

19 Source : CustomIconProvider.android.cs
with MIT License
from adenearnshaw

private int GetId(string memberName)
        {
            var type = _drawableClreplaced;
            object value = type.GetFields().FirstOrDefault(p => p.Name == memberName)?.GetValue(type)
                           ?? type.GetProperties().FirstOrDefault(p => p.Name == memberName)?.GetValue(type);
            if (value is int)
                return (int)value;
            return 0;
        }

19 Source : Configuration.cs
with MIT License
from AdrianWilczynski

public void Override(CommandBase command)
        {
            foreach (var property in typeof(Configuration).GetProperties())
            {
                if (property.GetValue(this) is object value)
                {
                    typeof(CommandBase).GetProperty(property.Name).SetValue(command, value);
                }
            }
        }

19 Source : FileIO.cs
with GNU General Public License v3.0
from aedenthorn

public static void LoadTMXSpouseRooms()
        {
            try
            {
                Maps.tmxSpouseRooms.Clear();
                var tmxlAPI = Helper.ModRegistry.GetApi("Platonymous.TMXLoader");
                var tmxlreplacedembly = tmxlAPI?.GetType()?.replacedembly;
                var tmxlModType = tmxlreplacedembly?.GetType("TMXLoader.TMXLoaderMod");
                var tmxlEditorType = tmxlreplacedembly?.GetType("TMXLoader.TMXreplacedetEditor");

                if (tmxlModType == null)
                    return;

                var tmxlHelper = Helper.Reflection.GetField<IModHelper>(tmxlModType, "helper").GetValue();
                foreach (var editor in tmxlHelper.Content.replacedetEditors)
                {
                    try
                    {
                        if (editor == null)
                            continue;
                        if (!ReferenceEquals(editor.GetType(),tmxlEditorType)) continue;

                        if (editor.GetType().GetField("type", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(editor).ToString() != "SpouseRoom") continue;

                        string name = (string)tmxlEditorType.GetField("replacedetName").GetValue(editor);
                        if (name != "FarmHouse1_marriage") continue;

                        object edit = tmxlEditorType.GetField("edit", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(editor);
                        string info = (string)edit.GetType().GetProperty("info").GetValue(edit);

                        Map map = Helper.Reflection.GetField<Map>(editor, "newMap").GetValue();
                        if (map != null && !Maps.tmxSpouseRooms.ContainsKey(info))
                        {
                            Monitor.Log("Adding TMX spouse room for " + info, LogLevel.Debug);
                            Maps.tmxSpouseRooms.Add(info, map);
                        }
                    }
                    catch (Exception ex)
                    {
                        Monitor.Log($"Failed getting TMX spouse room data. Exception: {ex}", LogLevel.Debug);
                    }
                }

            }
            catch (Exception ex)
            {
                Monitor.Log($"Failed getting TMX spouse room data. Exception: {ex}", LogLevel.Debug);
            }
        }

19 Source : StructuredState.cs
with MIT License
from AElfProject

internal override void OnContextSet()
        {
            foreach (var kv in _propertyInfos)
            {
                var propertyInfo = kv.Value;
                ((StateBase) propertyInfo.GetValue(this)).Context = Context;
            }

            base.OnContextSet();
        }

19 Source : StructuredState.cs
with MIT License
from AElfProject

internal override void Clear()
        {
            foreach (var kv in _propertyInfos)
            {
                var propertyInfo = kv.Value;
                ((StateBase) propertyInfo.GetValue(this)).Clear();
            }
        }

19 Source : StructuredState.cs
with MIT License
from AElfProject

internal override TransactionExecutingStateSet GetChanges()
        {
            var stateSet = new TransactionExecutingStateSet();
            foreach (var kv in _propertyInfos)
            {
                var propertyInfo = kv.Value;
                var propertyValue = (StateBase) propertyInfo.GetValue(this);
                var changes = propertyValue.GetChanges();
                foreach (var kv1 in changes.Writes)
                {
                    stateSet.Writes[kv1.Key] = kv1.Value;
                }
                
                foreach (var kv1 in changes.Deletes)
                {
                    stateSet.Deletes[kv1.Key] = kv1.Value;
                }

                foreach (var kv1 in changes.Reads)
                {
                    stateSet.Reads[kv1.Key] = kv1.Value;
                }
            }

            return stateSet;
        }

19 Source : StructuredState.cs
with MIT License
from AElfProject

internal override void OnPathSet()
        {
            foreach (var kv in _propertyInfos)
            {
                var propertyInfo = kv.Value;
                var path = this.Path.Clone();
                path.Parts.Add(kv.Key);
                ((StateBase) propertyInfo.GetValue(this)).Path = path;
            }

            base.OnPathSet();
        }

19 Source : MainWindow.xaml.cs
with MIT License
from AgileoAutomation

private System.Windows.Media.Color ConvertSystemDrawingToWindowsMediaColor(System.Drawing.Color color)
        {
            string colorName = color.Name;
            Type type = typeof(System.Windows.Media.Colors);
            PropertyInfo property = type.GetProperty(colorName);
            System.Windows.Media.Color adaptedColor = (System.Windows.Media.Color)property.GetValue(null);
            return adaptedColor;
        }

19 Source : ComponentSpecification.cs
with MIT License
from AgileoAutomation

private Color GetColor(string colorname)
        {
            Type type = typeof(Color);

            try
            {
                PropertyInfo property = type.GetProperty(colorname);
                return (Color)property.GetValue(null);
            }
            catch
            {
                return randomColor();
            }
        }

19 Source : MainWindow.xaml.cs
with MIT License
from AgileoAutomation

private Microsoft.Msagl.Drawing.Color ConvertSystemDrawingToMsaglColor(SoftwareComponent component)
        {
            string colorName = component.Color.Name;
            Type type = typeof(Microsoft.Msagl.Drawing.Color);
            PropertyInfo property = type.GetProperty(colorName);
            Microsoft.Msagl.Drawing.Color adaptedColor = (Microsoft.Msagl.Drawing.Color)property.GetValue(null);
            return adaptedColor;
        }

19 Source : DbRepositorySimplified.cs
with Apache License 2.0
from agoda-com

private static string CreateCacheKey(string sqlCommandString, object parameters)
        {
            var sb = new StringBuilder();
            sb.Append(sqlCommandString);
            sb.Append(":");
            foreach(var p in parameters.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                sb.Append($"@{p.Name}+{p.GetValue(parameters)}&");
            }

            return sb.ToString();
        }

19 Source : Map.cs
with Apache License 2.0
from Aguafrommars

public static Dictionary<string, object> ToDictionary<T>(T obj)
        {
            var type = obj.GetType();
            var properties = type.GetProperties()
                .Where(p => p.PropertyType.IsValueType || p.PropertyType == typeof(string));
            var dictionary = new Dictionary<string, object>(properties.Count());
            foreach (var property in properties)
            {
                dictionary.Add(property.Name, property.GetValue(obj));
            }
            return dictionary;
        }

19 Source : UniqueValidator.cs
with Apache License 2.0
from Aguafrommars

public override bool IsValid(ValidationContext<T> context, string value)
        {
            var editedItem = context.InstanceToValidate;
            var propertyName = context.PropertyName;
            propertyName = propertyName.Substring(propertyName.LastIndexOf('.') + 1);
            var property = typeof(T).GetTypeInfo().GetProperty(propertyName);
            return _items.All(item =>
              item.Equals(editedItem) || property.GetValue(item) as string != value);
        }

19 Source : AdminStore.cs
with Apache License 2.0
from Aguafrommars

private async Task<object> GetSubItemsAsync(TEnreplacedy enreplacedy, Type propertyType)
        {
            var storeType = typeof(IAdminStore<>).MakeGenericType(propertyType.GetGenericArguments()[0]);
            var subStore = _provider.GetRequiredService(storeType);
            var getPageResponseMethod = storeType.GetMethod(nameof(IAdminStore<object>.GetAsync), new[] { typeof(PageRequest), typeof(CancellationToken) });
            var task = getPageResponseMethod.Invoke(subStore, new[]
            {
                    new PageRequest
                    {
                        Filter = $"{GetSubEnreplacedyParentIdName(_enreplacedyType)} eq '{enreplacedy.Id}'",
                        Take = null
                    },
                    null
                });
            await (task as Task).ConfigureAwait(false);
            var response = task.GetType().GetProperty(nameof(Task<object>.Result)).GetValue(task);
            var items = response.GetType().GetProperty(nameof(PageResponse<object>.Items)).GetValue(response);
            return items;
        }

19 Source : ClientRegisterationConverter.cs
with Apache License 2.0
from Aguafrommars

private JObject SerializedProperties(object value)
        {
            var jObject = new JObject();
            var properties = value.GetType().GetProperties();

            foreach (var property in properties)
            {
                var jsonPropertyAttribute = property.GetCustomAttributes(typeof(JsonPropertyAttribute), false)
                    .FirstOrDefault(a => a is JsonPropertyAttribute jsonProperty) as JsonPropertyAttribute;
                var propertyName = jsonPropertyAttribute?.PropertyName ?? property.Name;
                if (property.PropertyType == typeof(IEnumerable<LocalizableProperty>))
                {
                    SerializeLocalizableProperty(property, value, propertyName, jObject);
                    continue;
                }
                var v = property.GetValue(value);
                if (v == null)
                {
                    continue;
                }
                if (v is JsonWebKeys jsonWebKeys)
                {
                    SerializeJwks(jObject, propertyName, jsonWebKeys);
                    continue;
                }
                jObject.Add(new JProperty(propertyName, v));
            }

            return jObject;
        }

19 Source : ImportService.cs
with Apache License 2.0
from 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 Source : AdminStore.cs
with Apache License 2.0
from 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 Source : AdminStore.cs
with Apache License 2.0
from 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 Source : AdminStore.cs
with Apache License 2.0
from 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));
            }
        }

See More Examples