Esempio n. 1
0
        public ListType(IType elementType)
            : base(TypeKind.List)
        {
            if (elementType == null)
            {
                throw new ArgumentNullException(nameof(elementType));
            }

            if (elementType.IsListType())
            {
                throw new ArgumentException(
                          "It is not possible to put a list type into list type.",
                          nameof(elementType));
            }

            _isInputType = elementType.IsInputType();
            _inputType   = elementType as IInputType;

            ElementType = elementType;

            if (_isInputType && _inputType != null)
            {
                NativeType = CreateListType(_inputType.NativeType);
            }
        }
Esempio n. 2
0
 private void VisitValue(
     IInputType type, object obj,
     Action <object> setValue,
     ISet <object> processed)
 {
     if (obj is null)
     {
         setValue(null);
     }
     else if (type.IsListType())
     {
         VisitList(
             (ListType)type.ListType(),
             obj, setValue, processed);
     }
     else if (type.IsLeafType())
     {
         VisitLeaf(
             (INamedInputType)type.NamedType(),
             obj, setValue, processed);
     }
     else if (type.IsInputObjectType())
     {
         VisitInputObject(
             (InputObjectType)type.NamedType(),
             obj, setValue, processed);
     }
     else
     {
         throw new NotSupportedException();
     }
 }
Esempio n. 3
0
        public Dictionary <string, ArgumentValue> CoerceArgumentValues(
            ObjectType objectType,
            FieldSelection fieldSelection,
            VariableCollection variables)
        {
            Dictionary <string, ArgumentValue> coercedArgumentValues =
                new Dictionary <string, ArgumentValue>();

            Dictionary <string, IValueNode> argumentValues =
                fieldSelection.Node.Arguments
                .Where(t => t.Value != null)
                .ToDictionary(t => t.Name.Value, t => t.Value);

            foreach (InputField argument in fieldSelection.Field.Arguments.Values)
            {
                string     argumentName  = argument.Name;
                IInputType argumentType  = argument.Type;
                IValueNode defaultValue  = argument.DefaultValue;
                object     argumentValue = CoerceArgumentValue(
                    argumentName, argumentType, defaultValue,
                    variables, argumentValues);

                if (argumentType is NonNullType && argumentValue == null)
                {
                    throw new QueryException(new ArgumentError(
                                                 $"The argument type of '{argumentName}' is a non-null type.",
                                                 argumentName, fieldSelection.Node));
                }

                coercedArgumentValues[argumentName] = new ArgumentValue(
                    argumentType, argumentType.NativeType, argumentValue);
            }

            return(coercedArgumentValues);
        }
        public static bool EndsWith(
            FilterOperation operation,
            IInputType type,
            IValueNode value,
            IQueryableFilterVisitorContext context,
            [NotNullWhen(true)] out Expression?result)
        {
            object parsedValue = type.ParseLiteral(value);

            if (parsedValue == null)
            {
                context.ReportError(
                    ErrorHelper.CreateNonNullError(operation, type, value, context));

                result = null;
                return(false);
            }

            if (operation.Type == typeof(string) &&
                type.IsInstanceOfType(value))
            {
                Expression property = GetProperty(operation, context);

                result = FilterExpressionBuilder.EndsWith(property, parsedValue);
                return(true);
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
Esempio n. 5
0
        private static object ConvertValue(
            ITypeConversion converter,
            IInputType type,
            object value)
        {
            Type sourceType = typeof(object);

            if (type.IsListType() && value is IEnumerable <object> e)
            {
                if (e.Any())
                {
                    Type elementType = e.FirstOrDefault()?.GetType();
                    if (elementType != null)
                    {
                        sourceType =
                            typeof(IEnumerable <>).MakeGenericType(elementType);
                    }
                }
                else
                {
                    return(Activator.CreateInstance(type.ClrType));
                }
            }

            return(converter.Convert(sourceType, type.ClrType, value));
        }
Esempio n. 6
0
        public bool TryHandle(
            FilterOperation operation,
            IInputType type,
            IValueNode value,
            Expression instance,
            ITypeConversion converter,
            out Expression expression)
        {
            if (operation.Type == typeof(bool) &&
                type.IsInstanceOfType(value))
            {
                MemberExpression property =
                    Expression.Property(instance, operation.Property);

                object parserValue = type.ParseLiteral(value);

                switch (operation.Kind)
                {
                case FilterOperationKind.Equals:
                    expression = FilterExpressionBuilder.Equals(
                        property, parserValue);
                    return(true);

                case FilterOperationKind.NotEquals:
                    expression = FilterExpressionBuilder.Not(
                        FilterExpressionBuilder.Equals(
                            property, parserValue)
                        );
                    return(true);
                }
            }

            expression = null;
            return(false);
        }
        protected override void VisitList(
            IList <object> list,
            ConverterContext context)
        {
            if (!context.InputType.IsListType())
            {
                throw new QueryException(ErrorBuilder.New()
                                         .SetMessage($"The value of {context.Name} has a wrong structure.")
                                         .SetCode(ErrorCodes.Execution.InvalidType)
                                         .AddLocation(context.Node)
                                         .Build());
            }

            IInputType originalType = context.InputType;
            ListType   listType     = context.InputType.ListType();

            context.InputType = (IInputType)listType.ElementType;

            var items = new IValueNode[list.Count];

            for (int i = 0; i < list.Count; i++)
            {
                context.Object = null;
                Visit(list[i], context);
                items[i] = (IValueNode)context.Object;
            }

            context.Object    = new ListValueNode(items);
            context.InputType = originalType;
        }
Esempio n. 8
0
        private static void AddVariables(
            IResolverContext context,
            NameString schemaName,
            IQueryRequestBuilder builder,
            DocumentNode query,
            IEnumerable <VariableValue> variableValues)
        {
            OperationDefinitionNode operation =
                query.Definitions.OfType <OperationDefinitionNode>().First();
            var usedVariables = new HashSet <string>(
                operation.VariableDefinitions.Select(t =>
                                                     t.Variable.Name.Value));

            foreach (VariableValue variableValue in variableValues)
            {
                if (usedVariables.Contains(variableValue.Name))
                {
                    object value = variableValue.Value;

                    if (context.Schema.TryGetType(
                            variableValue.Type.NamedType().Name.Value,
                            out InputObjectType inputType))
                    {
                        IInputType wrapped = WrapType(inputType, variableValue.Type);
                        value = ObjectVariableRewriter.RewriteVariable(
                            schemaName, wrapped, value);
                    }

                    builder.AddVariableValue(variableValue.Name, value);
                }
            }
        }
Esempio n. 9
0
        private static object ParseListType(
            IInputType sourceType,
            Type targetType,
            IValueNode literal)
        {
            var           sourceElementType = (IInputType)sourceType.ElementType();
            Type          targetElementType = GetListElementType(targetType);
            List <object> items             = new List <object>();

            if (literal is ListValueNode lv)
            {
                foreach (IValueNode element in lv.Items)
                {
                    items.Add(ParseLiteral(
                                  sourceElementType, targetElementType,
                                  element));
                }
            }
            else
            {
                items.Add(ParseLiteral(
                              sourceElementType, targetElementType,
                              literal));
            }

            return(CreateListObject(targetType, targetElementType, items));
        }
Esempio n. 10
0
        internal void CompleteInputField(
            ITypeRegistry typeRegistry,
            Action <SchemaError> reportError,
            INamedType parentType)
        {
            _type = _typeFactory(typeRegistry);
            if (_type == null)
            {
                reportError(new SchemaError(
                                $"The type of the input field {Name} is null.",
                                parentType));
            }

            if (_defaultValueFactory == null)
            {
                DefaultValue = new NullValueNode(null);
            }
            else
            {
                DefaultValue = _defaultValueFactory(typeRegistry);
            }

            if (parentType is InputObjectType &&
                Property == null &&
                typeRegistry.TryGetTypeBinding(parentType, out InputObjectTypeBinding binding) &&
                binding.Fields.TryGetValue(Name, out InputFieldBinding fieldBinding))
            {
                Property = fieldBinding.Property;
            }
        }
        public VariableValue Resolve(
            IResolverContext context,
            ScopedVariableNode variable,
            IInputType targetType)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (variable is null)
            {
                throw new ArgumentNullException(nameof(variable));
            }

            if (_resolvers.TryGetValue(variable.Scope.Value, out IScopedVariableResolver? resolver))
            {
                return(resolver.Resolve(context, variable, targetType));
            }

            throw ThrowHelper.RootScopedVariableResolver_ScopeNotSupported(
                      variable.Scope.Value,
                      context.FieldSelection,
                      context.Path);
        }
Esempio n. 12
0
        public bool TryHandle(
            FilterOperation operation,
            IInputType type,
            IValueNode value,
            Expression instance,
            ITypeConversion converter,
            out Expression expression)
        {
            if (operation.Type == typeof(string) &&
                (value is StringValueNode || value.IsNull()))
            {
                object parsedValue = type.ParseLiteral(value);

                MemberExpression property =
                    Expression.Property(instance, operation.Property);

                return(TryCreateExpression(
                           operation,
                           property,
                           parsedValue,
                           out expression));
            }

            expression = null;
            return(false);
        }
        public VariableValue Resolve(
            IResolverContext context,
            ScopedVariableNode variable,
            IInputType targetType)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (variable == null)
            {
                throw new ArgumentNullException(nameof(variable));
            }

            if (!ScopeNames.Fields.Equals(variable.Scope.Value))
            {
                throw new ArgumentException(
                          StitchingResources
                          .FieldScopedVariableResolver_CannotHandleVariable,
                          nameof(variable));
            }

            if (context.ObjectType.Fields.TryGetField(variable.Name.Value, out IObjectField? field))
            {
                object parent = context.Parent <object>();

                IValueNode?valueLiteral = null;

                if (parent is IReadOnlyDictionary <string, object> dict &&
                    dict.TryGetValue(field.Name, out object?value))
                {
                    if (value is IValueNode v)
                    {
                        valueLiteral = v;
                    }
                    else if (field.Type.IsInputType() && field.Type is IInputType type)
                    {
                        valueLiteral = type.ParseValue(value);
                    }
                }

                return(new VariableValue
                       (
                           variable.ToVariableName(),
                           targetType.ToTypeNode(),
                           valueLiteral ?? NullValueNode.Default,
                           null
                       ));
            }

            throw new QueryException(ErrorBuilder.New()
                                     .SetMessage(
                                         StitchingResources.FieldScopedVariableResolver_InvalidFieldName,
                                         variable.Name.Value)
                                     .SetCode(ErrorCodes.Stitching.FieldNotDefined)
                                     .SetPath(context.Path)
                                     .AddLocation(context.FieldSelection)
                                     .Build());
        }
Esempio n. 14
0
 public static object RewriteVariable(
     NameString schemaName,
     IInputType type,
     object value)
 {
     return(RewriteVariableValue(in schemaName, type, value));
 }
 private static IValueNode ParseValue(
     HashSet <object> processed,
     IInputType inputType,
     object obj)
 {
     if (inputType.IsNonNullType())
     {
         return(ParseValue(processed,
                           (IInputType)inputType.InnerType(),
                           obj));
     }
     else if (inputType.IsListType())
     {
         return(ParseList(processed, inputType, obj));
     }
     else if (inputType.IsScalarType() || inputType.IsEnumType())
     {
         return(ParseScalar(inputType, obj));
     }
     else if (inputType.IsInputObjectType() &&
              !processed.Contains(obj))
     {
         return(ParseObject(processed, (InputObjectType)inputType, obj));
     }
     else
     {
         return(NullValueNode.Default);
     }
 }
Esempio n. 16
0
        public bool TryHandle(
            FilterOperation operation,
            IInputType type,
            IValueNode value,
            IQueryableFilterVisitorContext context,
            [NotNullWhen(true)] out Expression?expression)
        {
            if (operation.Type == typeof(bool) && type.IsInstanceOfType(value))
            {
                Expression property = context.GetInstance();

                if (!operation.IsSimpleArrayType())
                {
                    property = Expression.Property(context.GetInstance(), operation.Property);
                }

                object parserValue = type.ParseLiteral(value);

                switch (operation.Kind)
                {
                case FilterOperationKind.Equals:
                    expression = FilterExpressionBuilder.Equals(
                        property, parserValue);
                    return(true);

                case FilterOperationKind.NotEquals:
                    expression = FilterExpressionBuilder.NotEquals(
                        property, parserValue);
                    return(true);
                }
            }

            expression = null;
            return(false);
        }
Esempio n. 17
0
        public bool TryHandle(
            FilterOperation operation,
            IInputType type,
            IValueNode value,
            Expression instance,
            ITypeConversion converter,
            out Expression expression)
        {
            if (operation.Type == typeof(IComparable) &&
                type.IsInstanceOfType(value))
            {
                MemberExpression property = Expression.Property(instance, operation.Property);
                var parsedValue           = type.ParseLiteral(value);

                if (!operation.Property.PropertyType.IsInstanceOfType(parsedValue))
                {
                    parsedValue = converter.Convert(
                        typeof(object),
                        operation.Property.PropertyType,
                        parsedValue);
                }

                return(TryCreateExpression(
                           operation,
                           property,
                           parsedValue,
                           out expression));
            }

            expression = null;
            return(false);
        }
Esempio n. 18
0
        public VariableValue Resolve(
            IResolverContext context,
            ScopedVariableNode variable,
            IInputType targetType)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (variable == null)
            {
                throw new ArgumentNullException(nameof(variable));
            }

            if (_resolvers.TryGetValue(variable.Scope.Value,
                                       out IScopedVariableResolver resolver))
            {
                return(resolver.Resolve(context, variable, targetType));
            }

            throw new QueryException(ErrorBuilder.New()
                                     .SetMessage(
                                         StitchingResources.RootScopedVariableResolver_ScopeNotSupported,
                                         variable.Scope.Value)
                                     .SetCode(ErrorCodes.ScopeNotDefined)
                                     .SetPath(context.Path)
                                     .AddLocation(context.FieldSelection)
                                     .Build());
        }
        public bool TryHandle(
            FilterOperation operation,
            IInputType type,
            IValueNode value,
            IQueryableFilterVisitorContext context,
            out Expression expression)
        {
            if (operation.Type == typeof(string) &&
                type.IsInstanceOfType(value))
            {
                object parsedValue = type.ParseLiteral(value);

                Expression property = context.GetInstance();

                if (!operation.IsSimpleArrayType())
                {
                    property = Expression.Property(
                        context.GetInstance(), operation.Property);
                }

                return(TryCreateExpression(
                           operation,
                           property,
                           parsedValue,
                           out expression));
            }

            expression = null;
            return(false);
        }
Esempio n. 20
0
 private void CompleteDefaultValue(
     IInputType type,
     Action <SchemaError> reportError,
     INamedType parentType)
 {
     try
     {
         if (DefaultValue == null)
         {
             if (_nativeDefaultValue == null)
             {
                 DefaultValue = new NullValueNode();
             }
             else
             {
                 DefaultValue = type.ParseValue(_nativeDefaultValue);
             }
         }
     }
     catch (Exception ex)
     {
         reportError(new SchemaError(
                         "Could not parse the native value for input field " +
                         $"`{parentType.Name}.{Name}`.", parentType, ex));
     }
 }
Esempio n. 21
0
        public static IValueNode CreateDefaultValue(
            ICompletionContext context,
            ArgumentDefinition definition,
            IInputType fieldType)
        {
            try
            {
                if (definition.NativeDefaultValue != null)
                {
                    return(fieldType.ParseValue(
                               definition.NativeDefaultValue));
                }

                return(definition.DefaultValue.IsNull()
                    ? NullValueNode.Default
                    : definition.DefaultValue);
            }
            catch (Exception ex)
            {
                context.ReportError(SchemaErrorBuilder.New()
                                    .SetMessage(TypeResources.FieldInitHelper_InvalidDefaultValue)
                                    .SetCode(TypeErrorCodes.MissingType)
                                    .SetTypeSystemObject(context.Type)
                                    .AddSyntaxNode(definition.SyntaxNode)
                                    .SetException(ex)
                                    .Build());
                return(NullValueNode.Default);
            }
        }
Esempio n. 22
0
        public IValueNode Convert(object from, IInputType type, VariableDefinitionNode variable)
        {
            if (from == null)
            {
                throw new ArgumentNullException(nameof(from));
            }

            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (variable is null)
            {
                throw new ArgumentNullException(nameof(variable));
            }

            var context = new ConverterContext
            {
                InputType = type,
                Node      = variable,
                Name      = "$" + variable.Variable.Name.Value
            };

            Visit(from, context);
            return((IValueNode)context.Object);
        }
Esempio n. 23
0
 public static IValueNode CreateDefaultValue(
     ITypeCompletionContext context,
     ArgumentDefinition argumentDefinition,
     IInputType argumentType,
     FieldCoordinate argumentCoordinate)
 {
     try
     {
         return(argumentDefinition.NativeDefaultValue != null
             ? argumentType.ParseValue(argumentDefinition.NativeDefaultValue)
             : argumentDefinition.DefaultValue);
     }
     catch (Exception ex)
     {
         context.ReportError(SchemaErrorBuilder.New()
                             .SetMessage(
                                 TypeResources.FieldInitHelper_InvalidDefaultValue,
                                 argumentCoordinate)
                             .SetCode(ErrorCodes.Schema.MissingType)
                             .SetTypeSystemObject(context.Type)
                             .AddSyntaxNode(argumentDefinition.SyntaxNode)
                             .SetException(ex)
                             .Build());
         return(NullValueNode.Default);
     }
 }
Esempio n. 24
0
 public ArgumentValue(IInputType type, IError error)
 {
     Type    = type ?? throw new ArgumentNullException(nameof(type));
     Error   = error ?? throw new ArgumentNullException(nameof(error));
     Value   = null;
     Literal = null;
 }
Esempio n. 25
0
 internal static IValueNode?CompleteDefaultValue(
     ITypeCompletionContext context,
     ArgumentDefinition argumentDefinition,
     IInputType argumentType,
     FieldCoordinate argumentCoordinate)
 {
     try
     {
         return(argumentDefinition.RuntimeDefaultValue != null
             ? context.DescriptorContext.InputFormatter.FormatValue(
                    argumentDefinition.RuntimeDefaultValue,
                    argumentType,
                    Path.Root)
             : argumentDefinition.DefaultValue);
     }
     catch (Exception ex)
     {
         context.ReportError(SchemaErrorBuilder.New()
                             .SetMessage(
                                 TypeResources.FieldInitHelper_InvalidDefaultValue,
                                 argumentCoordinate)
                             .SetCode(ErrorCodes.Schema.MissingType)
                             .SetTypeSystemObject(context.Type)
                             .AddSyntaxNode(argumentDefinition.SyntaxNode)
                             .SetException(ex)
                             .Build());
         return(NullValueNode.Default);
     }
 }
Esempio n. 26
0
 public ArgumentValue(IInputType type, object value)
 {
     Type    = type ?? throw new ArgumentNullException(nameof(type));
     Value   = value;
     Error   = null;
     Literal = null;
 }
Esempio n. 27
0
 public Variable(
     string name,
     IInputType type,
     object defaultValue)
     : this(name, type, defaultValue, defaultValue)
 {
 }
 private static void HandleFieldValue(
     HashSet <object> processed,
     Dictionary <string, IValueNode> fieldValues,
     InputField field,
     IInputType fieldType,
     object fieldValue)
 {
     if (fieldValue == null)
     {
         fieldValues[field.Name] = NullValueNode.Default;
     }
     else if (fieldType.IsNonNullType())
     {
         HandleFieldValue(processed, fieldValues, field,
                          (IInputType)fieldType.InnerType(), fieldValue);
     }
     else if (fieldType.IsListType())
     {
         fieldValues[field.Name] = ParseList(
             processed, fieldType, fieldValue);
     }
     else if (fieldType.IsScalarType() || fieldType.IsEnumType())
     {
         fieldValues[field.Name] = ParseScalar(
             fieldType, fieldValue);
     }
     else if (fieldType.IsInputObjectType() &&
              !processed.Contains(fieldValue))
     {
         fieldValues[field.Name] = ParseObject(
             processed, (InputObjectType)fieldType, fieldValue);
     }
 }
Esempio n. 29
0
        public static IValueNode CreateDefaultValue(
            ICompletionContext context,
            ArgumentDefinition definition,
            IInputType fieldType)
        {
            try
            {
                if (definition.NativeDefaultValue != null)
                {
                    return(fieldType.ParseValue(
                               definition.NativeDefaultValue));
                }

                return(definition.DefaultValue.IsNull()
                    ? NullValueNode.Default
                    : definition.DefaultValue);
            }
            catch (Exception ex)
            {
                // TODO : RESOURCES
                context.ReportError(SchemaErrorBuilder.New()
                                    .SetMessage(
                                        "Could not parse the native value of input field " +
                                        $"`{context.Type.Name}.{definition.Name}`.")
                                    .SetCode(TypeErrorCodes.MissingType)
                                    .SetTypeSystemObject(context.Type)
                                    .AddSyntaxNode(definition.SyntaxNode)
                                    .SetException(ex)
                                    .Build());
                return(NullValueNode.Default);
            }
        }
        private IValueNode ReplaceVariable(
            VariableNode variable,
            IInputType type)
        {
            if (_variables.TryGetVariable(
                    variable.Name.Value,
                    out object v))
            {
                if (!type.ClrType.IsInstanceOfType(v) &&
                    !_typeConversion.TryConvert(
                        typeof(object),
                        type.ClrType,
                        v,
                        out v))
                {
                    throw new QueryException(
                              ErrorBuilder.New()
                              .SetMessage(CoreResources.VarRewriter_CannotConvert)
                              .SetCode(ErrorCodes.Utilities.NoConverter)
                              .AddLocation(variable)
                              .Build());
                }

                return(type.ParseValue(v));
            }

            return(type.ParseValue(null));
        }
        /// <summary>
        /// Creates a new feature.
        /// </summary>
        /// <param name="name">Unique name of the feature</param>
        /// <param name="defaultValue">Default value</param>
        /// <param name="displayName">Display name of the feature</param>
        /// <param name="description">A brief description for this feature</param>
        /// <param name="scope">Feature scope</param>
        /// <param name="inputType">Input type</param>
        public Feature Create(string name, string defaultValue, ILocalizableString displayName = null,
            ILocalizableString description = null, FeatureScopes scope = FeatureScopes.All, IInputType inputType = null)
        {
            if (Features.ContainsKey(name))
            {
                throw new OwException("There is already a feature with name: " + name);
            }

            var feature = new Feature(name, defaultValue, displayName, description, scope, inputType);
            Features[feature.Name] = feature;
            return feature;

        }
Esempio n. 32
0
        /// <summary>
        /// Creates a new feature.
        /// </summary>
        /// <param name="name">Unique name of the feature</param>
        /// <param name="defaultValue">Default value</param>
        /// <param name="displayName">Display name of the feature</param>
        /// <param name="description">A brief description for this feature</param>
        /// <param name="scope">Feature scope</param>
        /// <param name="inputType">Input type</param>
        public Feature(string name, string defaultValue, ILocalizableString displayName = null, ILocalizableString description = null, FeatureScopes scope = FeatureScopes.All, IInputType inputType = null)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            Name = name;
            DisplayName = displayName;
            Description = description;
            Scope = scope;
            DefaultValue = defaultValue;
            InputType = inputType ?? new CheckboxInputType();

            _children = new List<Feature>();
            Attributes = new Dictionary<string, object>();
        }
Esempio n. 33
0
 /// <summary>
 /// Adds a child feature.
 /// </summary>
 /// <returns>Returns newly created child feature</returns>
 public Feature CreateChildFeature(string name, string defaultValue, ILocalizableString displayName = null, ILocalizableString description = null, FeatureScopes scope = FeatureScopes.All, IInputType inputType = null)
 {
     var feature = new Feature(name, defaultValue, displayName, description, scope, inputType) { Parent = this };
     _children.Add(feature);
     return feature;
 }