Ejemplo n.º 1
0
        private TypeInitializer InitializeTypes(
            IServiceProvider services,
            IDescriptorContext descriptorContext,
            IBindingLookup bindingLookup,
            IEnumerable <ITypeReference> types,
            Func <ISchema> schemaResolver)
        {
            var initializer = new TypeInitializer(
                services, descriptorContext, types, _resolverTypes,
                _contextData, _isOfType, IsQueryType);

            foreach (FieldMiddleware component in _globalComponents)
            {
                initializer.GlobalComponents.Add(component);
            }

            foreach (FieldReference reference in _resolvers.Keys)
            {
                initializer.Resolvers[reference] = new RegisteredResolver(
                    typeof(object), _resolvers[reference]);
            }

            foreach (RegisteredResolver resolver in bindingLookup.Bindings
                     .SelectMany(t => t.CreateResolvers()))
            {
                var reference = new FieldReference(
                    resolver.Field.TypeName,
                    resolver.Field.FieldName);
                initializer.Resolvers[reference] = resolver;
            }

            initializer.Initialize(schemaResolver);
            return(initializer);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Constants
        /// </summary>

        internal Slot GetOrMakeConstant(object value)
        {
            Debug.Assert(!(value is CompilerConstant));

            Slot ret;

            if (_constants.TryGetValue(value, out ret))
            {
                return(ret);
            }

            Type type = value.GetType();

            // Create a name like "c$3.141592$712"
            string name = value.ToString();

            if (name.Length > 20)
            {
                name = name.Substring(0, 20);
            }
            name = "c$" + name + "$" + _constants.Count;

            FieldBuilder fb = _myType.DefineField(name, type, FieldAttributes.Static | FieldAttributes.InitOnly);

            ret = new StaticFieldSlot(fb);

            TypeInitializer.EmitConstantNoCache(value);
            _initGen.EmitFieldSet(fb);

            _constants[value] = ret;
            return(ret);
        }
Ejemplo n.º 3
0
        private SchemaTypesDefinition CreateSchemaDefinition(
            TypeInitializer initializer)
        {
            var definition = new SchemaTypesDefinition();

            definition.Types = initializer.Types.Values
                               .Select(t => t.Type)
                               .OfType <INamedType>()
                               .Distinct()
                               .ToArray();

            definition.DirectiveTypes = initializer.Types.Values
                                        .Select(t => t.Type)
                                        .OfType <DirectiveType>()
                                        .Distinct()
                                        .ToArray();

            RegisterOperationName(OperationType.Query,
                                  _options.QueryTypeName);
            RegisterOperationName(OperationType.Mutation,
                                  _options.MutationTypeName);
            RegisterOperationName(OperationType.Subscription,
                                  _options.SubscriptionTypeName);

            definition.QueryType = ResolveOperation(
                initializer, OperationType.Query);
            definition.MutationType = ResolveOperation(
                initializer, OperationType.Mutation);
            definition.SubscriptionType = ResolveOperation(
                initializer, OperationType.Subscription);

            return(definition);
        }
Ejemplo n.º 4
0
        public void WriteToStreamAsyncReturnsODataRepresentation()
        {
            // Arrange
            ODataConventionModelBuilder modelBuilder = new ODataConventionModelBuilder();

            modelBuilder.EntitySet <WorkItem>("WorkItems");
            IEdmModel model = modelBuilder.GetEdmModel();

            HttpRequestMessage request       = new HttpRequestMessage(HttpMethod.Get, "http://localhost/WorkItems(10)");
            HttpConfiguration  configuration = new HttpConfiguration();
            string             routeName     = "Route";

            configuration.MapODataServiceRoute(routeName, null, model);
            request.SetConfiguration(configuration);
            IEdmEntitySet entitySet = model.EntityContainer.EntitySets().Single();

            request.ODataProperties().Path = new ODataPath(new EntitySetSegment(entitySet),
                                                           new KeySegment(new[] { new KeyValuePair <string, object>("ID", 10) }, entitySet.EntityType(), entitySet));
            request.EnableODataDependencyInjectionSupport(routeName);

            ODataMediaTypeFormatter formatter = CreateFormatterWithJson(model, request, ODataPayloadKind.Resource);

            // Act
            ObjectContent <WorkItem> content = new ObjectContent <WorkItem>(
                (WorkItem)TypeInitializer.GetInstance(SupportedTypes.WorkItem), formatter);

            // Assert
            JsonAssert.Equal(Resources.WorkItemEntry, content.ReadAsStringAsync().Result);
        }
Ejemplo n.º 5
0
        private void IEnumerableOfEntityTypeSerializesAsODataFeed(string expectedContent, bool json)
        {
            ODataMediaTypeFormatter formatter = CreateFormatter();

            IEnumerable <Employee> collectionOfPerson = new Collection <Employee>()
            {
                (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee, 0),
                (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee, 1),
            };

            ObjectContent <IEnumerable <Employee> > content = new ObjectContent <IEnumerable <Employee> >(collectionOfPerson,
                                                                                                          formatter, json ? ODataMediaTypes.ApplicationJsonODataMinimalMetadata :
                                                                                                          ODataMediaTypes.ApplicationAtomXmlTypeFeed);

            string actualContent = content.ReadAsStringAsync().Result;

            if (json)
            {
                JsonAssert.Equal(expectedContent, actualContent);
            }
            else
            {
                RegexReplacement replaceUpdateTime = new RegexReplacement(
                    "<updated>*.*</updated>", "<updated>UpdatedTime</updated>");
                Assert.Xml.Equal(expectedContent, actualContent, replaceUpdateTime);
            }
        }
Ejemplo n.º 6
0
        public Schema Create()
        {
            IServiceProvider services      = _services ?? new EmptyServiceProvider();
            IBindingLookup   bindingLookup =
                _bindingCompiler.Compile(DescriptorContext.Create(services));

            var types = new List <ITypeReference>(_types);

            if (_documents.Count > 0)
            {
                types.AddRange(ParseDocuments(services, bindingLookup));
            }

            var lazy = new LazySchema();

            TypeInitializer initializer =
                InitializeTypes(services, bindingLookup, types, () => lazy.Schema);

            SchemaDefinition definition = CreateSchemaDefinition(initializer);

            if (definition.QueryType == null && _options.StrictValidation)
            {
                // TODO : Resources
                throw new SchemaException(
                          SchemaErrorBuilder.New()
                          .SetMessage("No QUERY TYPE")
                          .Build());
            }

            var schema = new Schema(definition);

            lazy.Schema = schema;
            return(schema);
        }
Ejemplo n.º 7
0
            private static TypeInitializer CreateTypeInitializer(
                SchemaBuilder builder,
                IDescriptorContext context,
                IReadOnlyList <ITypeReference> typeReferences,
                TypeRegistry typeRegistry)
            {
                Dictionary <OperationType, ITypeReference> operations =
                    builder._operations.ToDictionary(
                        t => t.Key,
                        t => t.Value(context.TypeInspector));

                var initializer = new TypeInitializer(
                    context,
                    typeRegistry,
                    typeReferences,
                    builder._isOfType,
                    type => GetOperationKind(type, context.TypeInspector, operations));

                foreach (FieldMiddleware component in builder._globalComponents)
                {
                    initializer.GlobalComponents.Add(component);
                }

                foreach (KeyValuePair <Type, (CreateRef, CreateRef)> binding in builder._clrTypes)
                {
                    typeRegistry.TryRegister(
                        (ExtendedTypeReference)binding.Value.Item1(context.TypeInspector),
                        binding.Value.Item2.Invoke(context.TypeInspector));
                }

                return(initializer);
            }
Ejemplo n.º 8
0
        public void Initializer_SchemaOptions_Are_Null()
        {
            // arrange
            var initialTypes = new List <ITypeReference>();

            initialTypes.Add(new ClrTypeReference(
                                 typeof(Foo),
                                 TypeContext.Output));

            var serviceProvider = new EmptyServiceProvider();

            var typeInitializer = new TypeInitializer(
                serviceProvider,
                DescriptorContext.Create(),
                initialTypes,
                new List <Type>(),
                new Dictionary <string, object>(),
                null,
                t => t is ObjectType <Foo>);

            // act
            Action action =
                () => typeInitializer.Initialize(() => null, null);

            // assert
            Assert.Throws <ArgumentNullException>(action);
        }
        private SchemaTypesDefinition CreateSchemaDefinition(
            TypeInitializer typeInitializer,
            DiscoveredTypes discoveredTypes)
        {
            var definition = new SchemaTypesDefinition();

            RegisterOperationName(OperationType.Query, _options.QueryTypeName);
            RegisterOperationName(OperationType.Mutation, _options.MutationTypeName);
            RegisterOperationName(OperationType.Subscription, _options.SubscriptionTypeName);

            definition.QueryType = ResolveOperation(
                typeInitializer, OperationType.Query);
            definition.MutationType = ResolveOperation(
                typeInitializer, OperationType.Mutation);
            definition.SubscriptionType = ResolveOperation(
                typeInitializer, OperationType.Subscription);

            IReadOnlyCollection <TypeSystemObjectBase> types =
                RemoveUnreachableTypes(discoveredTypes, definition);

            definition.Types = types
                               .OfType <INamedType>()
                               .Distinct()
                               .ToArray();

            definition.DirectiveTypes = types
                                        .OfType <DirectiveType>()
                                        .Distinct()
                                        .ToArray();

            return(definition);
        }
Ejemplo n.º 10
0
 public MongoDbSet(IMongoDatabase database, IDbsetContainer dbsetContainer, ITypeInitializer typeInitializer, ICustomServiceProvider serviceProvider)
 {
     this.Database           = database;
     this.TypeInitializer    = typeInitializer;
     this.CurrentTypeModel   = TypeInitializer.GetTypeMetadata <TEntity>();
     this.ServiceProvider    = serviceProvider;
     this.DbsetContainer     = dbsetContainer;
     this.SetRelationsMethod = this.GetType().GetMethod(nameof(this.SetRelations), BindingFlags.NonPublic | BindingFlags.Instance);
 }
Ejemplo n.º 11
0
        public void EntityTypeSerializesAsODataEntry()
        {
            ODataMediaTypeFormatter formatter = CreateFormatter();
            Employee employee = (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee);
            ObjectContent <Employee> content = new ObjectContent <Employee>(employee, formatter);

            RegexReplacement replaceUpdateTime = new RegexReplacement("<updated>*.*</updated>", "<updated>UpdatedTime</updated>");

            Assert.Xml.Equal(BaselineResource.TestEntityTypeBasic, content.ReadAsStringAsync().Result, regexReplacements: replaceUpdateTime);
        }
Ejemplo n.º 12
0
        public Schema Create()
        {
            IServiceProvider  services          = _services ?? new EmptyServiceProvider();
            DescriptorContext descriptorContext =
                DescriptorContext.Create(_options, services);

            IBindingLookup bindingLookup =
                _bindingCompiler.Compile(descriptorContext);

            var types = new List <ITypeReference>(_types);

            if (_documents.Count > 0)
            {
                types.AddRange(ParseDocuments(services, bindingLookup));
            }

            if (_schema == null)
            {
                types.Add(new SchemaTypeReference(new Schema()));
            }
            else
            {
                types.Add(_schema);
            }

            var lazy = new LazySchema();

            TypeInitializer initializer =
                InitializeTypes(
                    services,
                    descriptorContext,
                    bindingLookup,
                    types,
                    () => lazy.Schema);

            SchemaTypesDefinition definition =
                CreateSchemaDefinition(initializer);

            if (definition.QueryType == null && _options.StrictValidation)
            {
                throw new SchemaException(
                          SchemaErrorBuilder.New()
                          .SetMessage(TypeResources.SchemaBuilder_NoQueryType)
                          .Build());
            }

            Schema schema = initializer.Types.Values
                            .Select(t => t.Type)
                            .OfType <Schema>()
                            .First();

            schema.CompleteSchema(definition);
            lazy.Schema = schema;
            return(schema);
        }
Ejemplo n.º 13
0
        public void EntityTypeSerializesAsODataEntry()
        {
            // Arrange
            ODataMediaTypeFormatter formatter = CreateFormatter();
            Employee employee = (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee);
            ObjectContent <Employee> content = new ObjectContent <Employee>(employee, formatter,
                                                                            ODataMediaTypes.ApplicationJsonODataMinimalMetadata);

            // Act & Assert
            JsonAssert.Equal(Resources.EmployeeEntry, content.ReadAsStringAsync().Result);
        }
Ejemplo n.º 14
0
        public Schema Create()
        {
            IServiceProvider services = _services ?? new EmptyServiceProvider();

            var descriptorContext = DescriptorContext.Create(
                _options,
                services,
                CreateConventions(services),
                _contextData);

            foreach (Action <IDescriptorContext> action in _onBeforeCreate)
            {
                action(descriptorContext);
            }

            IBindingLookup bindingLookup =
                _bindingCompiler.Compile(descriptorContext);

            IReadOnlyCollection <ITypeReference> types =
                GetTypeReferences(services, bindingLookup);

            var lazy = new LazySchema();

            TypeInitializer initializer =
                CreateTypeInitializer(
                    services,
                    descriptorContext,
                    bindingLookup,
                    types);

            DiscoveredTypes discoveredTypes = initializer.Initialize(() => lazy.Schema, _options);

            SchemaTypesDefinition definition = CreateSchemaDefinition(initializer, discoveredTypes);

            if (definition.QueryType == null && _options.StrictValidation)
            {
                throw new SchemaException(
                          SchemaErrorBuilder.New()
                          .SetMessage(TypeResources.SchemaBuilder_NoQueryType)
                          .Build());
            }

            Schema schema = discoveredTypes.Types
                            .Select(t => t.Type)
                            .OfType <Schema>()
                            .First();

            schema.CompleteSchema(definition);
            lazy.Schema = schema;
            TypeInspector.Default.Clear();
            return(schema);
        }
Ejemplo n.º 15
0
        public void CollectionOfObjectsSerializesAsOData()
        {
            Collection <object> collectionOfObjects = new Collection <object>();

            collectionOfObjects.Add(1);
            collectionOfObjects.Add("Frank");
            collectionOfObjects.Add(TypeInitializer.GetInstance(SupportedTypes.Person, 2));
            collectionOfObjects.Add(TypeInitializer.GetInstance(SupportedTypes.Employee, 3));

            ObjectContent <Collection <object> > content = new ObjectContent <Collection <object> >(collectionOfObjects, _formatter);

            Assert.Throws <ODataException>(() => content.ReadAsStringAsync().Result);
        }
Ejemplo n.º 16
0
            private static TypeRegistry InitializeTypes(
                SchemaBuilder builder,
                IDescriptorContext context,
                IReadOnlyList <ITypeReference> types,
                LazySchema lazySchema)
            {
                var             typeRegistry = new TypeRegistry(context.TypeInterceptor);
                TypeInitializer initializer  =
                    CreateTypeInitializer(builder, context, types, typeRegistry);

                initializer.Initialize(() => lazySchema.Schema, builder._options);
                return(typeRegistry);
            }
Ejemplo n.º 17
0
        public void CollectionOfComplexTypeSerializesAsOData()
        {
            IEnumerable <Person> collectionOfPerson = new Collection <Person>()
            {
                (Person)TypeInitializer.GetInstance(SupportedTypes.Person, 0),
                (Person)TypeInitializer.GetInstance(SupportedTypes.Person, 1),
                (Person)TypeInitializer.GetInstance(SupportedTypes.Person, 2)
            };

            ObjectContent <IEnumerable <Person> > content = new ObjectContent <IEnumerable <Person> >(collectionOfPerson, _formatter);

            Assert.Xml.Equal(BaselineResource.TestCollectionOfPerson, content.ReadAsStringAsync().Result);
        }
            private static TypeInitializer CreateTypeInitializer(
                SchemaBuilder builder,
                IDescriptorContext context,
                IBindingLookup bindingLookup,
                IReadOnlyList <ITypeReference> typeReferences,
                TypeRegistry typeRegistry)
            {
                Dictionary <OperationType, ITypeReference> operations =
                    builder._operations.ToDictionary(t => t.Key, t => t.Value(context.TypeInspector));

                var interceptor = new AggregateTypeInitializationInterceptor(
                    CreateInterceptors(builder, context.Services));

                var initializer = new TypeInitializer(
                    context,
                    typeRegistry,
                    typeReferences,
                    builder._resolverTypes,
                    interceptor,
                    builder._isOfType,
                    type => IsQueryType(context.TypeInspector, type, operations));

                foreach (FieldMiddleware component in builder._globalComponents)
                {
                    initializer.GlobalComponents.Add(component);
                }

                foreach (FieldReference reference in builder._resolvers.Keys)
                {
                    initializer.Resolvers[reference] = new RegisteredResolver(
                        typeof(object), builder._resolvers[reference]);
                }

                foreach (RegisteredResolver resolver in
                         bindingLookup.Bindings.SelectMany(t => t.CreateResolvers()))
                {
                    var reference = new FieldReference(
                        resolver.Field.TypeName,
                        resolver.Field.FieldName);
                    initializer.Resolvers[reference] = resolver;
                }

                foreach (KeyValuePair <Type, (CreateRef, CreateRef)> binding in builder._clrTypes)
                {
                    typeRegistry.TryRegister(
                        (ExtendedTypeReference)binding.Value.Item1(context.TypeInspector),
                        binding.Value.Item2.Invoke(context.TypeInspector));
                }

                return(initializer);
            }
Ejemplo n.º 19
0
        private void CollectionOfComplexTypeSerializesAsOData(string expectedContent, bool json)
        {
            IEnumerable <Person> collectionOfPerson = new Collection <Person>()
            {
                (Person)TypeInitializer.GetInstance(SupportedTypes.Person, 0),
                (Person)TypeInitializer.GetInstance(SupportedTypes.Person, 1),
                (Person)TypeInitializer.GetInstance(SupportedTypes.Person, 2)
            };

            ObjectContent <IEnumerable <Person> > content = new ObjectContent <IEnumerable <Person> >(collectionOfPerson,
                                                                                                      _formatter, GetMediaType(json));

            AssertEqual(json, expectedContent, content.ReadAsStringAsync().Result);
        }
Ejemplo n.º 20
0
        public void IEnumerableOfEntityTypeSerializesAsODataFeed()
        {
            ODataMediaTypeFormatter formatter = CreateFormatter();

            IEnumerable <Employee> collectionOfPerson = new Collection <Employee>()
            {
                (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee, 0),
                (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee, 1),
            };

            ObjectContent <IEnumerable <Employee> > content = new ObjectContent <IEnumerable <Employee> >(collectionOfPerson, formatter);

            RegexReplacement replaceUpdateTime = new RegexReplacement("<updated>*.*</updated>", "<updated>UpdatedTime</updated>");

            Assert.Xml.Equal(BaselineResource.TestFeedOfEmployee, content.ReadAsStringAsync().Result, regexReplacements: replaceUpdateTime);
        }
Ejemplo n.º 21
0
        public void CollectionOfComplexTypeSerializesAsOData()
        {
            // Arrange
            IEnumerable <Person> collectionOfPerson = new Collection <Person>()
            {
                (Person)TypeInitializer.GetInstance(SupportedTypes.Person, 0),
                (Person)TypeInitializer.GetInstance(SupportedTypes.Person, 1),
                (Person)TypeInitializer.GetInstance(SupportedTypes.Person, 2)
            };

            ObjectContent <IEnumerable <Person> > content = new ObjectContent <IEnumerable <Person> >(collectionOfPerson,
                                                                                                      _formatter, ODataMediaTypes.ApplicationJsonODataMinimalMetadata);

            // Act & Assert
            JsonAssert.Equal(Resources.CollectionOfPerson, content.ReadAsStringAsync().Result);
        }
        private TypeInitializer CreateTypeInitializer(
            IServiceProvider services,
            IDescriptorContext descriptorContext,
            IBindingLookup bindingLookup,
            IEnumerable <ITypeReference> types)
        {
            var interceptor = new AggregateTypeInitializationInterceptor(
                CreateInterceptors(services));

            var initializer = new TypeInitializer(
                services,
                descriptorContext,
                _contextData,
                types,
                _resolverTypes,
                interceptor,
                _isOfType,
                IsQueryType);

            foreach (FieldMiddleware component in _globalComponents)
            {
                initializer.GlobalComponents.Add(component);
            }

            foreach (FieldReference reference in _resolvers.Keys)
            {
                initializer.Resolvers[reference] = new RegisteredResolver(
                    typeof(object), _resolvers[reference]);
            }

            foreach (RegisteredResolver resolver in bindingLookup.Bindings
                     .SelectMany(t => t.CreateResolvers()))
            {
                var reference = new FieldReference(
                    resolver.Field.TypeName,
                    resolver.Field.FieldName);
                initializer.Resolvers[reference] = resolver;
            }

            foreach (KeyValuePair <IClrTypeReference, ITypeReference> binding in
                     _clrTypes)
            {
                initializer.ClrTypes[binding.Key] = binding.Value;
            }

            return(initializer);
        }
Ejemplo n.º 23
0
        public void Register_ClrType_InferSchemaTypes()
        {
            // arrange
            var initialTypes = new List <ITypeReference>();

            initialTypes.Add(new ClrTypeReference(
                                 typeof(Foo),
                                 TypeContext.Output));

            var serviceProvider = new EmptyServiceProvider();

            var typeInitializer = new TypeInitializer(
                serviceProvider,
                DescriptorContext.Create(),
                initialTypes,
                new List <Type>(),
                new Dictionary <string, object>(),
                new AggregateTypeInitilizationInterceptor(),
                null,
                t => t is ObjectType <Foo>);

            // act
            typeInitializer.Initialize(() => null, new SchemaOptions());

            // assert
            bool exists = typeInitializer.Types.TryGetValue(
                new ClrTypeReference(
                    typeof(ObjectType <Foo>),
                    TypeContext.Output),
                out RegisteredType type);

            Assert.True(exists);
            Assert.IsType <ObjectType <Foo> >(type.Type).Fields.ToDictionary(
                t => t.Name.ToString(),
                t => TypeVisualizer.Visualize(t.Type))
            .MatchSnapshot(new SnapshotNameExtension("FooType"));

            exists = typeInitializer.Types.TryGetValue(
                new ClrTypeReference(typeof(ObjectType <Bar>), TypeContext.Output),
                out type);

            Assert.True(exists);
            Assert.IsType <ObjectType <Bar> >(type.Type).Fields.ToDictionary(
                t => t.Name.ToString(),
                t => TypeVisualizer.Visualize(t.Type))
            .MatchSnapshot(new SnapshotNameExtension("BarType"));
        }
        private static void WriteToStreamAsyncReturnsODataRepresentation(string expectedContent, bool json)
        {
            ODataConventionModelBuilder modelBuilder = new ODataConventionModelBuilder();

            modelBuilder.EntitySet <WorkItem>("WorkItems");
            IEdmModel model = modelBuilder.GetEdmModel();

            HttpRequestMessage request       = new HttpRequestMessage(HttpMethod.Get, "http://localhost/WorkItems(10)");
            HttpConfiguration  configuration = new HttpConfiguration();
            string             routeName     = "Route";

            configuration.Routes.MapODataRoute(routeName, null, model);
            request.SetConfiguration(configuration);
            request.SetEdmModel(model);
            IEdmEntitySet entitySet = model.EntityContainers().Single().EntitySets().Single();

            request.SetODataPath(new ODataPath(new EntitySetPathSegment(entitySet), new KeyValuePathSegment("10")));
            request.SetODataRouteName(routeName);

            ODataMediaTypeFormatter formatter;

            if (json)
            {
                formatter = CreateFormatterWithJson(model, request, ODataPayloadKind.Entry);
            }
            else
            {
                formatter = CreateFormatter(model, request, ODataPayloadKind.Entry);
            }

            ObjectContent <WorkItem> content = new ObjectContent <WorkItem>(
                (WorkItem)TypeInitializer.GetInstance(SupportedTypes.WorkItem), formatter);

            string actualContent = content.ReadAsStringAsync().Result;

            if (json)
            {
                JsonAssert.Equal(expectedContent, actualContent);
            }
            else
            {
                RegexReplacement replaceUpdateTime = new RegexReplacement(
                    "<updated>*.*</updated>", "<updated>UpdatedTime</updated>");
                Assert.Xml.Equal(expectedContent, actualContent, replaceUpdateTime);
            }
        }
Ejemplo n.º 25
0
        public Schema Create()
        {
            IServiceProvider services = _services
                                        ?? new EmptyServiceProvider();

            var descriptorContext = DescriptorContext.Create(
                _options,
                services,
                CreateConventions(services));

            IBindingLookup bindingLookup =
                _bindingCompiler.Compile(descriptorContext);

            IReadOnlyCollection <ITypeReference> types =
                GetTypeReferences(services, bindingLookup);

            var lazy = new LazySchema();

            TypeInitializer initializer =
                InitializeTypes(
                    services,
                    descriptorContext,
                    bindingLookup,
                    types,
                    () => lazy.Schema);

            SchemaTypesDefinition definition =
                CreateSchemaDefinition(initializer);

            if (definition.QueryType == null && _options.StrictValidation)
            {
                throw new SchemaException(
                          SchemaErrorBuilder.New()
                          .SetMessage(TypeResources.SchemaBuilder_NoQueryType)
                          .Build());
            }

            Schema schema = initializer.Types.Values
                            .Select(t => t.Type)
                            .OfType <Schema>()
                            .First();

            schema.CompleteSchema(definition);
            lazy.Schema = schema;
            return(schema);
        }
Ejemplo n.º 26
0
        public void IEnumerableOfEntityTypeSerializesAsODataFeed()
        {
            // Arrange
            ODataMediaTypeFormatter formatter = CreateFormatter();

            IEnumerable <Employee> collectionOfPerson = new Collection <Employee>()
            {
                (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee, 0),
                (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee, 1),
            };

            ObjectContent <IEnumerable <Employee> > content = new ObjectContent <IEnumerable <Employee> >(collectionOfPerson,
                                                                                                          formatter, ODataMediaTypes.ApplicationJsonODataMinimalMetadata);

            // Act & Assert
            JsonAssert.Equal(Resources.FeedOfEmployee, content.ReadAsStringAsync().Result);
        }
Ejemplo n.º 27
0
        public async Task EntityTypeSerializesAsODataEntry()
        {
            // Arrange
            const string  routeName = "OData";
            IEdmEntitySet entitySet = _model.EntityContainer.FindEntitySet("employees");
            ODataPath     path      = new ODataPath(new EntitySetSegment(entitySet));

            var      config    = RoutingConfigurationFactory.CreateWithRootContainer(routeName, b => b.AddService(ServiceLifetime.Singleton, s => _model));
            var      request   = RequestFactory.Create(HttpMethod.Get, "http://localhost/property", config, routeName, path);
            var      payload   = new ODataPayloadKind[] { ODataPayloadKind.Resource };
            var      formatter = FormatterTestHelper.GetFormatter(payload, request);
            Employee employee  = (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee);
            var      content   = FormatterTestHelper.GetContent(employee, formatter,
                                                                ODataMediaTypes.ApplicationJsonODataMinimalMetadata);

            // Act & Assert
            JsonAssert.Equal(Resources.EmployeeEntry, await FormatterTestHelper.GetContentResult(content, request));
        }
Ejemplo n.º 28
0
        public Employee(int index, ReferenceDepthContext context)
            : base(index, context)
        {
            this.EmployeeId = index;
            this.WorkItem   = new WorkItem()
            {
                EmployeeID = index, IsCompleted = false, NumberOfHours = ((index + 100) / 6), WorkItemID = index + 25
            };
            this.Manager = (Employee)TypeInitializer.InternalGetInstance(SupportedTypes.Employee, (index + 1) % (DataSource.MaxIndex + 1), context);

            this.DirectReports = new System.Collections.Generic.List <Employee>();
            Employee directEmployee = (Employee)TypeInitializer.InternalGetInstance(SupportedTypes.Employee, (index + 2) % (DataSource.MaxIndex + 1), context);

            if (directEmployee != null)
            {
                this.DirectReports.Add(directEmployee);
            }
        }
Ejemplo n.º 29
0
        public void Register_SchemaType_ClrTypeExists()
        {
            // arrange
            var initialTypes = new List <ITypeReference>();

            initialTypes.Add(new ClrTypeReference(
                                 typeof(FooType),
                                 TypeContext.Output));

            var serviceProvider = new EmptyServiceProvider();

            var typeInitializer = new TypeInitializer(
                serviceProvider,
                initialTypes,
                new List <Type>(),
                new Dictionary <string, object>(),
                null,
                t => t is FooType);

            // act
            typeInitializer.Initialize(() => null);

            // assert
            bool exists = typeInitializer.Types.TryGetValue(
                new ClrTypeReference(typeof(FooType), TypeContext.Output),
                out RegisteredType type);

            Assert.True(exists);
            Assert.IsType <FooType>(type.Type).Fields.ToDictionary(
                t => t.Name.ToString(),
                t => TypeVisualizer.Visualize(t.Type))
            .MatchSnapshot(new SnapshotNameExtension("FooType"));

            exists = typeInitializer.Types.TryGetValue(
                new ClrTypeReference(typeof(BarType), TypeContext.Output),
                out type);

            Assert.True(exists);
            Assert.IsType <BarType>(type.Type).Fields.ToDictionary(
                t => t.Name.ToString(),
                t => TypeVisualizer.Visualize(t.Type))
            .MatchSnapshot(new SnapshotNameExtension("BarType"));
        }
Ejemplo n.º 30
0
        private void EntityTypeSerializesAsODataEntry(string expectedContent, bool json)
        {
            ODataMediaTypeFormatter formatter = CreateFormatter();
            Employee employee = (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee);
            ObjectContent <Employee> content = new ObjectContent <Employee>(employee, formatter, json ?
                                                                            ODataMediaTypes.ApplicationJsonODataMinimalMetadata : ODataMediaTypes.ApplicationAtomXmlTypeEntry);

            string actualContent = content.ReadAsStringAsync().Result;

            if (json)
            {
                JsonAssert.Equal(expectedContent, actualContent);
            }
            else
            {
                RegexReplacement replaceUpdateTime = new RegexReplacement(
                    "<updated>*.*</updated>", "<updated>UpdatedTime</updated>");
                Assert.Xml.Equal(expectedContent, actualContent, replaceUpdateTime);
            }
        }