private static ITypeReference CreateConnectionTypeRef( IDescriptorContext context, MemberInfo?resolverMember, Type?type, PagingOptions options) { // first we will try and infer the schema type from the collection. IExtendedType schemaType = PagingHelper.GetSchemaType( context.TypeInspector, resolverMember, type); // we need to ensure that the schema type is a valid output type. For this we create a // type info which decomposes the type into its logical type components and is able // to check if the named type component is really an output type. if (!context.TypeInspector.TryCreateTypeInfo(schemaType, out ITypeInfo? typeInfo) || !typeInfo.IsOutputType()) { throw PagingObjectFieldDescriptorExtensions_InvalidType(); } options = context.GetSettings(options); // once we have identified the correct type we will create the // paging result type from it. IExtendedType connectionType = context.TypeInspector.GetType( options.IncludeTotalCount ?? false ? typeof(ConnectionCountType <>).MakeGenericType(schemaType.Source) : typeof(ConnectionType <>).MakeGenericType(schemaType.Source)); // last but not leas we create a type reference that can be put on the field definition // to tell the type discovery that this field needs this result type. return(TypeReference.Create(connectionType, TypeContext.Output)); }
public static IDictionary <string, object?>?FindAnnotationAttributes(MemberInfo?element, string annotationName) { IDictionary <string, object?> attributes = new Dictionary <string, object?>(); CustomAttributeData? attributeData = GetAnnotation(element, annotationName); bool found = false; if (attributeData != null) { CollectAttributes(attributeData, attributes); found = true; } else { HashSet <string> visited = new HashSet <string>(); foreach (CustomAttributeData customAttributeData in CustomAttributeData.GetCustomAttributes(element)) { if (CollectAnnotationAttributes(customAttributeData.AttributeType, annotationName, visited, attributes)) { found = true; CollectAttributes(customAttributeData, attributes); } } } return(found ? attributes : null); }
/// <summary> /// Applies the offset paging middleware to the current field. /// </summary> /// <param name="descriptor"> /// The object field descriptor. /// </param> /// <param name="itemType"> /// The schema type representation of the item. /// </param> /// <param name="entityType"> /// The entity type represents the runtime type of the item. /// </param> /// <param name="resolvePagingProvider"> /// A delegate allowing to dynamically define a paging resolver for a field. /// </param> /// <param name="options"> /// The paging settings that shall be applied to this field. /// </param> /// <returns> /// Returns the field descriptor for chaining in other configurations. /// </returns> public static IObjectFieldDescriptor UseOffsetPaging( this IObjectFieldDescriptor descriptor, Type?itemType = null, Type?entityType = null, GetOffsetPagingProvider?resolvePagingProvider = null, PagingOptions options = default) { if (descriptor is null) { throw new ArgumentNullException(nameof(descriptor)); } resolvePagingProvider ??= ResolvePagingProvider; descriptor.AddOffsetPagingArguments(); PagingHelper.UsePaging( descriptor, entityType, (services, source, name) => resolvePagingProvider(services, source, name), options); descriptor .Extend() .OnBeforeCreate((c, d) => { MemberInfo?resolverMember = d.ResolverMember ?? d.Member; d.Type = CreateTypeRef(c, resolverMember, itemType, options); d.CustomSettings.Add(typeof(CollectionSegment)); }); return(descriptor); }
internal static JsonPropertyInfo CreateProperty( Type declaredPropertyType, MemberInfo?memberInfo, Type parentClassType, bool isVirtual, JsonConverter converter, JsonSerializerOptions options, JsonIgnoreCondition?ignoreCondition = null, JsonTypeInfo?jsonTypeInfo = null) { // Create the JsonPropertyInfo instance. JsonPropertyInfo jsonPropertyInfo = converter.CreateJsonPropertyInfo(); jsonPropertyInfo.Initialize( parentClassType, declaredPropertyType, converterStrategy: converter.ConverterStrategy, memberInfo, isVirtual, converter, ignoreCondition, options, jsonTypeInfo); return(jsonPropertyInfo); }
internal MethodCommandMessageHandlingMember( IMessageHandlingMember <T> @delegate, IDictionary <string, object?>?annotationAttributes ) : base(@delegate) { _routingKey = "".Equals(annotationAttributes?["routingKey"]) ? null : (string)annotationAttributes?["routingKey"] !; MemberInfo?executable = @delegate.Unwrap <MemberInfo>(); if ("".Equals(annotationAttributes?["commandName"])) { _commandName = @delegate.PayloadType().Name; } else { _commandName = (string)annotationAttributes?["commandName"] !; } bool factoryMethod = executable is MethodInfo methodInfo && methodInfo.IsStatic; if (executable?.DeclaringType != null && factoryMethod && !executable.DeclaringType.IsInstanceOfType(((MethodInfo)executable).ReturnType)) { throw new AseConfigurationException("static @CommandHandler methods must declare a return value " + "which is equal to or a subclass of the declaring type"); } _isFactoryHandler = executable is ConstructorInfo || factoryMethod; }
internal static void ValidateType(Type type, Type?parentClassType, MemberInfo?memberInfo, JsonSerializerOptions options) { if (IsInvalidForSerialization(type)) { ThrowHelper.ThrowInvalidOperationException_CannotSerializeInvalidType(type, parentClassType, memberInfo); } }
public void ConvertsNullToNullWithoutThrowingExceptionToSupportImplicitConversionRules() { Member <MemberInfo>? @null = null; MemberInfo? converted = @null; Assert.Null(converted); }
internal JsonPropertyInfo CreateProperty( Type declaredPropertyType, MemberInfo?memberInfo, Type parentClassType, bool isVirtual, JsonConverter converter, JsonSerializerOptions options, JsonIgnoreCondition?ignoreCondition = null, JsonTypeInfo?jsonTypeInfo = null, JsonConverter?customConverter = null, bool isUserDefinedProperty = false) { // Create the JsonPropertyInfo instance. JsonPropertyInfo jsonPropertyInfo = converter.CreateJsonPropertyInfo(parentTypeInfo: this); jsonPropertyInfo.Initialize( parentClassType, declaredPropertyType, converterStrategy: converter.ConverterStrategy, memberInfo, isVirtual, converter, ignoreCondition, options, jsonTypeInfo, isUserDefinedProperty: isUserDefinedProperty); jsonPropertyInfo.CustomConverter = customConverter; return(jsonPropertyInfo); }
/// <summary> /// Gets a collection of attributes for the specified class member. /// </summary> /// <typeparam name="TAttribute">Type of attribute.</typeparam> /// <typeparam name="TTarget">Type of object where need to find an attribute.</typeparam> /// <typeparam name="TMemberInfo">Type of the member info, for example: <see cref="PropertyInfo"/>.</typeparam> /// <param name="property">Member selector.</param> /// <param name="inherit">Include inherit attributes.</param> /// <returns>Collection of attributes.</returns> public static IEnumerable <TAttribute> GetAttributes <TAttribute, TTarget, TMemberInfo>(Expression <Func <TTarget, object?> > property, bool inherit) where TAttribute : Attribute where TMemberInfo : MemberInfo { var me = ExpressionHelper.GetMemberExpression(property); if (me != null) { var memberName = me.Member.Name; var memberInfoType = typeof(TMemberInfo); var ti = typeof(TTarget).GetTypeInfo(); MemberInfo?mi = null; if (typeof(PropertyInfo).IsAssignableFrom(memberInfoType)) { mi = ti.GetProperty(memberName); } else if (typeof(FieldInfo).IsAssignableFrom(memberInfoType)) { mi = ti.GetField(memberName); } else if (typeof(FieldInfo).IsAssignableFrom(memberInfoType)) { mi = ti.GetMethod(memberName); } if (mi != null) { return(mi.GetCustomAttributes <TAttribute>(inherit)); } } return(Enumerable.Empty <TAttribute>()); }
public override string?OnNavigationRemoved( IConventionEntityTypeBuilder sourceEntityTypeBuilder, IConventionEntityTypeBuilder targetEntityTypeBuilder, string navigationName, MemberInfo?memberInfo) { if (!sourceEntityTypeBuilder.Metadata.IsInModel) { return(null); } using (_dispatcher.DelayConventions()) { _stringConventionContext.ResetState(navigationName); foreach (var navigationConvention in _conventionSet.NavigationRemovedConventions) { if (sourceEntityTypeBuilder.Metadata.FindNavigation(navigationName) != null) { return(null); } navigationConvention.ProcessNavigationRemoved( sourceEntityTypeBuilder, targetEntityTypeBuilder, navigationName, memberInfo, _stringConventionContext); if (_stringConventionContext.ShouldStopProcessing()) { return(_stringConventionContext.Result); } } } return(sourceEntityTypeBuilder.Metadata.FindNavigation(navigationName) != null ? null : navigationName); }
internal ResultObject(object?o, DumpQuotas quotas, string?header = null, MemberInfo?member = null) { _quotas = quotas; _member = member; IsExpanded = quotas.MaxExpandedDepth > 0; Initialize(o, header); }
private void FindMember(IEnumerable <CommandMember>?members) { if (members == null) { Debug.Print("EventBinder: No Members: {0}", _dataContext); return; } var temp = members.FirstOrDefault(mem => mem.Name == _targetName); if (temp == null) { Debug.Print("EventBinder: No Valid Member found: {0}|{1}", _dataContext, _targetName); return; } _member = temp.MemberInfo; _sync = temp.Synchronize; try { _simpleConverter = temp.Converter != null?temp.Converter.FastCreateInstance() as TypeConverter : null; } catch (Exception e) { Debug.Print($"Error Bind Event: {e.GetType()}--{e.Message}"); } }
public static bool TryParseFromUserinfoBase64url(string userinfoBase64url, [NotNullWhen(true)] out MemberInfo?memberInfo) { if (TryParseFromUserinfoBase64url(userinfoBase64url, out var method, out var password)) { memberInfo = new(method, password); return(true); }
public static void DiscoverArguments( IDescriptorContext context, ICollection <ArgumentDefinition> arguments, MemberInfo?member) { if (arguments == null) { throw new ArgumentNullException(nameof(arguments)); } if (member is MethodInfo method) { var processed = new HashSet <NameString>( arguments.Select(t => t.Name)); foreach (ParameterInfo parameter in method.GetParameters()) { if (IsArgumentType(method, parameter)) { ArgumentDefinition argumentDefinition = ArgumentDescriptor .New(context, parameter) .CreateDefinition(); if (processed.Add(argumentDefinition.Name)) { arguments.Add(argumentDefinition); } } } } }
private static FieldSetter <TResult, TField> CompileSetter(MemberInfo?memberInfo) { var result = Expression.Parameter(typeof(TResult).MakeByRefType()); Expression target; if (memberInfo == null) { target = result; } else if (memberInfo is FieldInfo fieldInfo) { target = Expression.Field(result, fieldInfo); } else if (memberInfo is PropertyInfo propertyInfo) { target = Expression.Property(result, propertyInfo); } else { throw new ArgumentException($"Cannot set value of {memberInfo.DeclaringType?.Name}.{memberInfo.Name}"); } var value = Expression.Parameter(typeof(TField)); var assignment = Expression.Assign(target, value); var lambda = Expression.Lambda <FieldSetter <TResult, TField> >(assignment, result, value); return(lambda.Compile()); }
public static MemberInfo?GetNestedMember(this Type type, string path) { var currentType = type; MemberInfo?currentMember = null; foreach (var memberName in path.Split('.')) { var property = GetProperty(currentType, memberName); if (property != null) { currentMember = property; currentType = property.PropertyType; continue; } var field = GetField(currentType, memberName); if (field != null) { currentMember = field; currentType = field.FieldType; continue; } var method = GetMethod(currentType, memberName); if (method != null) //If we found a method just return it { return(method); } return(null); } return(currentMember); }
internal static JsonPropertyInfo CreateProperty( Type declaredPropertyType, Type?runtimePropertyType, MemberInfo?memberInfo, Type parentClassType, JsonConverter converter, JsonSerializerOptions options, JsonNumberHandling?parentTypeNumberHandling = null, JsonIgnoreCondition?ignoreCondition = null) { // Create the JsonPropertyInfo instance. JsonPropertyInfo jsonPropertyInfo = converter.CreateJsonPropertyInfo(); jsonPropertyInfo.Initialize( parentClassType, declaredPropertyType, runtimePropertyType, runtimeClassType: converter.ClassType, memberInfo, converter, ignoreCondition, parentTypeNumberHandling, options); return(jsonPropertyInfo); }
static ObjectMemberSharedInfo CreateItem(ObjectConverter item, IntermediateItem intermediate, MapGenerator gen) { var dest = new ObjectMemberSharedInfo(); MemberInfo?memberInfo = intermediate.Details.Unprocessed; Type itemType; if (memberInfo is FieldInfo field) { itemType = field.FieldType; MemberAccessorGenerator.GenerateFieldAccessor(ref dest.Accessor, memberInfo); } else if (memberInfo is PropertyInfo property) { itemType = property.PropertyType; MemberAccessorGenerator.GeneratePropertyAccessor(gen, dest, property, item); } else { throw new Exception("Unrecognized member info in shared info"); } dest.Map = gen.GetMap(itemType); return(dest); }
/// <summary> /// Get Specified property or field member info of provided type /// </summary> /// <param name="type">Type to retrieve property from</param> /// <param name="propertyOrFieldName">Name of property or field</param> static MemberInfo GetPropertyOrField(Type type, string propertyOrFieldName) { // Member search binding flags const BindingFlags bindingFlagsPublic = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy; const BindingFlags bindingFlagsNonPublic = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy; // Attempt to get the public property MemberInfo?propertyOrField = type.GetProperty(propertyOrFieldName, bindingFlagsPublic); // If not found if (propertyOrField == null) { // Attempt to get public field propertyOrField = type.GetField(propertyOrFieldName, bindingFlagsPublic); } // If not found if (propertyOrField == null) { // Attempt to get non-public property propertyOrField = type.GetProperty(propertyOrFieldName, bindingFlagsNonPublic); } // If not found if (propertyOrField == null) { // Attempt to get non-public property propertyOrField = type.GetField(propertyOrFieldName, bindingFlagsNonPublic); } // If property/ field was not resolved if (propertyOrField == null && type.IsInterface) { // Get All the implemented interfaces of the type var baseInterfaces = new List <Type>(type.GetInterfaces()); // Iterate over inherited interfaces foreach (var baseInterfaceType in baseInterfaces) { // Recurse looking in the parent interface for the property propertyOrField = GetPropertyOrField(baseInterfaceType, propertyOrFieldName); // If property found if (propertyOrField != null) { // Break execution break; } } } // If property is still empty if (propertyOrField == null) { // Property does not exist on current type throw new ArgumentException($"'{propertyOrFieldName}' is not a member of type {type.FullName}"); } return(propertyOrField); }
public IObjectFieldDescriptor ResolveNodeWith <TResolver>( Expression <Func <TResolver, object?> > method) { if (method is null) { throw new ArgumentNullException(nameof(method)); } MemberInfo?member = method.TryExtractMember(); if (member is MethodInfo m) { FieldResolverDelegates resolver = Context.ResolverCompiler.CompileResolve( m, typeof(object), typeof(TResolver), ParameterExpressionBuilders); return(ResolveNode(resolver.Resolver !)); } throw new ArgumentException( TypeResources.NodeDescriptor_MustBeMethod, nameof(member)); }
internal void Fixup(ParseRecord record, ParseRecord parent) { object?obj = record._newObj; switch (_valueFixupEnum) { case ValueFixupEnum.Array: _arrayObj !.SetValue(obj, _indexMap !); break; case ValueFixupEnum.Header: throw new PlatformNotSupportedException(); case ValueFixupEnum.Member: Debug.Assert(_objectInfo !._objectManager != null); if (_objectInfo._isSi) { _objectInfo._objectManager.RecordDelayedFixup(parent._objectId, _memberName !, record._objectId); } else { MemberInfo?memberInfo = _objectInfo.GetMemberInfo(_memberName); if (memberInfo != null) { _objectInfo._objectManager.RecordFixup(parent._objectId, memberInfo, record._objectId); } } break; } }
public override void OnConfigure( IDescriptorContext context, IObjectTypeDescriptor descriptor, Type type) { var nodeDescriptor = new NodeDescriptor(descriptor, type); descriptor.Extend().OnBeforeCreate(definition => { // since we bind the id field late we need to hint to the type discovery // that we will need the ID scalar. definition.Dependencies.Add( TypeDependency.FromSchemaType( context.TypeInspector.GetType(typeof(IdType)))); }); descriptor.Extend().OnBeforeCompletion((descriptorContext, definition) => { // first we try to resolve the id field. if (IdField is not null) { MemberInfo?idField = type.GetMember(IdField).FirstOrDefault(); if (idField is null) { throw NodeAttribute_IdFieldNotFound(type, IdField); } nodeDescriptor.IdField(idField); } else if (context.TypeInspector.GetNodeIdMember(type) is { } id) { nodeDescriptor.IdField(id); }
Expression ConvertAssignmentArgument(IBuildContext context, Expression expr, MemberInfo?memberInfo, bool enforceServerSide, string?alias) { var resultExpr = expr; resultExpr = CorrectConditional(context, resultExpr, enforceServerSide, alias); // Update nullability resultExpr = resultExpr.Transform(UpdateNullabilityFromExtension); if (resultExpr.NodeType == ExpressionType.Convert || resultExpr.NodeType == ExpressionType.ConvertChecked) { var conv = (UnaryExpression)resultExpr; if (memberInfo?.GetMemberType().IsNullable() == true && conv.Operand is ConvertFromDataReaderExpression readerExpression && !readerExpression.Type.IsNullable()) { resultExpr = readerExpression.MakeNullable(); } } else if (resultExpr.NodeType == ExpressionType.Extension && resultExpr is ConvertFromDataReaderExpression readerExpression) { if (memberInfo?.GetMemberType().IsNullable() == true && !readerExpression.Type.IsNullable()) { resultExpr = readerExpression.MakeNullable(); } } return(resultExpr); }
public static IExtendedType GetSchemaType( ITypeInspector typeInspector, MemberInfo?member, Type?type) { if (type is null && member is not null && typeInspector.GetOutputReturnTypeRef(member) is ExtendedTypeReference r && typeInspector.TryCreateTypeInfo(r.Type, out ITypeInfo? typeInfo)) { // if the member has already associated a schema type with an attribute for instance // we will just take it. Since we want the entity element we are going to take // the element type of the list or array as our entity type. if (r.Type.IsSchemaType && r.Type.IsArrayOrList) { return(r.Type.ElementType !); } // if the member type is unknown we will try to infer it by extracting // the named type component from it and running the type inference. // It might be that we either are unable to infer or get the wrong type // in special cases. In the case we are getting it wrong the user has // to explicitly bind the type. if (SchemaTypeResolver.TryInferSchemaType( typeInspector, r.WithType(typeInspector.GetType(typeInfo.NamedType)), out ExtendedTypeReference schemaTypeRef)) { // if we are able to infer the type we will reconstruct its structure so that // we can correctly extract from it the element type with the correct // nullability information. Type current = schemaTypeRef.Type.Type; foreach (TypeComponent component in typeInfo.Components.Reverse().Skip(1)) { if (component.Kind == TypeComponentKind.NonNull) { current = typeof(NonNullType <>).MakeGenericType(current); } else if (component.Kind == TypeComponentKind.List) { current = typeof(ListType <>).MakeGenericType(current); } } if (typeInspector.GetType(current) is { IsArrayOrList : true } schemaType) { return(schemaType.ElementType !); } } } if (type is null || !typeof(IType).IsAssignableFrom(type)) { throw ThrowHelper.UsePagingAttribute_NodeTypeUnknown(member); } return(typeInspector.GetType(type)); }
/// <summary> /// 获取枚举上的<see cref="DescriptionAttribute" />的Description值 /// </summary> /// <param name="value"></param> /// <returns>如果DescriptionAttribute不存在或Description为null则返回null</returns> public static string?GetDescription(this Enum value) { Check.NotNull(value); MemberInfo?memberInfo = value.GetType().GetMember(value.ToString(), MemberTypes.Field, BindingFlags.Public | BindingFlags.Static).FirstOrDefault(); return(memberInfo?.GetCustomAttribute <DescriptionAttribute>()?.Description); }
private Tuple <MethodInfo, MemberInfo?>?FindCommandPair([NotNull] IReflect targetType, out bool finded) { finded = false; var methods = targetType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); var main = (from method in methods let attr = method.GetCustomAttribute <CommandTargetAttribute>() where attr != null && attr.ProvideMemberName(method) == Name select new { Method = method, IsSync = attr.Synchronize }).FirstOrDefault(); if (main == null) { Debug.Print($"CommandBinder: No Command-Method Found: {Name}"); return(null); } finded = true; _isSync = main.IsSync; var mainAttr = main.Method.GetCustomAttribute <CommandTargetAttribute>(); MemberInfo?second = null; foreach (var m in targetType.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { var attr = m.GetCustomAttribute <CommandTargetAttribute>(); if (attr == null) { continue; } var name = attr.ProvideMemberName(m); if (mainAttr?.CanExecuteMember != null) { if (mainAttr.CanExecuteMember != name) { continue; } } else { if (Name != name && m == main.Method) { continue; } if ("Can" + Name != name) { continue; } } second = m; break; } return(Tuple.Create(main.Method, second)); }
protected MemberRef(TypeRef declaringType, MemberInfo memberInfo) { Requires.NotNull(declaringType, nameof(declaringType)); Requires.NotNull(memberInfo, nameof(memberInfo)); this.DeclaringType = declaringType; this.cachedMemberInfo = memberInfo; this.IsStatic = memberInfo.IsStatic(); }
public override string OnNavigationRemoved( IConventionEntityTypeBuilder sourceEntityTypeBuilder, IConventionEntityTypeBuilder targetEntityTypeBuilder, string navigationName, MemberInfo?memberInfo) { Add(new OnNavigationRemovedNode(sourceEntityTypeBuilder, targetEntityTypeBuilder, navigationName, memberInfo)); return(navigationName); }
public static void ThrowInvalidOperationException_NumberHandlingOnPropertyInvalid(JsonPropertyInfo jsonPropertyInfo) { MemberInfo?memberInfo = jsonPropertyInfo.MemberInfo; Debug.Assert(memberInfo != null); Debug.Assert(!jsonPropertyInfo.IsForTypeInfo); throw new InvalidOperationException(SR.Format(SR.NumberHandlingOnPropertyInvalid, memberInfo.Name, memberInfo.DeclaringType)); }
private static Action CreateAction <TResult>(object?obj, MemberInfo?memberInfo, TResult newValue) { TResult oldValue; switch (memberInfo) { case PropertyInfo propertyInfo: oldValue = (TResult)propertyInfo.GetMethod.Invoke(obj, Array.Empty <object>()); propertyInfo.SetMethod.Invoke(obj, new object[] { newValue ! });