/// <summary>
        ///     Bind to the given model type
        /// </summary>
        /// <param name="context">Current context</param>
        /// <param name="modelType">Model type to bind to</param>
        /// <param name="instance">Optional existing instance</param>
        /// <param name="configuration">The <see cref="BindingConfig" /> that should be applied during binding.</param>
        /// <param name="blackList">Blacklisted property names</param>
        /// <returns>Bound model</returns>
        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration,
            params string[] blackList)
        {
            Type genericType = null;
            if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable())
            {
                //make sure it has a generic type
                if (modelType.IsGenericType())
                {
                    genericType = modelType.GetGenericArguments().FirstOrDefault();
                }
                else
                {
                    var implementingIEnumerableType =
                        modelType.GetInterfaces().Where(i => i.IsGenericType()).FirstOrDefault(
                            i => i.GetGenericTypeDefinition() == typeof (IEnumerable<>));
                    genericType = implementingIEnumerableType == null ? null : implementingIEnumerableType.GetGenericArguments().FirstOrDefault();
                }

                if (genericType == null)
                {
                    throw new ArgumentException("When modelType is an enumerable it must specify the type", "modelType");
                }
            }

            var bindingContext =
                CreateBindingContext(context, modelType, instance, configuration, blackList, genericType);

            var bodyDeserializedModel = DeserializeRequestBody(bindingContext);

            return (instance as IEnumerable<string>) ?? bodyDeserializedModel;
        }
Example #2
0
        protected override void DefinePorts()
        {
            if (returnType != null)
            {
                if (returnType.IsEnumerable())
                {
                    enter = ControlInput("enter", OnEnterCoroutine);
                    if (yieldable != null)
                    {
                        if (yieldable.@yield)
                        {
                            exit = ControlOutput("exit");
                        }
                    }
                }
                else
                {
                    enter = ControlInput("enter", OnEnter);
                }

                if (returnType != typeof(Void))
                {
                    returns = ValueInput(returnType, "returns");
                }
            }
        }
Example #3
0
        /// <summary>
        /// Convert the string representation to the destination type
        /// </summary>
        /// <param name="input">Input string</param>
        /// <param name="destinationType">Destination type</param>
        /// <param name="context">Current context</param>
        /// <returns>Converted object of the destination type</returns>
        public object Convert(string input, Type destinationType, BindingContext context)
        {
            if (string.IsNullOrEmpty(input))
            {
                return null;
            }

            var items = input.Split(',');

            // Strategy, schmategy ;-)
            if (destinationType.IsCollection())
            {
                return this.ConvertCollection(items, destinationType, context);
            }

            if (destinationType.IsArray())
            {
                return this.ConvertArray(items, destinationType, context);
            }

            if (destinationType.IsEnumerable())
            {
                return this.ConvertEnumerable(items, destinationType, context);
            }

            return null;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="IncludePathMetadataFragment"/> class that has the given declaring type, property type, and property access expression.
 /// </summary>
 /// <param name="declaringType">The <see cref="System.Type"/> that contains the represented property as a member.</param>
 /// <param name="propertyType">The <see cref="System.Type"/> of the represented property.</param>
 /// <param name="propertyAccessExpression">The <see cref="System.Linq.Expressions.MemberExpression"/> used to access the represented property.</param>
 public IncludePathMetadataFragment(Type declaringType, Type propertyType, MemberExpression propertyAccessExpression)
 {
     DeclaringType = declaringType;
     IsEnumerable = propertyType.IsEnumerable();
     PropertyAccessExpression = propertyAccessExpression;
     PropertySingularType = propertyType.ToSingleType();
     PropertyType = propertyType;
 }
Example #5
0
        public static bool IsDefactoComplexType(Type type)
        {
            if (type.IsString())
                return false;

            if (type.IsEnumerable())
                return true;

            return (type.IsClass || type.IsInterface || type.IsEnum);
        }
        public Expression BuildSource(Expression expression, Type destinationType, IMappingConfiguration mappingConfiguration)
        {
            if (!expression.Type.IsEnumerable() || !destinationType.IsEnumerable())
                return null;

            var isArray = destinationType.IsArray;
            var sourceElementType = TypeUtils.GetElementTypeOfEnumerable(expression.Type);
            var destinationElementType = TypeUtils.GetElementTypeOfEnumerable(destinationType);
            return Expression.Convert(CreateSelect(mappingConfiguration, sourceElementType, destinationElementType, expression, isArray ? "ToArray" : "ToList"), destinationType);
        }
        /// <summary>
        /// Determines if the type specified is a nullable type
        /// </summary>
        /// <param name="type">The type to check</param>
        /// <returns>True, if the type is nullable; otherwise false</returns>
        /// <exception cref="System.Reflection.TargetInvocationException"></exception>
        public static bool IsNullableType(this Type type)
        {
            Validate.IsNotNull(type);

            if (type.IsEnumerable())
            {
                return(false);
            }
            else
            {
                return(false == type.IsValueType || (Nullable.GetUnderlyingType(type) != null));
            }
        }
Example #8
0
 public static Type GetEnumerableType(this Type t)
 {
     if (t.IsEnumerableT())
     {
         return(t.GetInterface(typeof(IEnumerable <>).Name)
                .GenericTypeArguments[0]);
     }
     else if (t.IsEnumerable())
     {
         return(typeof(object));
     }
     return(null);
 }
        private static Type SimplifyType(Type type)
        {
            if (type.IsEnumerable())
            {
                Type elementType = type.ExtractEnumerableElementType();

                if (elementType != null)
                {
                    return typeof (IEnumerable<>).MakeGenericType(elementType);
                }
            }

            return type;
        }
 private static bool IsTypeOfInterest(Type type)
 {
     return type.IsEnumerable() &&
            (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof (IEnumerable<>));
 }
Example #11
0
        private ModelSpec CreateModelSpec(Type type)
        {
            // Primitives, incl. enums
            if (_predefinedTypeMap.ContainsKey(type))
                return _predefinedTypeMap[type];

            if (type.IsEnum)
                return new ModelSpec
                    {
                        Type = "string",
                        Enum = type.GetEnumNames()
                    };

            Type enumerableTypeArgument;
            if (type.IsEnumerable(out enumerableTypeArgument))
                return CreateContainerSpec(enumerableTypeArgument);

            Type nullableTypeArgument;
            if (type.IsNullable(out nullableTypeArgument))
                return FindOrCreateFor(nullableTypeArgument);

            return CreateComplexSpec(type);
        }
 public void should_indicate_if_type_is_enumerable(Type type)
 {
     type.IsEnumerable().ShouldBeTrue();
 }
        public bool HasPayload(Type type)
        {
            if (type.IsEnumerable())
            {
                type = type.GetEnumerableType();
            }

            return IsPayload(type);
        }
        private DataType GetOrRegister(Type type, bool deferIfComplex, Queue<Type> deferredTypes)
        {
            if (_customMappings.ContainsKey(type))
                return _customMappings[type]();

            if (IndeterminateMappings.ContainsKey(type))
                return IndeterminateMappings[type]();

            if (PrimitiveMappings.ContainsKey(type))
                return PrimitiveMappings[type]();

            if (type.IsEnum)
                return new DataType { Type = "string", Enum = type.GetEnumNames() };

            Type innerType;
            if (type.IsNullable(out innerType))
                return GetOrRegister(innerType, deferIfComplex, deferredTypes);

            Type itemType;
            if (type.IsEnumerable(out itemType))
            {
                if (itemType.IsEnumerable() && !IsSupportedEnumerableItem(itemType))
                    throw new InvalidOperationException(
                        String.Format("Type {0} is not supported. Swagger does not support containers of containers", type));

                return new DataType { Type = "array", Items = GetOrRegister(itemType, true, deferredTypes) };
            }

            // Anthing else is complex
            if (deferIfComplex)
            {
                if (!_complexMappings.ContainsKey(type))
                    deferredTypes.Enqueue(type);

                // Just return a reference for now
                return new DataType { Ref = UniqueIdFor(type) };
            }

            return _complexMappings.GetOrAdd(type, () => CreateComplexDataType(type, deferredTypes));
        }
Example #15
0
        public void IsEnumerableTest(Type type, bool expectedResult)
        {
            var result = type.IsEnumerable();

            Assert.AreEqual(expectedResult, result, "Check for enumerable type has failed.");
        }
 public void IsEnumerableDoesNotDetectCertainTypesOfCollections(Type type)
 {
     Assert.False(type.IsEnumerable());
 }
Example #17
0
        private DataType CreateDataType(Type type, bool deferIfComplex, IDictionary<Type, DataType> complexMappings)
        {
            if (_customMappings.ContainsKey(type))
                return _customMappings[type];

            if (StaticMappings.ContainsKey(type))
                return StaticMappings[type];

            if (type.IsEnum)
                return new DataType { Type = "string", Enum = type.GetEnumNames() };

            Type innerType;
            if (type.IsNullable(out innerType))
                return CreateDataType(innerType, deferIfComplex, complexMappings);

            Type itemType;
            if (type.IsEnumerable(out itemType))
                return new DataType { Type = "array", Items = CreateDataType(itemType, true, complexMappings) };

            // Anthing else is complex

            if (deferIfComplex)
            {
                if (!complexMappings.ContainsKey(type))
                    complexMappings.Add(type, null);

                // Just return a reference for now
                return new DataType { Ref = UniqueIdFor(type) };
            }

            return CreateComplexDataType(type, complexMappings);
        }
Example #18
0
 public static Type GetElementType(Type seqType)
 {
     if (seqType.IsEnumerable())
     {
         var ienum = FindIEnumerable(seqType);
         return ienum == null ? seqType : ienum.GetGenericArguments()[0];
     }
     if (seqType.IsSymbols())
     {
         return seqType.GetGenericArguments()[0];
     }
     return seqType.IsSymbol() ? seqType.GetGenericArguments()[0] : seqType;
 }
        public object Decompress(object payload, Type expected)
        {
            if (payload != null)
            {
                PayloadDescriptor payloadDescriptor;
                var enumerable = false;

                if (expected.IsEnumerable())
                {
                    enumerable = true;
                    payloadDescriptor = _provider.GetPayload(expected.GetEnumerableType());
                }
                else
                {
                    payloadDescriptor = _provider.GetPayload(expected);
                }

                // Check if our payload object is actually a payload
                if (payloadDescriptor != null)
                {
                    if (enumerable)
                    {
                        IList list = null;

                        // Arrays have no default constructor so cannot be created by the Activator
                        if (expected.IsArray)
                        {
                            list = new List<object>();
                        }
                        else
                        {
                            list = Activator.CreateInstance(expected) as IList;
                        }

                        var compressedPayload = payload as object[];

                        foreach (object data in compressedPayload)
                        {
                            list.Add(Decompress(ConvertToObjectArray(data), payloadDescriptor));
                        }

                        if (expected.IsArray)
                        {
                            var arr = Array.CreateInstance(expected.GetEnumerableType(), list.Count);

                            list.CopyTo(arr, 0);

                            return arr;
                        }

                        return list;
                    }
                    else
                    {
                        return Decompress(payload, payloadDescriptor);
                    }
                }
            }

            return payload;
        }
 public override bool CanWriteType(Type type)
 {
     return type.IsEnumerable();
 }
Example #21
0
 /// <summary>
 /// Whether the converter can convert to the destination type
 /// </summary>
 /// <param name="destinationType">Destination type</param>
 /// <param name="context">The current binding context</param>
 /// <returns>True if conversion supported, false otherwise</returns>
 public bool CanConvertTo(Type destinationType, BindingContext context)
 {
     return destinationType.IsCollection() || destinationType.IsEnumerable() || destinationType.IsArray();
 }
Example #22
0
        /// <summary>
        /// Bind to the given model type
        /// </summary>
        /// <param name="context">Current context</param>
        /// <param name="modelType">Model type to bind to</param>
        /// <param name="instance">Optional existing instance</param>
        /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param>
        /// <param name="blackList">Blacklisted property names</param>
        /// <returns>Bound model</returns>
        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
        {
            Type genericType = null;
            if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable())
            {
                //make sure it has a generic type
                if (modelType.IsGenericType())
                {
                    genericType = modelType.GetGenericArguments().FirstOrDefault();
                }
                else
                {
                    var ienumerable =
                        modelType.GetInterfaces().Where(i => i.IsGenericType()).FirstOrDefault(
                            i => i.GetGenericTypeDefinition() == typeof(IEnumerable<>));
                    genericType = ienumerable == null ? null : ienumerable.GetGenericArguments().FirstOrDefault();
                }

                if (genericType == null)
                {
                    throw new ArgumentException("when modeltype is an enumerble it must specify the type", "modelType");
                }
            }

            var bindingContext =
                this.CreateBindingContext(context, modelType, instance, configuration, blackList, genericType);

            var bodyDeserializedModel = this.DeserializeRequestBody(bindingContext);

            if (bodyDeserializedModel != null)
            {
                UpdateModelWithDeserializedModel(bodyDeserializedModel, bindingContext);
            }

            var bindingExceptions = new List<PropertyBindingException>();

            if (!bindingContext.Configuration.BodyOnly)
            {
                if (bindingContext.DestinationType.IsCollection() || bindingContext.DestinationType.IsArray() ||
                    bindingContext.DestinationType.IsEnumerable())
                {
                    var loopCount = GetBindingListInstanceCount(context);
                    var model = (IList)bindingContext.Model;
                    for (var i = 0; i < loopCount; i++)
                    {
                        object genericinstance;
                        if (model.Count > i)
                        {
                            genericinstance = model[i];
                        }
                        else
                        {
                            genericinstance = Activator.CreateInstance(bindingContext.GenericType);
                            model.Add(genericinstance);
                        }

                        foreach (var modelProperty in bindingContext.ValidModelProperties)
                        {
                            var existingCollectionValue = modelProperty.GetValue(genericinstance, null);

                            var collectionStringValue = GetValue(modelProperty.Name, bindingContext, i);

                            if (BindingValueIsValid(collectionStringValue, existingCollectionValue, modelProperty,
                                                    bindingContext))
                            {
                                try
                                {
                                    BindProperty(modelProperty, collectionStringValue, bindingContext, genericinstance);
                                }
                                catch (PropertyBindingException ex)
                                {
                                    bindingExceptions.Add(ex);
                                }
                            }
                        }
                    }
                }
                else
                {
                    foreach (var modelProperty in bindingContext.ValidModelProperties)
                    {
                        var existingValue = modelProperty.GetValue(bindingContext.Model, null);

                        var stringValue = GetValue(modelProperty.Name, bindingContext);

                        if (BindingValueIsValid(stringValue, existingValue, modelProperty, bindingContext))
                        {
                            try
                            {
                                BindProperty(modelProperty, stringValue, bindingContext);
                            }
                            catch (PropertyBindingException ex)
                            {
                                bindingExceptions.Add(ex);
                            }
                        }
                    }
                }

                if (bindingExceptions.Any())
                {
                    throw new ModelBindingException(modelType, bindingExceptions);
                }
            }

            if (modelType.IsArray())
            {
                var generictoArrayMethod = toArrayMethodInfo.MakeGenericMethod(new[] { genericType });
                return generictoArrayMethod.Invoke(null, new[] { bindingContext.Model });
            }
            return bindingContext.Model;
        }
 public void IsEnumerableDetectsMultipleTypesOfCollections(Type type)
 {
     Assert.True(type.IsEnumerable());
 }
Example #24
0
        private DataType GetOrRegister(Type type, bool deferIfComplex, Queue<Type> deferredTypes)
        {
            if (_customMappings.ContainsKey(type))
                return _customMappings[type]();

            if (PrimitiveMappings.ContainsKey(type))
                return PrimitiveMappings[type]();

            if (type.IsEnum)
                return new DataType { Type = "string", Enum = type.GetEnumNames() };

            Type innerType;
            if (type.IsNullable(out innerType))
                return GetOrRegister(innerType, deferIfComplex, deferredTypes);

            Type itemType;
            if (type.IsEnumerable(out itemType))
                return new DataType { Type = "array", Items = GetOrRegister(itemType, true, deferredTypes) };

            // Anthing else is complex
            if (deferIfComplex)
            {
                if (!_complexMappings.ContainsKey(type))
                    deferredTypes.Enqueue(type);

                // Just return a reference for now
                return new DataType { Ref = UniqueIdFor(type) };
            }

            return _complexMappings.GetOrAdd(type, () => CreateComplexDataType(type, deferredTypes));
        }
Example #25
0
        private static object CreateModel(Type modelType, Type genericType, object instance)
        {
            if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable())
            {
                //make sure instance has a Add method. Otherwise call `.ToList`
                if (instance != null && modelType.IsInstanceOfType(instance))
                {
                    var addMethod = modelType.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);
                    if (addMethod != null)
                    {
                        return instance;
                    }
                    var genericMethod = toListMethodInfo.MakeGenericMethod(genericType);
                    return genericMethod.Invoke(null, new[] { instance });
                }

                //else just make a list
                var listType = typeof(List<>).MakeGenericType(genericType);
                return Activator.CreateInstance(listType);
            }

            if (instance == null)
            {
                return Activator.CreateInstance(modelType);
            }

            return !modelType.IsInstanceOfType(instance) ?
                Activator.CreateInstance(modelType) :
                instance;
        }
        private ModelSpec CreateSpecFor(Type type, bool deferIfComplex, Dictionary<Type, ModelSpec> deferredMappings)
        {
            if (_customMappings.ContainsKey(type))
                return _customMappings[type];

            if (PrimitiveMappings.ContainsKey(type))
                return PrimitiveMappings[type];

            if (type.IsEnum)
                return new ModelSpec {Type = "string", Enum = type.GetEnumNames()};

            Type innerType;
            if (type.IsNullable(out innerType))
                return CreateSpecFor(innerType, deferIfComplex, deferredMappings);

            Type itemType;
            if (type.IsEnumerable(out itemType))
                return new ModelSpec { Type = "array", Items = CreateSpecFor(itemType, true, deferredMappings) };

            // Anthing else is complex

            if (deferIfComplex)
            {
                if (!deferredMappings.ContainsKey(type))
                    deferredMappings.Add(type, null);
                
                // Just return a reference for now
                return new ModelSpec {Ref = UniqueIdFor(type)};
            }

            return CreateComplexSpecFor(type, deferredMappings);
        }