Here are the examples of the csharp api System.Type.GetProperties() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2825 Examples
19
Source : ScAllColumnTypes.cs
with MIT License
from 0x1000000
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
with MIT License
from 1100100
private static IEnumerable<PropertyInfo> GetProperties(object param)
{
return ParamProperties.GetOrAdd(param.GetType(), key =>
{
return key.GetProperties().Where(p => p.CanRead).ToList();
});
}
19
Source : ExpressionActivator.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
private Expression CreateExpression(ParameterExpression parameter, string expression)
{
var expressions1 = Factorization(expression);
var expressions2 = new Dictionary<string, Expression>();
foreach (var item in expressions1)
{
var subexpr = item.Value.Trim('(', ')');
var @opterator = ResovleOperator(item.Value);
var opt = GetExpressionType(@opterator);
if (opt == ExpressionType.Not)
{
Expression exp;
var text = subexpr.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
if (expressions2.ContainsKey(text))
{
exp = expressions2[text];
}
else if (parameter.Type.GetProperties().Any(a => a.Name == text))
{
var property = parameter.Type.GetProperty(text);
exp = Expression.MakeMemberAccess(parameter, property);
}
else
{
exp = Expression.Constant(Convert.ToBoolean(text));
}
expressions2.Add(item.Key, Expression.MakeUnary(opt, exp, null));
}
else
{
var text1 = subexpr
.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0]
.Trim();
var text2 = subexpr
.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[1]
.Trim();
string temp = null;
Expression exp1, exp2;
//永远将变量放在第一个操作数
if (parameter.Type.GetProperties().Any(a => a.Name == text2))
{
temp = text1;
text1 = text2;
text2 = temp;
}
//是否为上一次的分式
if (expressions2.ContainsKey(text1))
{
exp1 = expressions2[text1];
}
else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
{
//是否为变量
var property = parameter.Type.GetProperty(text1);
exp1 = Expression.MakeMemberAccess(parameter, property);
}
else
{
exp1 = ResovleConstantExpression(text1);
}
//是否为上一次的分式
if (expressions2.ContainsKey(text2))
{
exp2 = expressions2[text2];
}
//如果第一个操作数是变量
else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
{
var constantType = parameter.Type.GetProperty(text1).PropertyType;
exp2 = ResovleConstantExpression(text2, constantType);
}
else
{
exp2 = ResovleConstantExpression(text1, (exp1 as ConstantExpression)?.Type);
}
expressions2.Add(item.Key, Expression.MakeBinary(opt, exp1, exp2));
}
}
return expressions2.Last().Value;
}
19
Source : DbMetaInfoProvider.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
public List<DbColumnMetaInfo> GetColumns(Type type)
{
return _columns.GetOrAdd(type, t =>
{
var list = new List<DbColumnMetaInfo>();
var properties = type.GetProperties();
foreach (var item in properties)
{
var columnName = item.Name;
var isPrimaryKey = false;
var isDefault = false;
var isIdenreplacedy = false;
var isNotMapped = false;
var isConcurrencyCheck = false;
var isComplexType = false;
if (item.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault() != null)
{
var attribute = item.GetCustomAttributes(typeof(ColumnAttribute), true)
.FirstOrDefault() as ColumnAttribute;
columnName = attribute.Name;
}
if (item.GetCustomAttributes(typeof(PrimaryKeyAttribute), true).FirstOrDefault() != null)
{
isPrimaryKey = true;
}
if (item.GetCustomAttributes(typeof(IdenreplacedyAttribute), true).FirstOrDefault() != null)
{
isIdenreplacedy = true;
}
if (item.GetCustomAttributes(typeof(DefaultAttribute), true).FirstOrDefault() != null)
{
isDefault = true;
}
if (item.GetCustomAttributes(typeof(ConcurrencyCheckAttribute), true).FirstOrDefault() != null)
{
isConcurrencyCheck = true;
}
if (item.GetCustomAttributes(typeof(NotMappedAttribute), true).FirstOrDefault() != null)
{
isNotMapped = true;
}
if (item.GetCustomAttributes(typeof(ComplexTypeAttribute), true).FirstOrDefault() != null)
{
isComplexType = true;
}
list.Add(new DbColumnMetaInfo()
{
CsharpType = item.PropertyType,
IsDefault = isDefault,
ColumnName = columnName,
CsharpName = item.Name,
IsPrimaryKey = isPrimaryKey,
IsIdenreplacedy = isIdenreplacedy,
IsNotMapped = isNotMapped,
IsConcurrencyCheck = isConcurrencyCheck,
IsComplexType = isComplexType
});
}
return list;
});
}
19
Source : EntityMapperProvider.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
private Func<IDataRecord, T> CreateTypeSerializerHandler<T>(MemberMapper mapper, IDataRecord record)
{
var type = typeof(T);
var methodName = $"Serializer{Guid.NewGuid():N}";
var dynamicMethod = new DynamicMethod(methodName, type, new Type[] { typeof(IDataRecord) }, type, true);
var generator = dynamicMethod.GetILGenerator();
LocalBuilder local = generator.DeclareLocal(type);
var dataInfos = new DataReaderCellInfo[record.FieldCount];
for (int i = 0; i < record.FieldCount; i++)
{
var dataname = record.GetName(i);
var datatype = record.GetFieldType(i);
var typename = record.GetDataTypeName(i);
dataInfos[i] = new DataReaderCellInfo(i, typename, datatype, dataname);
}
if (dataInfos.Length == 1 && (type.IsValueType || type == typeof(string) || type == typeof(object)))
{
var dataInfo = dataInfos.First();
var convertMethod = mapper.FindConvertMethod(type, dataInfo.DataType);
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldc_I4, 0);
if (convertMethod.IsVirtual)
generator.Emit(OpCodes.Callvirt, convertMethod);
else
generator.Emit(OpCodes.Call, convertMethod);
if (type == typeof(object) && convertMethod.ReturnType.IsValueType)
{
generator.Emit(OpCodes.Box, convertMethod.ReturnType);
}
generator.Emit(OpCodes.Stloc, local);
generator.Emit(OpCodes.Ldloc, local);
generator.Emit(OpCodes.Ret);
return dynamicMethod.CreateDelegate(typeof(Func<IDataRecord, T>)) as Func<IDataRecord, T>;
}
var constructor = mapper.FindConstructor(type);
if (constructor.GetParameters().Length > 0)
{
var parameters = constructor.GetParameters();
var locals = new LocalBuilder[parameters.Length];
for (int i = 0; i < locals.Length; i++)
{
locals[i] = generator.DeclareLocal(parameters[i].ParameterType);
}
for (int i = 0; i < locals.Length; i++)
{
var item = mapper.FindConstructorParameter(dataInfos, parameters[i]);
if (item == null)
{
continue;
}
var convertMethod = mapper.FindConvertMethod(parameters[i].ParameterType, item.DataType);
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldc_I4, item.Ordinal);
if (convertMethod.IsVirtual)
generator.Emit(OpCodes.Callvirt, convertMethod);
else
generator.Emit(OpCodes.Call, convertMethod);
generator.Emit(OpCodes.Stloc, locals[i]);
}
for (int i = 0; i < locals.Length; i++)
{
generator.Emit(OpCodes.Ldloc, locals[i]);
}
generator.Emit(OpCodes.Newobj, constructor);
generator.Emit(OpCodes.Stloc, local);
generator.Emit(OpCodes.Ldloc, local);
generator.Emit(OpCodes.Ret);
return dynamicMethod.CreateDelegate(typeof(Func<IDataRecord, T>)) as Func<IDataRecord, T>;
}
else
{
var properties = type.GetProperties();
generator.Emit(OpCodes.Newobj, constructor);
generator.Emit(OpCodes.Stloc, local);
foreach (var item in dataInfos)
{
var property = mapper.FindMember(properties, item) as PropertyInfo;
if (property == null)
{
continue;
}
var convertMethod = mapper.FindConvertMethod(property.PropertyType, item.DataType);
if (convertMethod == null)
{
continue;
}
int i = record.GetOrdinal(item.DataName);
generator.Emit(OpCodes.Ldloc, local);
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldc_I4, i);
if (convertMethod.IsVirtual)
generator.Emit(OpCodes.Callvirt, convertMethod);
else
generator.Emit(OpCodes.Call, convertMethod);
generator.Emit(OpCodes.Callvirt, property.GetSetMethod());
}
generator.Emit(OpCodes.Ldloc, local);
generator.Emit(OpCodes.Ret);
return dynamicMethod.CreateDelegate(typeof(Func<IDataRecord, T>)) as Func<IDataRecord, T>;
}
}
19
Source : EntityDescriptor.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
private void SetColumns()
{
//加载属性列表
var properties = new List<PropertyInfo>();
foreach (var p in EnreplacedyType.GetProperties())
{
var type = p.PropertyType;
if (type == typeof(TimeSpan) || (!type.IsGenericType || type.IsNullable()) && (type.IsGuid() || type.IsNullable() || Type.GetTypeCode(type) != TypeCode.Object)
&& Attribute.GetCustomAttributes(p).All(attr => attr.GetType() != typeof(NotMappingColumnAttribute)))
{
properties.Add(p);
}
}
foreach (var p in properties)
{
var column = new ColumnDescriptor(p, DbContext.Adapter);
if (column.IsPrimaryKey)
{
PrimaryKey = new PrimaryKeyDescriptor(p);
Columns.Insert(0, column);
}
else
{
Columns.Add(column);
}
}
//如果主键为null,则需要指定为没有主键
if (PrimaryKey == null)
{
PrimaryKey = new PrimaryKeyDescriptor();
}
}
19
Source : BuildInFormatters.cs
with MIT License
from 1996v
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
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
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 : RandomHelper.cs
with MIT License
from 1996v
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 : XmlHelper.cs
with MIT License
from 279328316
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 : XmlHelper.cs
with MIT License
from 279328316
with MIT License
from 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
Source : XmlHelper.cs
with MIT License
from 279328316
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 : TypeExtension.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static IEnumerable<MethodInfo> GetApis(this Type type)
{
var addMethods = type.GetEvents().Select(_event => _event.GetAddMethod());
var removeMethods = type.GetEvents().Select(_event => _event.GetRemoveMethod());
var getMethods = type.GetProperties().Select(_propety => _propety.GetGetMethod());
var setMethods = type.GetProperties().Select(_propety => _propety.GetSetMethod());
var enumerable = addMethods
.Concat(removeMethods)
.Concat(getMethods)
.Concat(setMethods)
.Where(_method=>_method != null)
.Select(_method => _method.Name);
var methods = enumerable.ToList();
methods.Add("Dispose");
return type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(_method=> !methods.Contains(_method.Name));
}
19
Source : InternalExtensions.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static Dictionary<string, PropertyInfo> GetPropertiesDictIgnoreCase(this Type that) => that == null ? null : _dicGetPropertiesDictIgnoreCase.GetOrAdd(that, tp =>
{
var props = that.GetProperties().GroupBy(p => p.DeclaringType).Reverse().SelectMany(p => p); //将基类的属性位置放在前面 #164
var dict = new Dictionary<string, PropertyInfo>(StringComparer.CurrentCultureIgnoreCase);
foreach (var prop in props)
{
if (dict.TryGetValue(prop.Name, out var existsProp))
{
if (existsProp.DeclaringType != prop) dict[prop.Name] = prop;
continue;
}
dict.Add(prop.Name, prop);
}
return dict;
});
19
Source : InternalExtensions.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static string GetDescription(this Type that)
{
object[] attrs = null;
try
{
attrs = that.GetCustomAttributes(false).ToArray(); //.net core 反射存在版本冲突问题,导致该方法异常
}
catch { }
var dyattr = attrs?.Where(a => {
return ((a as Attribute)?.TypeId as Type)?.Name == "DescriptionAttribute";
}).FirstOrDefault();
if (dyattr != null)
{
var valueProp = dyattr.GetType().GetProperties().Where(a => a.PropertyType == typeof(string)).FirstOrDefault();
var comment = valueProp?.GetValue(dyattr, null)?.ToString();
if (string.IsNullOrEmpty(comment) == false)
return comment;
}
return null;
}
19
Source : JsonMapper.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static void AddArrayMetadata (Type type)
{
if (array_metadata.ContainsKey (type))
return;
ArrayMetadata data = new ArrayMetadata ();
data.IsArray = type.IsArray;
if (type.GetInterface ("System.Collections.IList") != null)
data.IsList = true;
if (type is ILRuntime.Reflection.ILRuntimeWrapperType)
{
var wt = (ILRuntime.Reflection.ILRuntimeWrapperType)type;
if (data.IsArray)
{
data.ElementType = wt.CLRType.ElementType.ReflectionType;
}
else
{
data.ElementType = wt.CLRType.GenericArguments[0].Value.ReflectionType;
}
}
else
{
foreach (PropertyInfo p_info in type.GetProperties())
{
if (p_info.Name != "Item")
continue;
ParameterInfo[] parameters = p_info.GetIndexParameters();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof(int))
data.ElementType = p_info.PropertyType;
}
}
lock (array_metadata_lock) {
try {
array_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
19
Source : JsonMapper.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static void AddObjectMetadata (Type type)
{
if (object_metadata.ContainsKey (type))
return;
ObjectMetadata data = new ObjectMetadata ();
if (type.GetInterface ("System.Collections.IDictionary") != null)
data.IsDictionary = true;
data.Properties = new Dictionary<string, PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (Attribute.IsDefined(p_info, typeof(JsonIgnoreAttribute), true))
continue;
if (p_info.Name == "Item") {
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof(string))
{
if (type is ILRuntime.Reflection.ILRuntimeWrapperType)
{
data.ElementType = ((ILRuntime.Reflection.ILRuntimeWrapperType)type).CLRType.GenericArguments[1].Value.ReflectionType;
}
else
data.ElementType = p_info.PropertyType;
}
continue;
}
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.Type = p_info.PropertyType;
data.Properties.Add (p_info.Name, p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
if (Attribute.IsDefined(f_info, typeof(JsonIgnoreAttribute), true))
continue;
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
p_data.Type = f_info.FieldType;
data.Properties.Add (f_info.Name, p_data);
}
lock (object_metadata_lock) {
try {
object_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
19
Source : JsonMapper.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static void AddTypeProperties (Type type)
{
if (type_properties.ContainsKey (type))
return;
IList<PropertyMetadata> props = new List<PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (Attribute.IsDefined(p_info, typeof(JsonIgnoreAttribute), true))
continue;
if (p_info.Name == "Item")
continue;
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.IsField = false;
props.Add (p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
if (Attribute.IsDefined(f_info, typeof(JsonIgnoreAttribute), true))
continue;
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
props.Add (p_data);
}
lock (type_properties_lock) {
try {
type_properties.Add (type, props);
} catch (ArgumentException) {
return;
}
}
}
19
Source : TypeFuzzer.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 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
Source : JSONParser.cs
with MIT License
from 5minlab
with MIT License
from 5minlab
static object ParseObject(Type type, string json) {
object instance = FormatterServices.GetUninitializedObject(type);
//The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON
List<string> elems = Split(json);
if (elems.Count % 2 != 0)
return instance;
Dictionary<string, FieldInfo> nameToField;
Dictionary<string, PropertyInfo> nameToProperty;
if (!fieldInfoCache.TryGetValue(type, out nameToField)) {
nameToField = type.GetFields().Where(field => field.IsPublic).ToDictionary(field => field.Name);
fieldInfoCache.Add(type, nameToField);
}
if (!propertyInfoCache.TryGetValue(type, out nameToProperty)) {
nameToProperty = type.GetProperties().ToDictionary(p => p.Name);
propertyInfoCache.Add(type, nameToProperty);
}
for (int i = 0; i < elems.Count; i += 2) {
if (elems[i].Length <= 2)
continue;
string key = elems[i].Substring(1, elems[i].Length - 2);
string value = elems[i + 1];
FieldInfo fieldInfo;
PropertyInfo propertyInfo;
if (nameToField.TryGetValue(key, out fieldInfo))
fieldInfo.SetValue(instance, ParseValue(fieldInfo.FieldType, value));
else if (nameToProperty.TryGetValue(key, out propertyInfo))
propertyInfo.SetValue(instance, ParseValue(propertyInfo.PropertyType, value), null);
}
return instance;
}
19
Source : PropertyExtension.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
public static string ComparisonTo<T1, T2>(this T1 source, T2 current)
{
string diff = "";
try
{
Type t1 = source.GetType();
Type t2 = current.GetType();
PropertyInfo[] property2 = t2.GetProperties();
//排除主键和基础字段
List<string> exclude = new List<string>() { "Id" };
foreach (PropertyInfo p in property2)
{
string name = p.Name;
if (exclude.Contains(name)) { continue; }
var value1 = t1.GetProperty(name)?.GetValue(source, null)?.ToString();
var value2 = p.GetValue(current, null)?.ToString();
if (value1 != value2)
{
diff += $"[{name}]:'{value1}'=>'{value2}';\r\n";
}
}
}
catch(Exception)
{
}
return diff;
}
19
Source : ConfigDomainService.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
private List<ConfigModel> GetAppConfigValue(Dictionary<string,string> configDic, Type type, string parentName = "")
{
var configs = new List<ConfigModel>();
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
string name = prop.Name;
string key = string.IsNullOrEmpty(parentName) ? $"{name}" : $"{parentName}:{name}";
if (prop.PropertyType.IsValueType || prop.PropertyType.Name.StartsWith("String"))
{
string value = "";
try
{
configDic.TryGetValue(key, out value);
}
catch (Exception)
{
}
if (string.IsNullOrEmpty(value))
{
if (prop.PropertyType == typeof(int) || prop.PropertyType == typeof(int?) ||
prop.PropertyType == typeof(bool) || prop.PropertyType == typeof(bool?) ||
prop.PropertyType == typeof(float) || prop.PropertyType == typeof(float?) ||
prop.PropertyType == typeof(double)|| prop.PropertyType == typeof(double?)
)
{
var defaultValue = Activator.CreateInstance(prop.PropertyType);
value = defaultValue.ToString();
}
else if (prop.PropertyType == typeof(DateTime?) || prop.PropertyType == typeof(DateTime))
{
value = DateTime.Now.ToString();
}
else if (prop.PropertyType == typeof(Guid?) || prop.PropertyType == typeof(Guid))
{
value = Guid.Empty.ToString();
}
}
var attribute = prop.GetCustomAttribute(typeof(DisplayNameAttribute)) as DisplayNameAttribute;
configs.Add(new ConfigModel
{
Key = key,
Name = attribute?.DisplayName ?? name,
Value = value,
Type = prop.PropertyType
});
}
else
{
configs.AddRange(GetAppConfigValue(configDic, prop.PropertyType, key));
}
}
return configs;
}
19
Source : Edit.cshtml.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
public void SetValue(Type type, string parentName = "")
{
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
string name = prop.Name;
string key = string.IsNullOrEmpty(parentName) ? $"{name}" : $"{parentName}:{name}";
if (prop.PropertyType.IsValueType || prop.PropertyType.Name.StartsWith("String"))
{
var value = Request.Form[key];
NewConfigs.TryAdd(key, value);
}
else
{
SetValue(prop.PropertyType, key);
}
}
}
19
Source : Amf3Writer.cs
with MIT License
from a1q123456
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 : CommandMessage.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
public void DeserializeAmf0(SerializationContext context)
{
var buffer = context.ReadBuffer.Span;
if (!context.Amf0Reader.TryGetNumber(buffer, out var txid, out var consumed))
{
throw new InvalidOperationException();
}
TranscationID = txid;
buffer = buffer.Slice(consumed);
context.Amf0Reader.TryGetObject(buffer, out var commandObj, out consumed);
CommandObject = commandObj;
buffer = buffer.Slice(consumed);
var optionArguments = GetType().GetProperties().Where(p => p.GetCustomAttribute<OptionalArgumentAttribute>() != null).ToList();
var i = 0;
while (buffer.Length > 0)
{
if (!context.Amf0Reader.TryGetValue(buffer, out _, out var optArg, out consumed))
{
break;
}
buffer = buffer.Slice(consumed);
optionArguments[i].SetValue(this, optArg);
i++;
if (i >= optionArguments.Count)
{
break;
}
}
}
19
Source : CommandMessage.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
public void DeserializeAmf3(SerializationContext context)
{
var buffer = context.ReadBuffer.Span;
if (!context.Amf3Reader.TryGetDouble(buffer, out var txid, out var consumed))
{
throw new InvalidOperationException();
}
TranscationID = txid;
buffer = buffer.Slice(consumed);
context.Amf3Reader.TryGetObject(buffer, out var commandObj, out consumed);
CommandObject = commandObj as AmfObject;
buffer = buffer.Slice(consumed);
var optionArguments = GetType().GetProperties().Where(p => p.GetCustomAttribute<OptionalArgumentAttribute>() != null).ToList();
var i = 0;
while (buffer.Length > 0)
{
context.Amf0Reader.TryGetValue(buffer, out _, out var optArg, out _);
optionArguments[i].SetValue(this, optArg);
}
}
19
Source : CommandMessage.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
public void SerializeAmf3(SerializationContext context)
{
using (var writeContext = new Amf.Serialization.Amf3.SerializationContext(context.WriteBuffer))
{
if (ProcedureName == null)
{
ProcedureName = GetType().GetCustomAttribute<RtmpCommandAttribute>().Name;
}
Debug.replacedert(!string.IsNullOrEmpty(ProcedureName));
context.Amf3Writer.WriteBytes(ProcedureName, writeContext);
context.Amf3Writer.WriteBytes(TranscationID, writeContext);
context.Amf3Writer.WriteValueBytes(CommandObject, writeContext);
var optionArguments = GetType().GetProperties().Where(p => p.GetCustomAttribute<OptionalArgumentAttribute>() != null).ToList();
foreach (var optionArgument in optionArguments)
{
context.Amf3Writer.WriteValueBytes(optionArgument.GetValue(this), writeContext);
}
}
}
19
Source : Amf0Writer.cs
with MIT License
from a1q123456
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 : Amf3Reader.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
public void RegisterTypedObject<T>() where T: new()
{
var type = typeof(T);
var props = type.GetProperties();
var fields = props.Where(p => p.CanWrite && Attribute.GetCustomAttribute(p, typeof(ClreplacedFieldAttribute)) != null).ToList();
var members = fields.ToDictionary(p => ((ClreplacedFieldAttribute)Attribute.GetCustomAttribute(p, typeof(ClreplacedFieldAttribute))).Name ?? p.Name, p => new Action<object, object>(p.SetValue));
if (members.Keys.Where(s => string.IsNullOrEmpty(s)).Any())
{
throw new InvalidOperationException("Field name cannot be empty or null");
}
string mapedName = null;
var attr = type.GetCustomAttribute<TypedObjectAttribute>();
if (attr != null)
{
mapedName = attr.Name;
}
var typeName = mapedName == null ? type.Name : mapedName;
var state = new TypeRegisterState()
{
Members = members,
Type = type
};
_registeredTypes.Add(type);
_registeredTypedObejectStates.Add(typeName, state);
}
19
Source : Amf0Reader.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
public void RegisterType<T>() where T : new()
{
var type = typeof(T);
var props = type.GetProperties();
var fields = props.Where(p => p.CanWrite && Attribute.GetCustomAttribute(p, typeof(ClreplacedFieldAttribute)) != null).ToList();
var members = fields.ToDictionary(p => ((ClreplacedFieldAttribute)Attribute.GetCustomAttribute(p, typeof(ClreplacedFieldAttribute))).Name ?? p.Name, p => new Action<object, object>(p.SetValue));
if (members.Keys.Where(s => string.IsNullOrEmpty(s)).Any())
{
throw new InvalidOperationException("Field name cannot be empty or null");
}
string mapedName = null;
var attr = type.GetCustomAttribute<TypedObjectAttribute>();
if (attr != null)
{
mapedName = attr.Name;
}
var typeName = mapedName == null ? type.Name : mapedName;
var state = new TypeRegisterState()
{
Members = members,
Type = type
};
_registeredTypes.Add(type);
_registeredTypeStates.Add(typeName, state);
_amf3Reader.RegisterTypedObject(typeName, state);
}
19
Source : CommandMessage.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
public void SerializeAmf0(SerializationContext context)
{
using (var writeContext = new Amf.Serialization.Amf0.SerializationContext(context.WriteBuffer))
{
if (ProcedureName == null)
{
ProcedureName = GetType().GetCustomAttribute<RtmpCommandAttribute>().Name;
}
Debug.replacedert(!string.IsNullOrEmpty(ProcedureName));
context.Amf0Writer.WriteBytes(ProcedureName, writeContext);
context.Amf0Writer.WriteBytes(TranscationID, writeContext);
context.Amf0Writer.WriteValueBytes(CommandObject, writeContext);
var optionArguments = GetType().GetProperties().Where(p => p.GetCustomAttribute<OptionalArgumentAttribute>() != null).ToList();
foreach (var optionArgument in optionArguments)
{
context.Amf0Writer.WriteValueBytes(optionArgument.GetValue(this), writeContext);
}
}
}
19
Source : BitfinexResultConverter.cs
with MIT License
from aabiryukov
with MIT License
from 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
Source : ReaderCache.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
static int GetParameterHash(object dynamicObject)
{
unchecked
{
int hash = 31; //any prime number
PropertyInfo[] propertyInfo = dynamicObject.GetType().GetProperties();
for (int i = 0; i < propertyInfo.Length; i++)
{
object propertyName = propertyInfo[i].Name;
//dynamic property will always return System.Object as property type. Get Type from the value
Type propertyType = GetTypeOfDynamicProperty(propertyInfo[i], dynamicObject);
//prime numbers to generate hash
hash = (-97 * ((hash * 29) + propertyName.GetHashCode())) + propertyType.GetHashCode();
}
return hash;
}
}
19
Source : ReaderCache.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
private static Action<object, IDbCommand> AddParametersIL(object param, IDbCommand cmd)
{
Type pType = param.GetType();
Type[] args = { typeof(object), typeof(IDbCommand) };
DynamicMethod method = new DynamicMethod("DynamicAddParam" + Guid.NewGuid().ToString(), null, args, typeof(ParameterCache).Module, true);
ILGenerator il = method.GetILGenerator();
foreach (PropertyInfo property in pType.GetProperties())
{
il.Emit(OpCodes.Ldarg_1);//load the idbcommand. Loads the argument at index 0 onto the evaluation stack.
//name
il.Emit(OpCodes.Ldstr, property.Name);
//dbtype
//dynamic property will always return System.Object as property type. Get Type from the value
Type type = GetTypeOfDynamicProperty(property, param);
if (type.IsEnum) type = Enum.GetUnderlyingType(type);
if(TypeCache.TypeToDbType.TryGetValue(type, out DbType dbType))
il.Emit(OpCodes.Ldc_I4_S, (byte)dbType);
else
il.Emit(OpCodes.Ldc_I4_S, (byte)DbType.String); //TODO: fix when unkown type
//value
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, property.GetMethod);
//box if value type
if (property.PropertyType.IsValueType)
il.Emit(OpCodes.Box, property.PropertyType);
il.Emit(OpCodes.Call, addInParameter);
il.Emit(OpCodes.Nop);
}
il.Emit(OpCodes.Ret);
var actionType = System.Linq.Expressions.Expression.GetActionType(typeof(object), typeof(IDbCommand));
return (Action<object, IDbCommand>)method.CreateDelegate(actionType);
}
19
Source : ReaderCache.cs
with Apache License 2.0
from aadreja
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 : VxHelpers.cs
with MIT License
from Aaltuj
with MIT License
from Aaltuj
internal static IEnumerable<PropertyInfo> GetModelProperties(Type modelType)
{
return modelType.GetProperties()
.Where(w => w.GetCustomAttribute<VxIgnoreAttribute>() == null);
}
19
Source : InspectorGenericFields.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from 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
Source : InspectorFieldsUtility.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static List<InspectorFieldData> GetInspectorFields(System.Object target)
{
List<InspectorFieldData> fields = new List<InspectorFieldData>();
Type myType = target.GetType();
foreach (PropertyInfo prop in myType.GetProperties())
{
var attrs = (InspectorField[])prop.GetCustomAttributes(typeof(InspectorField), false);
foreach (var attr in attrs)
{
fields.Add(new InspectorFieldData() { Name = prop.Name, Attributes = attr, Value = prop.GetValue(target, null) });
}
}
foreach (FieldInfo field in myType.GetFields())
{
var attrs = (InspectorField[])field.GetCustomAttributes(typeof(InspectorField), false);
foreach (var attr in attrs)
{
fields.Add(new InspectorFieldData() { Name = field.Name, Attributes = attr, Value = field.GetValue(target) });
}
}
return fields;
}
19
Source : InspectorGenericFields.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static List<InspectorPropertySetting> GetSettings(T source)
{
Type myType = source.GetType();
List<InspectorPropertySetting> settings = new List<InspectorPropertySetting>();
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)
{
settings.Add(InspectorField.FieldToProperty(attr, propInfo.GetValue(source, null), propInfo.Name));
}
}
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)
{
settings.Add(InspectorField.FieldToProperty(attr, fieldInfo.GetValue(source), fieldInfo.Name));
}
}
return settings;
}
19
Source : SurfaceMeshWithPaletteProvider.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private List<Color> GetCashedColorsCollection()
{
return typeof(Colors).GetProperties().Select(x => (Color)x.GetValue(null, null)).ToList();
}
19
Source : WorldObject.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public string DebugOutputString(WorldObject obj)
{
var sb = new StringBuilder();
sb.AppendLine("ACE Debug Output:");
sb.AppendLine("ACE Clreplaced File: " + GetType().Name + ".cs");
sb.AppendLine("Guid: " + obj.Guid.Full + " (0x" + obj.Guid.Full.ToString("X") + ")");
sb.AppendLine("----- Private Fields -----");
foreach (var prop in obj.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).OrderBy(field => field.Name))
{
if (prop.GetValue(obj) == null)
continue;
sb.AppendLine($"{prop.Name.Replace("<", "").Replace(">k__BackingField", "")} = {prop.GetValue(obj)}");
}
sb.AppendLine("----- Public Properties -----");
foreach (var prop in obj.GetType().GetProperties().OrderBy(property => property.Name))
{
if (prop.GetValue(obj, null) == null)
continue;
switch (prop.Name.ToLower())
{
case "guid":
sb.AppendLine($"{prop.Name} = {obj.Guid.Full} (GuidType.{obj.Guid.Type.ToString()})");
break;
case "descriptionflags":
sb.AppendLine($"{prop.Name} = {ObjectDescriptionFlags.ToString()}" + " (" + (uint)ObjectDescriptionFlags + ")");
break;
case "weenieflags":
var weenieFlags = CalculateWeenieHeaderFlag();
sb.AppendLine($"{prop.Name} = {weenieFlags.ToString()}" + " (" + (uint)weenieFlags + ")");
break;
case "weenieflags2":
var weenieFlags2 = CalculateWeenieHeaderFlag2();
sb.AppendLine($"{prop.Name} = {weenieFlags2.ToString()}" + " (" + (uint)weenieFlags2 + ")");
break;
case "itemtype":
sb.AppendLine($"{prop.Name} = {obj.ItemType.ToString()}" + " (" + (uint)obj.ItemType + ")");
break;
case "creaturetype":
sb.AppendLine($"{prop.Name} = {obj.CreatureType.ToString()}" + " (" + (uint)obj.CreatureType + ")");
break;
case "containertype":
sb.AppendLine($"{prop.Name} = {obj.ContainerType.ToString()}" + " (" + (uint)obj.ContainerType + ")");
break;
case "usable":
sb.AppendLine($"{prop.Name} = {obj.ItemUseable.ToString()}" + " (" + (uint)obj.ItemUseable + ")");
break;
case "radarbehavior":
sb.AppendLine($"{prop.Name} = {obj.RadarBehavior.ToString()}" + " (" + (uint)obj.RadarBehavior + ")");
break;
case "physicsdescriptionflag":
var physicsDescriptionFlag = CalculatedPhysicsDescriptionFlag();
sb.AppendLine($"{prop.Name} = {physicsDescriptionFlag.ToString()}" + " (" + (uint)physicsDescriptionFlag + ")");
break;
case "physicsstate":
var physicsState = PhysicsObj.State;
sb.AppendLine($"{prop.Name} = {physicsState.ToString()}" + " (" + (uint)physicsState + ")");
break;
//case "propertiesspellid":
// foreach (var item in obj.PropertiesSpellId)
// {
// sb.AppendLine($"PropertySpellId.{Enum.GetName(typeof(Spell), item.SpellId)} ({item.SpellId})");
// }
// break;
case "validlocations":
sb.AppendLine($"{prop.Name} = {obj.ValidLocations}" + " (" + (uint)obj.ValidLocations + ")");
break;
case "currentwieldedlocation":
sb.AppendLine($"{prop.Name} = {obj.CurrentWieldedLocation}" + " (" + (uint)obj.CurrentWieldedLocation + ")");
break;
case "priority":
sb.AppendLine($"{prop.Name} = {obj.ClothingPriority}" + " (" + (uint)obj.ClothingPriority + ")");
break;
case "radarcolor":
sb.AppendLine($"{prop.Name} = {obj.RadarColor}" + " (" + (uint)obj.RadarColor + ")");
break;
case "location":
sb.AppendLine($"{prop.Name} = {obj.Location.ToLOCString()}");
break;
case "destination":
sb.AppendLine($"{prop.Name} = {obj.Destination.ToLOCString()}");
break;
case "instantiation":
sb.AppendLine($"{prop.Name} = {obj.Instantiation.ToLOCString()}");
break;
case "sanctuary":
sb.AppendLine($"{prop.Name} = {obj.Sanctuary.ToLOCString()}");
break;
case "home":
sb.AppendLine($"{prop.Name} = {obj.Home.ToLOCString()}");
break;
case "portalsummonloc":
sb.AppendLine($"{prop.Name} = {obj.PortalSummonLoc.ToLOCString()}");
break;
case "houseboot":
sb.AppendLine($"{prop.Name} = {obj.HouseBoot.ToLOCString()}");
break;
case "lastoutsidedeath":
sb.AppendLine($"{prop.Name} = {obj.LastOutsideDeath.ToLOCString()}");
break;
case "linkedlifestone":
sb.AppendLine($"{prop.Name} = {obj.LinkedLifestone.ToLOCString()}");
break;
case "channelsactive":
sb.AppendLine($"{prop.Name} = {(Channel)obj.GetProperty(PropertyInt.ChannelsActive)}" + " (" + (uint)obj.GetProperty(PropertyInt.ChannelsActive) + ")");
break;
case "channelsallowed":
sb.AppendLine($"{prop.Name} = {(Channel)obj.GetProperty(PropertyInt.ChannelsAllowed)}" + " (" + (uint)obj.GetProperty(PropertyInt.ChannelsAllowed) + ")");
break;
case "playerkillerstatus":
sb.AppendLine($"{prop.Name} = {obj.PlayerKillerStatus}" + " (" + (uint)obj.PlayerKillerStatus + ")");
break;
default:
sb.AppendLine($"{prop.Name} = {prop.GetValue(obj, null)}");
break;
}
}
sb.AppendLine("----- Property Dictionaries -----");
foreach (var item in obj.GetAllPropertyBools())
sb.AppendLine($"PropertyBool.{Enum.GetName(typeof(PropertyBool), item.Key)} ({(int)item.Key}) = {item.Value}");
foreach (var item in obj.GetAllPropertyDataId())
sb.AppendLine($"PropertyDataId.{Enum.GetName(typeof(PropertyDataId), item.Key)} ({(int)item.Key}) = {item.Value}");
foreach (var item in obj.GetAllPropertyFloat())
sb.AppendLine($"PropertyFloat.{Enum.GetName(typeof(PropertyFloat), item.Key)} ({(int)item.Key}) = {item.Value}");
foreach (var item in obj.GetAllPropertyInstanceId())
sb.AppendLine($"PropertyInstanceId.{Enum.GetName(typeof(PropertyInstanceId), item.Key)} ({(int)item.Key}) = {item.Value}");
foreach (var item in obj.GetAllPropertyInt())
sb.AppendLine($"PropertyInt.{Enum.GetName(typeof(PropertyInt), item.Key)} ({(int)item.Key}) = {item.Value}");
foreach (var item in obj.GetAllPropertyInt64())
sb.AppendLine($"PropertyInt64.{Enum.GetName(typeof(PropertyInt64), item.Key)} ({(int)item.Key}) = {item.Value}");
foreach (var item in obj.GetAllPropertyString())
sb.AppendLine($"PropertyString.{Enum.GetName(typeof(PropertyString), item.Key)} ({(int)item.Key}) = {item.Value}");
sb.AppendLine("\n");
return sb.ToString().Replace("\r", "");
}
19
Source : DownloadPersonalData.cshtml.cs
with MIT License
from ADefWebserver
with MIT License
from ADefWebserver
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
_logger.LogInformation("User with ID '{UserId}' asked for their personal data.", _userManager.GetUserId(User));
// Only include personal data for download
var personalData = new Dictionary<string, string>();
var personalDataProps = typeof(ApplicationUser).GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(PersonalDataAttribute)));
foreach (var p in personalDataProps)
{
personalData.Add(p.Name, p.GetValue(user)?.ToString() ?? "null");
}
Response.Headers.Add("Content-Disposition", "attachment; filename=PersonalData.json");
return new FileContentResult(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(personalData)), "text/json");
}
19
Source : ObjectExtenders.cs
with MIT License
from adoconnection
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 : CopyObjectExtensions.cs
with MIT License
from adospace
with MIT License
from adospace
public static void CopyPropertiesTo(this object source, object dest, PropertyInfo[] destProps)
{
if (source.GetType().FullName != dest.GetType().FullName)
{
//can't copy state over a type with a different name: surely it's a different type
return;
}
var sourceProps = source.GetType()
.GetProperties()
.Where(x => x.CanRead)
.ToList();
foreach (var sourceProp in sourceProps)
{
var targetProperty = destProps.FirstOrDefault(x => x.Name == sourceProp.Name);
if (targetProperty != null)
{
var sourceValue = sourceProp.GetValue(source, null);
if (sourceValue != null && sourceValue.GetType().IsEnum)
{
sourceValue = Convert.ChangeType(sourceValue, Enum.GetUnderlyingType(sourceProp.PropertyType));
}
try
{
targetProperty.SetValue(dest, sourceValue, null);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Unable to copy property '{targetProperty.Name}' of state ({source.GetType()}) to new state after hot reload (Exception: '{DumpExceptionMessage(ex)}')");
}
}
}
}
19
Source : CustomIconProvider.android.cs
with MIT License
from adenearnshaw
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 : ObjectShredder.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public DataTable ExtendTable(DataTable table, Type type)
{
// Extend the table schema if the input table was null or if the value
// in the sequence is derived from type T.
foreach (FieldInfo f in type.GetFields())
{
if (!_ordinalMap.ContainsKey(f.Name))
{
var ft = f.FieldType;
if (ft.IsGenericType && ft.GetGenericTypeDefinition() == typeof(Nullable<>))
{
ft = Nullable.GetUnderlyingType(ft);
}
// Add the field as a column in the table if it doesn't exist
// already.
DataColumn dc = table.Columns.Contains(f.Name)
? table.Columns[f.Name]
: table.Columns.Add(f.Name, ft);
// Add the field to the ordinal map.
_ordinalMap.Add(f.Name, dc.Ordinal);
}
}
foreach (PropertyInfo p in type.GetProperties())
{
if (!_ordinalMap.ContainsKey(p.Name))
{
var pt = p.PropertyType;
if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
{
pt = Nullable.GetUnderlyingType(pt);
}
// Add the property as a column in the table if it doesn't exist
// already.
DataColumn dc = table.Columns.Contains(p.Name)
? table.Columns[p.Name]
: table.Columns.Add(p.Name, pt);
// Add the property to the ordinal map.
_ordinalMap.Add(p.Name, dc.Ordinal);
}
}
// Return the table.
return table;
}
19
Source : ObjectShredder.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public object[] ShredObject(DataTable table, T instance)
{
FieldInfo[] fi = _fi;
PropertyInfo[] pi = _pi;
if (instance.GetType() != typeof(T))
{
// If the instance is derived from T, extend the table schema
// and get the properties and fields.
ExtendTable(table, instance.GetType());
fi = instance.GetType().GetFields();
pi = instance.GetType().GetProperties();
}
// Add the property and field values of the instance to an array.
var values = new object[table.Columns.Count];
foreach (FieldInfo f in fi)
{
values[_ordinalMap[f.Name]] = f.GetValue(instance);
}
foreach (PropertyInfo p in pi)
{
values[_ordinalMap[p.Name]] = p.GetValue(instance, null);
}
// Return the property and field values of the instance.
return values;
}
19
Source : EntityInfo.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private IDictionary<string, AttributeInfo> LoadProperties(Func<PropertyInfo, AttributeLogicalNameAttribute, string> keySelector)
{
var properties = new Dictionary<string, AttributeInfo>();
foreach (var pi in EnreplacedyType.GetProperties())
{
var attribute = pi.GetFirstOrDefaultCustomAttribute<AttributeLogicalNameAttribute>();
var relationship = pi.GetFirstOrDefaultCustomAttribute<RelationshipSchemaNameAttribute>();
if (attribute != null && pi.Name != "Id" && relationship == null)
{
properties.Add(keySelector(pi, attribute), new AttributeInfo(pi, attribute));
}
}
return properties;
}
19
Source : EntityInfo.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private IDictionary<TKey, RelationshipInfo> Loadreplacedociations<TKey>(Func<PropertyInfo, RelationshipSchemaNameAttribute, TKey> keySelector)
{
var replacedociations = new Dictionary<TKey, RelationshipInfo>();
foreach (var pi in EnreplacedyType.GetProperties())
{
var replacedociation = pi.GetFirstOrDefaultCustomAttribute<RelationshipSchemaNameAttribute>();
if (replacedociation != null)
{
replacedociations.Add(keySelector(pi, replacedociation), new RelationshipInfo(pi, replacedociation));
}
}
return replacedociations;
}
See More Examples