System.Type.GetProperty(string, System.Reflection.BindingFlags)

Here are the examples of the csharp api System.Type.GetProperty(string, System.Reflection.BindingFlags) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1133 Examples 7

19 View Source File : DynamicProxy.cs
License : MIT License
Project Creator : 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([email protected]"{(proxyMethodName == "Before" ? [email protected]"
        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" ? 
        [email protected]"if (__DP_ARG___is_return == false)
        {{
            __DP_ARG___is_return = __DP_ARG___{proxyMethodName}{a}.Returned;{(returnType != typeof(void) ? [email protected]"
            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([email protected]"
        {(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 [email protected]"
            if (!object.ReferenceEquals({methodParameterName}, __DP_ARG___parameters[""{methodParameterName}""])) {methodParameterName} = {(methodParameterType.IsValueType ? [email protected]"({methodParameterType.DisplayCsharp()})__DP_ARG___parameters[""{methodParameterName}""]" : [email protected]"__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 ? [email protected]"

        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([email protected]"

    {(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([email protected]"

    {propModification}{(getMethod?.IsStatic == true ? "static " : "")}{(getMethod?.IsVirtual == true ? "override " : "")}{returnTypeCSharpName} {prop2.Name}
    {{");

                if (getMethod != null)
                {
                    if (getMethodAttributeAny == false) sb.Append([email protected]"
        {propGetModification} get
        {{
            return base.{prop2.Name}
        }}");
                    else sb.Append([email protected]"
        {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([email protected]"
        {propSetModification} set
        {{
            base.{prop2.Name} = value;
        }}");
                    else sb.Append([email protected]"
        {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([email protected]"
    }}");
            }
            #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 => [email protected]"
    private {serviceType.Key.DisplayCsharp()} {serviceType.Value};")));
                foreach (var ctor in ctors)
                {
                    var ctorParams = ctor.GetParameters();
                    sb.Append([email protected]"

    {(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 => [email protected]"{serviceType.Key.DisplayCsharp()} parameter{serviceType.Value}"))})
        : base({(string.Join(", ", ctorParams.Select(a => a.Name)))})
    {{{string.Join("", fromServicesTypes.Select(serviceType => [email protected]"
        {serviceType.Value} = parameter{serviceType.Value};"))}
    }}");
                }
                for (var a = 0; a < matchedAttributesFromServices.Count; a++)
                {
                    sb.Append([email protected]"

    private void __DP_ARG___attribute{a}_FromServicesCopyTo({_idynamicProxyName} attr)
    {{{string.Join("", matchedAttributesFromServices[a].Select(fs => [email protected]"
        __DP_Meta.{nameof(DynamicProxyMeta.SetDynamicProxyAttributePropertyValue)}({a}, attr, ""{fs.Name}"", {fromServicesTypes[fs.FieldType]});"))}
    }}");
                }
                #endregion

                proxyCscode = [email protected]"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 View Source File : Helpers.cs
License : MIT License
Project Creator : 404Lcc

internal static PropertyInfo GetProperty(Type type, string name, bool nonPublic)
        {
            return type.GetProperty(name,
                nonPublic ? BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
                          : BindingFlags.Instance | BindingFlags.Public);
        }

19 View Source File : CometaryExtensions.cs
License : MIT License
Project Creator : 71

public static PropertyInfo GetCorrespondingProperty(this IPropertySymbol symbol)
        {
            return symbol.ContainingType.GetCorrespondingType().GetProperty(symbol.Name, symbol.GetCorrespondingBindingFlags());
        }

19 View Source File : Proxy.cs
License : MIT License
Project Creator : 71

public bool TrySet(string name, object value)
        {
            // Compute key, and try to find an already computed delegate
            int key = Combine(ObjectTypeHash, name.GetHashCode());

            if (data.Setters.TryGetValue(key, out var del))
            {
                del(Object, value);
                return true;
            }

            // Nothing already computed, compute it now
            PropertyInfo prop = ObjectType.GetProperty(name, ALL);

            if (prop == null)
                return false;

            data.Setters[key] = Helpers.MakeDelegate<Func<object, object, object>>(name, il =>
            {
                if ((prop.GetMethod ?? prop.SetMethod).IsStatic)
                {
                    il.Emit(OpCodes.Ldarg_0);
                }
                else
                {
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldarg_1);
                }

                if (prop.PropertyType.GetTypeInfo().IsValueType)
                    il.Emit(OpCodes.Unbox_Any);
                else if (prop.PropertyType != typeof(object))
                    il.Emit(OpCodes.Castclreplaced, prop.PropertyType);

                il.Emit(OpCodes.Call, prop.SetMethod);

                if (prop.PropertyType.GetTypeInfo().IsValueType)
                    il.Emit(OpCodes.Box, prop.PropertyType);

                il.Emit(OpCodes.Ret);
            });

            return true;
        }

19 View Source File : Proxy.cs
License : MIT License
Project Creator : 71

public bool TryGet(string name, out object result)
        {
            object obj = Object;

            // Compute key, and try to find an already computed delegate
            int key = Combine(ObjectTypeHash, name.GetHashCode());

            if (data.Getters.TryGetValue(key, out var del))
            {
                result = del(obj);
                return true;
            }

            // Nothing already computed, compute it now
            PropertyInfo prop = obj.GetType().GetProperty(name, ALL);

            if (prop == null)
            {
                result = null;
                return false;
            }

            data.Getters[key] = del = Helpers.MakeDelegate<Func<object, object>>(name, il =>
            {
                if (!(prop.GetMethod ?? prop.SetMethod).IsStatic)
                    il.Emit(OpCodes.Ldarg_0);

                il.Emit(OpCodes.Call, prop.GetMethod);

                if (prop.PropertyType.GetTypeInfo().IsValueType)
                    il.Emit(OpCodes.Box, prop.PropertyType);

                il.Emit(OpCodes.Ret);
            });

            result = del(obj);
            return true;
        }

19 View Source File : Ryder.Lightweight.cs
License : MIT License
Project Creator : 71

private static Func<MethodBase, RuntimeMethodHandle> MakeGetMethodHandle()
            {
                // Generate the "GetMethodHandle" delegate.
                DynamicMethod getMethodHandle = new DynamicMethod(
                    nameof(GetMethodHandle),
                    typeof(RuntimeMethodHandle),
                    new[] { typeof(MethodBase) },
                    typeof(RuntimeMethodHandle), true);

                ILGenerator il = getMethodHandle.GetILGenerator(16);

                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Callvirt, typeof(MethodBase).GetProperty("MethodHandle", PUBLIC_INSTANCE).GetMethod);
                il.Emit(OpCodes.Ret);

                return getMethodHandle.CreateDelegate(typeof(Func<MethodBase, RuntimeMethodHandle>))
                    as Func<MethodBase, RuntimeMethodHandle>;
            }

19 View Source File : PropertyTests.cs
License : MIT License
Project Creator : 71

[Fact]
        public void TestStaticProperties()
        {
            PropertyInfo randomProperty = typeof(PropertyTests)
                .GetProperty(nameof(Random), BindingFlags.Static | BindingFlags.Public);
            PropertyInfo nowProperty = typeof(DateTime)
                .GetProperty(nameof(DateTime.Now), BindingFlags.Static | BindingFlags.Public);


            DateTime.Now.ShouldNotBe(Random, tolerance: TimeSpan.FromMilliseconds(100));

            using (Redirection.Redirect(randomProperty, nowProperty))
            {
                DateTime.Now.ShouldBe(Random, tolerance: TimeSpan.FromMilliseconds(100));
            }

            DateTime.Now.ShouldNotBe(Random, tolerance: TimeSpan.FromMilliseconds(100));
        }

19 View Source File : PropertyTests.cs
License : MIT License
Project Creator : 71

[Fact]
        public void TestInstanceProperties()
        {
            PropertyInfo baseValueProperty = typeof(PropertyTests)
                .GetProperty(nameof(Value), BindingFlags.Instance | BindingFlags.Public);
            PropertyInfo overrideValueProperty = typeof(OverridePropertyTests)
                .GetProperty(nameof(Value), BindingFlags.Instance | BindingFlags.Public);


            OverridePropertyTests overriden = new OverridePropertyTests();

            Value.ShouldNotBe(overriden.Value);

            using (Redirection.Redirect(baseValueProperty, overrideValueProperty))
            {
                Value.ShouldBe(overriden.Value);
            }

            Value.ShouldNotBe(overriden.Value);
        }

19 View Source File : ReactiveTests.cs
License : MIT License
Project Creator : 71

[Fact]
        public void TestReactiveMethod()
        {
            MethodInfo method = typeof(DateTime)
                .GetProperty(nameof(DateTime.Now), BindingFlags.Static | BindingFlags.Public)
                .GetGetMethod();

            int count = 0;
            DateTime bday = new DateTime(1955, 10, 28);

            // Note: Observing this test through the debugger will call DateTime.Now,
            //       thus incrementing 'count', and breaking the test. Watch out.
            using (Redirection.Observe(method)
                              .Where(_ => count++ % 2 == 0)
                              .Subscribe(ctx => ctx.ReturnValue = bday))
            {
                DateTime.Now.ShouldBe(bday);
                DateTime.Now.ShouldNotBe(bday);
                DateTime.Now.ShouldBe(bday);
                DateTime.Now.ShouldNotBe(bday);
            }

            DateTime.Now.ShouldNotBe(bday);
            DateTime.Now.ShouldNotBe(bday);

            count.ShouldBe(4);
        }

19 View Source File : ReactiveTests.cs
License : MIT License
Project Creator : 71

[Fact]
        public void TestBuiltInObserver()
        {
            DateTime birthday = new DateTime(1955, 10, 28);
            MethodInfo method = typeof(DateTime)
                .GetProperty(nameof(DateTime.Now), BindingFlags.Static | BindingFlags.Public)
                .GetGetMethod();

            DateTime.Now.ShouldNotBe(birthday);

            using (Redirection.Observe(method, ctx => ctx.ReturnValue = birthday))
            {
                DateTime.Now.ShouldBe(birthday);
            }

            DateTime.Now.ShouldNotBe(birthday);
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 71

private static Func<MethodBase, RuntimeMethodHandle> MakeGetMethodHandle()
        {
            // Generate the "GetMethodHandle" delegate.
            DynamicMethod getMethodHandle = new DynamicMethod(
                nameof(GetMethodHandle),
                typeof(RuntimeMethodHandle),
                new[] { typeof(MethodBase) },
                typeof(RuntimeMethodHandle), true);

            ILGenerator il = getMethodHandle.GetILGenerator(16);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Callvirt, typeof(MethodBase).GetProperty("MethodHandle", PUBLIC_INSTANCE).GetMethod);
            il.Emit(OpCodes.Ret);

            return getMethodHandle.CreateDelegate(typeof(Func<MethodBase, RuntimeMethodHandle>))
                as Func<MethodBase, RuntimeMethodHandle>;
        }

19 View Source File : VelocityEmitterEditor.cs
License : MIT License
Project Creator : aarthificial

private static bool TryGetRendererData(out ForwardRendererData data)
        {
            if (!(GraphicsSettings.currentRenderPipeline is UniversalRenderPipelinereplacedet pipeline))
            {
                data = null;
                return false;
            }

            data = typeof(UniversalRenderPipelinereplacedet).GetProperty(
                    "scriptableRendererData",
                    BindingFlags.Instance | BindingFlags.NonPublic
                )
                ?.GetValue(pipeline) as ForwardRendererData;

            return data != null;
        }

19 View Source File : MixedRealityInspectorUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static Rect GetEditorMainWindowPos()
        {
            var containerWinType = AppDomain.CurrentDomain.GetAllDerivedTypes(typeof(ScriptableObject)).FirstOrDefault(t => t.Name == "ContainerWindow");

            if (containerWinType == null)
            {
                throw new MissingMemberException("Can't find internal type ContainerWindow. Maybe something has changed inside Unity");
            }

            var showModeField = containerWinType.GetField("m_ShowMode", BindingFlags.NonPublic | BindingFlags.Instance);
            var positionProperty = containerWinType.GetProperty("position", BindingFlags.Public | BindingFlags.Instance);

            if (showModeField == null || positionProperty == null)
            {
                throw new MissingFieldException("Can't find internal fields 'm_ShowMode' or 'position'. Maybe something has changed inside Unity");
            }

            var windows = Resources.FindObjectsOfTypeAll(containerWinType);

            foreach (var win in windows)
            {

                var showMode = (int)showModeField.GetValue(win);
                if (showMode == 4) // main window
                {
                    var pos = (Rect)positionProperty.GetValue(win, null);
                    return pos;
                }
            }

            throw new NotSupportedException("Can't find internal main window. Maybe something has changed inside Unity");
        }

19 View Source File : WebRequestExtensions.cs
License : MIT License
Project Creator : Accelerider

public static void SetHeaderValue(this WebHeaderCollection header, string name, string value)
        {
            var property = typeof(WebHeaderCollection).GetProperty("InnerCollection",
                System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            if (property != null)
            {
                var collection = property.GetValue(header, null) as NameValueCollection;
                collection[name] = value;
            }
        }

19 View Source File : NeuralLearner.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence

private static void SetPropertyValues<U>(string propertyName,
            object objectInconcern, U valueToSet)
        {
            var prop = objectInconcern.GetType().GetProperty(propertyName
                , BindingFlags.Public | BindingFlags.Instance);

            var types = prop != null && prop.ToString() != "" ? prop.ToString().Split(' ')[0] : "";
            var typeToParse = types.Replace("System.", "");

            if (null == prop || !prop.CanWrite || types == "") return;
            prop.SetValue(objectInconcern, valueToSet, null);
        }

19 View Source File : HttpHelper.cs
License : GNU General Public License v3.0
Project Creator : aduskin

static HttpWebRequest Http_Core(string _type, string _url, Encoding _encoding, List<replacedem> _header, object _conmand = null)
      {
         #region 启动HTTP请求之前的初始化操作
         bool isget = false;
         if (_type == "GET")
         {
            isget = true;
         }

         if (isget)
         {
            if (_conmand is List<replacedem>)
            {
               List<replacedem> _conmand_ = (List<replacedem>)_conmand;

               string param = "";
               foreach (replacedem item in _conmand_)
               {
                  if (string.IsNullOrEmpty(param))
                  {
                     if (_url.Contains("?"))
                     {
                        param += "&" + item.Name + "=" + item.Value;
                     }
                     else
                     {
                        param = "?" + item.Name + "=" + item.Value;
                     }
                  }
                  else
                  {
                     param += "&" + item.Name + "=" + item.Value;
                  }
               }
               _url += param;
            }

         }
         Uri uri = null;
         try
         {
            uri = new Uri(_url);
         }
         catch { }
         #endregion
         if (uri != null)
         {
            //string _scheme = uri.Scheme.ToUpper();
            try
            {

               HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
               req.Proxy = null;
               req.Host = uri.Host;
               req.Method = _type;
               req.AllowAutoRedirect = false;
               bool isContentType = true;
               #region 设置请求头
               if (_header != null && _header.Count > 0)
               {
                  bool isnotHeader = true;
                  System.Collections.Specialized.NameValueCollection collection = null;

                  foreach (replacedem item in _header)
                  {
                     string _Lower_Name = item.Name.ToLower();
                     switch (_Lower_Name)
                     {
                        case "host":
                           req.Host = item.Value;
                           break;
                        case "accept":
                           req.Accept = item.Value;
                           break;
                        case "user-agent":
                           req.UserAgent = item.Value;
                           break;
                        case "referer":
                           req.Referer = item.Value;
                           break;
                        case "content-type":
                           isContentType = false;
                           req.ContentType = item.Value;
                           break;
                        case "cookie":
                           #region 设置COOKIE
                           string _cookie = item.Value;
                           CookieContainer cookie_container = new CookieContainer();
                           if (_cookie.IndexOf(";") >= 0)
                           {
                              string[] arrCookie = _cookie.Split(';');
                              //加载Cookie
                              //cookie_container.SetCookies(new Uri(url), cookie);
                              foreach (string sCookie in arrCookie)
                              {
                                 if (string.IsNullOrEmpty(sCookie))
                                 {
                                    continue;
                                 }
                                 if (sCookie.IndexOf("expires") > 0)
                                 {
                                    continue;
                                 }
                                 cookie_container.SetCookies(uri, sCookie);
                              }
                           }
                           else
                           {
                              cookie_container.SetCookies(uri, _cookie);
                           }
                           req.CookieContainer = cookie_container;
                           #endregion
                           break;
                        default:
                           if (isnotHeader && collection == null)
                           {
                              var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                              if (property != null)
                              {
                                 collection = property.GetValue(req.Headers, null) as System.Collections.Specialized.NameValueCollection;
                              }
                              isnotHeader = false;
                           }
                           //设置对象的Header数据
                           if (collection != null)
                           {
                              collection[item.Name] = item.Value;
                           }
                           break;

                     }
                  }
               }
               #endregion

               #region 设置POST数据 
               if (!isget)
               {
                  if (_conmand != null)
                  {
                     if (_conmand is List<replacedem>)
                     {
                        List<replacedem> _conmand_ = (List<replacedem>)_conmand;
                        //POST参数
                        if (isContentType)
                        {
                           req.ContentType = "application/x-www-form-urlencoded";
                        }
                        string param = "";
                        foreach (replacedem item in _conmand_)
                        {
                           if (string.IsNullOrEmpty(param))
                           {
                              param = item.Name + "=" + item.Value;
                           }
                           else
                           {
                              param += "&" + item.Name + "=" + item.Value;
                           }
                        }

                        byte[] bs = _encoding.GetBytes(param);

                        req.ContentLength = bs.Length;

                        using (Stream reqStream = req.GetRequestStream())
                        {
                           reqStream.Write(bs, 0, bs.Length);
                           reqStream.Close();
                        }
                     }
                     else if (_conmand is string[])
                     {
                        try
                        {
                           string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                           byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                           byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

                           req.ContentType = "multipart/form-data; boundary=" + boundary;


                           using (Stream reqStream = req.GetRequestStream())
                           {
                              string[] files = (string[])_conmand;

                              string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                              byte[] buff = new byte[1024];
                              for (int i = 0; i < files.Length; i++)
                              {
                                 string file = files[i];
                                 reqStream.Write(boundarybytes, 0, boundarybytes.Length);

                                 string contentType = MimeMappingProvider.Shared.GetMimeMapping(file);

                                 //string contentType = System.Web.MimeMapping.GetMimeMapping(file);

                                 //string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(file), contentType);
                                 string header = string.Format(headerTemplate, "media", Path.GetFileName(file), contentType);//微信
                                 byte[] headerbytes = _encoding.GetBytes(header);
                                 reqStream.Write(headerbytes, 0, headerbytes.Length);

                                 using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
                                 {

                                    int contentLen = fileStream.Read(buff, 0, buff.Length);

                                    int Value = contentLen;
                                    //文件上传开始
                                    //tProgress.Invoke(new Action(() =>
                                    //{
                                    //    tProgress.Maximum = (int)fileStream.Length;
                                    //    tProgress.Value = Value;
                                    //}));

                                    while (contentLen > 0)
                                    {
                                       //文件上传中

                                       reqStream.Write(buff, 0, contentLen);
                                       contentLen = fileStream.Read(buff, 0, buff.Length);
                                       Value += contentLen;

                                       //tProgress.Invoke(new Action(() =>
                                       //{
                                       //    tProgress.Value = Value;
                                       //}));
                                    }
                                 }
                              }

                              //文件上传结束
                              reqStream.Write(endbytes, 0, endbytes.Length);
                           }
                        }
                        catch
                        {
                           if (isContentType)
                           {
                              req.ContentType = null;
                           }
                           req.ContentLength = 0;
                        }

                     }
                     else
                     {
                        //POST参数 
                        if (isContentType)
                        {
                           req.ContentType = "application/x-www-form-urlencoded";
                        }
                        string param = _conmand.ToString();

                        byte[] bs = _encoding.GetBytes(param);

                        req.ContentLength = bs.Length;

                        using (Stream reqStream = req.GetRequestStream())
                        {
                           reqStream.Write(bs, 0, bs.Length);
                           reqStream.Close();
                        }
                     }

                  }
                  else
                  {
                     req.ContentLength = 0;
                  }
               }
               #endregion

               return req;
            }
            catch
            {
            }
         }
         return null;
      }

19 View Source File : EHHelper.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static bool BuildInternalPreserve(Type type)
        {
            try
            {
                const BindingFlags fl = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
                var at = (string) typeof(Environment).InvokeMember("GetResourceString", fl, null, null, new object[] {"Word_At"});

                var preserve = type.GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
                var field = type.GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);
                var stackTrace = type.GetProperty("StackTrace", BindingFlags.Instance | BindingFlags.Public).GetGetMethod();
                var fmt = typeof(string).GetMethod("Format", new[] {typeof(string), typeof(object), typeof(object)});

                var dm = new DynamicMethod("", typeof(void), new[] {typeof(Exception), typeof(string), typeof(bool)}, true);
                var ilGen = dm.GetILGenerator();
                var lbl = ilGen.DefineLabel();
                var lbl2 = ilGen.DefineLabel();
                var lbl3 = ilGen.DefineLabel();

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Brtrue, lbl2);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Callvirt, stackTrace);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Br, lbl3);
                ilGen.MarkLabel(lbl2);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
                ilGen.MarkLabel(lbl3);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Call, preserve);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Stfld, field);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Brfalse, lbl);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Brtrue, lbl);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldstr,
                    "{1}" + Environment.NewLine + "   " + at + " DarksVM.Load() [{0}]" + Environment.NewLine);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Call, fmt);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Stfld, field);


                ilGen.Emit(System.Reflection.Emit.OpCodes.Throw);

                ilGen.MarkLabel(lbl);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Throw);

                rethrow = (Throw) dm.CreateDelegate(typeof(Throw));
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
            return true;
        }

19 View Source File : StickerEditor.cs
License : MIT License
Project Creator : agens-no

public override void OnInteractivePreviewGUI(Rect r, GUIStyle background)
        {
            if (textureEditors == null || textureEditors.Count == 0)
            {
                CreateTextureEditor();
            }

            if (currentTextureEditor != null)
            {
                currentTextureEditor.OnInteractivePreviewGUI(r, background);
            }

            if (playing && Sequence.boolValue && Frames.arraySize > 1)
            {
                if (RepaintMethod == null)
                {
                    var type = typeof(Editor).replacedembly.GetType("UnityEditor.GUIView");
                    var prop = type.GetProperty("current", BindingFlags.Static | BindingFlags.Public);
                    GUIView = prop.GetValue(null, null);
                    RepaintMethod = GUIView.GetType().GetMethod("Repaint", BindingFlags.Public | BindingFlags.Instance);
                }

                RepaintMethod.Invoke(GUIView, null);
            }
        }

19 View Source File : StickerPackEditor.cs
License : MIT License
Project Creator : agens-no

private void RepaintView()
        {
            if (repaintMethod == null)
            {
                var type = typeof(Editor).replacedembly.GetType("UnityEditor.GUIView");
                var prop = type.GetProperty("current", BindingFlags.Static | BindingFlags.Public);
                guiView = prop.GetValue(null, null);
                repaintMethod = guiView.GetType().GetMethod("Repaint", BindingFlags.Public | BindingFlags.Instance);
            }
            repaintMethod.Invoke(guiView, null);
        }

19 View Source File : MemoryCacheManager.cs
License : MIT License
Project Creator : ahmet-cetinkaya

public void RemoveByPattern(string pattern)
        {
            var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection",
                BindingFlags.NonPublic | BindingFlags.Instance);
            var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic;
            var cacheCollectionValues = new List<ICacheEntry>();

            foreach (var cacheItem in cacheEntriesCollection)
            {
                ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null);
                cacheCollectionValues.Add(cacheItemValue);
            }

            var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
            var keysToRemove = cacheCollectionValues
                .Where(d => regex.IsMatch(d.Key.ToString()))
                .Select(d => d.Key)
                .ToList();

            foreach (var key in keysToRemove) _memoryCache.Remove(key);
        }

19 View Source File : AssetBundleFilesAnalyze.cs
License : MIT License
Project Creator : akof1314

public static void replacedyzeObjectReference(replacedetBundleFileInfo info, Object o)
        {
            if (o == null || info.objDict.ContainsKey(o))
            {
                return;
            }

            var serializedObject = new SerializedObject(o);
            info.objDict.Add(o, serializedObject);

            if (inspectorMode == null)
            {
                inspectorMode = typeof(SerializedObject).GetProperty("inspectorMode", BindingFlags.NonPublic | BindingFlags.Instance);
            }
            inspectorMode.SetValue(serializedObject, InspectorMode.Debug, null);

            var it = serializedObject.Gereplacederator();
            while (it.NextVisible(true))
            {
                if (it.propertyType == SerializedPropertyType.ObjectReference && it.objectReferenceValue != null)
                {
                    replacedyzeObjectReference(info, it.objectReferenceValue);
                }
            }

            // 只能用另一种方式获取的引用
            replacedyzeObjectReference2(info, o);
        }

19 View Source File : Uncapsulator.cs
License : MIT License
Project Creator : albahari

FieldOrProperty GetFieldOrProperty (Type type, string name, BindingFlags bindingFlags, bool throwIfNotFound)
        {
            var cache = _options.UseGlobalCache
                ? _globalFieldAndPropertyCache
                : (_fieldAndPropertyCache ?? (_fieldAndPropertyCache = new Dictionary<object, FieldOrProperty> ()));

            object cacheKey = _options.UseGlobalCache
                ? (object)new GlobalFieldPropertyCacheKey { Type = type, Name = name, BindingFlags = bindingFlags }
                : (type == _type) + name;   // type may be _type or _callSiteInterfaceType

            if (!TryGetValueWithLock (cache, cacheKey, out var result))
            {
                result = new FieldOrProperty (
                    GetTypeHierarchy (type)
                        .Select (t => (MemberInfo)t.GetProperty (name, bindingFlags) ?? t.GetField (name, bindingFlags))
                        .FirstOrDefault (x => x != null));

                lock (cache) cache[cacheKey] = result;
            }

            // If we can't match, it's better to throw than return null, so that we can report _type in the error message.
            if (result.MemberInfo == null && throwIfNotFound)
                throw new MissingMemberException ($"'{type}' does not contain a definition for '{name}'.").Wrap ();

            return result;
        }

19 View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho

public static IOrderedQueryable<T> Order<T>(this IQueryable<T> source, string propertyName, bool descending, bool anotherLevel = false)
        {
            var type = typeof(T);
            var propertyInfo = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Public);
            if(propertyInfo == null)
            {
                throw new ArgumentOutOfRangeException(nameof(propertyName));
            }
            ParameterExpression parameter = Expression.Parameter(type, String.Empty); // I don't care about some naming
            MemberExpression property = Expression.Property(parameter, propertyInfo);
            LambdaExpression sort = Expression.Lambda(property, parameter);
            MethodCallExpression call = Expression.Call(
                typeof(Queryable),
                (!anotherLevel ? "OrderBy" : "ThenBy") + (descending ? "Descending" : String.Empty),
                new[] { typeof(T), property.Type },
                source.Expression,
                Expression.Quote(sort));
            return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call);
        }

19 View Source File : ObjectExtensions.cs
License : MIT License
Project Creator : albyho

public static T UpdateFrom<T>(this T source, object target)
        {
            if (source == null) return default(T);
            if (target == null) return source;

            Type type = typeof(T);

            foreach (PropertyDescriptor targetPropertyDescriptor in TypeDescriptor.GetProperties(target))
            {
                PropertyInfo sourcePropertyInfo = type.GetProperty(targetPropertyDescriptor.Name, BindingFlags.Instance | BindingFlags.Public);
                if (sourcePropertyInfo != null && sourcePropertyInfo.CanWrite)
                {
                    var targetPropertyAccessor = new PropertyAccessor(sourcePropertyInfo);
                    var value = targetPropertyDescriptor.GetValue(target);
                    if (value != null)
                    {
                        if (sourcePropertyInfo.PropertyType.IsEnum)
                            targetPropertyAccessor.SetValue(source, Enum.ToObject(sourcePropertyInfo.PropertyType, value));
                        else
                            targetPropertyAccessor.SetValue(source, value);
                    }
                    else
                    {
                        targetPropertyAccessor.SetValue(source, null);
                    }
                }
            }
            return source;
        }

19 View Source File : EditorHelper.cs
License : MIT License
Project Creator : alen-smajic

private static object GetValue_Imp(object source, string name)
		{
			if (source == null)
				return null;
			var type = source.GetType();

			while (type != null)
			{
				var f = type.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
				if (f != null)
					return f.GetValue(source);

				var p = type.GetProperty(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
				if (p != null)
					return p.GetValue(source, null);

				type = type.BaseType;
			}
			return null;
		}

19 View Source File : CustomShaderInspector.cs
License : MIT License
Project Creator : alexismorin

public static Rect TopLevel_GetLast()
		{
			System.Type guiLayoutGroup = System.Type.GetType( "UnityEngine.GUILayoutGroup, UnityEngine" );
			var topLevel = GUILayoutUtilityEx.Type.GetProperty( "topLevel", BindingFlags.NonPublic | BindingFlags.Static ).GetValue( null, null );
			return ( Rect ) guiLayoutGroup.InvokeMember( "GetLast", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, topLevel, new object[] { } );
		}

19 View Source File : CustomShaderInspector.cs
License : MIT License
Project Creator : alexismorin

public static DisableBatchingType GetDisableBatching( Shader s )
		{
			return ( DisableBatchingType ) ShaderEx.Type.GetProperty( "disableBatching", BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( s, new object[ 0 ] );
		}

19 View Source File : CustomShaderInspector.cs
License : MIT License
Project Creator : alexismorin

public static int GetCurrentMode()
		{
			return ( int ) ShaderInspectorPlatformsPopupEx.Type.GetProperty( "currentMode", BindingFlags.Public | BindingFlags.Static ).GetValue( null, null );
		}

19 View Source File : CustomShaderInspector.cs
License : MIT License
Project Creator : alexismorin

public static int GetCurrentPlatformMask()
		{
			return ( int ) ShaderInspectorPlatformsPopupEx.Type.GetProperty( "currentPlatformMask", BindingFlags.Public | BindingFlags.Static ).GetValue( null, null );
		}

19 View Source File : CustomShaderInspector.cs
License : MIT License
Project Creator : alexismorin

public static int GetCurrentVariantStripping()
		{
			return ( int ) ShaderInspectorPlatformsPopupEx.Type.GetProperty( "currentVariantStripping", BindingFlags.Public | BindingFlags.Static ).GetValue( null, null );
		}

19 View Source File : Tire.cs
License : Apache License 2.0
Project Creator : Algoryx

protected static System.Reflection.PropertyInfo GetRadiusProperty( System.Type type )
    {
      return type.GetProperty( "Radius", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public );
    }

19 View Source File : PropertyInfoExtensionsTests.cs
License : MIT License
Project Creator : aliencube

[TestMethod]
        public void Given_Property_When_GetJsonPropertyName_Invoked_Then_It_Should_Return_PropertyName()
        {
            var name = "FakeProperty";
            var jsonPropertyName = "FakeProperty";
            var property = typeof(FakeModel).GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
            var namingStrategy = new DefaultNamingStrategy();

            var result = PropertyInfoExtensions.GetJsonPropertyName(property, namingStrategy);

            result.Should().Be(jsonPropertyName);
        }

19 View Source File : PropertyInfoExtensionsTests.cs
License : MIT License
Project Creator : aliencube

[TestMethod]
        public void Given_Property_When_GetJsonPropertyName_Invoked_Then_It_Should_Return_JsonPropertyName()
        {
            var name = "FakeProperty2";
            var jsonPropertyName = "anotherFakeProperty";
            var property = typeof(FakeModel).GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
            var namingStrategy = new DefaultNamingStrategy();

            var result = PropertyInfoExtensions.GetJsonPropertyName(property, namingStrategy);

            result.Should().Be(jsonPropertyName);
        }

19 View Source File : PropertyInfoExtensionsTests.cs
License : MIT License
Project Creator : aliencube

[TestMethod]
        public void Given_Property_When_GetJsonPropertyName_IsEmpty_Then_It_Should_Return_ElementName()
        {
            var name = "FakePropertyNoPropertyValue";
            var property = typeof(FakeModel).GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
            var namingStrategy = new DefaultNamingStrategy();

            var result = PropertyInfoExtensions.GetJsonPropertyName(property, namingStrategy);

            result.Should().NotBeNullOrEmpty();
            result.Should().Be(name);
        }

19 View Source File : PropertyInfoExtensionsTests.cs
License : MIT License
Project Creator : aliencube

[TestMethod]
        public void Given_Property_When_DefaultJsonProperyAnnotation_Invoked_Then_It_Should_Return_ElementName()
        {
            var name = "FakePropertyNoAnnotation";
            var property = typeof(FakeModel).GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
            var namingStrategy = new DefaultNamingStrategy();

            var result = PropertyInfoExtensions.GetJsonPropertyName(property, namingStrategy);

            result.Should().NotBeNullOrEmpty();
            result.Should().Be(name);
        }

19 View Source File : PropertyInfoExtensionsTests.cs
License : MIT License
Project Creator : aliencube

[TestMethod]
        public void Given_Property_When_DefaultJsonProperyAnnotation_Invoked_WithCamelCaseNaming_Then_It_Should_Return_ElementName()
        {
            var name = "FakePropertyNoAnnotation";
            var camelCaseName = "fakePropertyNoAnnotation";
            var property = typeof(FakeModel).GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
            var namingStrategy = new CamelCaseNamingStrategy();

            var result = PropertyInfoExtensions.GetJsonPropertyName(property, namingStrategy);

            result.Should().NotBeNullOrEmpty();
            result.Should().Be(camelCaseName);
        }

19 View Source File : CloudEventContentTests.cs
License : MIT License
Project Creator : aliencube

[TestMethod]
        public void Given_CloudEvent_When_Instantiated_Should_HaveProperty()
        {
            var data = "hello world";

            var ev = new AnotherFakeEvent();
            ev.EventType = "com.example.someevent";
            ev.CloudEventsVersion = "0.1";
            ev.Source = (new Uri("http://localhost")).ToString();
            ev.EventId = Guid.NewGuid().ToString();
            ev.Data = data;

            var content = new FakeCloudEventContent<string>(ev);

            var pi = typeof(FakeCloudEventContent<string>).GetProperty("CloudEvent", BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty);

            pi.GetValue(content).Should().NotBeNull();
            pi.GetValue(content).Should().Be(ev);
        }

19 View Source File : PropertyInfoExtensionsTests.cs
License : MIT License
Project Creator : aliencube

[TestMethod]
        public void Given_Property_When_GetJsonPropertyName_IsEmpty_WithCamelCaseNaming_Then_It_Should_Return_ElementName()
        {
            var name = "FakePropertyNoPropertyValue";
            var camelCaseName = "fakePropertyNoPropertyValue";
            var property = typeof(FakeModel).GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
            var namingStrategy = new CamelCaseNamingStrategy();

            var result = PropertyInfoExtensions.GetJsonPropertyName(property, namingStrategy);

            result.Should().NotBeNullOrEmpty();
            result.Should().Be(camelCaseName);
        }

19 View Source File : TypeExtension.cs
License : MIT License
Project Creator : AlphaYu

public static PropertyInfo GetProperty<T>([NotNull] this T @this, string name, BindingFlags bindingAttr)
            => @this.GetType().GetProperty(name, bindingAttr);

19 View Source File : BaseTypeObject.cs
License : MIT License
Project Creator : Alprog

public override SyntaxObject GetMember(Token token)
        {
            var memberName = token.Data as string;
            var propertyInfo = Type.GetProperty(memberName, Flags);
            if (propertyInfo != null)
            {
                return new Property(propertyInfo, Instance, token);
            }

            var fieldInfo = Type.GetField(memberName, Flags);
            if (fieldInfo != null)
            {
                return new Property(fieldInfo, Instance, token);
            }

            var memberInfo = Type.GetMethod(memberName, Flags);
            if (memberInfo != null)
            {
                return new Function(memberInfo, Instance, token);
            }

            return base.GetMember(token);
        }

19 View Source File : ReflectionExtension.cs
License : MIT License
Project Creator : AlphaYu

public static PropertyInfo GetProperty<T>([NotNull] this T @this, string name, BindingFlags bindingAttr)
        {
            return @this.GetType().GetProperty(name, bindingAttr);
        }

19 View Source File : DataHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

private static void ResetDataField(string[] keys, object data, int index = 0)
        {
            string key = keys[index];
            Type current = data.GetType();
            bool isLastKey = (keys.Length - 1) == index;

            PropertyInfo property = current.GetProperty(
               key,
               BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

            if (property == null)
            {
                return;
            }

            object propertyValue = property.GetValue(data, null);

            if (propertyValue == null)
            {
                return;
            }

            if (isLastKey)
            {
                object defaultValue = property.PropertyType.IsValueType ? Activator.CreateInstance(property.PropertyType) : null;
                property.SetValue(data, defaultValue);
                return;
            }

            ResetDataField(keys, property.GetValue(data, null), index + 1);
        }

19 View Source File : DataHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

private static string GetValueFromDatamodel(string[] keys, object data, int index = 0)
        {
            string key = keys[index];
            bool isLastKey = (keys.Length - 1) == index;
            Type current = data.GetType();

            PropertyInfo property = current.GetProperty(
               key,
               BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

            if (property == null)
            {
                string errorMessage = $"Could not find the field {string.Join(".", keys)}, property {key} is not defined in the data model.";
                throw new IndexOutOfRangeException(errorMessage);
            }
            else
            {
                object propertyValue = property.GetValue(data, null);
                if (isLastKey)
                {
                    return propertyValue == null ? (string)propertyValue : propertyValue.ToString();
                }
                else
                {
                    // no need to look further down, it is not defined yet.
                    if (propertyValue == null)
                    {
                        return null;
                    }

                    // recurivly replacedign values
                    return GetValueFromDatamodel(keys, property.GetValue(data, null), index + 1);
                }
            }
        }

19 View Source File : PrefillSI.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

private void replacedignValueToDataModel(string[] keys, JToken value, object currentObject, int index = 0, bool continueOnError = false)
        {
            string key = keys[index];
            bool isLastKey = (keys.Length - 1) == index;
            Type current = currentObject.GetType();
            PropertyInfo property = current.GetProperty(
                key,
                BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

            if (property == null)
            {
                if (!continueOnError)
                {
                    string errorMessage = $"Could not prefill the field {string.Join(".", keys)}, property {key} is not defined in the data model";
                    _logger.LogError(errorMessage);
                    throw new Exception(errorMessage);
                }
            }
            else
            {
                object propertyValue = property.GetValue(currentObject, null);
                if (isLastKey)
                {
                    if (propertyValue == null || allowOverwrite)
                    {
                        // create instance of the property type defined in the datamodel
                        var instance = value.ToObject(property.PropertyType);

                        // replacedign the value
                        property.SetValue(currentObject, instance);
                    }
                    else
                    {
                        // The target field has a value, and we do not have permission to overwrite values
                    }
                }
                else
                {
                    if (propertyValue == null)
                    {
                        // the object does not exsist, create a new one with the property type
                        var instance = Activator.CreateInstance(property.PropertyType);
                        property.SetValue(currentObject, instance, null);
                    }

                    // recurivly replacedign values
                    replacedignValueToDataModel(keys, value, property.GetValue(currentObject, null), index + 1, continueOnError);
                }
            }
        }

19 View Source File : HotReloader.cs
License : MIT License
Project Creator : AndreiMisiukevich

private void ReloadElement(object obj, ReloadItem reloadItem, Type csharpType = null)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(reloadItem.Code) && csharpType != null)
                {
                    var prop = obj.GetType().GetProperty("HotReloadCtorParams", BindingFlags.Instance | BindingFlags.NonPublic)
                        ?? obj.GetType().GetProperty("HotReloadCtorParams", BindingFlags.Instance | BindingFlags.Public);
                    var parameters = (prop?.GetValue(obj) as object[]) ?? new object[0];
                    switch (obj)
                    {
                        case Page page:
                            var newPage = Activator.CreateInstance(csharpType, parameters) as Page;
                            if (newPage == null)
                            {
                                return;
                            }
                            _ignoredElementInit = newPage;
                            if (App.MainPage == page)
                            {
                                App.MainPage = newPage;
                                break;
                            }
                            newPage.BindingContext = page.BindingContext;


                            if (page.Parent is MultiPage<Page> mPage)
                            {
                                mPage.Children.Insert(mPage.Children.IndexOf(page), newPage);
                                mPage.Children.Remove(page);
                                break;
                            }
                            if (page.Parent is MasterDetailPage mdPage)
                            {
                                if (mdPage.Master == page)
                                {
                                    mdPage.Master = newPage;
                                }
                                else if (mdPage.Detail == page)
                                {
                                    mdPage.Detail = newPage;
                                }
                                break;
                            }
                            page.Navigation.InsertPageBefore(newPage, page);
                            if (page.Navigation.NavigationStack.LastOrDefault() == page)
                            {
                                page.Navigation.PopAsync(false);
                            }
                            else
                            {
                                page.Navigation.RemovePage(page);
                            }
                            break;
                        case View view:
                            var newView = Activator.CreateInstance(csharpType, parameters) as View;
                            if (newView == null)
                            {
                                return;
                            }
                            _ignoredElementInit = newView;
                            switch (view.Parent)
                            {
                                case ContentView contentView:
                                    contentView.Content = newView;
                                    break;
                                case ScrollView scrollView:
                                    scrollView.Content = newView;
                                    break;
                                case Layout<View> layout:
                                    layout.Children.Insert(layout.Children.IndexOf(view), newView);
                                    layout.Children.Remove(view);
                                    break;
                                case ContentPage page:
                                    page.Content = newView;
                                    break;
                            }
                            break;
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("### HOTRELOAD ERROR: CANNOT RELOAD C# CODE ###");
            }

            if (!reloadItem.HasXaml)
            {
                OnLoaded(obj, csharpType != null);
                return;
            }

            var xamlDoc = reloadItem.Xaml;

            if (obj is VisualElement ve)
            {
                ve.Resources = null;
            }

            //[0] Parse new xaml with resources
            var rebuildEx = RebuildElement(obj, xamlDoc);
            if (!(obj is VisualElement) && !(obj is Application))
            {
                if (rebuildEx != null)
                {
                    throw rebuildEx;
                }
                OnLoaded(obj, true);
                return;
            }

            //[1] Check if any dictionary was updated before
            foreach (var dict in GetResourceDictionaries((obj as VisualElement)?.Resources ?? (obj as Application)?.Resources).ToArray())
            {
                var name = dict.GetType().FullName;

                //[1.0] update own res
                if (_resourceMapping.TryGetValue(name, out ReloadItem item))
                {
                    dict.Clear();
                    LoadFromXaml(dict, item.Xaml);
                }

                //[1.1] Update Source resources
                var sourceItem = GereplacedemForReloadingSourceRes(dict.Source, obj);
                if (sourceItem != null)
                {
                    //(?): Seems no need in this stuff
                    //dict.GetType().GetField("_source", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(dict, null);
                    //var resType = obj.GetType().replacedembly.GetType(RetrieveClreplacedName(sourceItem.Xaml.InnerXml));
                    //var rd = Activator.CreateInstance(resType) as ResourceDictionary;
                    //rd.Clear();
                    //rd.LoadFromXaml(sourceItem.Xaml.InnerXml);
                    //dict.Add(rd);
                    var rd = new ResourceDictionary();
                    LoadFromXaml(rd, sourceItem.Xaml);
                    foreach (var key in rd.Keys)
                    {
                        dict.Remove(key);
                    }
                    LoadFromXaml(dict, sourceItem.Xaml);
                }
                else if (dict.Source != null)
                {
                    var dId = GetResId(dict.Source, obj);
                    if (dId != null)
                    {
                        sourceItem = _resourceMapping.FirstOrDefault(it => it.Key.EndsWith(dId, StringComparison.Ordinal)).Value;
                        if (sourceItem != null)
                        {
                            var rd = new ResourceDictionary();
                            LoadFromXaml(rd, sourceItem.Xaml);
                            foreach (var key in rd.Keys)
                            {
                                dict.Remove(key);
                            }
                            LoadFromXaml(dict, sourceItem.Xaml);
                        }
                    }
                }

                var styleSheets = dict.GetType().GetProperty("StyleSheets", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(dict) as IList<StyleSheets.StyleSheet>;
                if (styleSheets != null)
                {
                    var sheets = xamlDoc.GetElementsByTagName("StyleSheet");
                    for (var i = 0; i < styleSheets.Count; ++i)
                    {
                        var src = sheets[i].Attributes["Source"];
                        if (src == null)
                        {
                            continue;
                        }
                        var rId = GetResId(new Uri(src.Value, UriKind.Relative), obj);
                        if (rId == null)
                        {
                            continue;
                        }
                        var rItem = _resourceMapping.FirstOrDefault(it => it.Key.EndsWith(rId, StringComparison.Ordinal)).Value;
                        if (rItem == null)
                        {
                            continue;
                        }
                        styleSheets.RemoveAt(i);
                        var newSheet = StyleSheets.StyleSheet.FromString(rItem.Css);
                        styleSheets.Insert(i, newSheet);
                        break;
                    }
                }
            }

            var modifiedXml = new XmlDoreplacedent();
            modifiedXml.LoadXml(xamlDoc.InnerXml);

            var isResourceFound = false;

            if (!(obj is Application))
            {
                foreach (XmlNode node in modifiedXml.LastChild)
                {
                    if (node.Name.EndsWith(".Resources", StringComparison.CurrentCulture))
                    {
                        node.ParentNode.RemoveChild(node);
                        isResourceFound = true;
                        break;
                    }
                }
            }

            //[2] Update object without resources (Force to re-apply all styles)
            if (isResourceFound)
            {
                rebuildEx = RebuildElement(obj, modifiedXml);
            }

            if (rebuildEx != null)
            {
                throw rebuildEx;
            }

            SetupNamedChildren(obj);
            OnLoaded(obj, true);
        }

19 View Source File : HotReloader.cs
License : MIT License
Project Creator : AndreiMisiukevich

private Exception RebuildElement(object obj, XmlDoreplacedent xmlDoc)
        {
            try
            {
                switch (obj)
                {
                    case MultiPage<Page> multiPage:
                        multiPage.Children.Clear();
                        break;
                    case ContentPage contentPage:
                        contentPage.Content = null;
                        break;
                    case ContentView contentView:
                        contentView.Content = null;
                        break;
                    case ScrollView scrollView:
                        scrollView.Content = null;
                        break;
                    case Layout<View> layout:
                        layout.Children.Clear();
                        break;
                    case Application app:
                        app.Resources.Clear();
                        break;
                }

                if (IsSubclreplacedOfShell(obj))
                {
                    var shellType = obj.GetType();
                    shellType.GetProperty("FlyoutHeaderTemplate", BindingFlags.Instance | BindingFlags.Public).SetValue(obj, null);
                    shellType.GetProperty("FlyoutHeader", BindingFlags.Instance | BindingFlags.Public).SetValue(obj, null);
                    var items = shellType.GetProperty("Items", BindingFlags.Instance | BindingFlags.Public).GetValue(obj, null);
                    items.GetType().GetMethod("Clear", BindingFlags.Instance | BindingFlags.Public).Invoke(items, null);
                }

                if (obj is Grid grid)
                {
                    grid.RowDefinitions.Clear();
                    grid.ColumnDefinitions.Clear();
                }

                if (obj is View view)
                {
                    ClearView(view, xmlDoc);
                }
                if (obj is Page page)
                {
                    page.ToolbarItems.Clear();
                }

                if (obj is ViewCell cell)
                {
                    return UpdateViewCell(cell, xmlDoc.InnerXml);
                }

                LoadFromXaml(obj, xmlDoc);
                return null;
            }
            catch (Exception ex)
            {
                return ex;
            }
        }

19 View Source File : Accessor.cs
License : MIT License
Project Creator : andruzzzhka

private static (Getter, Setter) MakeAccessors(string propName)
        {
            var prop = typeof(T).GetProperty(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            if (prop == null)
                throw new MissingMemberException(typeof(T).Name, propName);

            var getM = prop.GetGetMethod(true);
            var setM = prop.GetSetMethod(true);
            Getter getter = null;
            Setter setter = null;

            if (typeof(T).IsValueType)
            {
                if (getM != null)
                    getter = (Getter)Delegate.CreateDelegate(typeof(Getter), getM);
                if (setM != null)
                    setter = (Setter)Delegate.CreateDelegate(typeof(Setter), setM);
            }
            else
            {
                if (getM != null)
                {
                    var dyn = new DynamicMethod($"<>_get__{propName}", typeof(U), new[] { typeof(T).MakeByRefType() }, typeof(PropertyAccessor<T, U>), true);
                    var il = dyn.GetILGenerator();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldind_Ref);
                    il.Emit(OpCodes.Tailcall);
                    il.Emit(getM.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, getM);
                    il.Emit(OpCodes.Ret);
                    getter = (Getter)dyn.CreateDelegate(typeof(Getter));
                }
                if (setM != null)
                {
                    var dyn = new DynamicMethod($"<>_set__{propName}", typeof(void), new[] { typeof(T).MakeByRefType(), typeof(U) }, typeof(PropertyAccessor<T, U>), true);
                    var il = dyn.GetILGenerator();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldind_Ref);
                    il.Emit(OpCodes.Ldarg_1);
                    il.Emit(OpCodes.Tailcall);
                    il.Emit(setM.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, setM);
                    il.Emit(OpCodes.Ret);
                    setter = (Setter)dyn.CreateDelegate(typeof(Setter));
                }
            }

            return (getter, setter);
        }

19 View Source File : CustomExtensions.cs
License : MIT License
Project Creator : andruzzzhka

public static void SetPrivateProperty<T>(this object obj, string propName, T val)
        {
            Type t = obj.GetType();
            if (t.GetProperty(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) == null)
                throw new ArgumentOutOfRangeException("propName", string.Format("Property {0} was not found in Type {1}", propName, obj.GetType().FullName));
            t.InvokeMember(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty | BindingFlags.Instance, null, obj, new object[] { val });
        }

19 View Source File : Utilities.cs
License : MIT License
Project Creator : andydandy74

public static void ClearSelection()
        {
            var dynamoSelection = typeof(DynamoModel).replacedembly.GetType("Dynamo.Selection.DynamoSelection");
            var selectionInstance = dynamoSelection.GetProperty("Instance", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
            var clearMethod = dynamoSelection.GetMethod("ClearSelection", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
            clearMethod.Invoke(selectionInstance.GetValue(null), null);
        }

19 View Source File : MappingExtensions.cs
License : GNU General Public License v3.0
Project Creator : andysal

private static Expression<Func<T, K>> CreateExpression<T, K>(String propertyName)
        {
            Type type = typeof(T);
            PropertyInfo pi = type.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

            if (pi == null) throw new ArgumentException("propertyName is not valid.");

            ParameterExpression argumentExpression = Expression.Parameter(type, "x");
            MemberExpression memberExpression = Expression.Property(argumentExpression, pi);
            LambdaExpression lambda = Expression.Lambda(memberExpression, argumentExpression);

            Expression<Func<T, K>> expression = (Expression<Func<T, K>>)lambda;

            return expression;
        }

See More Examples