Exemplo n.º 1
0
        private ShadowPropertyDefinition AddShadowPropertyDefinition(String propertyName, Type propertyType)
        {
            _shadowPropertyIndex++;

            String     shadowPropertyIndex   = _shadowPropertyIndex.ToString(CultureInfo.InvariantCulture);
            String     shadowPropertyGetName = "ShadowPropertyGet" + shadowPropertyIndex;
            MethodInfo?getMethodInfo         = typeof(Types.DynamicType).GetMethod(shadowPropertyGetName, BindingFlags.Instance | BindingFlags.NonPublic);

            if (getMethodInfo == null)
            {
                throw new InvalidOperationException(shadowPropertyGetName + " out of range, property name " + propertyName);
            }

            getMethodInfo = getMethodInfo.GetGenericMethodDefinition().MakeGenericMethod(new Type[] { propertyType });

            String    shadowPropertyFieldName = "ShadowProperty" + shadowPropertyIndex;
            FieldInfo?fieldInfo = typeof(Types.DynamicType).GetField(shadowPropertyFieldName, BindingFlags.Instance | BindingFlags.NonPublic);

            if (fieldInfo == null)
            {
                throw new InvalidOperationException(shadowPropertyFieldName + " out of range, proeprty name " + propertyName);
            }

            var shadowPropertyDefinition = new ShadowPropertyDefinition(getMethodInfo, fieldInfo);

            _shadowPropertyDefinitions.Add(propertyName, shadowPropertyDefinition);
            _shadowPropertyFieldInfoByGetName.Add(shadowPropertyGetName, fieldInfo);
            return(shadowPropertyDefinition);
        }
 /// <summary>
 ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
 ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
 ///     any release. You should only use it directly in your code with extreme caution and knowing that
 ///     doing so can result in application failures when updating to a new Entity Framework Core release.
 /// </summary>
 public virtual bool CanSetField(FieldInfo?fieldInfo, ConfigurationSource?configurationSource)
 => (configurationSource.Overrides(Metadata.GetFieldInfoConfigurationSource()) &&
     (fieldInfo == null ||
      PropertyBase.IsCompatible(
          fieldInfo, Metadata.ClrType, Metadata.DeclaringType.ClrType, Metadata.Name,
          shouldThrow: configurationSource == ConfigurationSource.Explicit))) ||
 Equals(Metadata.FieldInfo, fieldInfo);
Exemplo n.º 3
0
        private bool IsCallbackType(object callback, Type t)
        {
            Type typ;

            if (callback is EventCallback)
            {
                typ = typeof(EventCallback);
            }
            else if (callback is EventCallback <MouseEventArgs> )
            {
                typ = typeof(EventCallback <MouseEventArgs>);
            }
            else
            {
                throw new NotSupportedException();
            }

            FieldInfo?delField = typ.GetField("Delegate", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

            if (delField == null)
            {
                throw new NotSupportedException();
            }
            return(delField.GetValue(callback)?.GetType() == t);
        }
Exemplo n.º 4
0
        internal static bool TryGetFieldInfo(Expression @object, string memberName, [NotNullWhen(true)] out FieldInfo?fieldInfo)
        {
            var type = @object.Type;

            fieldInfo = type.GetField(memberName);
            return(fieldInfo != null);
        }
Exemplo n.º 5
0
        public static void SetPrivateField(object target, string fieldName, object value)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (string.IsNullOrEmpty(fieldName))
            {
                throw new ArgumentNullOrDefaultException(nameof(fieldName));
            }

            var       type = target.GetType();
            FieldInfo?fi   = null;

            while (type != null)
            {
                fi = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
                if (fi != null)
                {
                    break;
                }

                type = type.BaseType !;
            }

            if (fi == null)
            {
                throw new ArgumentPropertyException($"Field '{fieldName}' not found in type hierarchy.");
            }

            fi.SetValue(target, value);
        }
Exemplo n.º 6
0
        private void PerformFileSystemWatcherPatch()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Type.GetType("Mono.Runtime") != null)
            {
                var watcherField = typeof(FileSystemWatcher).GetField("watcher", BindingFlags.Static | BindingFlags.NonPublic);
                var watcher      = watcherField?.GetValue(null);

                if (watcher?.GetType().GetField("watches", BindingFlags.Static | BindingFlags.NonPublic)?.GetValue(watcher) is Hashtable watches)
                {
                    FieldInfo?incSubdirsField = null;

                    // DictionaryEntry<FileSystemWatcher, DefaultWatcherData>
                    foreach (var data in watches)
                    {
                        if (data is DictionaryEntry entry)
                        {
                            if (entry.Key is FileSystemWatcher fileSystemWatcher)
                            {
                                fileSystemWatcher.IncludeSubdirectories = false;
                            }

                            incSubdirsField ??= entry.Value.GetType().GetField("IncludeSubdirs", BindingFlags.Public | BindingFlags.Instance);
                            incSubdirsField?.SetValue(entry.Value, false);
                        }
                    }
                }
            }
        }
Exemplo n.º 7
0
    public async Task ColorAsync(string keywords)
    {
        // Remove non-alphabetical characters and spaces from keywords.
        var regex = new Regex("[^a-zA-Z]");

        keywords = regex.Replace(keywords, "");
        keywords = string.Join("", keywords.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));

        // SKColors contains predefined named color objects.
        var type = typeof(SKColors);

        // Get color by keyword color name using reflection.
        FieldInfo?info = type.GetField(
            keywords,
            BindingFlags.IgnoreCase |
            BindingFlags.Instance |
            BindingFlags.Public |
            BindingFlags.Static);
        object?temp = info?.GetValue(null);

        // Reflection was successful.
        if (temp is SKColor color)
        {
            await GetColorAsync(color);

            return;
        }

        await RespondAsync("Could not understand color keywords... (┬┬﹏┬┬)", ephemeral : true);
    }
Exemplo n.º 8
0
        public static IntPtr OffsetOf(Type t, string fieldName)
        {
            if (t is null)
            {
                throw new ArgumentNullException(nameof(t));
            }

            FieldInfo?f = t.GetField(
                fieldName,
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
                );

            if (f is null)
            {
                throw new ArgumentException(
                          SR.Format(SR.Argument_OffsetOfFieldNotFound, t.FullName),
                          nameof(fieldName)
                          );
            }

            if (!(f is RtFieldInfo rtField))
            {
                throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo, nameof(fieldName));
            }

            return(OffsetOfHelper(rtField));
        }
Exemplo n.º 9
0
        public static string GetEnumDescription(object enumValue, Type enumType)
        {
            string?enumString = enumValue?.ToString();

            if (enumString == null)
            {
                return(string.Empty);
            }

            FieldInfo?field = enumType?.GetField(enumString);

            if (field == null)
            {
                return(string.Empty);
            }

            object[] atts = field.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (atts.FirstOrDefault() is DescriptionAttribute descriptionAttribute)
            {
                return(descriptionAttribute.Description);
            }

            return(string.Empty);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Creates a <see cref="MemberExpression"/> accessing a property or field.
        /// </summary>
        /// <param name="expression">The containing object of the member.  This can be null for static members.</param>
        /// <param name="propertyOrFieldName">The member to be accessed.</param>
        /// <returns>The created <see cref="MemberExpression"/>.</returns>
        public static MemberExpression PropertyOrField(Expression expression, string propertyOrFieldName)
        {
            ExpressionUtils.RequiresCanRead(expression, nameof(expression));
            // bind to public names first
            PropertyInfo?pi = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);

            if (pi != null)
            {
                return(Property(expression, pi));
            }
            FieldInfo?fi = expression.Type.GetField(propertyOrFieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);

            if (fi != null)
            {
                return(Field(expression, fi));
            }
            pi = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
            if (pi != null)
            {
                return(Property(expression, pi));
            }
            fi = expression.Type.GetField(propertyOrFieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
            if (fi != null)
            {
                return(Field(expression, fi));
            }

            throw Error.NotAMemberOfType(propertyOrFieldName, expression.Type, nameof(propertyOrFieldName));
        }
Exemplo n.º 11
0
        public ValueTypeFixupInfo(long containerID, FieldInfo?member, int[]?parentIndex)
        {
            // If both member and arrayIndex are null, we don't have enough information to create
            // a tunnel to do the fixup.
            if (member == null && parentIndex == null)
            {
                throw new ArgumentException(SR.Argument_MustSupplyParent);
            }

            if (containerID == 0 && member == null)
            {
                _containerID = containerID;
                _parentField = member;
                _parentIndex = parentIndex;
            }

            // If the member isn't null, we know that they supplied a MemberInfo as the parent.  This means
            // that the arrayIndex must be null because we can't have a FieldInfo into an array.
            if (member != null)
            {
                if (parentIndex != null)
                {
                    throw new ArgumentException(SR.Argument_MemberAndArray);
                }

                if (member.FieldType.IsValueType && containerID == 0)
                {
                    throw new ArgumentException(SR.Argument_MustSupplyContainer);
                }
            }

            _containerID = containerID;
            _parentField = member;
            _parentIndex = parentIndex;
        }
Exemplo n.º 12
0
        static ReflectedNegotiateState()
        {
            var secAssembly = typeof(AuthenticationException).Assembly;
            var ntAuthType  = secAssembly.GetType("System.Net.NTAuthentication", throwOnError: true) !;

            _constructor     = ntAuthType.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).First();
            _getOutgoingBlob = ntAuthType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).Where(info =>
                                                                                                           info.Name.Equals("GetOutgoingBlob") && info.GetParameters().Count() == 3).Single();
            _isCompleted = ntAuthType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).Where(info =>
                                                                                                       info.Name.Equals("get_IsCompleted")).Single();
            _protocol = ntAuthType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).Where(info =>
                                                                                                    info.Name.Equals("get_ProtocolName")).Single();
            _closeContext = ntAuthType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).Where(info =>
                                                                                                        info.Name.Equals("CloseContext")).Single();

            var securityStatusType = secAssembly.GetType("System.Net.SecurityStatusPal", throwOnError: true) !;

            _statusCode      = securityStatusType.GetField("ErrorCode") !;
            _statusException = securityStatusType.GetField("Exception") !;

            if (!OperatingSystem.IsWindows())
            {
                var interopType   = secAssembly.GetType("Interop", throwOnError: true) !;
                var netNativeType = interopType.GetNestedType("NetSecurityNative", BindingFlags.NonPublic | BindingFlags.Static) !;
                _gssExceptionType = netNativeType.GetNestedType("GssApiException", BindingFlags.NonPublic) !;
                _gssMinorStatus   = _gssExceptionType.GetField("_minorStatus", BindingFlags.Instance | BindingFlags.NonPublic) !;
            }

            var negoStreamPalType = secAssembly.GetType("System.Net.Security.NegotiateStreamPal", throwOnError: true) !;

            _getIdentity = negoStreamPalType.GetMethods(BindingFlags.NonPublic | BindingFlags.Static).Where(info =>
                                                                                                            info.Name.Equals("GetIdentity")).Single();
            _getException = negoStreamPalType.GetMethods(BindingFlags.NonPublic | BindingFlags.Static).Where(info =>
                                                                                                             info.Name.Equals("CreateExceptionFromError")).Single();
        }
Exemplo n.º 13
0
        private static Object? Decode(this CustomAttribute attribute, Type actualType, ILogProvider? log = null)
        {
            Object? obj = null;
            var args = MapCustomAtribArgs(attribute.ConstructorArguments, log);
            try
            {          
                obj = Activator.CreateInstance(actualType, args);
            } catch(Exception e)
            {
                log?.Error($"Error constructing patcher from attribute:\n{e}");
                log?.Message($"Arg info:\n    {String.Join("\n    ", attribute.ConstructorArguments.Select(ca => ca.Type.FullName))}");
                log?.Message($"Read args:\n    {String.Join("\n    ", args.Select(a => $"{a?.GetType()?.FullName} {a?.ToString()}"))}");
            }

            foreach(CANamedArgument? namedArg in attribute.NamedArguments)
            {
                var type = Type.GetType(namedArg.Type.AssemblyQualifiedName);
                if(type is null) return null;
                if(namedArg.IsField)
                {
                    FieldInfo? fld = actualType.GetFieldOfType(namedArg.Name, type);
                    if(fld is null) return null;
                    fld.SetValue(obj, namedArg.Value);
                } else if(namedArg.IsProperty)
                {
                    PropertyInfo? prop = actualType.GetPropertyOfType(namedArg.Name, type, true);
                    if(prop is null) return null;
                    prop.SetMethod!.Invoke(obj, new[] { namedArg.Value });
                }
            }
            return obj;
        }
Exemplo n.º 14
0
        /// <inheritdoc/>
        public override object?ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            var stringValue = (string)value;

            string[] descriptorParts = stringValue.Split(KEY_DELIMITER);

            if (descriptorParts.Length != 2)
            {
                throw new ArgumentException(Strings.FenestraKeyIsInvalid, nameof(value));
            }

            string providerTypeName = descriptorParts[0];
            string keyName          = descriptorParts[1];

            Type?providerType = Type.GetType(providerTypeName);

            if (null == providerType)
            {
                throw new ArgumentException(Strings.FenestraKeyCannotFindType, nameof(value));
            }

            FieldInfo?providerField = providerType.GetField(keyName);

            if (null == providerField)
            {
                throw new ArgumentException(Strings.FenestraKeyCannotFindField, nameof(value));
            }

            return(providerField.GetValue(null));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Locates an element or list of elements for a Page Object member, and returns a
        /// proxy object for the element or list of elements.
        /// </summary>
        /// <param name="member">The <see cref="MemberInfo"/> containing information about
        /// a class's member.</param>
        /// <param name="locator">The <see cref="IElementLocator"/> used to locate elements.</param>
        /// <returns>A transparent proxy to the WebDriver element object.</returns>
        public virtual object?Decorate(MemberInfo member, IElementLocator locator)
        {
            FieldInfo?   field    = member as FieldInfo;
            PropertyInfo?property = member as PropertyInfo;

            Type?targetType = null;

            if (field != null)
            {
                targetType = field.FieldType;
            }

            if (property != null && property.CanWrite)
            {
                targetType = property.PropertyType;
            }

            if (targetType == null)
            {
                return(null);
            }

            IList <By> bys = CreateLocatorList(member);

            if (bys.Count > 0)
            {
                bool cache = ShouldCacheLookup(member);
                return(CreateObject(targetType, locator, bys, cache));
            }

            return(null);
        }
Exemplo n.º 16
0
        private static DbProviderFactory GetFactoryInstance(Type providerFactoryClass)
        {
            ADP.CheckArgumentNull(providerFactoryClass, nameof(providerFactoryClass));
            if (!providerFactoryClass.IsSubclassOf(typeof(DbProviderFactory)))
            {
                throw ADP.Argument(SR.Format(SR.ADP_DbProviderFactories_NotAFactoryType, providerFactoryClass.FullName));
            }

            FieldInfo?providerInstance = providerFactoryClass.GetField(InstanceFieldName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static);

            if (null == providerInstance)
            {
                throw ADP.InvalidOperation(SR.ADP_DbProviderFactories_NoInstance);
            }
            if (!providerInstance.FieldType.IsSubclassOf(typeof(DbProviderFactory)))
            {
                throw ADP.InvalidOperation(SR.ADP_DbProviderFactories_NoInstance);
            }
            object?factory = providerInstance.GetValue(null);

            if (null == factory)
            {
                throw ADP.InvalidOperation(SR.ADP_DbProviderFactories_NoInstance);
            }
            return((DbProviderFactory)factory);
        }
        static ExplicitParamsModifierCache()
        {
            FieldInfo?idInjectField = null;

            foreach (var field in typeof(TParams).GetFields(BindingFlags.Public | BindingFlags.NonPublic))
            {
                if (field.GetCustomAttribute <RpcIDAttribute>() is null)
                {
                    continue;
                }
                else
                {
                    idInjectField = field;
                    break;
                }
            }
            if (idInjectField is null)
            {
                ModifierType = typeof(EmptyModifier <TParams>);
            }
            else
            {
                ModifierType = RpcMethodEntryFactoryBuildingHelper.CreateIdInjecter(typeof(TParams).FullName + ".IdInjecter", idInjectField, typeof(TParams));
            }
        }
Exemplo n.º 18
0
        // assumes the instance is already on the stack
        private void EmitMemberAddress(MemberInfo member, Type?objectType)
        {
            FieldInfo?field = member as FieldInfo;

            if ((object?)field != null)
            {
                // Verifiable code may not take the address of an init-only field.
                // If we are asked to do so then get the value out of the field, stuff it
                // into a local of the same type, and then take the address of the local.
                // Typically this is what we want to do anyway; if we are saying
                // Foo.bar.ToString() for a static value-typed field bar then we don't need
                // the address of field bar to do the call.  The address of a local which
                // has the same value as bar is sufficient.

                // The C# compiler will not compile a lambda expression tree
                // which writes to the address of an init-only field. But one could
                // probably use the expression tree API to build such an expression.
                // (When compiled, such an expression would fail silently.)  It might
                // be worth it to add checking to the expression tree API to ensure
                // that it is illegal to attempt to write to an init-only field,
                // the same way that it is illegal to write to a read-only property.
                // The same goes for literal fields.
                if (!field.IsLiteral && !field.IsInitOnly)
                {
                    _ilg.EmitFieldAddress(field);
                    return;
                }
            }

            EmitMemberGet(member, objectType);
            LocalBuilder temp = GetLocal(GetMemberType(member));

            _ilg.Emit(OpCodes.Stloc, temp);
            _ilg.Emit(OpCodes.Ldloca, temp);
        }
Exemplo n.º 19
0
        public override object ConvertFrom(ITypeDescriptorContext?context, CultureInfo?culture, object?value)
        {
            var strValue = value?.ToString();

            if (strValue != null)
            {
                string[] parts = strValue.Split('.');
                if (parts != null && parts.Length == 1 || (parts != null && parts.Length == 2 && parts[0] == "Keyboard"))
                {
                    var kbType = typeof(Keyboard);

                    string    keyboard = parts[parts.Length - 1];
                    FieldInfo?field    = kbType.GetFields()?.FirstOrDefault(fi => fi.IsStatic && fi.Name == keyboard);
                    if (field?.GetValue(null) is Keyboard kb)
                    {
                        return(kb);
                    }

                    PropertyInfo?property = kbType.GetProperties()?.FirstOrDefault(pi => pi != null && pi.Name == keyboard && pi.CanRead && (pi.GetMethod?.IsStatic ?? false));
                    if (property != null && property?.GetValue(null, null) is Keyboard propKb)
                    {
                        return(propKb);
                    }
                }
            }

            throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", strValue, typeof(Keyboard)));
        }
Exemplo n.º 20
0
    private static bool IsTimeoutThreadAbortException(Exception exception)
    {
        if (!(exception is ThreadAbortException abort))
        {
            return(false);
        }

        if (abort.ExceptionState == null)
        {
            return(false);
        }

        Type stateType = abort.ExceptionState.GetType();

        if (stateType.FullName != "System.Web.HttpApplication+CancelModuleException")
        {
            return(false);
        }

        FieldInfo?timeoutField = stateType.GetField("_timeout", BindingFlags.Instance | BindingFlags.NonPublic);

        if (timeoutField == null)
        {
            return(false);
        }

        return((bool?)timeoutField.GetValue(abort.ExceptionState) ?? false);
    }
    public void DistributedLocks_AreReEntrant_FromTheSameThread_OnTheSameResource()
    {
        // Clean
        ContainerFixture.Clean();

        // arrange
        const string resource = "lock:test";

        using CosmosDbDistributedLock outer = new(resource, TimeSpan.FromSeconds(5), Storage);
        using CosmosDbDistributedLock inner = new(resource, TimeSpan.FromSeconds(5), Storage);

        // Assert
        Lock?result = null;

        try
        {
            result = Storage.Container.ReadItemWithRetries <Lock>(resource, PartitionKeys.Lock);
        }
        catch
        {
            /* ignored */
        }

        Assert.NotNull(result);

        FieldInfo?acquiredLocksField = typeof(CosmosDbDistributedLock).GetField("acquiredLocks", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);

        Assert.NotNull(acquiredLocksField);

        ThreadLocal <Dictionary <string, int> > outerValue = (ThreadLocal <Dictionary <string, int> >)acquiredLocksField !.GetValue(outer) !;

        Assert.Equal(2, outerValue.Value ![resource]);
Exemplo n.º 22
0
    /// <summary>
    ///     Gets the field.
    /// </summary>
    /// <typeparam name="TDeclaring">The type of the declaring.</typeparam>
    /// <typeparam name="TValue">The type of the value.</typeparam>
    /// <param name="fieldName">Name of the field.</param>
    /// <returns></returns>
    /// <exception cref="ArgumentNullException">fieldName</exception>
    /// <exception cref="ArgumentException">
    ///     Value can't be empty or consist only of white-space characters. - <paramref name="fieldName" />
    ///     or
    ///     Value type <typeparamref name="TValue" /> does not match field <typeparamref name="TDeclaring" />.
    ///     <paramref name="fieldName" /> type.
    /// </exception>
    /// <exception cref="InvalidOperationException">
    ///     Could not find field <typeparamref name="TDeclaring" />.
    ///     <paramref name="fieldName" />.
    /// </exception>
    private static FieldInfo GetField <TDeclaring, TValue>(string fieldName)
    {
        if (fieldName == null)
        {
            throw new ArgumentNullException(nameof(fieldName));
        }

        if (string.IsNullOrWhiteSpace(fieldName))
        {
            throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(fieldName));
        }

        // get the field
        FieldInfo?field = typeof(TDeclaring).GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

        if (field == null)
        {
            throw new InvalidOperationException($"Could not find field {typeof(TDeclaring)}.{fieldName}.");
        }

        // validate field type
        if (field.FieldType != typeof(TValue))
        {
            throw new ArgumentException(
                      $"Value type {typeof(TValue)} does not match field {typeof(TDeclaring)}.{fieldName} type {field.FieldType}.");
        }

        return(field);
    }
Exemplo n.º 23
0
        internal static object?DetermineValue(
            object o,
            FieldInfo?fieldInfo,
            PropertyInfo?propertyInfo
            )
        {
            object?value;

            try
            {
                value = fieldInfo != null
                        ? fieldInfo.GetValue(o)
                        : propertyInfo !.GetValue(o, null)
                ;
            }
            catch (Exception excp)
            {
                var innerExceptionData =
                    excp.InnerException != null
                        ? string.Format(
                        ", InnerException={{{0}: \"{1}\"}}",
                        excp.InnerException.GetType().Name,
                        excp.InnerException.Message
                        )
                        : string.Empty
                ;

                value = $"{excp.GetType().Name}: \"{excp.Message}\"{innerExceptionData}";
            }

            return(value);
        }
        internal static FieldInfo GetField(FieldInfo Field, TypeBuilderInstantiation type)
        {
            FieldInfo?m = null;

            // This ifdef was introduced when non-generic collections were pulled from
            // silverlight. See code:Dictionary#DictionaryVersusHashtableThreadSafety
            // for information about this change.
            //
            // There is a pre-existing race condition in this code with the side effect
            // that the second thread's value clobbers the first in the hashtable. This is
            // an acceptable race condition since we make no guarantees that this will return the
            // same object.
            //
            // We're not entirely sure if this cache helps any specific scenarios, so
            // long-term, one could investigate whether it's needed. In any case, this
            // method isn't expected to be on any critical paths for performance.
            if (type.m_hashtable.Contains(Field))
            {
                m = (type.m_hashtable[Field] as FieldInfo) !;
            }
            else
            {
                m = new FieldOnTypeBuilderInstantiation(Field, type);
                type.m_hashtable[Field] = m;
            }

            return(m);
        }
Exemplo n.º 25
0
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty jsonProp = base.CreateProperty(member, memberSerialization);

            if (jsonProp.ShouldSerialize == null)
            {
                jsonProp.ShouldSerialize = entity =>
                {
                    if (member is PropertyInfo prop)
                    {
                        if (prop.PropertyType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(prop.PropertyType))
                        {
                            FieldInfo?backingField = entity.GetType().GetField($"<{member.Name}>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance);
                            if (backingField != null)
                            {
                                object?backingFieldValue = backingField.GetValue(entity);
                                if (backingFieldValue is IPersistentCollection persistentCollection)
                                {
                                    return(persistentCollection.WasInitialized);
                                }
                            }
                        }
                    }

                    return(NHibernateUtil.IsPropertyInitialized(entity, member.Name));
                };
            }

            return(jsonProp);
        }
Exemplo n.º 26
0
        public static void Matches(RoutedEventValues expectedValues)
        {
            string expectedFieldName = expectedValues.Name + "Event";

            FieldInfo?reFieldInfo = expectedValues.OwnerType.GetField(expectedFieldName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

            Assert.IsNotNull(reFieldInfo, $"Missing static routed event field `{expectedFieldName}`.");

            // Check routed event instance.
            RoutedEvent?routedEvent = reFieldInfo !.GetValue(null) as RoutedEvent;

            Assert.IsNotNull(routedEvent);

            Assert.AreEqual(expectedValues.OwnerType, routedEvent !.OwnerType);
            Assert.AreEqual(expectedValues.Name, routedEvent.Name);
            Assert.AreEqual(expectedValues.HandlerType, routedEvent.HandlerType);
            Assert.AreEqual(expectedValues.RoutingStrategy, routedEvent.RoutingStrategy);

            if (expectedValues.IsAttached)
            {
                // Check generated add/remove methods.
                _AssertMethod($"Add{expectedValues.Name}Handler");
                _AssertMethod($"Remove{expectedValues.Name}Handler");

                void _AssertMethod(string name)
                {
                    MethodInfo?methodInfo = expectedValues.OwnerType.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

                    // Exists?
                    Assert.IsNotNull(methodInfo, $"Missing method `{name}`.");

                    // Visibility?
                    Assert.IsTrue(methodInfo !.Attributes.HasFlag(expectedValues.Visibility));

                    // Parameters?
                    ParameterInfo[] parameters = methodInfo.GetParameters();
                    Assert.AreEqual(2, parameters.Length);

                    Type targetType = expectedValues.AttachmentNarrowingType ?? typeof(DependencyObject);

                    Assert.AreEqual(targetType, parameters[0].ParameterType);
                    Assert.AreEqual(expectedValues.HandlerType, parameters[1].ParameterType);
                }
            }
            else
            {
                // Check generated CLR event.
                EventInfo?clrEventEventInfo = expectedValues.OwnerType.GetEvent(expectedValues.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

                // Exists?
                Assert.IsNotNull(clrEventEventInfo, $"Missing CLR event `{expectedValues.Name}`.");

                // Visibility?
                Assert.IsTrue(clrEventEventInfo !.AddMethod !.Attributes.HasFlag(expectedValues.Visibility));

                // Type?
                Assert.AreEqual(expectedValues.HandlerType, clrEventEventInfo !.EventHandlerType);
            }
        }
Exemplo n.º 27
0
        public SlimProperty(
            string name,
            Type clrType,
            PropertyInfo?propertyInfo,
            FieldInfo?fieldInfo,
            SlimEntityType declaringEntityType,
            PropertyAccessMode propertyAccessMode,
            bool nullable,
            bool concurrencyToken,
            ValueGenerated valueGenerated,
            PropertySaveBehavior beforeSaveBehavior,
            PropertySaveBehavior afterSaveBehavior,
            int?maxLength,
            bool?unicode,
            int?precision,
            int?scale,
            Type?providerClrType,
            Func <IProperty, IEntityType, ValueGenerator>?valueGeneratorFactory,
            ValueConverter?valueConverter,
            ValueComparer?valueComparer,
            ValueComparer?keyValueComparer,
            CoreTypeMapping?typeMapping)
            : base(name, propertyInfo, fieldInfo, propertyAccessMode)
        {
            DeclaringEntityType    = declaringEntityType;
            ClrType                = clrType;
            _isNullable            = nullable;
            _isConcurrencyToken    = concurrencyToken;
            _valueGenerated        = valueGenerated;
            _beforeSaveBehavior    = beforeSaveBehavior;
            _afterSaveBehavior     = afterSaveBehavior;
            _valueGeneratorFactory = valueGeneratorFactory;
            _valueConverter        = valueConverter;

            if (maxLength != null)
            {
                SetAnnotation(CoreAnnotationNames.MaxLength, maxLength);
            }
            if (unicode != null)
            {
                SetAnnotation(CoreAnnotationNames.Unicode, unicode);
            }
            if (precision != null)
            {
                SetAnnotation(CoreAnnotationNames.Precision, precision);
            }
            if (scale != null)
            {
                SetAnnotation(CoreAnnotationNames.Scale, scale);
            }
            if (providerClrType != null)
            {
                SetAnnotation(CoreAnnotationNames.ProviderClrType, providerClrType);
            }

            _typeMapping      = typeMapping;
            _valueComparer    = valueComparer ?? TypeMapping.Comparer;
            _keyValueComparer = keyValueComparer ?? TypeMapping.KeyComparer;
        }
Exemplo n.º 28
0
 public DataMember(FieldInfo field)
 {
     _prop         = null;
     _field        = field;
     Name          = field.Name;
     DataType      = field.FieldType;
     DeclaringType = field.DeclaringType;
 }
Exemplo n.º 29
0
 public virtual void ProcessPropertyFieldChanged(
     IConventionPropertyBuilder propertyBuilder,
     FieldInfo?newFieldInfo,
     FieldInfo?oldFieldInfo,
     IConventionContext <FieldInfo> context)
 {
     Process(propertyBuilder, context);
 }
 public override FieldInfo?OnPropertyFieldChanged(
     IConventionPropertyBuilder propertyBuilder,
     FieldInfo?newFieldInfo,
     FieldInfo?oldFieldInfo)
 {
     Add(new OnPropertyFieldChangedNode(propertyBuilder, newFieldInfo, oldFieldInfo));
     return(newFieldInfo);
 }