Esempio n. 1
0
 private static bool IsCopyableCollectionType(Type type)
 {
     return type.IsArray ||
            typeof(IList).IsAssignableFrom(type) ||
            type.Implements(typeof(IList<>)) ||
            typeof(IDictionary).IsAssignableFrom(type) ||
            type.Implements(typeof(IDictionary<,>)) ||
            type.Implements(typeof(ISet<>));
 }
Esempio n. 2
0
        public static BasicTypes GetConversionType(Type innType, Type outType)
        {
            if (innType.Implements<IDictionary>() && outType.Implements<IDictionary>())
                return BasicTypes.Dictionary;
            if (innType.Implements<IEnumerable>() && outType.Implements<IEnumerable>() && !innType.IsValueType())
                return BasicTypes.List;
            if (innType.IsValueType() && outType.IsValueType() || TypeExtensions.CanConvert(outType, innType))
                return BasicTypes.Convertable;
            return BasicTypes.ComplexType;

        }
Esempio n. 3
0
        protected static void EnsureType(Type implementationType, Type serviceType, bool assertImplementation = true)
        {
            if (assertImplementation && (!implementationType.IsClass || implementationType.IsAbstract))
                throw new StyletIoCRegistrationException(String.Format("Type {0} is not a concrete class, and so can't be used to implemented service {1}", implementationType.GetDescription(), serviceType.GetDescription()));

            // Test this first, as it's a bit clearer than hitting 'type doesn't implement service'
            if (assertImplementation && implementationType.IsGenericTypeDefinition)
            {
                if (!serviceType.IsGenericTypeDefinition)
                    throw new StyletIoCRegistrationException(String.Format("You can't use an unbound generic type to implement anything that isn't an unbound generic service. Service: {0}, Type: {1}", serviceType.GetDescription(), implementationType.GetDescription()));

                // This restriction may change when I figure out how to pass down the correct type argument
                if (serviceType.GetTypeInfo().GenericTypeParameters.Length != implementationType.GetTypeInfo().GenericTypeParameters.Length)
                    throw new StyletIoCRegistrationException(String.Format("If you're registering an unbound generic type to an unbound generic service, both service and type must have the same number of type parameters. Service: {0}, Type: {1}", serviceType.GetDescription(), implementationType.GetDescription()));
            }
            else if (serviceType.IsGenericTypeDefinition)
            {
                if (implementationType.GetGenericArguments().Length > 0)
                    throw new StyletIoCRegistrationException(String.Format("You cannot bind the bound generic type {0} to the unbound generic service {1}", implementationType.GetDescription(), serviceType.GetDescription()));
                else
                    throw new StyletIoCRegistrationException(String.Format("You cannot bind the non-generic type {0} to the unbound generic service {1}", implementationType.GetDescription(), serviceType.GetDescription()));
            }

            if (!implementationType.Implements(serviceType))
                throw new StyletIoCRegistrationException(String.Format("Type {0} does not implement service {1}", implementationType.GetDescription(), serviceType.GetDescription()));
        }
Esempio n. 4
0
 public ErrorFilter(Type exceptionType, IStringMatcher messageMatcher = null, IStringMatcher sourceMatcher = null, bool recurseInnerExceptions=false)
     : base(messageMatcher,sourceMatcher)
 {
     if(exceptionType!=null && !exceptionType.Implements<Exception>()) throw new ArgumentException("The type must be an exception. It was: " + exceptionType, "exceptionType");
     _exceptionType = exceptionType;
     _recurseInnerExceptions = recurseInnerExceptions;
 }
 public ApplicationComponentDependencyAttribute(Type dependency)
 {
     if (!dependency.Implements<IApplicationComponent>())
     {
         throw new InvalidOperationException("Application component dependency type must implement IApplicationComponent.");
     }
 }
Esempio n. 6
0
            public void Process(Type type, PluginGraph graph)
            {
                if (!IsConcrete(type)) return;

                if (type.Name.EndsWith("Actor") && type.Implements<AsyncHttpActor>())
                    graph.AddType(typeof(AsyncHttpActor), type);
            }
        public SpecificationAttribute(Type specificationType)
        {
            if (!specificationType.Implements(typeof (ISpecification)))
            {
                throw new ValidationException("You must provide a valid specification type.");
            }

            SpecificationType = specificationType as ISpecification;
        }
Esempio n. 8
0
        // adds a transition
        private MigrationPlan Add(string sourceState, string targetState, Type migration)
        {
            if (sourceState == null)
            {
                throw new ArgumentNullException(nameof(sourceState));
            }
            if (targetState == null)
            {
                throw new ArgumentNullException(nameof(targetState));
            }
            if (string.IsNullOrWhiteSpace(targetState))
            {
                throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(targetState));
            }
            if (sourceState == targetState)
            {
                throw new ArgumentException("Source and target state cannot be identical.");
            }
            if (migration == null)
            {
                throw new ArgumentNullException(nameof(migration));
            }
            if (!migration.Implements <IMigration>())
            {
                throw new ArgumentException($"Type {migration.Name} does not implement IMigration.", nameof(migration));
            }

            sourceState = sourceState.Trim();
            targetState = targetState.Trim();

            // throw if we already have a transition for that state which is not null,
            // null is used to keep track of the last step of the chain
            if (_transitions.ContainsKey(sourceState) && _transitions[sourceState] != null)
            {
                throw new InvalidOperationException($"A transition from state \"{sourceState}\" has already been defined.");
            }

            // register the transition
            _transitions[sourceState] = new Transition(sourceState, targetState, migration);

            // register the target state if we don't know it already
            // this is how we keep track of the final state - because
            // transitions could be defined in any order, that might
            // be overridden afterwards.
            if (!_transitions.ContainsKey(targetState))
            {
                _transitions.Add(targetState, null);
            }

            _prevState  = targetState;
            _finalState = null; // force re-validation

            return(this);
        }
Esempio n. 9
0
 public object Materialize(Type type)
 {
     if (type.Implements(typeof(IList<>)) == false) {
         throw new NotImplementedException("Collection that does not implement IList<T> are not implemented yet.");
     }
     var argumentType = type.GetGenericArguments()[0];
     var collection = (IList) Activator.CreateInstance(type);
     foreach (var jsonObject in _jsonObjects) {
         collection.Add(jsonObject.Materialize(argumentType));
     }
     return collection;
 }
Esempio n. 10
0
        internal static TypeErrorsBuilder CheckRequiresReferenceHandling(
            this TypeErrorsBuilder typeErrors,
            Type type,
            MemberSettings settings,
            Func<Type, bool> requiresReferenceHandling)
        {
            if (settings.ReferenceHandling == ReferenceHandling.Throw)
            {
                if (typeof(IEnumerable).IsAssignableFrom(type))
                {
                    if (type.Implements(typeof(IDictionary<,>)))
                    {
                        var arguments = type.GetGenericArguments();
                        if (arguments.Length != 2 ||
                            requiresReferenceHandling(arguments[0]) ||
                            requiresReferenceHandling(arguments[1]))
                        {
                            typeErrors = typeErrors.CreateIfNull(type)
                                                   .Add(RequiresReferenceHandling.Enumerable);
                        }
                    }
                    else if (requiresReferenceHandling(type.GetItemType()))
                    {
                        typeErrors = typeErrors.CreateIfNull(type)
                                               .Add(RequiresReferenceHandling.Enumerable);
                    }
                }
                else if (type.IsKeyValuePair())
                {
                    var arguments = type.GetGenericArguments();
                    if (requiresReferenceHandling(arguments[0]) || requiresReferenceHandling(arguments[1]))
                    {
                        typeErrors = typeErrors.CreateIfNull(type)
                                               .Add(RequiresReferenceHandling.ComplexType);
                    }
                }
                else if (requiresReferenceHandling(type))
                {
                    typeErrors = typeErrors.CreateIfNull(type)
                                           .Add(RequiresReferenceHandling.ComplexType);
                }
            }

            return typeErrors;
        }
Esempio n. 11
0
        /// <summary>
        /// Get the appropriate <see cref="ICommandParser"/> used by the <see cref="IEvent"/> of the passed type.
        /// </summary>
        /// <param name="type">Type of the <see cref="IEvent"/> to get the parser for.</param>
        /// <returns>
        /// <see cref="ICommandParser"/> for the <see cref="IEvent"/> of the passed type. 
        /// If the <see cref="IEvent"/> of the passed type dosen't provide a <see cref="ICommandParser"/> <c>null</c> is returned.
        /// </returns>
        public static ICommandParser CreateCommandParserFor(Type type)
        {
            if(type.Implements<IEvent>())
            {
                IEvent action = EventFactory.CreateEvent(type);

                UsedCommandParser usedCommandParser = action.GetAttribute<UsedCommandParser>();
                if(usedCommandParser != null)
                {
                    Type commandParserType = usedCommandParser.ParserType;
                    object instance = Activator.CreateInstance(commandParserType);

                    if (instance.Implements<ICommandParser>())
                    {
                        return (ICommandParser)instance;
                    }
                }
            }
            return null;
        }
        protected static bool IsEquatableCore(Type type)
        {
            if (type == null)
            {
                return false;
            }

            bool result;
            if (EquatableCheckedTypes.TryGetValue(type, out result))
            {
                return result;
            }

            if (type.IsNullable())
            {
                var underlyingType = Nullable.GetUnderlyingType(type);
                result = IsEquatableCore(underlyingType);
                EquatableCheckedTypes.TryAdd(type, result);
                return result;
            }

            if (type.IsEnum)
            {
                result = true;
            }
            else if (type.IsImmutableArray())
            {
                // special casing ImmutableArray due to weird equality
                // Implements IEquatable<ImmutableArray> but Equals does not compare elements.
                result = false;
            }
            else
            {
                result = type.Implements(typeof(IEquatable<>), type);
            }

            EquatableCheckedTypes.TryAdd(type, result);
            return result;
        }
Esempio n. 13
0
        /// <summary>
        /// If this type implements IEnumerable«T» it returns typeof(T).
        /// </summary>
        public static Type GetEnumerableItemType(this Type type)
        {
            if (!type.Implements <IEnumerable>())
            {
                return(null);
            }

            if (type.IsArray)
            {
                return(type.GetElementType());
            }

            if (type.IsGenericType)
            {
                var implementedIEnumerableT = type.GetInterfaces().FirstOrDefault(x =>
                                                                                  x.GetGenericArguments().IsSingle() &&
                                                                                  x.GetGenericTypeDefinition() == typeof(IEnumerable <>));

                return(implementedIEnumerableT?.GetGenericArguments().Single());
            }

            return(null);
        }
Esempio n. 14
0
        protected override Type resolveOperatorType(Context ctx, Type leftType, Type rightType)
        {
            if (rightType == typeof(int))
            {
                // string repetition
                if (leftType == typeof(string))
                    return typeof(string);

                // array repetition
                if (leftType.IsArray)
                    return leftType;

                // typed sequence repetition
                var enumerable = leftType.ResolveImplementationOf(typeof(IEnumerable<>));
                if (enumerable != null)
                    return enumerable;

                // untyped sequence repetition
                if (leftType.Implements(typeof(IEnumerable), false))
                    return typeof(IEnumerable);
            }

            return null;
        }
 public void IsEquatableTest(Type type, bool expected)
 {
     Assert.AreEqual(expected, type.Implements(typeof(IEquatable<>), type));
 }
Esempio n. 16
0
 public static bool IsIEnumerableType(Type type)
 {
     return type.Implements(typeof(IEnumerable)) && type.IsInterface;
 }
Esempio n. 17
0
        static ScriptType GetScriptType(Type type)
        {
            if (type.IsAbstract || type.IsEnum)
                return ScriptType.Any;

            var scriptType = ScriptType.Any;
            if (type.Implements<CryScriptInstance>())
            {
                scriptType |= ScriptType.CryScriptInstance;

                if (type.Implements<EntityBase>())
                {
                    scriptType |= ScriptType.Entity;

                    if (type.Implements<ActorBase>())
                        scriptType |= ScriptType.Actor;
                    else if (type.Implements<GameRules>())
                        scriptType |= ScriptType.GameRules;
                }
                else if (type.Implements<FlowNode>())
                {
                    if (type.ImplementsGeneric(typeof(EntityFlowNode<>)))
                        scriptType |= ScriptType.EntityFlowNode;

                    scriptType |= ScriptType.FlowNode;
                }
            }

            return scriptType;
        }
Esempio n. 18
0
 private Type GetElementType(Type listType)
 {
     if (listType.Implements(typeof(IEnumerable<>)))
     {
         return listType.GetGenericArguments()[0];
     }
     else if (listType.IsArray)
     {
         return listType.GetElementType();
     }
     else return typeof(object);
 }
Esempio n. 19
0
		ApiTreeViewNodeTypeView TypeViewConstruct(Type type)
		{
			if (IsLeaf(type))
			{
				return null;
			}

			if (type.IsArray)
			{

			}

			if (type.Implements(typeof(IEnumerable)))
			{
				return new ApiTreeViewNodeTypeView()
				{
					AsSequence = true,
				};
			}

			var SetMember =
				type.GetMembers(BindingFlags.Public | BindingFlags.Instance)
				?.Where(MemberVisible)
				?.ToArray();

			return new ApiTreeViewNodeTypeView()
			{
				MemberView =
				SetMember
				?.Select(member => new ApiTreeViewNodeTypeMemberView()
				{
					Id = member?.Name,
					Getter = MemberGetter(member),
				})
				?.ToArray(),
			};
		}
Esempio n. 20
0
 protected virtual bool IsAssociationType(Type type)
 {
     if (type.Implements(typeof(IEnumerable<>)))
     {
         return IsAssociationType(type.GetTypeInfo().ImplementedInterfaces
             .Single(i => i.IsGenericType && i.GetGenericTypeDefinition().Equals(typeof(IEnumerable<>)))
             .GetGenericArguments()[0]);
     }
     else return type.Implements(typeof(IIdentifiable));
 }
Esempio n. 21
0
 public static bool IsCompositionRoot(this Type type) =>
 type.Implements(Constants.CompositionRootType);
Esempio n. 22
0
        public static bool IsDisposable(this Type type) =>
        type.Implements(Constants.DisposableType)
#if HAS_ASYNC_DISPOSABLE
        || type.Implements(Constants.AsyncDisposableType)
#endif
        ;
 public override bool CanWriteType(Type type)
 {
     return type.Implements<IPublication>() || type.Implements<IPublicationFeed>();
 }
 public void Implements(Type type, Type genericInterface,Type genericParameter, bool expected)
 {
     Assert.AreEqual(expected, type.Implements(genericInterface, genericParameter));
 }
Esempio n. 25
0
 /// <summary>
 /// Used for checking if a class implements an interface
 /// </summary>
 /// <typeparam name="T">Interface</typeparam>
 /// <param name="type">Class Implementing the interface</param>
 /// <returns></returns>
 public static bool Implements <T>(this Type type)
 {
     type.MustNotBeNull();
     return(type.Implements(typeof(T)));
 }
 public override bool CanReadType(Type type)
 {
     return type.Implements<IPublicationCommand>();
 }
Esempio n. 27
0
 public static bool Implements <TInterface>(this Type type) where TInterface : class
 {
     return(type.Implements(typeof(TInterface)));
 }
		private static PropertyInfo GetCollectionTCountProperty( Type targetType, Type elementType )
		{
			if ( !targetType.GetIsValueType() && targetType.Implements( typeof( ICollection<> ) ) )
			{
				return typeof( ICollection<> ).MakeGenericType( elementType ).GetProperty( "Count" );
			}

			var property = targetType.GetProperty( "Count" );
			if ( property != null && property.PropertyType == typeof( int ) && property.GetIndexParameters().Length == 0 )
			{
				return property;
			}

			return null;
		}
Esempio n. 29
0
 //[TestCase(typeof(HashSet<int>), typeof(IEnumerable), typeof(string), false)]
 public void Implements(Type type, Type interfaceType, Type parameterType, bool expected)
 {
     var actual = type.Implements(interfaceType, parameterType);
     Assert.AreEqual(expected, actual);
 }
Esempio n. 30
0
        public static bool Implements <TInterface>([NotNull] this Type type)
        {
            var interfaceType = typeof(TInterface);

            return(type.Implements(interfaceType));
        }
Esempio n. 31
0
            public void Process(Type type, Registry registry)
            {
                if (type == typeof(Extension))
                    return;

                if (type.Implements<Extension>())
                {
                    _log.Debug(x => x.Write("Loading extension: {0} ({1})", type.Name, type.Assembly.GetName().Name));

                    registry.AddType(typeof(Extension), type);
                }
            }
Esempio n. 32
0
 public static bool IsDisposable(this Type type) =>
 type.Implements(Constants.DisposableType);
Esempio n. 33
0
        public static bool Implements <TInterface>(this Type type)
        /*where TInterface: class*/ {
            Type interfaceType = typeof(TInterface);

            return(type.Implements(interfaceType));
        }
        public static string ToOrientValueString(this object value, Type targetType = null)
        {
            if (targetType == null)
            {
                if (value == null)
                    targetType = typeof(object);
                else
                    targetType = value.GetType();
            }

            if (value == null && targetType == typeof(object))
                return "null";
            else if (targetType.IsEnum)
            {
                if (value == DBNull.Value) return "null";
                return ((int)value).ToString();
            }
            else if (targetType == typeof(string))
            {
                if (value == DBNull.Value) return "null";
                return string.Format("'{0}'", EscapeText((string)value));
            }
            else if (targetType == typeof(ulong))
            {
                if (value == DBNull.Value) return "null";
                throw new NotSupportedException("Unsigned Long Integer values are not supported.  Use either Decimal, Double or byte[] storage types.");
            }
            else if (targetType == typeof(DateTime))
            {
                if (value == DBNull.Value) return "null";
                var dateString = ((DateTime)value).Kind == DateTimeKind.Utc ?
                    ((DateTime)value).ToString("s").Replace('T', ' ')
                    : ((DateTime)value).ToUniversalTime().ToString("s").Replace('T', ' ');
                return string.Format("'{0}'", dateString);
            }
            else if (targetType.IsArray)
            {
                if (value == DBNull.Value) return "null";
                if (value == null)
                {
                    return "null";
                }
                else if(((Array)value).Rank == 1)
                {
                    if (((Array)value).GetType().GetElementType().IsValueType || ((Array)value).GetType().GetElementType() == typeof(string))
                    {
                        var converter = CreateByteConverter(((Array)value).GetType().GetElementType());
                        var count = ((Array)value).Length;
                        var type = GetElementType(((Array)value).GetType().GetElementType());
                        using (var stream = new MemoryStream())
                        {
                            stream.Write(BitConverter.GetBytes(count), 0, 4);
                            stream.Write(BitConverter.GetBytes(type), 0, 4); // this approach will only work for intrinsic value types
                            byte[] bytes;
                            foreach (var item in (Array)value)
                            {
                                bytes = converter(item);
                                stream.Write(bytes, 0, bytes.Length);
                            }
                            stream.Position = 0;
                            return string.Format("'{0}'", Convert.ToBase64String(stream.ToArray()));
                        }
                    }
                    else if (((Array)value).GetType().GetElementType().Implements<IIdentifiable>())
                    {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < ((Array)value).Length; i++)
                        {
                            var item = ((Array)value).GetValue(i) as IIdentifiable;
                            if (item != null && !string.IsNullOrEmpty(item.Id))
                            {
                                if (sb.Length > 0)
                                    sb.Append(", ");
                                sb.Append(item.Id);
                            }
                        }
                        return sb.Length > 0 ? "[" + sb.ToString() + "]" : "null";
                    }
                }
            }
            else if (targetType == typeof(decimal))
            {
                if (value == DBNull.Value) return "null";
                var sValue = value.ToString();
                if (!sValue.Contains("."))
                    sValue += ".";
                return string.Format("'{0}'", sValue);
            }
            else if (targetType == typeof(double) || targetType == typeof(float))
            {
                if (value == DBNull.Value) return "null";
                return string.Format("'{0}'", value.ToString()); // wrapping in quotes allows orient to parse exponential number formats
            }
            else if (targetType.IsValueType)
            {
                if (value == DBNull.Value) return "null";
                return value.ToString();
            }
            else if (targetType.Implements<IIdentifiable>())
            {
                if (value == DBNull.Value || value == null || string.IsNullOrEmpty(((IIdentifiable)value).Id))
                {
                    return "#-1:-1";
                }
                else
                {
                    return ((IIdentifiable)value).Id;
                }
            }
            else if (targetType.Implements(typeof(IEnumerable<>))
                && targetType.GetGenericArguments()[0].Implements<IIdentifiable>())
            {
                if (value == DBNull.Value) return "null";
                var en = ((IEnumerable)value).GetEnumerator();
                StringBuilder sb = new StringBuilder();
                while (en.MoveNext())
                {
                    var item = en.Current as IIdentifiable;
                    if (item != null && !string.IsNullOrEmpty(item.Id))
                    {
                        if (sb.Length > 0)
                            sb.Append(", ");
                        sb.Append(item.Id);
                    }
                }
                return sb.Length > 0 ? "[" + sb.ToString() + "]" : "null";
            }
            else if (value is DBNull)
            {
                return "null";
            }
            throw new NotSupportedException("Cannot serialize type " + value.GetType().Name + " to a compatible storage format.");
        }
		private static bool TryCreateCollectionTraitsForHasGetEnumeratorType(
			Type source,
			CollectionTraitOptions options,
			MethodInfo getEnumerator,
			out CollectionTraits result
		)
		{
			if ( source.Implements( typeof( IDictionary<,> ) )
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
				|| source.Implements( typeof( IReadOnlyDictionary<,> ) )
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
			)
			{
				var ienumetaorT =
					getEnumerator.ReturnType.GetInterfaces()
						.FirstOrDefault( @interface => 
												@interface.GetIsGenericType() && @interface.GetGenericTypeDefinition() == typeof( IEnumerator<> ) 
						);
				if ( ienumetaorT != null )
				{
					var elementType = ienumetaorT.GetGenericArguments()[ 0 ];
					var elementTypeGenericArguments = elementType.GetGenericArguments();

					result = 
						new CollectionTraits(
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
							source.Implements( typeof( IDictionary<,> ) )
								? CollectionDetailedKind.GenericDictionary
								: CollectionDetailedKind.GenericReadOnlyDictionary,
#else
							CollectionDetailedKind.GenericDictionary,
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
							elementType,
							getEnumerator,
							GetAddMethod( source, elementTypeGenericArguments[ 0 ], elementTypeGenericArguments [ 1 ], options ),
							GetCountGetterMethod( source, elementType, options )
						);

					return true;
				}
			}

			if ( source.IsAssignableTo( typeof( IDictionary ) ) )
			{
				result = 
					new CollectionTraits(
						CollectionDetailedKind.NonGenericDictionary,
						typeof( DictionaryEntry ),
						getEnumerator,
						GetAddMethod( source, typeof( object ), typeof( object ), options ),
						GetCountGetterMethod( source, typeof( object ), options )
					);

				return true;
			}

			// Block to limit variable scope
			{
				var ienumetaorT =
					IsIEnumeratorT( getEnumerator.ReturnType )
						? getEnumerator.ReturnType
						: getEnumerator.ReturnType.GetInterfaces().FirstOrDefault( IsIEnumeratorT );

				if ( ienumetaorT != null )
				{
					// Get the open generic types once
					Type[] genericInterfaces =
						source.GetInterfaces()
							.Where( i => i.GetIsGenericType() )
							.Select( i => i.GetGenericTypeDefinition() )
							.ToArray();

					var genericTypes = new GenericCollectionTypes();
					genericTypes.IEnumerableT = ienumetaorT;
					genericTypes.ICollectionT = genericInterfaces.FirstOrDefault( i => i == typeof(ICollection<>) );
					genericTypes.IListT = genericInterfaces.FirstOrDefault( i => i == typeof(IList<>) );

#if !NETFX_35 && !UNITY
					genericTypes.ISetT = genericInterfaces.FirstOrDefault( i => i == typeof(ISet<>) );
#endif // !NETFX_35 && !UNITY
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
					genericTypes.IReadOnlyCollectionT = genericInterfaces.FirstOrDefault( i => i == typeof(IReadOnlyCollection<>) );
					genericTypes.IReadOnlyListT = genericInterfaces.FirstOrDefault( i => i == typeof(IReadOnlyList<>) );
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )

					return TryCreateCollectionTraitsForIEnumerableT( source, genericTypes, options, getEnumerator, out result );
				}
			}

			result = default( CollectionTraits );
			return false;
		}
Esempio n. 36
0
        public static bool TryCreate(Type type, out CryScript script)
        {
            if (type.IsAbstract || type.IsEnum)
            {
                script = default(CryScript);
                return false;
            }

            var scriptType = ScriptType.Any;
            if (type.Implements<CryScriptInstance>())
            {
                scriptType |= ScriptType.CryScriptInstance;

                if (type.Implements<EntityBase>())
                {
                    scriptType |= ScriptType.Entity;

                    if (type.Implements<ActorBase>())
                        scriptType |= ScriptType.Actor;
                    else if (type.Implements<GameRules>())
                        scriptType |= ScriptType.GameRules;
                }
                else if (type.Implements<FlowNode>())
                {
                    if (type.ImplementsGeneric(typeof(EntityFlowNode<>)))
                        scriptType |= ScriptType.EntityFlowNode;

                    scriptType |= ScriptType.FlowNode;
                }
            }

            if ((scriptType & (scriptType - 1)) == 0) // only had Any set.
            {
                script = default(CryScript);
                return false;
            }

            script = new CryScript(type, scriptType);
            return true;
        }
		private static bool TryCreateGenericCollectionTraits( Type source, Type type, CollectionTraitOptions options, out CollectionTraits result )
		{
			if ( type == typeof( IDictionary<MessagePackObject, MessagePackObject> )
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
				|| type == typeof( IReadOnlyDictionary<MessagePackObject, MessagePackObject> )
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
			)
			{
				result = 
					new CollectionTraits(
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
						( source == typeof( IDictionary<MessagePackObject, MessagePackObject> ) || source.Implements( typeof( IDictionary<MessagePackObject, MessagePackObject> ) ) )
							? CollectionDetailedKind.GenericDictionary
							: CollectionDetailedKind.GenericReadOnlyDictionary,
#else
						CollectionDetailedKind.GenericDictionary,
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
						typeof( KeyValuePair<MessagePackObject, MessagePackObject> ),
						GetGetEnumeratorMethodFromEnumerableType( source, typeof( IEnumerable<KeyValuePair<MessagePackObject, MessagePackObject>> ), options ),
						GetAddMethod( source, typeof( MessagePackObject ), typeof( MessagePackObject ), options ),
						GetCountGetterMethod( source, typeof( KeyValuePair<MessagePackObject, MessagePackObject> ), options )
					);

				return true;
			}

			if ( type == typeof( IEnumerable<MessagePackObject> ) )
			{
				var addMethod = GetAddMethod( source, typeof( MessagePackObject ), options | CollectionTraitOptions.WithAddMethod );
				if ( addMethod != null )
				{
					{
						result = 
							new CollectionTraits(
								( source == typeof( IList<MessagePackObject> ) || source.Implements( typeof( IList<MessagePackObject> ) ) )
									? CollectionDetailedKind.GenericList
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
									: ( source == typeof( IReadOnlyList<MessagePackObject> ) || source.Implements( typeof( IReadOnlyList<MessagePackObject> ) ) )
										? CollectionDetailedKind.GenericReadOnlyList
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
#if !NETFX_35 && !UNITY
										: ( source == typeof( ISet<MessagePackObject> ) || source.Implements( typeof( ISet<MessagePackObject> ) ) )
											? CollectionDetailedKind.GenericSet
#endif // !NETFX_35 && !UNITY
											: ( source == typeof( ICollection<MessagePackObject> ) ||
												source.Implements( typeof( ICollection<MessagePackObject> ) ) )
												? CollectionDetailedKind.GenericCollection
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
												: ( source == typeof( IReadOnlyCollection<MessagePackObject> ) || source.Implements( typeof( IReadOnlyCollection<MessagePackObject> ) ) )
													? CollectionDetailedKind.GenericReadOnlyCollection
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
													: CollectionDetailedKind.GenericEnumerable,
								typeof( MessagePackObject ),
								GetGetEnumeratorMethodFromEnumerableType( source, typeof( IEnumerable<MessagePackObject> ), options ),
								addMethod,
								GetCountGetterMethod( source, typeof( MessagePackObject ), options )
							);

						return true;
					}
				}
			}

			result = default( CollectionTraits );
			return false;
		}
Esempio n. 38
0
        public PropertyType Register(Type returnType, int depth = 0)
        {
            returnType = Nullable.GetUnderlyingType(returnType) ?? returnType;

            if (_models.ContainsKey(returnType))
            {
                return new PropertyType
                {
                    Type = _models[returnType].id,
                    Description = returnType.FriendlyName(),
                    Items = new Items
                    {
                        Ref = _models[returnType].id
                    }
                };
            }

            if (PrimitiveMappings.ContainsKey(returnType))
            {
                var mapping = PrimitiveMappings[returnType];
                return new PropertyType
                {
                    Description = returnType.FriendlyName(),
                    Type = mapping.Type,
                    Format = mapping.Format
                };
            }

            if (returnType.IsEnum)
            {
                return new PropertyType
                {
                    Description = returnType.FriendlyName(),
                    Type = "string",
                    Enum = Enum.GetNames(returnType)
                };
            }

            if (returnType.Implements<IEnumerable>())
            {
                var collectionType = returnType.GetElementType();
                if (returnType.IsGenericType)
                {
                    collectionType = returnType.GetGenericArguments()[0];
                }

                var colMapping = Register(collectionType, depth++);
                var isComplex = _models.ContainsKey(collectionType);

                return new PropertyType
                {
                    Description = returnType.FriendlyName(),
                    Type = "array",
                    Items = new Items
                    {
                        Ref = (isComplex)? colMapping.Type : "",
                        Type = (!isComplex)? colMapping.Type : ""
                    }
                };
            }

            if (returnType.IsPrimitive)
            {
                return new PropertyType
                {
                    Description = returnType.FriendlyName(),
                    Type = returnType.Name
                };
            }

            var modelSpec = new ModelSpec { id = ModelIdFromType(returnType) };
            _models.Add(returnType, modelSpec);
            
            foreach (var prop in returnType.GetProperties())
            {
                var mapping = Register(prop.PropertyType, depth++);
                modelSpec.properties.Add(prop.Name, mapping);

                if(prop.GetCustomAttribute<RequiredAttribute>() != null)
                    modelSpec.required.Add(prop.Name);
            }

            return new PropertyType
            {
                Description = returnType.FriendlyName(),
                Type = modelSpec.id,
            };
        }
 public override bool CanWriteType(Type type)
 {
     return type.Implements<IPublicationCategoriesDocument>();
 }