Here are the examples of the csharp api System.Type.GetProperties(System.Reflection.BindingFlags) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1446 Examples
19
Source : EntityMapperProvider.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
private Func<object, Dictionary<string, object>> CreateTypeDeserializerHandler(Type type)
{
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var methodName = $"{type.Name}Deserializer{Guid.NewGuid():N}";
var dynamicMethod = new DynamicMethod(methodName, typeof(Dictionary<string, object>), new Type[] { typeof(object) }, type, true);
var generator = dynamicMethod.GetILGenerator();
LocalBuilder enreplacedyLocal1 = generator.DeclareLocal(typeof(Dictionary<string, object>));
LocalBuilder enreplacedyLocal2 = generator.DeclareLocal(type);
generator.Emit(OpCodes.Newobj, typeof(Dictionary<string, object>).GetConstructor(Type.EmptyTypes));
generator.Emit(OpCodes.Stloc, enreplacedyLocal1);
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Castclreplaced, type);
generator.Emit(OpCodes.Stloc, enreplacedyLocal2);
foreach (var item in properties)
{
generator.Emit(OpCodes.Ldloc, enreplacedyLocal1);
generator.Emit(OpCodes.Ldstr, item.Name);
generator.Emit(OpCodes.Ldloc, enreplacedyLocal2);
generator.Emit(OpCodes.Callvirt, item.GetGetMethod());
if (item.PropertyType.IsValueType)
{
generator.Emit(OpCodes.Box, item.PropertyType);
}
var addMethod = typeof(Dictionary<string, object>).GetMethod(nameof(Dictionary<string, object>.Add), new Type[] { typeof(string), typeof(object) });
generator.Emit(OpCodes.Callvirt, addMethod);
}
generator.Emit(OpCodes.Ldloc, enreplacedyLocal1);
generator.Emit(OpCodes.Ret);
return dynamicMethod.CreateDelegate(typeof(Func<object, Dictionary<string, object>>)) as Func<object, Dictionary<string, object>>;
}
19
Source : TypeUtils.cs
with MIT License
from 1996v
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 : TypeUtils.cs
with MIT License
from 1996v
with MIT License
from 1996v
public static IEnumerable<PropertyInfo> GetAllProperties(this Type type, BindingFlags bind)
{
if (type.BaseType != null)
{
foreach (var item in GetAllProperties(type.BaseType, bind | BindingFlags.DeclaredOnly))
{
yield return item;
}
}
foreach (var item in type.GetProperties(bind | BindingFlags.DeclaredOnly))
{
yield return item;
}
}
19
Source : Serializer.cs
with MIT License
from 2881099
with MIT License
from 2881099
static Func<T, Dictionary<string, string>> CompilePropertySerializer()
{
var o_t = typeof(T);
var o = Expression.Parameter(o_t, "o");
var d_t = typeof(Dictionary<string, string>);
var d = Expression.Variable(d_t, "d");
var d_init = Expression.MemberInit(Expression.New(d_t));
var d_add = d_t.GetMethod("Add");
var d_setters = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance) // build setters via Add(k,v)
.Where(x => x.CanRead)
.Select(x =>
{
var prop = Expression.Property(o, x.Name);
var prop_mi_to_string = x.PropertyType.GetMethod("ToString", new Type[0]);
var add_to_dict = Expression.Call(d, d_add, Expression.Constant(x.Name), Expression.Call(prop, prop_mi_to_string));
if (!x.PropertyType.IsByRef)
return (Expression)add_to_dict;
else
return (Expression)Expression.IfThen(
Expression.Not(Expression.Equal(prop, Expression.Constant(null))),
add_to_dict);
});
// run this
var body = Expression.Block(new[] { d }, // scope variables
Expression.replacedign(d, d_init), // initialize
Expression.Block(d_setters), // set
d); // return
return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o)
.Compile();
}
19
Source : Serializer.cs
with MIT License
from 2881099
with MIT License
from 2881099
static Func<Dictionary<string, string>, T> CompilePropertyDeserializer()
{
var o_t = typeof(T);
var o = Expression.Variable(o_t, "o");
var o_new = Expression.New(typeof(T));
var d_t = typeof(Dictionary<string, string>);
var d = Expression.Parameter(d_t, "d");
var d_mi_try_get_value = d_t.GetMethod("TryGetValue");
var item_t = typeof(String);
var item = Expression.Variable(item_t, "item");
var tc_t = typeof(TypeConverter);
var tc = Expression.Variable(tc_t, "tc");
var tc_mi_can_convert_from = tc_t.GetMethod("CanConvertFrom", new[] { typeof(Type) });
var tc_mi_convert_from = tc_t.GetMethod("ConvertFrom", new[] { typeof(Object) });
var td_t = typeof(TypeDescriptor);
var td_mi_get_converter = td_t.GetMethod("GetConverter", new[] { typeof(Type) });
var binds = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.CanRead)
.Select(x =>
{
var value_t = x.PropertyType;
var value = Expression.Variable(value_t, "value");
var target = Expression.Label(x.PropertyType);
return Expression.Bind(x, Expression.Block(new[] { item, value },
Expression.replacedign(tc, Expression.Call(null, td_mi_get_converter, Expression.Constant(x.PropertyType))),
Expression.IfThen(
Expression.Call(d, d_mi_try_get_value, Expression.Constant(x.Name), item),
Expression.IfThen(
Expression.NotEqual(item, Expression.Constant(null)),
Expression.IfThen(
Expression.Call(tc, tc_mi_can_convert_from, Expression.Constant(typeof(String))),
Expression.Block(
Expression.replacedign(value, Expression.Convert(Expression.Call(tc, tc_mi_convert_from, item), x.PropertyType)),
Expression.Return(target, value, x.PropertyType))))),
Expression.Label(target, value)
));
}).ToArray();
var body = Expression.Block(new[] { o, tc },
Expression.MemberInit(o_new, binds)
);
return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
.Compile();
}
19
Source : DbContext.cs
with MIT License
from 2881099
with MIT License
from 2881099
internal void InitPropSets() {
var props = _dicGetDbSetProps.GetOrAdd(this.GetType(), tp =>
tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
.Where(a => a.PropertyType.IsGenericType &&
a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GenericTypeArguments[0])).ToArray());
foreach (var prop in props) {
var set = this.Set(prop.PropertyType.GenericTypeArguments[0]);
prop.SetValue(this, set);
AllSets.Add(prop.Name, set);
}
}
19
Source : DynamicProxy.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static DynamicProxyMeta CreateDynamicProxyMeta(Type type, bool isCompile, bool isThrow)
{
if (type == null) return null;
var typeCSharpName = type.DisplayCsharp();
if (type.IsNotPublic)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 需要使用 public 标记");
return null;
}
var matchedMemberInfos = new List<MemberInfo>();
var matchedAttributes = new List<DynamicProxyAttribute>();
var matchedAttributesFromServices = new List<FieldInfo[]>();
var clreplacedName = $"AopProxyClreplaced___{Guid.NewGuid().ToString("N")}";
var methodOverrideSb = new StringBuilder();
var sb = methodOverrideSb;
#region Common Code
Func<Type, DynamicProxyInjectorType, bool, int, string, string> getMatchedAttributesCode = (returnType, injectorType, isAsync, attrsIndex, proxyMethodName) =>
{
var sbt = new StringBuilder();
for (var a = attrsIndex; a < matchedAttributes.Count; a++)
{
sbt.Append($@"{(proxyMethodName == "Before" ? $@"
var __DP_ARG___attribute{a} = __DP_Meta.{nameof(DynamicProxyMeta.CreateDynamicProxyAttribute)}({a});
__DP_ARG___attribute{a}_FromServicesCopyTo(__DP_ARG___attribute{a});" : "")}
var __DP_ARG___{proxyMethodName}{a} = new {(proxyMethodName == "Before" ? _beforeAgumentsName : _afterAgumentsName)}(this, {_injectorTypeName}.{injectorType.ToString()}, __DP_Meta.MatchedMemberInfos[{a}], __DP_ARG___parameters, {(proxyMethodName == "Before" ? "null" : "__DP_ARG___return_value, __DP_ARG___exception")});
{(isAsync ? "await " : "")}__DP_ARG___attribute{a}.{proxyMethodName}(__DP_ARG___{proxyMethodName}{a});
{(proxyMethodName == "Before" ?
$@"if (__DP_ARG___is_return == false)
{{
__DP_ARG___is_return = __DP_ARG___{proxyMethodName}{a}.Returned;{(returnType != typeof(void) ? $@"
if (__DP_ARG___is_return) __DP_ARG___return_value = __DP_ARG___{proxyMethodName}{a}.ReturnValue;" : "")}
}}" :
$"if (__DP_ARG___{proxyMethodName}{a}.Exception != null && __DP_ARG___{proxyMethodName}{a}.ExceptionHandled == false) throw __DP_ARG___{proxyMethodName}{a}.Exception;")}");
}
return sbt.ToString();
};
Func<Type, DynamicProxyInjectorType, bool, string, string> getMatchedAttributesCodeReturn = (returnType, injectorType, isAsync, basePropertyValueTpl) =>
{
var sbt = new StringBuilder();
var taskType = returnType.ReturnTypeWithoutTask();
sbt.Append($@"
{(returnType == typeof(void) ? "return;" : (isAsync == false && returnType.IsTask() ?
(taskType.IsValueType || taskType.IsGenericParameter ?
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(({taskType.DisplayCsharp()})__DP_ARG___return_value) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);" :
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(__DP_ARG___return_value as {taskType.DisplayCsharp()}) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);"
) :
(returnType.IsValueType || returnType.IsGenericParameter ? $"return ({returnType.DisplayCsharp()})__DP_ARG___return_value;" : $"return __DP_ARG___return_value as {returnType.DisplayCsharp()};")))}");
return sbt.ToString();
};
Func<string, Type, string> getMatchedAttributesCodeAuditParameter = (methodParameterName, methodParameterType) =>
{
return $@"
if (!object.ReferenceEquals({methodParameterName}, __DP_ARG___parameters[""{methodParameterName}""])) {methodParameterName} = {(methodParameterType.IsValueType ? $@"({methodParameterType.DisplayCsharp()})__DP_ARG___parameters[""{methodParameterName}""]" : $@"__DP_ARG___parameters[""{methodParameterName}""] as {methodParameterType.DisplayCsharp()}")};";
};
#endregion
#region Methods
var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.IsStatic == false).ToArray();
var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
foreach (var method in methods)
{
if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))
if (type.GetProperty(method.Name.Substring(4), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) continue;
var attrs = method.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => method));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
if (method.IsVirtual == false || method.IsFinal)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 方法 {method.Name} 需要使用 virtual 标记");
continue;
}
#if net40
var returnType = method.ReturnType;
var methodIsAsync = false;
#else
var returnType = method.ReturnType.ReturnTypeWithoutTask();
var methodIsAsync = method.ReturnType.IsTask();
//if (attrs.Where(a => a.GetType().GetMethod("BeforeAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any() ||
// attrs.Where(a => a.GetType().GetMethod("AfterAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any())
//{
//}
#endif
var baseInvoke = type.IsInterface == false ? $@"
try
{{
if (__DP_ARG___is_return == false)
{{{string.Join("", method.GetParameters().Select(a => getMatchedAttributesCodeAuditParameter(a.Name, a.ParameterType)))}
{(returnType != typeof(void) ? "__DP_ARG___return_value = " : "")}{(methodIsAsync ? "await " : "")}base.{method.Name}({(string.Join(", ", method.GetParameters().Select(a => a.Name)))});
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}" : "";
sb.Append($@"
{(methodIsAsync ? "async " : "")}{method.DisplayCsharp(true)}
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();{string.Join("\r\n ", method.GetParameters().Select(a => $"__DP_ARG___parameters.Add(\"{a.Name}\", {a.Name});"))}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "Before")}{baseInvoke}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(returnType, DynamicProxyInjectorType.Method, methodIsAsync, null)}
}}");
}
#endregion
var propertyOverrideSb = new StringBuilder();
sb = propertyOverrideSb;
#region Property
var props = type.IsInterface == false ? type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) : new PropertyInfo[0];
foreach (var prop2 in props)
{
var getMethod = prop2.GetGetMethod(false);
var setMethod = prop2.GetSetMethod(false);
if (getMethod?.IsFinal == true || setMethod?.IsFinal == true || (getMethod?.IsVirtual == false && setMethod?.IsVirtual == false))
{
if (getMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true ||
setMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 属性 {prop2.Name} 需要使用 virtual 标记");
continue;
}
}
var attrs = prop2.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
var prop2AttributeAny = attrs.Any();
var getMethodAttributeAny = prop2AttributeAny;
var setMethodAttributeAny = prop2AttributeAny;
if (attrs.Any() == false && getMethod?.IsVirtual == true)
{
attrs = getMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
getMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false && setMethod?.IsVirtual == true)
{
attrs = setMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
setMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => prop2));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
var returnTypeCSharpName = prop2.PropertyType.DisplayCsharp();
var propModification = (getMethod?.IsPublic == true || setMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true || setMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true || setMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true || setMethod?.IsPrivate == true ? "private " : ""))));
var propSetModification = (setMethod?.IsPublic == true ? "public " : (setMethod?.Isreplacedembly == true ? "internal " : (setMethod?.IsFamily == true ? "protected " : (setMethod?.IsPrivate == true ? "private " : ""))));
var propGetModification = (getMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true ? "private " : ""))));
if (propSetModification == propModification) propSetModification = "";
if (propGetModification == propModification) propGetModification = "";
//if (getMethod.IsAbstract) sb.Append("abstract ");
sb.Append($@"
{propModification}{(getMethod?.IsStatic == true ? "static " : "")}{(getMethod?.IsVirtual == true ? "override " : "")}{returnTypeCSharpName} {prop2.Name}
{{");
if (getMethod != null)
{
if (getMethodAttributeAny == false) sb.Append($@"
{propGetModification} get
{{
return base.{prop2.Name}
}}");
else sb.Append($@"
{propGetModification} get
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false) __DP_ARG___return_value = base.{prop2.Name};
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(prop2.PropertyType, DynamicProxyInjectorType.Method, false, null)}
}}");
}
if (setMethod != null)
{
if (setMethodAttributeAny == false) sb.Append($@"
{propSetModification} set
{{
base.{prop2.Name} = value;
}}");
else sb.Append($@"
{propSetModification} set
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
__DP_ARG___parameters.Add(""value"", value);
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false)
{{{getMatchedAttributesCodeAuditParameter("value", prop2.PropertyType)}
base.{prop2.Name} = value;
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "After")}
}}");
}
sb.Append($@"
}}");
}
#endregion
string proxyCscode = "";
replacedembly proxyreplacedembly = null;
Type proxyType = null;
if (matchedMemberInfos.Any())
{
#region Constructors
sb = new StringBuilder();
var fromServicesTypes = matchedAttributesFromServices.SelectMany(fs => fs).GroupBy(a => a.FieldType).Select((a, b) => new KeyValuePair<Type, string>(a.Key, $"__DP_ARG___FromServices_{b}")).ToDictionary(a => a.Key, a => a.Value);
sb.Append(string.Join("", fromServicesTypes.Select(serviceType => $@"
private {serviceType.Key.DisplayCsharp()} {serviceType.Value};")));
foreach (var ctor in ctors)
{
var ctorParams = ctor.GetParameters();
sb.Append($@"
{(ctor.IsPrivate ? "private " : "")}{(ctor.IsFamily ? "protected " : "")}{(ctor.Isreplacedembly ? "internal " : "")}{(ctor.IsPublic ? "public " : "")}{clreplacedName}({string.Join(", ", ctorParams.Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))}{
(ctorParams.Any() && fromServicesTypes.Any() ? ", " : "")}{
string.Join(", ", fromServicesTypes.Select(serviceType => $@"{serviceType.Key.DisplayCsharp()} parameter{serviceType.Value}"))})
: base({(string.Join(", ", ctorParams.Select(a => a.Name)))})
{{{string.Join("", fromServicesTypes.Select(serviceType => $@"
{serviceType.Value} = parameter{serviceType.Value};"))}
}}");
}
for (var a = 0; a < matchedAttributesFromServices.Count; a++)
{
sb.Append($@"
private void __DP_ARG___attribute{a}_FromServicesCopyTo({_idynamicProxyName} attr)
{{{string.Join("", matchedAttributesFromServices[a].Select(fs => $@"
__DP_Meta.{nameof(DynamicProxyMeta.SetDynamicProxyAttributePropertyValue)}({a}, attr, ""{fs.Name}"", {fromServicesTypes[fs.FieldType]});"))}
}}");
}
#endregion
proxyCscode = $@"using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
public clreplaced {clreplacedName} : {typeCSharpName}
{{
private {_metaName} __DP_Meta = {typeof(DynamicProxy).DisplayCsharp()}.{nameof(GetAvailableMeta)}(typeof({typeCSharpName}));
//这里要注释掉,如果重写的基类没有无参构造函数,会报错
//public {clreplacedName}({_metaName} meta)
//{{
// __DP_Meta = meta;
//}}
{sb.ToString()}
{methodOverrideSb.ToString()}
{propertyOverrideSb.ToString()}
}}";
proxyreplacedembly = isCompile == false ? null : CompileCode(proxyCscode);
proxyType = isCompile == false ? null : proxyreplacedembly.GetExportedTypes()/*.DefinedTypes*/.Where(a => a.FullName.EndsWith(clreplacedName)).FirstOrDefault();
}
methodOverrideSb.Clear();
propertyOverrideSb.Clear();
sb.Clear();
return new DynamicProxyMeta(
type, ctors,
matchedMemberInfos.ToArray(), matchedAttributes.ToArray(),
isCompile == false ? proxyCscode : null, clreplacedName, proxyreplacedembly, proxyType);
}
19
Source : TransformCopyTest.cs
with MIT License
from 39M
with MIT License
from 39M
private void replacedertObjectsEqual(object a, object b) {
if ((a == null) != (b == null)) {
replacedert.Fail("One object was null an the other was not.");
return;
}
Type typeA = a.GetType();
Type typeB = b.GetType();
if (typeA != typeB) {
replacedert.Fail("Type " + typeA + " is not equal to type " + typeB + ".");
}
if (typeA.IsValueType) {
replacedert.That(a, Is.EqualTo(b));
return;
}
if (a is IList) {
IList aList = a as IList;
IList bList = b as IList;
replacedert.That(aList.Count, Is.EqualTo(bList.Count));
for (int i = 0; i < aList.Count; i++) {
replacedertObjectsEqual(aList[i], bList[i]);
}
} else {
FieldInfo[] fields = typeA.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields) {
replacedertObjectsEqual(field.GetValue(a), field.GetValue(b));
}
PropertyInfo[] properties = typeA.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties) {
if (property.GetIndexParameters().Length == 0) {
object propA;
try {
propA = property.GetValue(a, null);
} catch (Exception exceptionA) {
try {
property.GetValue(b, null);
replacedert.Fail("One property threw an exception where the other did not.");
return;
} catch (Exception exceptionB) {
replacedert.That(exceptionA.GetType(), Is.EqualTo(exceptionB.GetType()), "Both properties threw exceptions but their types were different.");
return;
}
}
object propB = property.GetValue(b, null);
replacedertObjectsEqual(propA, propB);
}
}
}
}
19
Source : Helpers.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
internal static MemberInfo[] GetInstanceFieldsAndProperties(Type type, bool publicOnly)
{
#if WINRT || PROFILE259
System.Collections.Generic.List<MemberInfo> members = new System.Collections.Generic.List<MemberInfo>();
foreach(FieldInfo field in type.GetRuntimeFields())
{
if(field.IsStatic) continue;
if(field.IsPublic || !publicOnly) members.Add(field);
}
foreach(PropertyInfo prop in type.GetRuntimeProperties())
{
MethodInfo getter = Helpers.GetGetMethod(prop, true, true);
if(getter == null || getter.IsStatic) continue;
if(getter.IsPublic || !publicOnly) members.Add(prop);
}
return members.ToArray();
#else
BindingFlags flags = publicOnly ? BindingFlags.Public | BindingFlags.Instance : BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic;
PropertyInfo[] props = type.GetProperties(flags);
FieldInfo[] fields = type.GetFields(flags);
MemberInfo[] members = new MemberInfo[fields.Length + props.Length];
props.CopyTo(members, 0);
fields.CopyTo(members, props.Length);
return members;
#endif
}
19
Source : MapDecorator.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static MethodInfo GetIndexerSetter()
{
#if PROFILE259
foreach(var prop in typeof(TDictionary).GetRuntimeProperties())
#else
foreach(var prop in typeof(TDictionary).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
#endif
{
if (prop.Name != "Item") continue;
if (prop.PropertyType != typeof(TValue)) continue;
var args = prop.GetIndexParameters();
if (args == null || args.Length != 1) continue;
if (args[0].ParameterType != typeof(TKey)) continue;
#if PROFILE259
var method = prop.SetMethod;
#else
var method = prop.GetSetMethod(true);
#endif
if (method != null)
{
return method;
}
}
throw new InvalidOperationException("Unable to resolve indexer for map");
}
19
Source : NotchSolutionDebugger.cs
with MIT License
from 5argon
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
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 : ReflectionCache.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
public static List<PropertyInfo> GereplacedemProps(Type t,Operation op)
{
if(ItemPropCache.TryGetValue(t,out var props))
{
if (props.TryGetValue(op, out var res))
return res;
else
return null;
}
var handle_prop = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.GetCustomAttributes(typeof(HandleAttribute), true).Any());
Dictionary<Operation, List<PropertyInfo>> opbind = new Dictionary<Operation, List<PropertyInfo>>();
foreach(var p in handle_prop)
{
Operation p_op = p.GetCustomAttributes(typeof(HandleAttribute), true).OfType<HandleAttribute>().FirstOrDefault().handleType;
if (opbind.TryGetValue(p_op, out var list))
{
list.Add(p);
}
else
{
opbind.Add(p_op, new List<PropertyInfo> { p });
}
//Logger.LogDebug($"Cache: {p_op}:{p.Name},{t}");
}
ItemPropCache.Add(t, opbind);
if (ItemPropCache.TryGetValue(t, out var props2))
{
if (props2.TryGetValue(op, out var res2))
return res2;
else
return null;
}
else
return null;
}
19
Source : Inspector.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
private static void _reflectProps(Type t, BindingFlags flags = BindingFlags.Public | BindingFlags.Instance)
{
if (cache_prop.ContainsKey(t))
return;
var propInfos =t.GetProperties(flags)
.Where(x =>
{
var handlers = x.GetCustomAttributes(typeof(HandleAttribute), true).OfType<HandleAttribute>();
bool handflag = handlers.Any();
bool ignoreflag = x.GetCustomAttributes(typeof(InspectIgnoreAttribute), true).OfType<InspectIgnoreAttribute>().Any();
if(handflag && (!ignoreflag))
{
if(!handler.ContainsKey(x))
handler.Add(x, handlers.FirstOrDefault().handleType);
}
return handflag && (!ignoreflag);
});
foreach(var p in propInfos)
{
if(cache_prop.TryGetValue(t,out var npair))
{
npair.Add(p.Name, p);
}
else
{
var d = new Dictionary<string, PropertyInfo>();
d.Add(p.Name, p);
cache_prop.Add(t, d);
}
//Logger.LogDebug($"Cache PropInfo:T:{t},name:{p.Name}");
}
//Logger.LogDebug($"_reflectProp_resutl:{propInfos.ToArray().Length}");
}
19
Source : EntityCache.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal static TableAttribute PrepareTableAttribute(Type enreplacedy)
{
TableAttribute result = (TableAttribute)enreplacedy.GetCustomAttributes(typeof(TableAttribute), false).FirstOrDefault();
if (result == null)
{
result = new TableAttribute
{
Name = enreplacedy.Name, //replaceduming enreplacedy clreplaced name is table name
NeedsHistory = Config.NeedsHistory,
NoCreatedBy = Config.NoCreatedBy,
NoCreatedOn = Config.NoCreatedOn,
NoUpdatedBy = Config.NoUpdatedBy,
NoUpdatedOn = Config.NoUpdatedOn,
NoVersionNo = Config.NoVersionNo,
NoIsActive = Config.NoIsActive
};
}
if (string.IsNullOrEmpty(result.Name)) result.Name = enreplacedy.Name;
//find all properties
var properties = enreplacedy.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
//TODO: check for valid property types to be added in list
if ((property.Name.Equals("keyid", StringComparison.OrdinalIgnoreCase) ||
property.Name.Equals("operation", StringComparison.OrdinalIgnoreCase)))
continue;
//check for ignore property attribute
var ignoreInfo = (IgnoreColumnAttribute)property.GetCustomAttribute(typeof(IgnoreColumnAttribute));
var primaryKey = (PrimaryKeyAttribute)property.GetCustomAttribute(typeof(PrimaryKeyAttribute));
var column = (ColumnAttribute)property.GetCustomAttribute(typeof(ColumnAttribute));
if (column == null) column = new ColumnAttribute();
if (string.IsNullOrEmpty(column.Name)) column.Name = property.Name;
if (property.Name.Equals("CreatedBy", StringComparison.OrdinalIgnoreCase))
column.Name = Config.CreatedByColumnName;
else if (property.Name.Equals("CreatedByName"))
column.Name = Config.CreatedByNameColumnName;
else if (property.Name.Equals("CreatedOn"))
column.Name = Config.CreatedOnColumnName;
else if (property.Name.Equals("UpdatedBy"))
column.Name = Config.UpdatedByColumnName;
else if (property.Name.Equals("UpdatedByName"))
column.Name = Config.UpdatedByNameColumnName;
else if (property.Name.Equals("UpdatedOn"))
column.Name = Config.UpdatedOnColumnName;
else if (property.Name.Equals("VersionNo"))
column.Name = Config.VersionNoColumnName;
else if (property.Name.Equals("IsActive"))
column.Name = Config.IsActiveColumnName;
if (!column.IsColumnDbTypeDefined)
{
if (column.Name.Equals(Config.CreatedByColumnName, StringComparison.OrdinalIgnoreCase) ||
column.Name.Equals(Config.UpdatedByColumnName, StringComparison.OrdinalIgnoreCase))
column.ColumnDbType = Config.CreatedUpdatedByColumnType;
else if (property.PropertyType.IsEnum)
column.ColumnDbType = TypeCache.TypeToDbType[property.PropertyType.GetEnumUnderlyingType()];
else if (property.PropertyType.IsValueType)
column.ColumnDbType = TypeCache.TypeToDbType[property.PropertyType];
else
{
TypeCache.TypeToDbType.TryGetValue(property.PropertyType, out DbType columnDbType);
column.ColumnDbType = columnDbType;
}
}
column.SetPropertyInfo(property, enreplacedy);
column.IgnoreInfo = ignoreInfo ?? new IgnoreColumnAttribute(false);
//Primary Key details
if (primaryKey != null)
{
column.PrimaryKeyInfo = primaryKey;
var virtualForeignKeys = (IEnumerable<ForeignKey>)property.GetCustomAttributes(typeof(ForeignKey));
if (virtualForeignKeys != null && virtualForeignKeys.Count() > 0)
{
if (result.VirtualForeignKeys == null) result.VirtualForeignKeys = new List<ForeignKey>();
result.VirtualForeignKeys.AddRange(virtualForeignKeys);
}
}
if (result.NoCreatedBy && (column.Name.Equals(Config.CreatedByColumnName, StringComparison.OrdinalIgnoreCase)
|| column.Name.Equals(Config.CreatedByNameColumnName, StringComparison.OrdinalIgnoreCase)))
continue;
else if (result.NoCreatedOn && column.Name.Equals(Config.CreatedOnColumnName, StringComparison.OrdinalIgnoreCase))
continue;
else if (result.NoUpdatedBy && ((column.Name.Equals(Config.UpdatedByColumnName, StringComparison.OrdinalIgnoreCase)
|| column.Name.Equals(Config.UpdatedByNameColumnName, StringComparison.OrdinalIgnoreCase))))
continue;
else if (result.NoUpdatedOn && column.Name.Equals(Config.UpdatedOnColumnName, StringComparison.OrdinalIgnoreCase))
continue;
else if (result.NoIsActive && column.Name.Equals(Config.IsActiveColumnName, StringComparison.OrdinalIgnoreCase))
continue;
else if (result.NoVersionNo && column.Name.Equals(Config.VersionNoColumnName, StringComparison.OrdinalIgnoreCase))
continue;
else
{
if (!column.IgnoreInfo.Insert)
result.DefaultInsertColumns.Add(column.Name);
//isactive,createdon,createdby column shall not be included in default update columns
if (!column.IgnoreInfo.Update
&& !column.Name.Equals(Config.IsActiveColumnName, StringComparison.OrdinalIgnoreCase)
&& !column.Name.Equals(Config.CreatedByColumnName, StringComparison.OrdinalIgnoreCase)
&& !column.Name.Equals(Config.CreatedOnColumnName, StringComparison.OrdinalIgnoreCase))
result.DefaultUpdateColumns.Add(column.Name);
if (!column.IgnoreInfo.Read)
result.DefaultReadColumns.Add(column.Name);
result.Columns[column.Name] = column;
}
}
if(result.Columns.LongCount(p=>p.Value.IsPrimaryKey && p.Value.PrimaryKeyInfo.IsIdenreplacedy) > 1)
{
throw new NotSupportedException("Primary key with multiple Idenreplacedy is not supported on " + result.Name);
}
if (result.Columns.LongCount(p => p.Value.IsPrimaryKey) > 1 && result.NeedsHistory)
{
throw new NotSupportedException($"History for {result.Name} is not supported as it has composite Primary key");
}
return result;
}
19
Source : ReflectionExtensions.cs
with MIT License
from ababik
with MIT License
from ababik
public static PropertyInfo[] GetInstanceProperties(Type type)
{
return type
.GetTypeInfo()
.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty)
.ToArray();
}
19
Source : RoslynDTOWrapperBase.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
protected static void InitializeSharedStaticData(object roslynDTO)
{
roslynDTO.ThrowOnNull(nameof(roslynDTO));
if (Interlocked.CompareExchange(ref _areStaticMembersInitialized, value: INITIALIZED, comparand: NOT_INITIALIZED) == NOT_INITIALIZED)
{
RoslynDTOType = roslynDTO.GetType();
var bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;
DtoFields = RoslynDTOType.GetFields(bindingFlags).ToDictionary(field => field.Name);
DtoProperties = RoslynDTOType.GetProperties(bindingFlags).ToDictionary(property => property.Name);
}
}
19
Source : Helpers.cs
with MIT License
from ad313
with MIT License
from ad313
private static Func<object, Dictionary<string, object>> CreateDictionaryGenerator(Type type)
{
var dm = new DynamicMethod($"Dictionary{Guid.NewGuid()}", typeof(Dictionary<string, object>), new[] { typeof(object) }, type, true);
ILGenerator il = dm.GetILGenerator();
il.DeclareLocal(typeof(Dictionary<string, object>));
il.Emit(OpCodes.Nop);
il.Emit(OpCodes.Newobj, typeof(Dictionary<string, object>).GetConstructor(Type.EmptyTypes));
il.Emit(OpCodes.Stloc_0);
foreach (var item in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
string columnName = item.Name;
il.Emit(OpCodes.Nop);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldstr, columnName);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, item.GetGetMethod());
if (item.PropertyType.IsValueType)
{
il.Emit(OpCodes.Box, item.PropertyType);
}
il.Emit(OpCodes.Callvirt, typeof(Dictionary<string, object>).GetMethod("Add"));
}
il.Emit(OpCodes.Nop);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ret);
return (Func<object, Dictionary<string, object>>)dm.CreateDelegate(typeof(Func<object, Dictionary<string, object>>));
}
19
Source : OrganizationServiceContextInfo.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private IDictionary<string, EnreplacedySetInfo> LoadEnreplacedySets(Func<PropertyInfo, EnreplacedyInfo, string> keySelector)
{
var dataContextPublicProperties = ContextType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);
var enreplacedySetTypes =
from property in dataContextPublicProperties
let propertyType = property.PropertyType
where propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(IQueryable<>)
let enreplacedyType = propertyType.GetGenericArguments().First()
select new EnreplacedySetInfo(property, new EnreplacedyInfo(enreplacedyType));
var enreplacedySets = new Dictionary<string, EnreplacedySetInfo>();
foreach (var type in enreplacedySetTypes)
{
var key = keySelector(type.Property, type.Enreplacedy);
if (!string.IsNullOrEmpty(key))
{
enreplacedySets.Add(key, type);
}
}
return enreplacedySets;
}
19
Source : TypeExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static IEnumerable<PropertyInfo> GetEnreplacedySetProperties(this Type crmDataContextType)
{
crmDataContextType.ThrowOnNull("crmDataContextType");
var dataContextPublicProperties = crmDataContextType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);
return dataContextPublicProperties.Where(property =>
{
var propertyType = property.PropertyType;
if (!propertyType.IsGenericType)
{
return false;
}
var genericDefinition = propertyType.GetGenericTypeDefinition();
return genericDefinition == typeof(IQueryable<>);
});
}
19
Source : GenericExtensions.cs
with MIT License
from adrenak
with MIT License
from adrenak
public static T GetCopyOf<T>(this Component comp, T other) where T : Component {
Type type = comp.GetType();
if (type != other.GetType()) return null; // type mis-match
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly;
PropertyInfo[] pinfos = type.GetProperties(flags);
foreach (var pinfo in pinfos) {
if (pinfo.CanWrite) {
try {
pinfo.SetValue(comp, pinfo.GetValue(other, null), null);
}
catch { } // In case of NotImplementedException being thrown. For some reason specifying that exception didn't seem to catch it, so I didn't catch anything specific.
}
}
FieldInfo[] finfos = type.GetFields(flags);
foreach (var finfo in finfos)
finfo.SetValue(comp, finfo.GetValue(other));
return comp as T;
}
19
Source : StructuredState.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private void DetectPropertyInfos()
{
_propertyInfos = this.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(x => x.PropertyType.IsSubclreplacedOf(typeof(StateBase)))
.ToDictionary(x => x.Name, x => x);
/*_states = this.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(x => x.PropertyType.IsSubclreplacedOf(typeof(StateBase)))
.ToDictionary(x => x.Name, x =>
{
var method = x.GetGetMethod();
var func = (Func<StateBase>) Delegate.CreateDelegate(typeof(Func<StateBase>),
this,
x.GetGetMethod());
return func();
});*/
}
19
Source : ContractReferenceState.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private void DetectPropertyInfos()
{
_methodReferenceProperties = this.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(x => x.PropertyType.IsMethodReference())
.ToDictionary(x => x.Name, x => x);
}
19
Source : ZeroDiscover.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
private void ReadEnreplacedy(TypeDoreplacedent typeDoreplacedent, Type type)
{
if (type == null || type.IsAutoClreplaced || !IsLetter(type.Name[0]) ||
type.IsInterface || type.IsMarshalByRef || type.IsCOMObject ||
type == typeof(object) || type == typeof(void) ||
type == typeof(ValueType) || type == typeof(Type) || type == typeof(Enum) ||
type.Namespace == "System" || type.Namespace?.Contains("System.") == true)
return;
if (typeDocs.TryGetValue(type, out var doc))
{
foreach (var field in doc.Fields)
{
if (typeDoreplacedent.Fields.ContainsKey(field.Key))
typeDoreplacedent.Fields[field.Key] = field.Value;
else
typeDoreplacedent.Fields.Add(field.Key, field.Value);
}
return;
}
if (typeDocs2.TryGetValue(type, out var _))
{
ZeroTrace.WriteError("ReadEnreplacedy", "over flow", type.Name);
return;
}
typeDocs2.Add(type, typeDoreplacedent);
if (type.IsArray)
{
ReadEnreplacedy(typeDoreplacedent, type.replacedembly.GetType(type.FullName.Split('[')[0]));
return;
}
if (type.IsGenericType && !type.IsValueType &&
type.GetGenericTypeDefinition().GetInterface(typeof(IEnumerable<>).FullName) != null)
{
ReadEnreplacedy(typeDoreplacedent, type.GetGenericArguments().Last());
return;
}
XmlMember.Find(type);
if (type.IsEnum)
{
foreach (var field in type.GetFields(BindingFlags.Static | BindingFlags.Public))
{
if (field.IsSpecialName)
{
continue;
}
var info = CheckMember(typeDoreplacedent, type, field, field.FieldType, false, false, false);
if (info != null)
{
info.TypeName = "int";
info.Example = ((int)field.GetValue(null)).ToString();
info.JsonName = null;
}
}
typeDocs.Add(type, new TypeDoreplacedent
{
fields = typeDoreplacedent.fields?.ToDictionary(p => p.Key, p => p.Value)
});
typeDoreplacedent.Copy(XmlMember.Find(type));
return;
}
var dc = type.GetAttribute<DataContractAttribute>();
var jo = type.GetAttribute<JsonObjectAttribute>();
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
if (property.IsSpecialName)
{
continue;
}
CheckMember(typeDoreplacedent, type, property, property.PropertyType, jo != null, dc != null);
}
foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
if (!char.IsLetter(field.Name[0]) || field.IsSpecialName)
{
continue;
}
CheckMember(typeDoreplacedent, type, field, field.FieldType, jo != null, dc != null);
}
typeDocs.Add(type, new TypeDoreplacedent
{
fields = typeDoreplacedent.fields?.ToDictionary(p => p.Key, p => p.Value)
});
typeDoreplacedent.Copy(XmlMember.Find(type));
}
19
Source : DbRepositorySimplified.cs
with Apache License 2.0
from agoda-com
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 : AdminStore.cs
with Apache License 2.0
from Aguafrommars
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));
}
}
19
Source : Enumerations.cs
with MIT License
from ahmed-abdelrazek
with MIT License
from ahmed-abdelrazek
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
19
Source : Serialization.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static object FromDictionary(Dictionary<string, object> dic, ref object obj)
{
System.Diagnostics.Debug.replacedert(obj != null);
FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public);
foreach (var f in fields)
{
if (dic.ContainsKey(f.Name))
{
var val = DataConverter.ChangeType(dic[f.Name], f.FieldType);
f.SetValue(obj, val);
}
}
PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var p in props)
{
if (dic.ContainsKey(p.Name))
{
var val = DataConverter.ChangeType(dic[p.Name], p.PropertyType);
p.SetValue(obj, val, null);
}
}
return obj;
}
19
Source : ConfigurationBase.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public void SetConfigurations(IDictionary<string, object> dic)
{
try
{
lock (_root)
{
FieldInfo[] fields = this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public);
foreach (var f in fields)
{
if (dic.ContainsKey(f.Name))
{
var val = DataConverter.ChangeType(dic[f.Name], f.FieldType);
f.SetValue(this, val);
}
}
PropertyInfo[] props = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var p in props)
{
if (dic.ContainsKey(p.Name))
{
var val = DataConverter.ChangeType(dic[p.Name], p.PropertyType);
p.SetValue(this, val, null);
}
}
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
}
19
Source : ReflectionUtilities.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public static IReadOnlyDictionary<string, object> ToDictionary<T>(this T obj)
{
if (obj == null)
throw new NullReferenceException();
return new CharSpanLookupReadOnlyDictionary<object>(typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(x => new KeyValuePair<string, object>(x.Name, x.GetValue(obj))));
}
19
Source : Serialization.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static string ToXml(object obj, string rootElement = null)
{
System.Xml.XmlDoreplacedent doc = new System.Xml.XmlDoreplacedent();
doc.LoadXml(string.Format(@"<{0}></{0}>", obj.GetType().Name));
PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var p in props)
{
var node = doc.CreateElement(p.Name);
node.InnerText = Convert.ToString(p.GetValue(obj, null));
doc.DoreplacedentElement.AppendChild(node);
}
return doc.OuterXml;
}
19
Source : Serialization.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static Dictionary<string, object> ToDictionary(object obj)
{
System.Diagnostics.Debug.replacedert(obj != null);
Dictionary<string, object> dic = new Dictionary<string, object>();
FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (FieldInfo f in fields)
dic.Add(f.Name, f.GetValue(obj));
PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (PropertyInfo p in props)
dic.Add(p.Name, p.GetValue(obj, null));
return dic;
}
19
Source : DataConverter.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static T Convert<T>(DataRow row)
where T : new()
{
T result = new T();
var fields = typeof(T).GetFields(BindingFlags.Instance | BindingFlags.Public);
foreach (var f in fields)
{
var col = row.Table.Columns[f.Name];
if (col != null)
f.SetValue(result, ChangeType(row[col], f.FieldType));
}
var props = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var p in props)
{
var col = row.Table.Columns[p.Name];
if (col != null)
p.SetValue(result, ChangeType(row[col], p.PropertyType), null);
}
return result;
}
19
Source : Serialization.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static T FromXml<T>(string xml)
where T : new()
{
T result = new T();
System.Xml.XmlDoreplacedent doc = new System.Xml.XmlDoreplacedent();
doc.LoadXml(xml);
if (doc.HasChildNodes)
{
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var p in props)
{
var node = doc.DoreplacedentElement[p.Name];
if (node != null)
p.SetValue(result, Convert.ChangeType(node.InnerText, p.PropertyType), null);
}
}
return result;
}
19
Source : ConfigurationBase.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public Dictionary<string, object> GetConfigurations()
{
lock (_root)
{
Dictionary<string, object> dic = new Dictionary<string, object>();
FieldInfo[] fields = this.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (FieldInfo f in fields)
dic.Add(f.Name, f.GetValue(this));
PropertyInfo[] props = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (PropertyInfo p in props)
dic.Add(p.Name, p.GetValue(this, null));
return dic;
}
}
19
Source : ConfigurationBase.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public Dictionary<string, object> GetConfigurations()
{
BindingFlags flag = BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic;
lock (_root)
{
Dictionary<string, object> dic = new Dictionary<string, object>();
FieldInfo[] fields = this.GetType().GetFields(flag);
foreach (FieldInfo f in fields)
{
if (!f.IsPrivate)
dic.Add(f.Name, f.GetValue(this));
}
PropertyInfo[] props = this.GetType().GetProperties(flag);
foreach (PropertyInfo p in props)
dic.Add(p.Name, p.GetValue(this, null));
return dic;
}
}
19
Source : ConfigurationBase.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public void SetConfigurations(IDictionary<string, object> dic)
{
try
{
BindingFlags flag = BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.SetField | BindingFlags.SetProperty;
lock (_root)
{
FieldInfo[] fields = this.GetType().GetFields(flag);
foreach (var f in fields)
{
if (f.IsPrivate || f.IsInitOnly)
continue;
if (dic.ContainsKey(f.Name))
{
var val = DataConverter.ChangeType(dic[f.Name], f.FieldType);
f.SetValue(this, val);
}
}
PropertyInfo[] props = this.GetType().GetProperties(flag);
foreach (var p in props)
{
if (dic.ContainsKey(p.Name))
{
var val = DataConverter.ChangeType(dic[p.Name], p.PropertyType);
p.SetValue(this, val, null);
}
}
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
}
19
Source : DataConverter.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static T Convert<T>(DataRow row, ref T obj)
{
try
{
var fields = typeof(T).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetField);
foreach (var f in fields)
{
var col = row.Table.Columns[f.Name];
if (col != null)
f.SetValue(obj, ChangeType(row[col], f.FieldType));
}
var props = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty);
foreach (var p in props)
{
var col = row.Table.Columns[p.Name];
if (col != null)
p.SetValue(obj, ChangeType(row[col], p.PropertyType), null);
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
return obj;
}
19
Source : DataConverter.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static T Convert<T>(System.Data.Common.DbDataReader reader, ref T obj)
{
try
{
var fields = typeof(T).GetFields(BindingFlags.Instance | BindingFlags.Public);
foreach (var f in fields)
{
var col = reader.GetOrdinal(f.Name);
if (col >= 0)
f.SetValue(obj, ChangeType(reader.GetValue(col), f.FieldType));
}
var props = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var p in props)
{
var col = reader.GetOrdinal(p.Name);
if (col >= 0)
p.SetValue(obj, ChangeType(reader.GetValue(col), p.PropertyType), null);
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
return obj;
}
19
Source : DataConverter.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static object StructFromValues(object obj, GetValueCallback getValue, bool hasField, bool hasInternal)
{
Debug.replacedert(obj != null);
try
{
// properties
{
var flags = BindingFlags.Instance | BindingFlags.Public | (hasInternal ? BindingFlags.NonPublic : 0);
var props = obj.GetType().GetProperties(flags);
foreach (var p in props)
{
if (hasInternal)
{
var m = p.GetSetMethod(true);
if (m.IsPrivate || m.IsFamily)
continue;
}
if (p.CanWrite)
{
var v = getValue(p.Name);
if (v != null)
p.SetValue(obj, ChangeType(v, p.PropertyType), null);
}
}
}
// fields
if (hasField)
{
var flags = BindingFlags.Instance | BindingFlags.Public | (hasInternal ? BindingFlags.NonPublic : 0);
var flds = obj.GetType().GetFields(flags);
foreach (var f in flds)
{
if (f.IsPrivate || f.IsFamily || f.IsInitOnly)
continue;
var v = getValue(f.Name);
if (v != null)
f.SetValue(obj, ChangeType(v, f.FieldType));
}
}
}
catch (Exception ex) { TraceLog.WriteException(ex); throw; }
return obj;
}
19
Source : DataConverter.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static void StructToValues(object obj, SetValueCallback setValue, bool hasField, bool hasInternal)
{
Debug.replacedert(obj != null);
try
{
// properties
{
var flags = BindingFlags.Instance | BindingFlags.Public | (hasInternal ? BindingFlags.NonPublic : 0);
var props = obj.GetType().GetProperties(flags);
foreach (var p in props)
{
if (hasInternal)
{
var m = p.GetSetMethod(true);
if (m.IsPrivate || m.IsFamily)
continue;
}
if (p.CanRead)
{
setValue(p.Name, p.GetValue(obj, null));
}
}
}
// fields
if (hasField)
{
var flags = BindingFlags.Instance | BindingFlags.Public | (hasInternal ? BindingFlags.NonPublic : 0);
var flds = obj.GetType().GetFields(flags);
foreach (var f in flds)
{
if (f.IsPrivate || f.IsFamily || f.IsInitOnly)
continue;
setValue(f.Name, f.GetValue(obj));
}
}
}
catch (Exception ex) { TraceLog.WriteException(ex); throw; }
}
19
Source : DataConverter.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static void StructToValues(object obj, SetValueCallback setValue, bool hasField, bool hasInternal)
{
Debug.replacedert(obj != null);
try
{
// properties
{
var flags = BindingFlags.Instance | BindingFlags.Public | (hasInternal ? BindingFlags.NonPublic : 0);
var props = obj.GetType().GetProperties(flags);
foreach (var p in props)
{
if (hasInternal)
{
var m = p.GetSetMethod(true);
if (m == null)
continue;
if (m.IsPrivate || m.IsFamily)
continue;
}
if (p.CanRead)
{
setValue(p.Name, p.GetValue(obj, null));
}
}
}
// fields
if (hasField)
{
var flags = BindingFlags.Instance | BindingFlags.Public | (hasInternal ? BindingFlags.NonPublic : 0);
var flds = obj.GetType().GetFields(flags);
foreach (var f in flds)
{
if (f.IsPrivate || f.IsFamily || f.IsInitOnly)
continue;
setValue(f.Name, f.GetValue(obj));
}
}
}
catch (Exception ex) { TraceLog.WriteException(ex); throw; }
}
19
Source : DefaultContractResolver.cs
with MIT License
from akaskela
with MIT License
from akaskela
private MemberInfo GetExtensionDataMemberForType(Type type)
{
IEnumerable<MemberInfo> members = GetClreplacedHierarchyForType(type).SelectMany(baseType =>
{
IList<MemberInfo> m = new List<MemberInfo>();
m.AddRange(baseType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
m.AddRange(baseType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
return m;
});
MemberInfo extensionDataMember = members.LastOrDefault(m =>
{
MemberTypes memberType = m.MemberType();
if (memberType != MemberTypes.Property && memberType != MemberTypes.Field)
{
return false;
}
// last instance of attribute wins on type if there are multiple
if (!m.IsDefined(typeof(JsonExtensionDataAttribute), false))
{
return false;
}
if (!ReflectionUtils.CanReadMemberValue(m, true))
{
throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' must have a getter.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name));
}
Type t = ReflectionUtils.GetMemberUnderlyingType(m);
Type dictionaryType;
if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out dictionaryType))
{
Type keyType = dictionaryType.GetGenericArguments()[0];
Type valueType = dictionaryType.GetGenericArguments()[1];
if (keyType.IsreplacedignableFrom(typeof(string)) && valueType.IsreplacedignableFrom(typeof(JToken)))
{
return true;
}
}
throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' type must implement IDictionary<string, JToken>.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name));
});
return extensionDataMember;
}
19
Source : ReflectionUtils.cs
with MIT License
from akaskela
with MIT License
from akaskela
public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr)
{
ValidationUtils.ArgumentNotNull(targetType, nameof(targetType));
List<PropertyInfo> propertyInfos = new List<PropertyInfo>(targetType.GetProperties(bindingAttr));
// GetProperties on an interface doesn't return properties from its interfaces
if (targetType.IsInterface())
{
foreach (Type i in targetType.GetInterfaces())
{
propertyInfos.AddRange(i.GetProperties(bindingAttr));
}
}
GetChildPrivateProperties(propertyInfos, targetType, bindingAttr);
// a base clreplaced private getter/setter will be inaccessable unless the property was gotten from the base clreplaced
for (int i = 0; i < propertyInfos.Count; i++)
{
PropertyInfo member = propertyInfos[i];
if (member.DeclaringType != targetType)
{
PropertyInfo declaredMember = (PropertyInfo)GetMemberInfoFromType(member.DeclaringType, member);
propertyInfos[i] = declaredMember;
}
}
return propertyInfos;
}
19
Source : ReflectionUtils.cs
with MIT License
from akaskela
with MIT License
from akaskela
private static void GetChildPrivateProperties(IList<PropertyInfo> initialProperties, Type targetType, BindingFlags bindingAttr)
{
// fix weirdness with private PropertyInfos only being returned for the current Type
// find base type properties and add them to result
// also find base properties that have been hidden by subtype properties with the same name
while ((targetType = targetType.BaseType()) != null)
{
foreach (PropertyInfo propertyInfo in targetType.GetProperties(bindingAttr))
{
PropertyInfo subTypeProperty = propertyInfo;
if (!IsPublic(subTypeProperty))
{
// have to test on name rather than reference because instances are different
// depending on the type that GetProperties was called on
int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name);
if (index == -1)
{
initialProperties.Add(subTypeProperty);
}
else
{
PropertyInfo childProperty = initialProperties[index];
// don't replace public child with private base
if (!IsPublic(childProperty))
{
// replace nonpublic properties for a child, but gotten from
// the parent with the one from the child
// the property gotten from the child will have access to private getter/setter
initialProperties[index] = subTypeProperty;
}
}
}
else
{
if (!subTypeProperty.IsVirtual())
{
int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name
&& p.DeclaringType == subTypeProperty.DeclaringType);
if (index == -1)
{
initialProperties.Add(subTypeProperty);
}
}
else
{
int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name
&& p.IsVirtual()
&& p.GetBaseDefinition() != null
&& p.GetBaseDefinition().DeclaringType.IsreplacedignableFrom(subTypeProperty.GetBaseDefinition().DeclaringType));
if (index == -1)
{
initialProperties.Add(subTypeProperty);
}
}
}
}
}
}
19
Source : OffsetManager.cs
with GNU Affero General Public License v3.0
from akira0245
with GNU Affero General Public License v3.0
from akira0245
public static void Setup(SigScanner scanner)
{
var props = typeof(Offsets).GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
.Select(i => (prop: i, Attribute: i.GetCustomAttribute<SigAttribute>())).Where(i => i.Attribute != null);
List<Exception> exceptions = new List<Exception>(100);
foreach ((PropertyInfo propertyInfo, SigAttribute sigAttribute) in props)
{
try
{
var sig = sigAttribute.SigString;
sig = string.Join(' ', sig.Split(new[] { ' ' }, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
.Select(i => i == "?" ? "??" : i));
IntPtr address;
switch (sigAttribute)
{
case StaticAddressAttribute:
address = scanner.GetStaticAddressFromSig(sig);
break;
case FunctionAttribute:
address = scanner.ScanText(sig);
break;
case OffsetAttribute:
{
address = scanner.ScanText(sig);
address += sigAttribute.Offset;
var structure = Marshal.PtrToStructure(address, propertyInfo.PropertyType);
propertyInfo.SetValue(null, structure);
PluginLog.Information($"[{nameof(OffsetManager)}][{propertyInfo.Name}] {propertyInfo.PropertyType.FullName} {structure}");
continue;
}
default:
throw new ArgumentOutOfRangeException();
}
address += sigAttribute.Offset;
propertyInfo.SetValue(null, address);
PluginLog.Information($"[{nameof(OffsetManager)}][{propertyInfo.Name}] {address.ToInt64():X}");
}
catch (Exception e)
{
PluginLog.Error(e, $"[{nameof(OffsetManager)}][{propertyInfo?.Name}] failed to find sig : {sigAttribute?.SigString}");
exceptions.Add(e);
}
}
if (exceptions.Any())
{
throw new AggregateException(exceptions);
}
}
19
Source : ObservableCollectionExtensions.cs
with Apache License 2.0
from AKruimink
with Apache License 2.0
from AKruimink
public static void UpdateCollection<T>(this ObservableCollection<T> collection, IList<T> newCollection)
{
if (newCollection == null || newCollection.Count == 0)
{
collection.Clear();
return;
}
var i = 0;
foreach (var item in newCollection)
{
if (collection.Count > i)
{
var itemIndex = collection.IndexOf(collection.Where(i => Comparer<T>.Default.Compare(i, item) == 0).FirstOrDefault());
if (itemIndex < 0)
{
// Item doesn't exist
collection.Insert(i, item);
}
else if (itemIndex > i || itemIndex < i)
{
// Item exists, but has moved up or down
collection.Move(itemIndex, i);
}
else
{
if ((!collection[i]?.Equals(item)) ?? false)
{
// Item has changed, replace it
if (item != null)
{
foreach (var sourceProperty in item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var targetProperty = collection[i]?.GetType().GetProperty(sourceProperty.Name);
if (targetProperty != null && targetProperty.CanWrite)
{
targetProperty.SetValue(collection[i], sourceProperty.GetValue(item, null), null);
}
}
}
}
}
}
else
{
// Item doesn't exist
collection.Add(item);
}
i++;
}
// Remove all old items
while (collection.Count > newCollection.Count)
{
collection.RemoveAt(i);
}
}
19
Source : TypeHelpers.cs
with MIT License
from AlexGhiondea
with MIT License
from AlexGhiondea
public static void ScanTypeForProperties<TOptions>(out TypeArgumentInfo tInfo)
{
tInfo = new TypeArgumentInfo();
PropertyInfo[] propertiesOnType = typeof(TOptions).GetTypeInfo().GetProperties(BindingFlags.Instance | BindingFlags.Public);
// first of all, find the commandArgument, if any.
tInfo.ActionArgument = FindCommandProperty(propertiesOnType);
// we want to be able to support empty groups.
if (tInfo.ActionArgument != null && IsEnum(tInfo.ActionArgument.PropertyType))
{
// get the values of the enum.
var enumValues = Enum.GetValues(tInfo.ActionArgument.PropertyType);
// Sort the enum by the enum values
Array.Sort(enumValues);
// add them to the dictionary now to make sure we preserve the order
foreach (var val in enumValues)
{
if (!tInfo.ArgumentGroups.ContainsKey(val.ToString()))
{
tInfo.ArgumentGroups.Add(val.ToString(), new ArgumentGroupInfo());
}
}
}
// parse the rest of the properties
foreach (PropertyInfo property in propertiesOnType)
{
// get the group containing this property (note: more than one group can have the same property)
// this allows common required parameters
List<ArgumentGroupInfo> groupsWhereThePropertyIsParticipating = GetGroupsForProperty(tInfo, property);
List<ActualArgumentAttribute> actualAttribs = property.GetCustomAttributes<ActualArgumentAttribute>().ToList();
if (actualAttribs.Count > 1)
{
throw new ArgumentException($"Only one of Required/Optional attribute are allowed per property ({property.Name}). Help information might be incorrect!");
}
// if we have no attributes on that property, move on
ActualArgumentAttribute baseAttrib = actualAttribs.FirstOrDefault();
if (baseAttrib == null)
{
continue;
}
// add the property to the groups it is a part of
if (baseAttrib is RequiredArgumentAttribute)
{
foreach (ArgumentGroupInfo grpPropInfo in groupsWhereThePropertyIsParticipating)
{
// do we have an override for this property? If we do, use that, otherwise use the regular one.
if (!grpPropInfo.OverridePositions.TryGetValue(property, out int requiredPositionIndex))
{
requiredPositionIndex = (int)baseAttrib.GetArgumentId();
}
if (grpPropInfo.RequiredArguments.ContainsKey(requiredPositionIndex))
{
throw new ArgumentException("Two required arguments share the same position!!");
}
// if we have a collection argument, keep track of it
if (baseAttrib.IsCollection)
{
// if we already have defined a required collection argument, throw an error
if (grpPropInfo.IndexOfCollectionArgument >= 0)
{
throw new ArgumentException("Cannot declare two required collection arguments. Please convert one of them to an optional collection one.");
}
grpPropInfo.IndexOfCollectionArgument = requiredPositionIndex;
}
grpPropInfo.RequiredArguments[requiredPositionIndex] = property;
}
}
else if (baseAttrib is OptionalArgumentAttribute)
{
foreach (ArgumentGroupInfo grpPropInfo in groupsWhereThePropertyIsParticipating)
{
if (grpPropInfo.OptionalArguments.ContainsKey((string)baseAttrib.GetArgumentId()))
{
throw new ArgumentException("Two optional arguments share the same name!!");
}
grpPropInfo.OptionalArguments[(string)baseAttrib.GetArgumentId()] = property;
}
}
}
// remove the empty one, if empty
if (tInfo.ArgumentGroups.TryGetValue(string.Empty, out ArgumentGroupInfo grp))
{
if (grp.OptionalArguments.Count == 0 && grp.RequiredArguments.Count == 0)
tInfo.ArgumentGroups.Remove(string.Empty);
}
// validate that the collection is the last argument
foreach (KeyValuePair<string, ArgumentGroupInfo> group in tInfo.ArgumentGroups)
{
if (group.Value.IndexOfCollectionArgument >= 0 && group.Value.IndexOfCollectionArgument != group.Value.RequiredArguments.Count - 1)
{
if (!string.IsNullOrEmpty(group.Key))
{
throw new ArgumentException($"The required collection argument for group `{group.Key}` needs to be on the last position of the required arguments.");
}
else
{
throw new ArgumentException("The required collection argument needs to be on the last position of the required arguments.");
}
}
}
}
19
Source : PayloadExtensions.cs
with Apache License 2.0
from alexz76
with Apache License 2.0
from alexz76
internal static object ToFinalPayload(this object originalModel, IList<object> links)
{
if (originalModel == null)
{
throw new InvalidOperationException("It must be a non-nullable instance.");
}
if (!links.Any())
{
return originalModel;
}
var originalType = originalModel.GetType();
replacedemblyBuilder replacedemblyBuilder = replacedemblyBuilder.DefineDynamicreplacedembly(new replacedemblyName("Sciensoft.Hateoas.Links"), replacedemblyBuilderAccess.RunAndCollect);
ModuleBuilder moduleBuilder = replacedemblyBuilder.DefineDynamicModule("DynamicLinkModule");
TypeBuilder typeBuilder = moduleBuilder.DefineType("LinkModel", TypeAttributes.Public | TypeAttributes.Clreplaced | TypeAttributes.AutoClreplaced, null); // itemType
var originalValues = new Dictionary<string, object>();
foreach (var property in originalType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy))
{
CreateProperty(typeBuilder, property.Name, property.PropertyType);
originalValues.TryAdd(property.Name, property.GetValue(originalModel));
}
CreateProperty(typeBuilder, "Links", links.GetType());
var payloadType = typeBuilder.CreateType();
var payloadInstance = Activator.CreateInstance(payloadType);
foreach (var pv in originalValues)
{
payloadType.GetProperty(pv.Key).SetValue(payloadInstance, pv.Value);
}
payloadType.GetProperty("Links").SetValue(payloadInstance, links);
return payloadInstance;
}
19
Source : InvokeWrapper.cs
with Apache License 2.0
from Algoryx
with Apache License 2.0
from Algoryx
public static PropertyWrapper[] FindProperties( Type type, BindingFlags bindingFlags = DefaultBindingFlags )
{
if ( bindingFlags == DefaultBindingFlags && s_defaultBindingsCache.TryGetValue( type, out var cachedProperties ) )
return cachedProperties;
var properties = ( from propertyInfo
in type.GetProperties( bindingFlags )
select new PropertyWrapper( propertyInfo ) ).OrderByDescending( wrapper => wrapper.Priority ).ToArray();
if ( bindingFlags == DefaultBindingFlags )
s_defaultBindingsCache.Add( type, properties );
return properties;
}
See More Examples