protected override void VisitList(
            IList <object> list,
            ConverterContext context)
        {
            Type elementType = DotNetTypeInfoFactory
                               .GetInnerListType(context.ClrType);

            if (elementType != null)
            {
                Type  listType = typeof(List <>).MakeGenericType(elementType);
                IList temp     = (IList)Activator.CreateInstance(listType);

                for (int i = 0; i < list.Count; i++)
                {
                    var valueContext = new ConverterContext();
                    valueContext.ClrType = elementType;
                    Visit(list[i], valueContext);

                    temp.Add(valueContext.Object);
                }

                context.Object = context.ClrType.IsAssignableFrom(listType)
                    ? temp
                    : _converter.Convert(listType, context.ClrType, temp);
            }
        }
Exemple #2
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));
        }
        protected override void VisitListValue(
            ListValueNode node,
            ConverterContext context)
        {
            if (context.InputType.IsListType())
            {
                ListType listType = context.InputType.ListType();
                Type     tempType = listType.ToClrType();
                IList    temp     = (IList)Activator.CreateInstance(tempType);

                for (int i = 0; i < node.Items.Count; i++)
                {
                    var valueContext = new ConverterContext();
                    valueContext.InputType = (IInputType)listType.ElementType;
                    valueContext.ClrType   = listType.ElementType.ToClrType();

                    VisitValue(node.Items[i], valueContext);

                    temp.Add(valueContext.Object);
                }

                Type expectedType = context.ClrType == typeof(object)
                    ? typeof(List <object>)
                    : context.ClrType;

                context.Object = expectedType.IsAssignableFrom(tempType)
                    ? temp
                    : _converter.Convert(tempType, expectedType, temp);
            }
        }
        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);
        }
        public void Register_Multiple_TypeConverters_As_Service()
        {
            // arrange
            var services = new ServiceCollection();

            // act
            services.AddTypeConverter <int, string>(
                from => from.ToString() + "_123");
            services.AddTypeConverter <char, string>(
                from => from + "_123");

            // assert
            ITypeConversion conversion =
                services.BuildServiceProvider().GetService <ITypeConversion>();

            Assert.Equal("123_123", conversion.Convert <int, string>(123));
            Assert.Equal("a_123", conversion.Convert <char, string>('a'));
        }
        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);

                switch (operation.Kind)
                {
                case FilterOperationKind.In:
                    expression = FilterExpressionBuilder.In(
                        property,
                        operation.Property.PropertyType,
                        ParseValue());
                    return(true);

                case FilterOperationKind.NotIn:
                    expression = FilterExpressionBuilder.Not(
                        FilterExpressionBuilder.In(
                            property,
                            operation.Property.PropertyType,
                            ParseValue())
                        );
                    return(true);
                }
            }

            expression = null;
            return(false);

            object ParseValue()
            {
                var  parsedValue = type.ParseLiteral(value);
                Type elementType = type.ElementType().ToClrType();

                if (operation.Property.PropertyType != elementType)
                {
                    Type listType = typeof(List <>).MakeGenericType(
                        operation.Property.PropertyType);

                    parsedValue = converter.Convert(
                        typeof(object),
                        listType,
                        parsedValue);
                }

                return(parsedValue);
            }
        }
 private static Optional <T> CreateOptionalValue <T>(
     IReadOnlyDictionary <string, object> values,
     string fieldName,
     ITypeConversion converter)
 {
     if (values.TryGetValue(fieldName, out object o))
     {
         return(o is T casted ? casted : converter.Convert <object, T>(o));
     }
     return(default);
        public static TTo Convert <TFrom, TTo>(
            this ITypeConversion typeConversion,
            object source)
        {
            if (typeConversion == null)
            {
                throw new ArgumentNullException(nameof(typeConversion));
            }

            return((TTo)typeConversion.Convert(
                       typeof(TFrom), typeof(TTo), source));
        }
Exemple #9
0
 private void VisitLeaf(
     INamedInputType type, object obj,
     Action <object> setValue, ISet <object> processed)
 {
     if (type is IHasClrType hasClrType)
     {
         Type   currentType = obj.GetType();
         object normalized  = currentType == hasClrType.ClrType
             ? obj
             : _converter.Convert(currentType, hasClrType.ClrType, obj);
         setValue(obj);
     }
 }
Exemple #10
0
        public bool TryGetVariable <T>(NameString name, out T value)
        {
            name.EnsureNotEmpty("name");

            if (_variables.TryGetValue(name, out VariableValue variableValue))
            {
                object coercedValue = null;

                if (typeof(T) == typeof(object))
                {
                    coercedValue = variableValue.Literal == null
                        ? variableValue.Value
                        : variableValue.Literal;
                }
                else if (typeof(IValueNode).IsAssignableFrom(typeof(T)))
                {
                    if (variableValue.Literal == null)
                    {
                        coercedValue = variableValue.Type.ParseValue(variableValue.Value);
                    }
                    else
                    {
                        coercedValue = variableValue.Literal;
                    }
                }
                else
                {
                    if (variableValue.Literal == null)
                    {
                        coercedValue = variableValue.Value;
                    }
                    else
                    {
                        coercedValue = variableValue.Type.ParseLiteral(variableValue.Literal);
                    }
                }

                if (coercedValue is T castedValue)
                {
                    value = castedValue;
                }
                else
                {
                    value = (T)_converter.Convert(typeof(object), typeof(T), coercedValue);
                }
                return(true);
            }

            value = default;
            return(false);
        }
Exemple #11
0
        async Task <object> INodeResolver.ResolveAsync(
            IResolverContext context, object id)
        {
            if (id is TId c)
            {
                return(await ResolveAsync(context, c).ConfigureAwait(false));
            }

            ITypeConversion typeConversion =
                context.Service <IServiceProvider>().GetTypeConversion();

            c = typeConversion.Convert <object, TId>(id);
            return(await ResolveAsync(context, c).ConfigureAwait(false));
        }
        public void Register_TypeConverter_As_Service()
        {
            // arrange
            var services = new ServiceCollection();

            // act
            services.AddTypeConverter <IntToStringConverter>();

            // assert
            ITypeConversion conversion =
                services.BuildServiceProvider().GetService <ITypeConversion>();

            Assert.Equal("123_123", conversion.Convert <int, string>(123));
        }
        private object Normalize(
            ITypeConversion converter,
            IType type,
            object value)
        {
            if (value is null)
            {
                return(value);
            }

            if (type is IHasClrType leafType &&
                !leafType.ClrType.IsInstanceOfType(value))
            {
                return(converter.Convert(
                           typeof(object), leafType.ClrType,
                           value));
            }

            return(value);
        }
Exemple #14
0
        public bool TryGetVariable <T>(NameString name, out T value)
        {
            name.EnsureNotEmpty("name");

            if (_variables.TryGetValue(name, out object coercedValue))
            {
                if (coercedValue is T castedValue)
                {
                    value = castedValue;
                }
                else
                {
                    value = (T)_converter.Convert(
                        typeof(object), typeof(T), coercedValue);
                }
                return(true);
            }

            value = default;
            return(false);
        }
Exemple #15
0
        public void Convert_WithDependencyInjection()
        {
            // arrange
            var services = new ServiceCollection();

            services.AddSingleton <ITypeConversion, TypeConversion>();
            services.AddSingleton <ITypeConverter, DummyConverter>();
            services.AddSingleton <DummyDependency>();

            IServiceProvider serviceProvider = services.BuildServiceProvider();

            // act
            ITypeConversion conversion =
                serviceProvider.GetService <ITypeConversion>();
            string converted = conversion.Convert <bool, string>(true);

            // assert
            string foo = serviceProvider.GetService <DummyDependency>().Foo;

            Assert.Equal(foo, converted);
        }
Exemple #16
0
        public bool TryGetVariable <T>(string variableName, out T variableValue)
        {
            if (string.IsNullOrEmpty(variableName))
            {
                throw new ArgumentNullException(nameof(variableName));
            }

            if (_variables.TryGetValue(variableName, out object value))
            {
                if (value is T v)
                {
                    variableValue = v;
                }
                else
                {
                    variableValue = (T)_converter.Convert(
                        typeof(object), typeof(T), value);
                }
                return(true);
            }

            variableValue = default;
            return(false);
        }
        public bool TryHandle(
            FilterOperation operation,
            IInputType type,
            IValueNode value,
            Expression instance,
            ITypeConversion converter,
            out Expression expression)
        {
            if (operation.Type == typeof(IComparable) &&
                value is IValueNode <IComparable> s)
            {
                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);
                }

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

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

                case FilterOperationKind.GreaterThan:
                    expression = FilterExpressionBuilder.GreaterThan(
                        property, parsedValue);
                    return(true);

                case FilterOperationKind.NotGreaterThan:
                    expression = FilterExpressionBuilder.Not(
                        FilterExpressionBuilder.GreaterThan(
                            property, parsedValue)
                        );
                    return(true);

                case FilterOperationKind.GreaterThanOrEqual:
                    expression = FilterExpressionBuilder.GreaterThanOrEqual(
                        property, parsedValue);
                    return(true);

                case FilterOperationKind.NotGreaterThanOrEqual:
                    expression = FilterExpressionBuilder.Not(
                        FilterExpressionBuilder.GreaterThanOrEqual(
                            property, parsedValue)
                        );
                    return(true);

                case FilterOperationKind.LowerThan:
                    expression = FilterExpressionBuilder.LowerThan(
                        property, parsedValue);
                    return(true);

                case FilterOperationKind.NotLowerThan:
                    expression = FilterExpressionBuilder.Not(
                        FilterExpressionBuilder.LowerThan(
                            property, parsedValue));
                    return(true);

                case FilterOperationKind.LowerThanOrEqual:
                    expression = FilterExpressionBuilder.LowerThanOrEqual(
                        property, parsedValue);
                    return(true);

                case FilterOperationKind.NotLowerThanOrEqual:
                    expression = FilterExpressionBuilder.Not(
                        FilterExpressionBuilder.LowerThanOrEqual(
                            property, parsedValue));
                    return(true);
                }
            }

            if (operation.Type == typeof(IComparable) && value is ListValueNode li)
            {
                MemberExpression property =
                    Expression.Property(instance, operation.Property);
                var parsedValue = type.ParseLiteral(value);

                switch (operation.Kind)
                {
                case FilterOperationKind.In:
                    expression = FilterExpressionBuilder.In(
                        property,
                        operation.Property.PropertyType,
                        parsedValue);
                    return(true);

                case FilterOperationKind.NotIn:
                    expression = FilterExpressionBuilder.Not(
                        FilterExpressionBuilder.In(
                            property,
                            operation.Property.PropertyType,
                            parsedValue)
                        );
                    return(true);
                }
            }

            expression = null;
            return(false);
        }
Exemple #18
0
        private static void ResolveScopedVariableArguments(
            IResolverContext context,
            SelectionPathComponent component,
            IOutputField field,
            ICollection <VariableValue> variables)
        {
            ITypeConversion typeConversion =
                context.Service <IServiceProvider>()
                .GetTypeConversion();

            foreach (ArgumentNode argument in component.Arguments)
            {
                if (!field.Arguments.TryGetField(argument.Name.Value,
                                                 out IInputField arg))
                {
                    throw new QueryException(new Error
                    {
                        Message = string.Format(
                            CultureInfo.InvariantCulture,
                            StitchingResources
                            .DelegationMiddleware_ArgumentNotFound,
                            argument.Name.Value)
                    });
                }

                if (argument.Value is ScopedVariableNode sv)
                {
                    VariableValue variable =
                        _resolvers.Resolve(context, sv, arg.Type.ToTypeNode());

                    if (context.Schema.TryGetType(
                            arg.Type.NamedType().Name,
                            out INamedInputType inputType))
                    {
                        object value = variable.Value;

                        if (!inputType.IsInstanceOfType(value))
                        {
                            value = typeConversion.Convert(
                                typeof(object), inputType.ClrType, value);
                        }

                        variable = new VariableValue
                                   (
                            variable.Name,
                            variable.Type,
                            inputType.Serialize(value),
                            variable.DefaultValue
                                   );
                    }
                    else
                    {
                        // TODO : resources
                        throw new QueryException(
                                  ErrorBuilder.New()
                                  .SetMessage(string.Format(
                                                  CultureInfo.InvariantCulture,
                                                  "Serialize argument {0} of type {1}.",
                                                  arg.Name, arg.Type.Visualize()))
                                  .SetPath(context.Path)
                                  .Build());
                    }

                    variables.Add(variable);
                }
            }
        }