public void CheckAndRecord(ConstraintsViolations violations)
        {
            foreach (var factory in _equalInstances.Concat(_otherInstances))
            {
                RecordedAssertions.DoesNotThrow(() =>
                {
                    var instance1 = factory();

                    RecordedAssertions.DoesNotThrow(() =>
                                                    RecordedAssertions.True(instance1.Equals(instance1),
                                                                            "a.Equals(object a) should return true", violations),
                                                    "a.Equals(object a) should return true", violations);
                }, "Should be able to create an object of type " + typeof(T), violations);

                var equatableEquals = TypeOf <T> .EquatableEquality();

                if (equatableEquals.HasValue)
                {
                    var instance1 = factory();
                    RecordedAssertions.DoesNotThrow(() =>
                                                    RecordedAssertions.True((bool)equatableEquals.Value().Evaluate(instance1, instance1),
                                                                            "a.Equals(a) should return true", violations),
                                                    "a.Equals(a) should return true", violations);
                }
            }
        }
Пример #2
0
        public GraphObjectType()
        {
            var name = TypeOf <T> .Attributes.GraphName();

            var description = TypeOf <T> .Attributes.GraphDescription();

            if (TypeOf <T> .Is(typeof(Connection <>)))
            {
                name ??= $"{TypeOf<T>.EnclosedType!.Name}Connection";
                description ??= $"A connection from an object to a list of objects of type `{TypeOf<T>.EnclosedType!.Name}`.";
            }
            else if (TypeOf <T> .Is(typeof(Edge <>)))
            {
                name ??= $"{TypeOf<T>.EnclosedType!.Name}Edge";
                description ??= $"An edge in a connection from an object to another object of type `{TypeOf<T>.EnclosedType!.Name}`.";
            }
            else
            {
                name ??= TypeOf <T> .Name;
                description ??= $"An object of type `{TypeOf<T>.Name}`.";

                TypeOf <T> .InterfaceTypes.Do(type => this.Interface(type));
            }

            this.Name              = name;
            this.Description       = description;
            this.DeprecationReason = TypeOf <T> .Attributes.ObsoleteMessage();

            TypeOf <T> .Properties.Values
            .If(property => property.Getter is not null && !property.Attributes.GraphIgnore() && !property.Attributes.GraphCursor())
            .Do(property => this.AddField(property.ToFieldType(false)));
        }
        /// <summary>
        /// Determina se o tipo é suportado pelo algoritmo de serialização.
        /// </summary>
        /// <param name="item">O item analisado.</param>
        /// <returns>Verdadeiro se o item é serializável; Falso caso contrário.</returns>
        public static bool IsSerializable(object item)
        {
            if (item == null || item is PropertyMap)
            {
                return(true);
            }

            if (item is IEnumerable list && !(item is string))
            {
                if (item is IDictionary map)
                {
                    var isSerializable =
                        map.Keys.Cast <object>().All(IsStringCompatible) &&
                        map.Values.Cast <object>().All(IsSerializable);
                    return(isSerializable);
                }

                var elementType = TypeOf.CollectionElement(item);
                if (elementType.IsGenericType && elementType.GetGenericTypeDefinition() == typeof(KeyValuePair <,>))
                {
                    return(false);
                }

                return(list.Cast <object>().All(IsSerializable));
            }

            if (item.GetType().IsGenericType&& item.GetType().GetGenericTypeDefinition() == typeof(KeyValuePair <,>))
            {
                return(false);
            }

            return(item.GetType().IsValueType || IsStringCompatible(item));
        }
        public void CheckAndRecord(ConstraintsViolations violations)
        {
            RecordedAssertions.DoesNotThrow(() =>
            {
                var equatableEquality = TypeOf <T> .EquatableEquality();
                if (equatableEquality.HasValue)
                {
                    foreach (var factory1 in _equalInstances)
                    {
                        foreach (var factory2 in _equalInstances)
                        {
                            RecordedAssertions.DoesNotThrow(() =>
                                                            RecordedAssertions.True((bool)equatableEquality.Value().Evaluate(factory1(), factory2()),
                                                                                    "a.Equals(T b) should return true for equal objects", violations),
                                                            "a.Equals(T b) should return true for equal objects", violations);
                            RecordedAssertions.DoesNotThrow(() =>
                                                            RecordedAssertions.True((bool)equatableEquality.Value().Evaluate(factory2(), factory1()),
                                                                                    "b.Equals<T>(a) should return true for equal objects", violations),
                                                            "b.Equals(T a) should return true for equal objects", violations);

                            RecordedAssertions.DoesNotThrow(() =>
                                                            RecordedAssertions.True(factory1().Equals(factory2()),
                                                                                    "a.Equals(object b) should return true for equal objects", violations),
                                                            "a.Equals(object b) should return true for equal objects", violations);
                            RecordedAssertions.DoesNotThrow(() =>
                                                            RecordedAssertions.True(factory2().Equals(factory1()),
                                                                                    "b.Equals(object a) should return true for equal objects", violations),
                                                            "b.Equals(object a) should return true for equal objects", violations);
                        }
                    }
                }
            }, "Should be able to create an object of type " + typeof(T), violations);
        }
Пример #5
0
        public void CheckAndRecord(ConstraintsViolations violations)
        {
            foreach (var factory1 in _equalInstances)
            {
                foreach (var factory2 in _otherInstances)
                {
                    RecordedAssertions.DoesNotThrow(() =>
                                                    RecordedAssertions.False(factory1().Equals(factory2()),
                                                                             "a.Equals(object b) should return false if they are not equal", violations),
                                                    "a.Equals(object b) should return false if they are not equal", violations);
                    RecordedAssertions.DoesNotThrow(() =>
                                                    RecordedAssertions.False(factory2().Equals(factory1()),
                                                                             "b.Equals(object a) should return false if they are not equal", violations),
                                                    "b.Equals(object a) should return false if they are not equal", violations);

                    var equatableEquals = TypeOf <T> .EquatableEquality();

                    if (equatableEquals.HasValue)
                    {
                        RecordedAssertions.DoesNotThrow(() =>
                                                        RecordedAssertions.False((bool)equatableEquals.Value().Evaluate(factory1(), factory2()),
                                                                                 "a.Equals(T b) should return false if they are not equal", violations),
                                                        "a.Equals(T b) should return false if they are not equal", violations);
                        RecordedAssertions.DoesNotThrow(() =>
                                                        RecordedAssertions.False((bool)equatableEquals.Value().Evaluate(factory2(), factory1()),
                                                                                 "b.Equals(T a) should return false if they are not equal", violations),
                                                        "b.Equals(T a) should return false if they are not equal", violations);
                    }
                }
            }
        }
Пример #6
0
        public IKeyConfiguredType WithKey(string id)
        {
            _key        = id;
            KeyProperty = TypeOf <T> .PropertyInfo(id);

            return(this);
        }
Пример #7
0
        public T Dummy <T>()
        {
            var fakeInterface = _fakeChainFactory.CreateFakeOrdinaryInterfaceGenerator <T>();

            if (typeof(T).IsPrimitive)
            {
                return(_fakeChainFactory.GetUnconstrainedInstance <T>().Resolve(this));
            }
            if (typeof(T) == typeof(string))
            {
                return(_fakeChainFactory.GetUnconstrainedInstance <T>().Resolve(this));
            }
            if (TypeOf <T> .IsImplementationOfOpenGeneric(typeof(IEnumerable <>)))
            {
                return(_emptyCollectionFixture.Create <T>());
            }
            if (TypeOf <T> .IsOpenGeneric(typeof(IEnumerable <>)))
            {
                return((T)_emptyCollectionGenerator.EmptyEnumerableOf(typeof(T).GetCollectionItemType()));
            }
            if (typeof(T).IsAbstract)
            {
                return(default(T));
            }
            if (fakeInterface.Applies())
            {
                return(fakeInterface.Apply(this));
            }
            return((T)FormatterServices.GetUninitializedObject(typeof(T)));
        }
Пример #8
0
        /// <summary>
        /// Reads the type, which can either be a method return/parameter type or a field type, and skips it.
        /// </summary>
        public TypeOf? ReadTypeOf(bool isMethodParameter)
        {
            while(ReadAnnotation().HasValue){} // skip type annotations

            if (isMethodParameter)SkipIfMatch("final^s"); // skip final keyword in method parameters
            else SkipGenerics(); // skip method return type generics

            // void
            if (SkipIfMatch("void^s"))return TypeOf.Void();

            // primitive
            Primitives? primitive = ReadPrimitive();

            if (primitive.HasValue){
                SkipTypeArrayAndGenerics();
                return TypeOf.Primitive(primitive.Value);
            }

            // object name
            string typeName = ReadFullTypeName();

            if (typeName.Length > 0){
                SkipTypeArrayAndGenerics();
                return TypeOf.Object(JavaParseUtils.FullToSimpleName(typeName));
            }

            // nothing
            return null;
        }
Пример #9
0
        public IKeyConfiguredType WithKey <TK>(Expression <Func <T, TK> > selector)
        {
            _key = TypeOf <T> .Property(selector).ToLowerInvariant();

            KeyProperty = TypeOf <T> .PropertyInfo(selector);

            return(this);
        }
Пример #10
0
 /// <summary>
 /// Creates a new NodeInput in NodeBody of specified type
 /// </summary>
 public static NodeInput Create(Node NodeBody, string InputName, TypeOf InputType)
 {
     NodeInput input = CreateInstance <NodeInput> ();
     input.body = NodeBody;
     input.type = InputType;
     input.name = InputName;
     NodeBody.AddInput (input);
     return input;
 }
Пример #11
0
        public RedisConfig OverrideSerializationService <TSerializationServiceType>()

            where TSerializationServiceType : IRedisSerializationService
        {
            var type = TypeOf.New <IRedisSerializationService, TSerializationServiceType>();

            OverrideSerializationService(type);
            return(this);
        }
Пример #12
0
 public static CacheModuleConfig AddMemoryCacheStorage(this CacheModuleConfig cacheModuleConfig, Action <CacheLayerOptions> configureDelegate)
 {
     cacheModuleConfig.AddCacheLayer(() => new MemoryCacheModule(new CacheLayerDefinition()), definition =>
     {
         definition.CacheServiceType = TypeOf.New <ICacheService, IMemoryCacheService>();
         configureDelegate?.Invoke(definition.Options);
     });
     return(cacheModuleConfig);
 }
Пример #13
0
 /// <summary>
 /// Creates a new NodeOutput in NodeBody of specified type
 /// </summary>
 public static NodeOutput Create(Node NodeBody, string OutputName, TypeOf OutputType)
 {
     NodeOutput output = CreateInstance <NodeOutput> ();
     output.body = NodeBody;
     output.type = OutputType;
     output.name = OutputName;
     NodeBody.AddOutput (output);
     return output;
 }
Пример #14
0
            public Bag NewBag()
            {
                var property     = properties.LastOrDefault();
                var propertyType = Host._GetPropertyType(property);
                var elementType  = TypeOf.CollectionElement(propertyType);

                return(new Bag {
                    ElementType = elementType
                });
            }
Пример #15
0
        public bool Applies()
        {
            var isCollection = TypeOf <T> .IsImplementationOfOpenGeneric(typeof(IProducerConsumerCollection <>)) ||
                               TypeOf <T> .IsImplementationOfOpenGeneric(typeof(ICollection <>));

            return(TypeOf <T> .IsConcrete() &&
                   typeof(T).IsGenericType &&
                   isCollection &&
                   TypeOf <T> .HasParameterlessConstructor());
        }
Пример #16
0
        private void SetProperty(object graph, string property, NodeModel document)
        {
            object value       = null;
            bool   customValue = false;

            var propertyInfo = graph._GetPropertyInfo(property);

            property = propertyInfo?.Name ?? property.ChangeCase(TextCase.PascalCase);

            if (graph is IPropertyValueSetter setter)
            {
                var done = setter.SetProperty(property, document, this);
                if (done)
                {
                    return;
                }
            }

            if (graph is IPropertyValueFactory factory)
            {
                customValue = factory.CreateValue(property, document, this, out value);
                if (!customValue && value != null)
                {
                    value = null;
                }
            }

            if (Is.Dictionary(graph))
            {
                var keyType = TypeOf.DictionaryKey(graph);
                var key     = Change.To(property, keyType);

                if (!customValue)
                {
                    var valueType = TypeOf.DictionaryValue(graph);
                    value = CreateGraph(document, valueType);
                }

                var dictionary = (IDictionary)graph;
                dictionary.Add(key, value);

                return;
            }

            if (propertyInfo == null)
            {
                throw new NoSuchPropertyException(graph.GetType(), property);
            }

            if (!customValue)
            {
                value = CreateGraph(document, propertyInfo.PropertyType);
            }
            graph._Set(property, value);
        }
        public MIPS Visitor(TypeOf instance, IFunctionCil function, GenerateToCil cil)
        {
            List <string> lines = new List <string>();

            lines.AddRange(Utils.SaveToRegister(instance.Y, function, "t0"));
            lines.AddRange(Utils.LoadFromRegister(instance.X, function, "t0"));
            return(new MIPS()
            {
                Functions = lines
            });
        }
 /// <summary>
 /// Пытется найти подходящий resolver для указанного примитивного типа
 /// </summary>
 /// <returns><c>true</c>, if create primitive resolver was tryed, <c>false</c> otherwise.</returns>
 /// <param name="type">Type.</param>
 /// <param name="resolver">Resolver.</param>
 private bool TryCreatePrimitiveResolver(Type type, out IResolver resolver)
 {
     if (TypeOf <Boolean> .Equals(type))
     {
         resolver = new BooleanResolver(); return(true);
     }
     if (TypeOf <Byte> .Equals(type))
     {
         resolver = new ByteResolver(); return(true);
     }
     if (TypeOf <Char> .Equals(type))
     {
         resolver = new CharResolver(); return(true);
     }
     if (TypeOf <Double> .Equals(type))
     {
         resolver = new DoubleResolver(); return(true);
     }
     if (TypeOf <Int16> .Equals(type))
     {
         resolver = new Int16Resolver(); return(true);
     }
     if (TypeOf <Int32> .Equals(type))
     {
         resolver = new Int32Resolver(); return(true);
     }
     if (TypeOf <Int64> .Equals(type))
     {
         resolver = new Int64Resolver(); return(true);
     }
     if (TypeOf <SByte> .Equals(type))
     {
         resolver = new SByteResolver(); return(true);
     }
     if (TypeOf <Single> .Equals(type))
     {
         resolver = new SingleResolver(); return(true);
     }
     if (TypeOf <UInt16> .Equals(type))
     {
         resolver = new UInt16Resolver(); return(true);
     }
     if (TypeOf <UInt32> .Equals(type))
     {
         resolver = new UInt32Resolver(); return(true);
     }
     if (TypeOf <UInt64> .Equals(type))
     {
         resolver = new UInt64Resolver(); return(true);
     }
     resolver = null;
     return(false);
 }
Пример #19
0
        public override T?Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.StartObject)
            {
                var output = TypeOf <T> .Create();

                while (reader.Read() && reader.TokenType == JsonTokenType.PropertyName)
                {
                    var name = reader.GetString();
                    if (reader.Read())
                    {
                        var property = TypeOf <T> .Properties[name !];
Пример #20
0
        private Entity FormatPayload(object payload)
        {
            var type   = payload.GetType();
            var entity = new Entity();

            if (payload is ICollection list)
            {
                entity.Add(Class.Records);

                var itemType = TypeOf.CollectionElement(type);
                var headers  = itemType.GetProperties().Select(x => (VName)x.Name).ToArray();

                entity.Add(new Property("__meta", new
                {
                    records = new
                    {
                        headers = headers.ToArray()
                    }
                }));

                foreach (var item in list)
                {
                    var child = FormatPayload(item);
                    entity.Add(child);
                }
            }
            else
            {
                entity.Add(new Class(type.FullName));
                entity.Add(Class.Record);

                var headers           = type.GetProperties().Select(x => (VName)x.Name).ToArray();
                var payloadProperties = Value.CreateObject(payload);

                entity.Add(new Property("__meta", new
                {
                    record = new
                    {
                        headers = headers.ToArray()
                    }
                }));

                entity.AddMany(payloadProperties);

                if (payload is Beans.Catalog)
                {
                    //entity.WithLinks().Add(new Link { Href = Req.RequestUri.Append("/Papers") });
                }
            }
            return(entity);
        }
Пример #21
0
        public static CacheModuleConfig AddCacheLayerLogging(this CacheModuleConfig cacheModuleConfig)
        {
            cacheModuleConfig.SetFirstCacheLayer(() => new PreLoggingCacheModule(new CacheLayerDefinition()), definition =>
            {
                definition.CacheServiceType = TypeOf.New <ICacheService, PreLoggingCacheService>();
            });

            cacheModuleConfig.SetLastCacheLayer(() => new PostLoggingCacheModule(new CacheLayerDefinition()), definition =>
            {
                definition.CacheServiceType = TypeOf.New <ICacheService, PostLoggingCacheService>();
            });

            return(cacheModuleConfig);
        }
        /// <summary>
        /// Tries the create default resolver.
        /// </summary>
        /// <returns><c>true</c>, if create default resolver was tryed, <c>false</c> otherwise.</returns>
        /// <param name="type">Type.</param>
        /// <param name="resolver">Resolver.</param>
        private bool TryCreateDefaultResolver(Type type, out IResolver resolver)
        {
            if (type.IsValueType)                                                       //Проверяем является ли тип значимым
            {
                if (type.IsPrimitive && TryCreatePrimitiveResolver(type, out resolver)) //Проверяем является ли тип примитивным
                {
                    return(true);
                }

                if (TypeOf <Decimal> .Equals(type))
                {
                    resolver = new DecimalResolver();
                    return(true);
                }
            }
            else
            {
                if (type.IsArray)
                {
                    resolver = CreateArrayResolver(type);
                    return(true);
                }

                if (TypeOf <Object> .Equals(type))
                {
                    resolver = new ObjectResolver(); return(true);
                }
                if (TypeOf <String> .Equals(type))
                {
                    resolver = new StringResolver(); return(true);
                }
                if (RuntimeType.Equals(type))
                {
                    resolver = new TypeResolver(Serializator); return(true);
                }

                if (Delegate.IsAssignableFrom(type))
                {
                    if ((Serializator.Options & SerializatorOption.ThrowOutExceptions) != 0)
                    {
                        throw new NotSupportedException("Serialization delegates is not supported");
                    }
                    resolver = new EmptyResolver(Serializator);
                    return(true);
                }
            }

            resolver = null;
            return(false);
        }
Пример #23
0
            public void SetValue(object value)
            {
                if (Bag != null)
                {
                    Bag.Add(value);
                    return;
                }

                if ((value is Bag bag) && (Host is IDictionary map))
                {
                    var type = TypeOf.DictionaryValue(map);
                    if (type == typeof(object))
                    {
                        var attrs = Host._GetAttributes <KnownTypeAttribute>();
                        type = (
                            from attr in attrs
                            where typeof(ICollection).IsAssignableFrom(attr.Type) &&
                            !typeof(IDictionary).IsAssignableFrom(attr.Type)
                            select attr.Type
                            ).FirstOrDefault();

                        if (type == null)
                        {
                            throw new NotSupportedException("Tipo de mapeamento não suportado: " + Host.GetType().FullName);
                        }
                    }
                    value = Change.To(value, type);
                }

                var realName = properties.Last();

                if (adders != null)
                {
                    object key, val;
                    foreach (var adder in adders)
                    {
                        var keyType = adder.GetParameters().First().ParameterType;
                        var valType = adder.GetParameters().Last().ParameterType;
                        if (Change.Try(realName, keyType, out key) && Change.Try(value, valType, out val))
                        {
                            Host._Call("Add", key, val);
                            return;
                        }
                    }
                }

                var propName = ResolvePropertyName(Host, realName);

                Host._Set(propName, value);
            }
Пример #24
0
            internal static void FindSerialiableFieldsInternal(List <FieldInfo> fields, Type targetType, bool includeBaseFields)
            {
                if (TypeOf <Object> .Equals(targetType))
                {
                    return;
                }

                SublistSerializableFieldsInternal(fields, targetType);

                if (includeBaseFields)
                {
                    FindSerialiableFieldsInternal(fields, targetType.BaseType, true);
                }
            }
Пример #25
0
            public Bag NewBag()
            {
                var property     = properties.LastOrDefault();
                var propertyType = Host._GetPropertyType(property);
                var elementType  = TypeOf.CollectionElement(propertyType);

                if (elementType == null || elementType == typeof(object) || elementType.IsInterface)
                {
                    elementType = typeof(HashMap);
                }
                return(new Bag
                {
                    ElementType = elementType
                });
            }
Пример #26
0
        /// <summary>
        /// Maps RowSet to models by their properties.<br/>
        /// Matches model property names to RowSet column names.
        /// </summary>
        public static T[] MapModels <T>(this RowSet @this)
            where T : new()
        {
            var properties = TypeOf <T> .Properties.GetValues(@this.Columns)
                             .If(property => property !.Setter is not null)
                             .ToArray();

            var items = new T[@this.Rows.Length];

            @this.Rows.Do((row, rowIndex) =>
            {
                var item = TypeOf <T> .Create();
                properties.Do((property, columnIndex) => property?.SetValue(item, row[columnIndex]));
                items[rowIndex] = item;
            });
            return(items);
        }
Пример #27
0
    public static void Main(String[] args)
    {
        Type t1 = typeof(TypeOf);

        Console.WriteLine(t1);

        Type t2 = new TypeOf().GetType();

        Console.WriteLine(t2);

        if (Object.ReferenceEquals(t1, t2))
        {
            Console.WriteLine("The same type.");
        }

        Type t3 = t2.GetType();

        Console.WriteLine(t3);
    }
Пример #28
0
        public override T?Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.StartObject)
            {
                var output = TypeOf <T> .Create();

                while (reader.Read() && reader.TokenType == JsonTokenType.PropertyName)
                {
                    var name = reader.GetString() !;
                    if (reader.Read())
                    {
                        var field = TypeOf <T> .Fields[name];
                        if (!field.Static && field.Setter is not null)
                        {
                            field.SetValue(output, reader.TokenType switch
                            {
                                JsonTokenType.StartObject or JsonTokenType.StartArray => JsonSerializer.Deserialize(ref reader, field.FieldType, options),
                                _ => reader.GetValue()
                            });
Пример #29
0
            public object NewValue()
            {
                if (Bag != null)
                {
                    return(Activator.CreateInstance(Bag.ElementType));
                }
                else if (Host is IDictionary map)
                {
                    var type = TypeOf.DictionaryValue(map);
                    if (type == typeof(object))
                    {
                        var attrs = Host._GetAttributes <KnownTypeAttribute>();
                        type = (
                            from attr in attrs
                            where typeof(IDictionary).IsAssignableFrom(attr.Type)
                            select attr.Type
                            ).FirstOrDefault();

                        if (type == null)
                        {
                            type = typeof(HashMap);
                        }
                    }
                    var instance = Activator.CreateInstance(type);
                    var property = properties.LastOrDefault();
                    map[property] = instance;
                    return(instance);
                }
                else
                {
                    var property     = properties.LastOrDefault();
                    var propertyName = ResolvePropertyName(Host, property);
                    var propertyInfo = Host._GetPropertyInfo(propertyName);
                    var propertyType = propertyInfo.PropertyType;
                    if (propertyType == typeof(object))
                    {
                        propertyType = typeof(HashMap);
                    }
                    var instance = Activator.CreateInstance(propertyType);
                    return(instance);
                }
            }
Пример #30
0
        /// <summary>
        /// Determina o DataType apropriado para representar o tipo ou instância indicado.
        /// </summary>
        /// <param name="typeOrInstance">O tipo ou a instância testada.</param>
        /// <returns>O DataType mais apropriado.</returns>
        public static string FromType(object typeOrInstance)
        {
            if (typeOrInstance == null)
            {
                return(null);
            }

            var type = (typeOrInstance is Type) ? (Type)typeOrInstance : typeOrInstance.GetType();

            type = TypeOf.Var(type) ?? type;
            type = Nullable.GetUnderlyingType(type) ?? type;

            var isList = false;

            if (type.IsArray)
            {
                isList = true;
                type   = type.GetElementType();
            }
            else if (typeof(IList <>).IsAssignableFrom(type))
            {
                isList = true;
                type   = type.GetGenericArguments().Single();
            }

            var typeName = Canonicalize(type);

            if (isList)
            {
                typeName += "[]";
            }

            if (typeName.Contains("AnonymousType"))
            {
                typeName = "AnonymousType";
            }

            return(typeName);
        }
Пример #31
0
        public T Dummy <T>(GenerationTrace trace)
        {
            var fakeInterface      = _fakeChainFactory.CreateFakeOrdinaryInterfaceGenerator <T>();
            var unconstrainedChain = _fakeChainFactory.GetUnconstrainedInstance <T>();

            if (typeof(T).IsPrimitive)
            {
                return(unconstrainedChain.Resolve(SynchronizedThis, trace));
            }

            if (typeof(T) == typeof(string))
            {
                return(unconstrainedChain.Resolve(SynchronizedThis, trace));
            }

            var emptyCollectionInstantiation = new EmptyCollectionInstantiation();

            if (TypeOf <T> .IsImplementationOfOpenGeneric(typeof(IEnumerable <>)))
            {
                return(emptyCollectionInstantiation.CreateCollectionPassedAsGenericType <T>());
            }

            if (TypeOf <T> .IsOpenGeneric(typeof(IEnumerable <>)))
            {
                return((T)emptyCollectionInstantiation.EmptyEnumerableOf(typeof(T).GetCollectionItemType()));
            }

            if (typeof(T).IsAbstract)
            {
                return(default(T));
            }

            if (fakeInterface.Applies())
            {
                return(fakeInterface.Apply(SynchronizedThis, trace));
            }

            return((T)FormatterServices.GetUninitializedObject(typeof(T)));
        }
Пример #32
0
        public object CreateGraph(NodeModel document, Type graphType)
        {
            if (document.IsDocument)
            {
                document = ((DocumentModel)document).Root;
            }

            if (typeof(IGraphDeserializer).IsAssignableFrom(graphType))
            {
                var graph = (IGraphDeserializer)Activator.CreateInstance(graphType);
                graph.Deserialize(document, this);
                return(graph);
            }

            if (document.IsObject)
            {
                var graph = Activator.CreateInstance(graphType);
                foreach (var property in document.ChildProperties())
                {
                    SetProperty(graph, property.Name, property.Value);
                }
                return(graph);
            }

            if (document.IsCollection)
            {
                var list     = new ArrayList();
                var itemType = TypeOf.CollectionElement(graphType);
                foreach (var child in document.Children())
                {
                    var item = CreateGraph(child, itemType);
                    list.Add(item);
                }
                var graph = (ICollection)Change.To(list, graphType);
                return(graph);
            }

            return(document.SerializationValue);
        }
Пример #33
0
		public virtual object Visit (TypeOf typeOfExpression)
		{
			return null;
		}
			public override object Visit (TypeOf typeOfExpression)
			{
				var result = new TypeOfExpression ();
				var location = LocationsBag.GetLocations (typeOfExpression);
				result.AddChild (new CSharpTokenNode (Convert (typeOfExpression.Location), TypeOfExpression.TypeofKeywordRole), TypeOfExpression.TypeofKeywordRole);
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location [0]), Roles.LPar), Roles.LPar);
				if (typeOfExpression.TypeExpression != null)
					result.AddChild (ConvertToType (typeOfExpression.TypeExpression), Roles.Type);
				if (location != null && location.Count > 1)
					result.AddChild (new CSharpTokenNode (Convert (location [1]), Roles.RPar), Roles.RPar);
				return result;
			}
Пример #35
0
void case_527()
#line 3806 "cs-parser.jay"
{
	  	lexer.TypeOfParsing = false;
		yyVal = new TypeOf ((FullNamedExpression) yyVals[-1+yyTop], GetLocation (yyVals[-4+yyTop]));
		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
	  }
Пример #36
0
void case_577()
#line 4204 "cs-parser.jay"
{
		yyVal = new TypeOf ((FullNamedExpression) yyVals[-1+yyTop], GetLocation (yyVals[-3+yyTop]));
		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
	  }
Пример #37
0
 public Field(string identifier, TypeOf type, Member info)
     : base(info)
 {
     this.Identifier = identifier;
     this.Type = type;
 }
Пример #38
0
 private Expression ParseTypeofSizeofOrDefault(TokenSet followers)
   //^ requires this.currentToken == Token.Typeof || this.currentToken == Token.Sizeof || this.currentToken == Token.Default;
   //^ ensures followers[this.currentToken] || this.currentToken == Token.EndOfFile;
 {
   Token tok = this.currentToken;
   SourceLocationBuilder slb = new SourceLocationBuilder(this.scanner.SourceLocationOfLastScannedToken);
   this.GetNextToken();
   this.Skip(Token.LeftParenthesis);
   TypeExpression type = this.ParseTypeExpression(false, true, followers|Token.RightParenthesis);
   slb.UpdateToSpan(this.scanner.SourceLocationOfLastScannedToken);
   this.SkipOverTo(Token.RightParenthesis, followers);
   Expression result;
   if (tok == Token.Typeof) 
     result = new TypeOf(type, slb);
   else if (tok == Token.Sizeof)
     result = new SizeOf(type, slb);
   else {
     //^ assert tok == Token.Default;
     result = new DefaultValue(type, slb);
   }
   //^ assume followers[this.currentToken] || this.currentToken == Token.EndOfFile;
   return result;
 }