/// <summary>
        /// Set Org.OData.Capabilities.V1.CountRestrictions to target.
        /// </summary>
        /// <param name="model">The model referenced to.</param>
        /// <param name="target">The target entity set to set the inline annotation.</param>
        /// <param name="isCountable">This entity set can be counted.</param>
        /// <param name="nonCountableProperties">These collection properties do not allow /$count segments.</param>
        /// <param name="nonCountableNavigationProperties">These navigation properties do not allow /$count segments.</param>
        public static void SetCountRestrictionsAnnotation(this EdmModel model, IEdmEntitySet target, bool isCountable,
            IEnumerable<IEdmProperty> nonCountableProperties,
            IEnumerable<IEdmNavigationProperty> nonCountableNavigationProperties)
        {
            if (model == null)
            {
                throw Error.ArgumentNull("model");
            }

            if (target == null)
            {
                throw Error.ArgumentNull("target");
            }

            nonCountableProperties = nonCountableProperties ?? EmptyStructuralProperties;
            nonCountableNavigationProperties = nonCountableNavigationProperties ?? EmptyNavigationProperties;

            IList<IEdmPropertyConstructor> properties = new List<IEdmPropertyConstructor>
            {
                new EdmPropertyConstructor(CapabilitiesVocabularyConstants.CountRestrictionsCountable,
                    new EdmBooleanConstant(isCountable)),

                new EdmPropertyConstructor(CapabilitiesVocabularyConstants.CountRestrictionsNonCountableProperties,
                    new EdmCollectionExpression(
                        nonCountableProperties.Select(p => new EdmPropertyPathExpression(p.Name)).ToArray())),

                new EdmPropertyConstructor(CapabilitiesVocabularyConstants.CountRestrictionsNonCountableNavigationProperties,
                    new EdmCollectionExpression(
                        nonCountableNavigationProperties.Select(p => new EdmNavigationPropertyPathExpression(p.Name)).ToArray()))
            };

            model.SetVocabularyAnnotation(target, properties, CapabilitiesVocabularyConstants.CountRestrictions);
        }
        public ODataFeedSerializerTests()
        {
            _model = SerializationTestsHelpers.SimpleCustomerOrderModel();
            _customerSet = _model.FindDeclaredEntityContainer("Default.Container").FindEntitySet("Customers");
            _customers = new[] {
                new Customer()
                {
                    FirstName = "Foo",
                    LastName = "Bar",
                    ID = 10,
                },
                new Customer()
                {
                    FirstName = "Foo",
                    LastName = "Bar",
                    ID = 42,
                }
            };

            _customersType = new EdmCollectionTypeReference(
                    new EdmCollectionType(
                        new EdmEntityTypeReference(
                            _customerSet.ElementType,
                            isNullable: false)),
                    isNullable: false);

            _writeContext = new ODataSerializerContext() { EntitySet = _customerSet, Model = _model };
        }
Exemple #3
0
        /// <summary>
        /// Creates a new ODataEntry from the specified entity set, instance, and type.
        /// </summary>
        /// <param name="entitySet">Entity set for the new entry.</param>
        /// <param name="value">Entity instance for the new entry.</param>
        /// <param name="entityType">Entity type for the new entry.</param>
        /// <returns>New ODataEntry with the specified entity set and type, property values from the specified instance.</returns>
        internal static ODataEntry CreateODataEntry(IEdmEntitySet entitySet, IEdmStructuredValue value, IEdmEntityType entityType)
        {
            var entry = new ODataEntry();
            entry.SetAnnotation(new ODataTypeAnnotation(entitySet, entityType));
            entry.Properties = value.PropertyValues.Select(p =>
            {
                object propertyValue;
                if (p.Value.ValueKind == EdmValueKind.Null)
                {
                    propertyValue = null;
                }
                else if (p.Value is IEdmPrimitiveValue)
                {
                    propertyValue = ((IEdmPrimitiveValue)p.Value).ToClrValue();
                }
                else
                {
                    Assert.Fail("Test only currently supports creating ODataEntry from IEdmPrimitiveValue instances.");
                    return null;
                }

                return new ODataProperty() { Name = p.Name, Value = propertyValue };
            });

            return entry;
        }
        /// <summary>
        /// Converts an item from the data store into an ODataEntry.
        /// </summary>
        /// <param name="element">The item to convert.</param>
        /// <param name="entitySet">The entity set that the item belongs to.</param>
        /// <param name="targetVersion">The OData version this segment is targeting.</param>
        /// <returns>The converted ODataEntry.</returns>
        public static ODataEntry ConvertToODataEntry(object element, IEdmEntitySet entitySet, ODataVersion targetVersion)
        {
            IEdmEntityType entityType = entitySet.EntityType();

            Uri entryUri = BuildEntryUri(element, entitySet, targetVersion);

            var entry = new ODataEntry
            {
                // writes out the edit link including the service base uri  , e.g.: http://<serviceBase>/Customers('ALFKI')
                EditLink = entryUri,

                // writes out the self link including the service base uri  , e.g.: http://<serviceBase>/Customers('ALFKI')
                ReadLink = entryUri,

                // we use the EditLink as the Id for this entity to maintain convention,
                Id = entryUri,

                // writes out the <category term='Customer'/> element 
                TypeName = element.GetType().Namespace + "." + entityType.Name,

                Properties = entityType.StructuralProperties().Select(p => ConvertToODataProperty(element, p.Name)),
            };

            return entry;
        }
Exemple #5
0
 /// <summary>
 /// Creates an <see cref="EntitySetNode"/>
 /// </summary>
 /// <param name="entitySet">The entity set this node represents</param>
 /// <exception cref="System.ArgumentNullException">Throws if the input entitySet is null.</exception>
 public EntitySetNode(IEdmEntitySet entitySet)
 {
     ExceptionUtils.CheckArgumentNotNull(entitySet, "entitySet");
     this.entitySet = entitySet;
     this.entityType = new EdmEntityTypeReference(this.NavigationSource.EntityType(), false);
     this.collectionTypeReference = EdmCoreModel.GetCollection(this.entityType);
 }
        public ODataFeedSerializerTests()
        {
            _model = SerializationTestsHelpers.SimpleCustomerOrderModel();
            _customerSet = _model.FindDeclaredEntityContainer("Default.Container").FindEntitySet("Customers");
            _customers = new[] {
                new Customer()
                {
                    FirstName = "Foo",
                    LastName = "Bar",
                    ID = 10,
                },
                new Customer()
                {
                    FirstName = "Foo",
                    LastName = "Bar",
                    ID = 42,
                }
            };

            _customersType = new EdmCollectionTypeReference(
                    new EdmCollectionType(
                        new EdmEntityTypeReference(
                            _customerSet.ElementType,
                            isNullable: false)),
                    isNullable: false);

            _urlHelper = new Mock<UrlHelper>(new HttpRequestMessage()).Object;
            _writeContext = new ODataSerializerWriteContext(new ODataResponseContext()) { EntitySet = _customerSet, UrlHelper = _urlHelper };
        }
        internal EntitySetInfo(IEdmModel edmModel, IEdmEntitySet edmEntitySet, ITypeResolver typeResolver)
        {
            Contract.Assert(edmModel != null);
            Contract.Assert(edmEntitySet != null);
            Contract.Assert(typeResolver != null);

            Name = edmEntitySet.Name;
            ElementType = new EntityTypeInfo(edmModel, edmEntitySet.ElementType, typeResolver);
            var entityTypes = new List<EntityTypeInfo>(3) { ElementType };

            // Create an EntityTypeInfo for any derived types in the model
            foreach (var edmDerivedType in edmModel.FindAllDerivedTypes(edmEntitySet.ElementType).OfType<IEdmEntityType>())
            {
                entityTypes.Add(new EntityTypeInfo(edmModel, edmDerivedType, typeResolver));
            }

            // Connect any derived types with their base class
            for (int i = 1; i < entityTypes.Count; ++i)
            {
                var baseEdmEntityType = entityTypes[i].EdmEntityType.BaseEntityType();
                if (baseEdmEntityType != null)
                {
                    var baseEntityTypeInfo = entityTypes.First(entityTypeInfo => entityTypeInfo.EdmEntityType == baseEdmEntityType);
                    if (baseEntityTypeInfo != null)
                    {
                        entityTypes[i].BaseTypeInfo = baseEntityTypeInfo;
                    }
                }
            }

            EntityTypes = entityTypes;
        }
        public ODataDeltaFeedSerializerTests()
        {
            _model = SerializationTestsHelpers.SimpleCustomerOrderModel();
            _customerSet = _model.EntityContainer.FindEntitySet("Customers");
            _model.SetAnnotationValue(_customerSet.EntityType(), new ClrTypeAnnotation(typeof(Customer)));
            _path = new ODataPath(new EntitySetPathSegment(_customerSet));
            _customers = new[] {
                new Customer()
                {
                    FirstName = "Foo",
                    LastName = "Bar",
                    ID = 10,
                },
                new Customer()
                {
                    FirstName = "Foo",
                    LastName = "Bar",
                    ID = 42,
                }
            };

            _deltaFeedCustomers = new EdmChangedObjectCollection(_customerSet.EntityType());
            EdmDeltaEntityObject newCustomer = new EdmDeltaEntityObject(_customerSet.EntityType());
            newCustomer.TrySetPropertyValue("ID", 10);
            newCustomer.TrySetPropertyValue("FirstName", "Foo");
            _deltaFeedCustomers.Add(newCustomer);

             _customersType = _model.GetEdmTypeReference(typeof(Customer[])).AsCollection();

            _writeContext = new ODataSerializerContext() { NavigationSource = _customerSet, Model = _model, Path = _path };
        }
        public ParameterAliasNodeTranslatorTest()
        {
            var builder = new ODataConventionModelBuilder();
            builder.EntitySet<ParameterAliasCustomer>("Customers");
            builder.EntitySet<ParameterAliasOrder>("Orders");

            builder.EntityType<ParameterAliasCustomer>().Function("CollectionFunctionCall")
                .ReturnsCollection<int>().Parameter<int>("p1");

            builder.EntityType<ParameterAliasCustomer>().Function("EntityCollectionFunctionCall")
                .ReturnsCollectionFromEntitySet<ParameterAliasCustomer>("Customers").Parameter<int>("p1");

            builder.EntityType<ParameterAliasCustomer>().Function("SingleEntityFunctionCall")
                .Returns<ParameterAliasCustomer>().Parameter<int>("p1");

            builder.EntityType<ParameterAliasCustomer>().Function("SingleEntityFunctionCallWithoutParameters")
                .Returns<ParameterAliasCustomer>();

            builder.EntityType<ParameterAliasCustomer>().Function("SingleValueFunctionCall")
                .Returns<int>().Parameter<int>("p1");

            _model = builder.GetEdmModel();
            _customersEntitySet = _model.FindDeclaredEntitySet("Customers");
            _customerEntityType = _customersEntitySet.EntityType();
            _parameterAliasMappedNode = new ConstantNode(123);
        }
 public ParserExtModel()
 {
     Person = (IEdmEntityType)Model.FindType("TestNS.Person");
     Pet = Model.FindType("TestNS.Pet");
     Fish = Model.FindType("TestNS.Fish");
     People = Model.FindDeclaredEntitySet("People");
     PetSet = Model.FindDeclaredEntitySet("PetSet");
 }
        public void Initialize()
        {
            this.model = Utils.BuildModel("Default.ExtendedNamespace");
            this.defaultContainer = model.EntityContainer;

            this.peopleSet = this.defaultContainer.FindEntitySet("People");
            this.placesSet = this.defaultContainer.FindEntitySet("Places");
            this.organizationsSet = this.defaultContainer.FindEntitySet("Organizations");
        }
        public static void SetEntitySetLinkBuilder(this IEdmModel model, IEdmEntitySet entitySet, EntitySetLinkBuilderAnnotation entitySetLinkBuilder)
        {
            if (model == null)
            {
                throw Error.ArgumentNull("model");
            }

            model.SetAnnotationValue(entitySet, entitySetLinkBuilder);
        }
        public MetadataUriRoundTripTests()
        {
            this.model = Utils.BuildModel("Default.ExtendedNamespace");
            this.defaultContainer = model.EntityContainer;

            this.peopleSet = this.defaultContainer.FindEntitySet("People");
            this.placesSet = this.defaultContainer.FindEntitySet("Places");
            this.organizationsSet = this.defaultContainer.FindEntitySet("Organizations");
        }
        internal static IEntitySetLinkBuilder GetEntitySetLinkBuilder(this IEdmModel model, IEdmEntitySet entitySet)
        {
            IEntitySetLinkBuilder annotation = model.GetAnnotationValue<IEntitySetLinkBuilder>(entitySet);
            if (annotation == null)
            {
                throw Error.NotSupported(SRResources.EntitySetHasNoBuildLinkAnnotation, entitySet.Name);
            }

            return annotation;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EntitySetPathSegment" /> class.
        /// </summary>
        /// <param name="entitySet">The entity set being accessed.</param>
        public EntitySetPathSegment(IEdmEntitySet entitySet)
        {
            if (entitySet == null)
            {
                throw Error.ArgumentNull("entitySet");
            }

            EntitySet = entitySet;
            EntitySetName = entitySet.Name;
        }
        /// <summary>
        /// Sets the navigation target for a particular navigation property.
        /// </summary>
        /// <param name="navigationProperty">The navigation property.</param>
        /// <param name="target">The target entity set.</param>
        public void SetNavigationTarget(IEdmNavigationProperty navigationProperty, IEdmEntitySet target)
        {
            this.navigationTargets[navigationProperty] = target;

            var stubTarget = (StubEdmEntitySet)target;
            if (stubTarget.FindNavigationTarget(navigationProperty.Partner) != this) 
            {
                stubTarget.SetNavigationTarget(navigationProperty.Partner, this);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EntitySetPathSegment" /> class.
        /// </summary>
        /// <param name="entitySet">The entity set being accessed.</param>
        public EntitySetPathSegment(IEdmEntitySet entitySet)
        {
            if (entitySet == null)
            {
                throw Error.ArgumentNull("entitySet");
            }

            EdmType = entitySet.ElementType.GetCollection();
            EntitySet = entitySet;
        }
Exemple #18
0
        /// <summary>
        /// Writes an OData entry.
        /// </summary>
        /// <param name="writer">The ODataWriter that will write the entry.</param>
        /// <param name="element">The item from the data store to write.</param>
        /// <param name="entitySet">The entity set in the model that the entry belongs to.</param>
        /// <param name="model">The data store model.</param>
        /// <param name="targetVersion">The OData version this segment is targeting.</param>
        /// <param name="expandedNavigationProperties">A list of navigation property names to expand.</param>
        public static void WriteEntry(ODataWriter writer, object element, IEdmEntitySet entitySet, IEdmModel model, ODataVersion targetVersion, IEnumerable<string> expandedNavigationProperties) 
        {
            var entry = ODataObjectModelConverter.ConvertToODataEntry(element, entitySet, targetVersion);

            writer.WriteStart(entry);

            // Here, we write out the links for the navigation properties off of the entity type
            WriteNavigationLinks(writer, element, entry.ReadLink, entitySet.EntityType(), model, targetVersion, expandedNavigationProperties);

            writer.WriteEnd();
        }
        public AutoGeneratedUrlsShouldPutKeyValueInDedicatedSegmentTests()
        {
            this.model = new EdmModel();
            this.entityContainer = new EdmEntityContainer("Namespace", "Container");

            this.personType = new EdmEntityType("Namespace", "Person");
            this.personType.AddKeys(this.personType.AddStructuralProperty("Key", EdmPrimitiveTypeKind.String));
            this.peopleSet = this.entityContainer.AddEntitySet("People", personType);
            model.AddElement(this.entityContainer);
            model.AddElement(this.personType);
        }
        public void Initialize()
        {
            this.model = new EdmModel();
            this.entityContainer = new EdmEntityContainer("Namespace", "Container");

            this.personType = new EdmEntityType("Namespace", "Person");
            this.personType.AddKeys(this.personType.AddStructuralProperty("Key", EdmPrimitiveTypeKind.String));
            this.peopleSet = this.entityContainer.AddEntitySet("People", personType);
            model.AddElement(this.entityContainer);
            model.AddElement(this.personType);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EntitySetPathSegment" /> class.
        /// </summary>
        /// <param name="previous">The previous segment in the path.</param>
        /// <param name="entitySet">The entity set being accessed.</param>
        public EntitySetPathSegment(ODataPathSegment previous, IEdmEntitySet entitySet)
            : base(previous)
        {
            if (entitySet == null)
            {
                throw Error.ArgumentNull("entitySet");
            }

            EdmType = entitySet.ElementType.GetCollection();
            EntitySet = entitySet;
        }
        public ODataSwaggerUtilitiesTest()
        {
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            _customer = model.Customer;
            _customers = model.Customers;

            IEdmAction action = new EdmAction("NS", "GetCustomers", null, false, null);
            _getCustomers = new EdmActionImport(model.Container, "GetCustomers", action);

            _isAnyUpgraded = model.Model.SchemaElements.OfType<IEdmFunction>().FirstOrDefault(e => e.Name == "IsAnyUpgraded");
            _isCustomerUpgradedWithParam = model.Model.SchemaElements.OfType<IEdmFunction>().FirstOrDefault(e => e.Name == "IsUpgradedWithParam");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EdmEntitySetFacade"/> class.
        /// </summary>
        /// <param name="serverEntitySet">The entity set from the server model.</param>
        /// <param name="containerFacade">The entity container facade to which the set belongs.</param>
        /// <param name="modelFacade">The model facade.</param>
        internal EdmEntitySetFacade(IEdmEntitySet serverEntitySet, EdmEntityContainerFacade containerFacade, EdmModelFacade modelFacade)
        {
            Debug.Assert(serverEntitySet != null, "serverEntitySet != null");
            Debug.Assert(containerFacade != null, "container != null");
            Debug.Assert(modelFacade != null, "modelFacade != null");

            this.serverEntitySet = serverEntitySet;
            this.Container = containerFacade;
            this.modelFacade = modelFacade;
            
            this.Name = this.serverEntitySet.Name;
        }
Exemple #24
0
        /// <summary>
        /// Writes an OData feed.
        /// </summary>
        /// <param name="writer">The ODataWriter that will write the feed.</param>
        /// <param name="entries">The items from the data store to write to the feed.</param>
        /// <param name="entitySet">The entity set in the model that the feed belongs to.</param>
        /// <param name="model">The data store model.</param>
        /// <param name="targetVersion">The OData version this segment is targeting.</param>
        /// <param name="expandedNavigationProperties">A list of navigation property names to expand.</param>
        public static void WriteFeed(ODataWriter writer, IEnumerable entries, IEdmEntitySet entitySet, IEdmModel model, ODataVersion targetVersion, IEnumerable<string> expandedNavigationProperties)
        {
            var feed = new ODataFeed {Id = new Uri(ServiceConstants.ServiceBaseUri, entitySet.Name)};
            writer.WriteStart(feed);

            foreach (var element in entries)
            {
                WriteEntry(writer, element, entitySet, model, targetVersion, expandedNavigationProperties);
            }

            writer.WriteEnd();
        }
        static ExapndOptionFunctionalTests()
        {
            string namespaceA = "NS";
            EdmModel edmModel = new EdmModel();
            EdmEntityType type1 = new EdmEntityType(namespaceA, "T1");
            EdmEntityType type2 = new EdmEntityType(namespaceA, "T2", type1);
            EdmEntityType type3 = new EdmEntityType(namespaceA, "T3", type2);
            EdmNavigationProperty nav21 = type2.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo()
            {
                Name = "Nav21",
                ContainsTarget = false,
                Target = type1,
                TargetMultiplicity = EdmMultiplicity.ZeroOrOne,
            });

            EdmNavigationProperty nav22 = type2.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo()
            {
                Name = "Nav22",
                ContainsTarget = false,
                Target = type2,
                TargetMultiplicity = EdmMultiplicity.One,
            });

            EdmNavigationProperty nav23 = type2.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo()
            {
                Name = "Nav23",
                ContainsTarget = false,
                Target = type3,
                TargetMultiplicity = EdmMultiplicity.Many,
            });

            
            edmModel.AddElement(type1);
            edmModel.AddElement(type2);
            edmModel.AddElement(type3);

            EdmEntityContainer container = new EdmEntityContainer(namespaceA, "Con1");
            var set1 = container.AddEntitySet(namespaceA, type1);
            var set2 = container.AddEntitySet(namespaceA, type2);
            var set3 = container.AddEntitySet(namespaceA, type3);
            edmModel.AddElement(container);
            set2.AddNavigationTarget(nav21, set1);
            set2.AddNavigationTarget(nav22, set2);
            set2.AddNavigationTarget(nav23, set3);

            Model = edmModel;
            T2Type = type2;
            T3Type = type3;
            T2Set = set2;
            T3Set = set3;
        }
		internal EntitySetMetadata(Type contextType, IContainerMetadata container, IEdmEntitySet edmEntitySet, IEntityTypeMetadata entityTypeMetadata, IEntityTypeMetadata[] entityTypeHierarchyMetadata)
		{
			Contract.Assert(container != null);
			Contract.Assert(edmEntitySet != null);
			Contract.Assert(entityTypeMetadata != null);
			Contract.Assert(entityTypeHierarchyMetadata != null);
			Contract.Assert(entityTypeHierarchyMetadata.Length >= 1);

			ContextType = contextType;
			ContainerMetadata = container;
			_edmEntitySet = edmEntitySet;
			ElementTypeMetadata = entityTypeMetadata;
			ElementTypeHierarchyMetadata = entityTypeHierarchyMetadata;
		}
        /// <summary>
        /// Set Org.OData.Capabilities.V1.NavigationRestrictions to target.
        /// </summary>
        /// <param name="model">The model referenced to.</param>
        /// <param name="target">The target entity set to set the inline annotation.</param>
        /// <param name="navigability">This entity set supports navigability.</param>
        /// <param name="restrictedProperties">These properties have navigation restrictions on.</param>
        public static void SetNavigationRestrictionsAnnotation(this EdmModel model, IEdmEntitySet target,
            CapabilitiesNavigationType navigability,
            IEnumerable<Tuple<IEdmNavigationProperty, CapabilitiesNavigationType>> restrictedProperties)
        {
            if (model == null)
            {
                throw Error.ArgumentNull("model");
            }

            if (target == null)
            {
                throw Error.ArgumentNull("target");
            }

            IEdmEnumType navigationType = model.GetCapabilitiesNavigationType();
            if (navigationType == null)
            {
                return;
            }

            restrictedProperties = restrictedProperties ?? new Tuple<IEdmNavigationProperty, CapabilitiesNavigationType>[0];

            string type = new EdmEnumTypeReference(navigationType, false).ToStringLiteral((long)navigability);

            IEnumerable<EdmRecordExpression> propertiesExpression = restrictedProperties.Select(p =>
            {
                var name = new EdmEnumTypeReference(navigationType, false).ToStringLiteral((long)p.Item2);
                return new EdmRecordExpression(new IEdmPropertyConstructor[]
                {
                    new EdmPropertyConstructor(
                        CapabilitiesVocabularyConstants.NavigationPropertyRestrictionNavigationProperty,
                        new EdmNavigationPropertyPathExpression(p.Item1.Name)),
                    new EdmPropertyConstructor(CapabilitiesVocabularyConstants.NavigationRestrictionsNavigability,
                        new EdmEnumMemberReferenceExpression(navigationType.Members.Single(m => m.Name == name)))
                });
            });

            IList<IEdmPropertyConstructor> properties = new List<IEdmPropertyConstructor>
            {
                new EdmPropertyConstructor(CapabilitiesVocabularyConstants.NavigationRestrictionsNavigability,
                    new EdmEnumMemberReferenceExpression(
                        navigationType.Members.Single(m => m.Name == type))),

                new EdmPropertyConstructor(CapabilitiesVocabularyConstants.NavigationRestrictionsRestrictedProperties,
                    new EdmCollectionExpression(propertiesExpression))
            };

            model.SetVocabularyAnnotation(target, properties, CapabilitiesVocabularyConstants.NavigationRestrictions);
        }
Exemple #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ODataPath" /> class.
        /// </summary>
        /// <param name="segments">The path segments for the path.</param>
        public ODataPath(IList<ODataPathSegment> segments)
        {
            if (segments == null)
            {
                throw Error.ArgumentNull("segments");
            }

            foreach (ODataPathSegment segment in segments)
            {
                _edmType = segment.GetEdmType(_edmType);
                _entitySet = segment.GetEntitySet(_entitySet);
            }

            _segments = new ReadOnlyCollection<ODataPathSegment>(segments);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="FeedContext" /> class.
        /// </summary>
        /// <param name="entitySet">The entity set.</param>
        /// <param name="urlHelper">The URL helper.</param>
        /// <param name="feedInstance">The feed instance.</param>
        public FeedContext(IEdmEntitySet entitySet, UrlHelper urlHelper, object feedInstance)
        {
            if (entitySet == null)
            {
                throw Error.ArgumentNull("entitySet");
            }

            if (feedInstance == null)
            {
                throw Error.ArgumentNull("feedInstance");
            }

            EntitySet = entitySet;
            UrlHelper = urlHelper;
            FeedInstance = feedInstance;
        }
        public ODataCollectionSerializerTests()
        {
            _model = SerializationTestsHelpers.SimpleCustomerOrderModel();
            _customerSet = _model.FindDeclaredEntityContainer("Default.Container").FindEntitySet("Customers");
            _edmIntType = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Int32, isNullable: false);
            _customer = new Customer()
            {
                FirstName = "Foo",
                LastName = "Bar",
                ID = 10,
            };

            ODataSerializerProvider serializerProvider = new DefaultODataSerializerProvider();
            _collectionType = new EdmCollectionTypeReference(new EdmCollectionType(_edmIntType), isNullable: false);
            _serializer = new ODataCollectionSerializer(serializerProvider);
        }
        private IEdmModel GetEdmModelWithOperations(out IEdmEntityType customerType, out IEdmEntitySet customers)
        {
            EdmModel      model    = new EdmModel();
            EdmEntityType customer = new EdmEntityType("NS", "Customer");

            customerType = customer;
            customer.AddKeys(customer.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            model.AddElement(customer);

            EdmAction upgradeAll = new EdmAction("NS", "UpgradeAll", returnType: null, isBound: true, entitySetPathExpression: null);

            upgradeAll.AddParameter("entityset",
                                    new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(customer, false))));
            model.AddElement(upgradeAll);

            IEdmTypeReference returnType = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Boolean, isNullable: false);
            IEdmTypeReference stringType = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.String, isNullable: false);
            IEdmTypeReference intType    = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Int32, isNullable: false);

            EdmFunction IsAnyUpgraded = new EdmFunction(
                "NS",
                "IsAnyUpgraded",
                returnType,
                isBound: true,
                entitySetPathExpression: null,
                isComposable: false);
            EdmCollectionType edmCollectionType = new EdmCollectionType(new EdmEntityTypeReference(customer, false));

            IsAnyUpgraded.AddParameter("entityset", new EdmCollectionTypeReference(edmCollectionType));
            model.AddElement(IsAnyUpgraded);

            EdmFunction isCustomerUpgradedWithParam = new EdmFunction(
                "NS",
                "IsUpgradedWithParam",
                returnType,
                isBound: true,
                entitySetPathExpression: null,
                isComposable: false);

            isCustomerUpgradedWithParam.AddParameter("entity", new EdmEntityTypeReference(customer, false));
            isCustomerUpgradedWithParam.AddParameter("city", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.String, isNullable: false));
            model.AddElement(isCustomerUpgradedWithParam);

            EdmFunction isAllUpgraded = new EdmFunction("NS", "IsAllUpgraded", returnType, isBound: true,
                                                        entitySetPathExpression: null, isComposable: false);

            isAllUpgraded.AddParameter("entityset",
                                       new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(customer, false))));
            isAllUpgraded.AddParameter("param", intType);
            model.AddElement(isAllUpgraded);

            EdmFunction getSalaray = new EdmFunction("NS", "GetWholeSalary", intType, isBound: true, entitySetPathExpression: null, isComposable: false);

            getSalaray.AddParameter("entityset", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(customer, false))));
            getSalaray.AddParameter("minSalary", intType);
            getSalaray.AddOptionalParameter("maxSalary", intType);
            getSalaray.AddOptionalParameter("aveSalary", intType, "129");
            model.AddElement(getSalaray);

            EdmEntityContainer container = new EdmEntityContainer("NS", "ModelWithInheritance");

            model.AddElement(container);
            customers = container.AddEntitySet("Customers", customer);

            return(model);
        }
Exemple #32
0
 public ODataEntityReferenceLinkSerializerTest()
 {
     _model       = SerializationTestsHelpers.SimpleCustomerOrderModel();
     _customerSet = _model.FindDeclaredEntityContainer("Default.Container").FindEntitySet("Customers");
 }
Exemple #33
0
 /// <summary>
 /// Initializes a new instance of ResourceSetContext.
 /// </summary>
 /// <returns>A new instance of ResourceSetContext.</returns>
 public static ResourceSetContext Create(IEdmEntitySet entitySetBase, HttpRequestMessage request)
 {
     return(new ResourceSetContext {
         EntitySetBase = entitySetBase, Request = request, Url = request.GetUrlHelper()
     });
 }
Exemple #34
0
 protected virtual void ProcessEntitySet(IEdmEntitySet set)
 {
     this.ProcessEntityContainerElement(set);
 }
Exemple #35
0
 internal void WriteEntitySetElementHeader(IEdmEntitySet entitySet)
 {
     this.xmlWriter.WriteStartElement(CsdlConstants.Element_EntitySet);
     this.WriteRequiredAttribute(CsdlConstants.Attribute_Name, entitySet.Name, EdmValueWriter.StringAsXml);
     this.WriteRequiredAttribute(CsdlConstants.Attribute_EntityType, entitySet.EntityType().FullName(), EdmValueWriter.StringAsXml);
 }
Exemple #36
0
 private static string EntitySetAsXml(IEdmEntitySet set)
 {
     return(set.Container.FullName() + "/" + set.Name);
 }
        /// <summary>
        /// Gets a BindingState for the test to use.
        /// </summary>
        /// <param name="type">Optional type for the implicit parameter.</param>
        /// <returns></returns>
        private BindingState GetBindingStateForTest(IEdmEntityTypeReference typeReference, IEdmEntitySet type)
        {
            type.Should().NotBeNull();
            EntityCollectionNode entityCollectionNode = new EntitySetNode(type);
            var implicitParameter = new EntityRangeVariable(ExpressionConstants.It, typeReference, entityCollectionNode);
            var state             = new BindingState(this.configuration)
            {
                ImplicitRangeVariable = implicitParameter
            };

            state.RangeVariables.Push(state.ImplicitRangeVariable);
            return(state);
        }
 internal ParameterModelReference(IEdmEntitySet entitySet, IEdmType type)
     : base(entitySet, type)
 {
 }
 public override IEdmEntitySet GetEntitySet(IEdmEntitySet previousEntitySet)
 {
     return(previousEntitySet);
 }
Exemple #40
0
        public void CreateEntitySetGetOperationReturnsSecurityForReadRestrictions(bool enableAnnotation)
        {
            string annotation = @"<Annotation Term=""Org.OData.Capabilities.V1.ReadRestrictions"">
  <Record>
    <PropertyValue Property=""Permissions"">
      <Collection>
        <Record>
          <PropertyValue Property=""SchemeName"" String=""Delegated (work or school account)"" />
          <PropertyValue Property=""Scopes"">
            <Collection>
              <Record>
                <PropertyValue Property=""Scope"" String=""User.ReadBasic.All"" />
              </Record>
              <Record>
                <PropertyValue Property=""Scope"" String=""User.Read.All"" />
              </Record>
            </Collection>
          </PropertyValue>
        </Record>
        <Record>
          <PropertyValue Property=""SchemeName"" String=""Application"" />
          <PropertyValue Property=""Scopes"">
            <Collection>
              <Record>
                <PropertyValue Property=""Scope"" String=""User.Read.All"" />
              </Record>
              <Record>
                <PropertyValue Property=""Scope"" String=""Directory.Read.All"" />
              </Record>
            </Collection>
          </PropertyValue>
        </Record>
      </Collection>
    </PropertyValue>
    <PropertyValue Property=""CustomHeaders"">
      <Collection>
        <Record>
          <PropertyValue Property=""Name"" String=""odata-debug"" />
          <PropertyValue Property=""Description"" String=""Debug support for OData services"" />
          <PropertyValue Property=""Required"" Bool=""false"" />
          <PropertyValue Property=""ExampleValues"">
            <Collection>
              <Record>
                <PropertyValue Property=""Value"" String=""html"" />
                <PropertyValue Property=""Description"" String=""Service responds with self-contained..."" />
              </Record>
              <Record>
                <PropertyValue Property=""Value"" String=""json"" />
                <PropertyValue Property=""Description"" String=""Service responds with JSON document..."" />
              </Record>
            </Collection>
          </PropertyValue>
        </Record>
      </Collection>
    </PropertyValue>
  </Record>
</Annotation>";

            // Arrange
            IEdmModel     model     = GetEdmModel(enableAnnotation ? annotation : "");
            ODataContext  context   = new ODataContext(model);
            IEdmEntitySet customers = model.EntityContainer.FindEntitySet("Customers");

            Assert.NotNull(customers); // guard
            ODataPath path = new ODataPath(new ODataNavigationSourceSegment(customers));

            // Act
            var get = _operationHandler.CreateOperation(context, path);

            // Assert
            Assert.NotNull(get);
            Assert.NotNull(get.Security);

            if (enableAnnotation)
            {
                Assert.Equal(2, get.Security.Count);

                string json = get.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0);
                Assert.Contains(@"
  ""security"": [
    {
      ""Delegated (work or school account)"": [
        ""User.ReadBasic.All"",
        ""User.Read.All""
      ]
    },
    {
      ""Application"": [
        ""User.Read.All"",
        ""Directory.Read.All""
      ]
    }
  ]".ChangeLineBreaks(), json);
            }
            else
            {
                Assert.Empty(get.Security);
            }
        }
Exemple #41
0
            private static Uri BuildNavigationNextPageLink(IEdmModel edmModel, OeEntryFactory entryFactory, ExpandedNavigationSelectItem expandedNavigationSelectItem, Object value)
            {
                SingleValueNode filterExpression;
                ResourceRangeVariableReferenceNode refNode;

                var segment = (NavigationPropertySegment)expandedNavigationSelectItem.PathToNavigationProperty.LastSegment;
                IEdmNavigationProperty navigationProperty = segment.NavigationProperty;

                if (navigationProperty.ContainsTarget)
                {
                    ModelBuilder.ManyToManyJoinDescription joinDescription = edmModel.GetManyToManyJoinDescription(navigationProperty);
                    navigationProperty = joinDescription.JoinNavigationProperty.Partner;

                    IEdmEntitySet joinNavigationSource             = OeEdmClrHelper.GetEntitySet(edmModel, joinDescription.JoinNavigationProperty);
                    ResourceRangeVariableReferenceNode joinRefNode = OeEdmClrHelper.CreateRangeVariableReferenceNode(joinNavigationSource, "d");

                    IEdmEntitySet targetNavigationSource             = OeEdmClrHelper.GetEntitySet(edmModel, joinDescription.TargetNavigationProperty);
                    ResourceRangeVariableReferenceNode targetRefNode = OeEdmClrHelper.CreateRangeVariableReferenceNode(targetNavigationSource);

                    var anyNode = new AnyNode(new Collection <RangeVariable>()
                    {
                        joinRefNode.RangeVariable, targetRefNode.RangeVariable
                    }, joinRefNode.RangeVariable)
                    {
                        Source = new CollectionNavigationNode(targetRefNode, joinDescription.TargetNavigationProperty.Partner, null),
                        Body   = OeGetParser.CreateFilterExpression(joinRefNode, GetKeys(navigationProperty))
                    };

                    refNode          = targetRefNode;
                    filterExpression = anyNode;
                }
                else
                {
                    if (navigationProperty.IsPrincipal())
                    {
                        navigationProperty = navigationProperty.Partner;
                    }

                    refNode          = OeEdmClrHelper.CreateRangeVariableReferenceNode((IEdmEntitySetBase)segment.NavigationSource);
                    filterExpression = OeGetParser.CreateFilterExpression(refNode, GetKeys(navigationProperty));
                }

                if (expandedNavigationSelectItem.FilterOption != null)
                {
                    filterExpression = new BinaryOperatorNode(BinaryOperatorKind.And, filterExpression, expandedNavigationSelectItem.FilterOption.Expression);
                }

                var pathSegments = new ODataPathSegment[] { new EntitySetSegment((IEdmEntitySet)refNode.NavigationSource) };
                var odataUri     = new ODataUri()
                {
                    Path            = new ODataPath(pathSegments),
                    Filter          = new FilterClause(filterExpression, refNode.RangeVariable),
                    OrderBy         = expandedNavigationSelectItem.OrderByOption,
                    SelectAndExpand = expandedNavigationSelectItem.SelectAndExpand,
                    Top             = expandedNavigationSelectItem.TopOption,
                    Skip            = expandedNavigationSelectItem.SkipOption,
                    QueryCount      = expandedNavigationSelectItem.CountOption
                };

                return(odataUri.BuildUri(ODataUrlKeyDelimiter.Parentheses));

                List <KeyValuePair <IEdmStructuralProperty, Object> > GetKeys(IEdmNavigationProperty edmNavigationProperty)
                {
                    var keys = new List <KeyValuePair <IEdmStructuralProperty, Object> >();
                    IEnumerator <IEdmStructuralProperty> dependentProperties = edmNavigationProperty.DependentProperties().GetEnumerator();

                    foreach (IEdmStructuralProperty key in edmNavigationProperty.PrincipalProperties())
                    {
                        dependentProperties.MoveNext();
                        Object keyValue = entryFactory.GetAccessorByName(key.Name).GetValue(value);
                        keys.Add(new KeyValuePair <IEdmStructuralProperty, Object>(dependentProperties.Current, keyValue));
                    }
                    return(keys);
                }
            }
Exemple #42
0
        public static ResourceRangeVariableReferenceNode CreateRangeVariableReferenceNode(IEdmEntitySet entitySet)
        {
            var entityTypeRef = (IEdmEntityTypeReference)((IEdmCollectionType)entitySet.Type).ElementType;
            var rangeVariable = new ResourceRangeVariable("", entityTypeRef, entitySet);

            return(new ResourceRangeVariableReferenceNode("", rangeVariable));
        }
Exemple #43
0
        static JObject CreateSwaggerPathForOperationOfEntity(IEdmOperation operation, IEdmEntitySet entitySet)
        {
            JArray swaggerParameters = new JArray();

            foreach (var key in entitySet.EntityType().Key())
            {
                string format;
                string type = GetPrimitiveTypeAndFormat(key.Type.Definition as IEdmPrimitiveType, out format);
                swaggerParameters.Parameter(key.Name, "path", "key: " + key.Name, type, format);
            }

            foreach (var parameter in operation.Parameters.Skip(1))
            {
                swaggerParameters.Parameter(parameter.Name, operation is IEdmFunction ? "path" : "body",
                                            "parameter: " + parameter.Name, parameter.Type.Definition);
            }

            JObject swaggerResponses = new JObject();

            if (operation.ReturnType == null)
            {
                swaggerResponses.Response("204", "Empty response");
            }
            else
            {
                swaggerResponses.Response("200", "Response from " + operation.Name,
                                          operation.ReturnType.Definition);
            }

            JObject swaggerOperation = new JObject()
                                       .Summary("Call operation  " + operation.Name)
                                       .Description("Call operation  " + operation.Name)
                                       .Tags(entitySet.Name, operation is IEdmFunction ? "Function" : "Action");

            if (swaggerParameters.Count > 0)
            {
                swaggerOperation.Parameters(swaggerParameters);
            }
            swaggerOperation.Responses(swaggerResponses.DefaultErrorResponse());
            return(new JObject()
            {
                { operation is IEdmFunction ? "get" : "post", swaggerOperation }
            });
        }
 private static FilterClause ParseFilter(string text, IEdmModel edmModel, IEdmEntityType edmEntityType, IEdmEntitySet edmEntitySet = null)
 {
     return(new ODataQueryOptionParser(edmModel, edmEntityType, edmEntitySet, new Dictionary <string, string>()
     {
         { "$filter", text }
     }).ParseFilter());
 }
Exemple #45
0
        protected IEnumerable ReadImpl(Stream response, Db.OeEntitySetAdapter entitySetMetaAdatpter)
        {
            ResourceSet = null;
            NavigationProperties.Clear();
            NavigationPropertyEntities.Clear();

            IODataResponseMessage responseMessage = new Infrastructure.OeInMemoryMessage(response, null);
            var settings = new ODataMessageReaderSettings()
            {
                EnableMessageStreamDisposal = false, Validations = ValidationKinds.None
            };

            using (var messageReader = new ODataMessageReader(responseMessage, settings, EdmModel))
            {
                IEdmEntitySet entitySet = OeEdmClrHelper.GetEntitySet(EdmModel, entitySetMetaAdatpter.EntitySetName);
                ODataReader   reader    = messageReader.CreateODataResourceSetReader(entitySet, entitySet.EntityType());

                var stack = new Stack <StackItem>();
                while (reader.Read())
                {
                    switch (reader.State)
                    {
                    case ODataReaderState.ResourceSetStart:
                        if (stack.Count == 0)
                        {
                            ResourceSet = (ODataResourceSetBase)reader.Item;
                        }
                        else
                        {
                            stack.Peek().ResourceSet = (ODataResourceSetBase)reader.Item;
                        }
                        break;

                    case ODataReaderState.ResourceStart:
                        stack.Push(new StackItem((ODataResource)reader.Item));
                        break;

                    case ODataReaderState.ResourceEnd:
                        StackItem stackItem = stack.Pop();

                        if (reader.Item != null)
                        {
                            if (stack.Count == 0)
                            {
                                yield return(CreateRootEntity((ODataResource)stackItem.Item, stackItem.NavigationProperties, entitySetMetaAdatpter.EntityType));
                            }
                            else
                            {
                                stack.Peek().AddEntry(CreateEntity((ODataResource)stackItem.Item, stackItem.NavigationProperties));
                            }
                        }
                        break;

                    case ODataReaderState.NestedResourceInfoStart:
                        stack.Push(new StackItem((ODataNestedResourceInfo)reader.Item));
                        break;

                    case ODataReaderState.NestedResourceInfoEnd:
                        StackItem item = stack.Pop();
                        stack.Peek().AddLink((ODataNestedResourceInfo)item.Item, item.Value, item.ResourceSet);
                        break;
                    }
                }
            }
        }
Exemple #46
0
        private bool TryBindIdentifier(string identifier, IEnumerable <FunctionParameterToken> arguments, QueryNode parent, BindingState state, out QueryNode boundFunction)
        {
            boundFunction = null;

            IEdmType bindingType       = null;
            var      singleValueParent = parent as SingleValueNode;

            if (singleValueParent != null)
            {
                if (singleValueParent.TypeReference != null)
                {
                    bindingType = singleValueParent.TypeReference.Definition;
                }
            }
            else
            {
                var collectionValueParent = parent as CollectionNode;
                if (collectionValueParent != null)
                {
                    bindingType = collectionValueParent.CollectionType.Definition;
                }
            }

            if (!UriEdmHelpers.IsBindingTypeValid(bindingType))
            {
                return(false);
            }

            IEdmFunctionImport            functionImport;
            List <FunctionParameterToken> syntacticArguments = arguments == null ? new List <FunctionParameterToken>() : arguments.ToList();

            if (!FunctionOverloadResolver.ResolveFunctionsFromList(identifier, syntacticArguments.Select(ar => ar.ParameterName).ToList(), bindingType, state.Model, out functionImport))
            {
                return(false);
            }

            if (singleValueParent != null && singleValueParent.TypeReference == null)
            {
                // if the parent exists, but has no type information, then we're in open type land, and we
                // shouldn't go any farther.
                throw new ODataException(ODataErrorStrings.FunctionCallBinder_CallingFunctionOnOpenProperty(identifier));
            }

            if (functionImport.IsSideEffecting)
            {
                return(false);
            }

            ICollection <FunctionParameterToken> parsedParameters;

            if (!FunctionParameterParser.TryParseFunctionParameters(syntacticArguments, state.Configuration, functionImport, out parsedParameters))
            {
                return(false);
            }

            IEnumerable <QueryNode> boundArguments = parsedParameters.Select(p => this.bindMethod(p));

            IEdmTypeReference returnType = functionImport.ReturnType;
            IEdmEntitySet     returnSet  = null;
            var singleEntityNode         = parent as SingleEntityNode;

            if (singleEntityNode != null)
            {
                returnSet = functionImport.GetTargetEntitySet(singleEntityNode.EntitySet, state.Model);
            }

            if (returnType.IsEntity())
            {
                boundFunction = new SingleEntityFunctionCallNode(identifier, new[] { functionImport }, boundArguments, (IEdmEntityTypeReference)returnType.Definition.ToTypeReference(), returnSet, parent);
            }
            else if (returnType.IsEntityCollection())
            {
                IEdmCollectionTypeReference collectionTypeReference = (IEdmCollectionTypeReference)returnType;
                boundFunction = new EntityCollectionFunctionCallNode(identifier, new[] { functionImport }, boundArguments, collectionTypeReference, returnSet, parent);
            }
            else if (returnType.IsCollection())
            {
                IEdmCollectionTypeReference collectionTypeReference = (IEdmCollectionTypeReference)returnType;
                boundFunction = new CollectionFunctionCallNode(identifier, new[] { functionImport }, boundArguments, collectionTypeReference, parent);
            }
            else
            {
                boundFunction = new SingleValueFunctionCallNode(identifier, new[] { functionImport }, boundArguments, returnType, parent);
            }

            return(true);
        }
        private void WriteToStream(Type type, object value, Stream writeStream, HttpContent content, HttpContentHeaders contentHeaders)
        {
            IEdmModel model = Request.GetEdmModel();

            if (model == null)
            {
                throw Error.InvalidOperation(SRResources.RequestMustHaveModel);
            }

            ODataSerializer serializer = GetSerializer(type, value, model, _serializerProvider);

            UrlHelper urlHelper = Request.GetUrlHelper();

            Contract.Assert(urlHelper != null);

            ODataPath     path            = Request.GetODataPath();
            IEdmEntitySet targetEntitySet = path == null ? null : path.EntitySet;

            // serialize a response
            HttpConfiguration configuration = Request.GetConfiguration();

            if (configuration == null)
            {
                throw Error.InvalidOperation(SRResources.RequestMustContainConfiguration);
            }

            IODataResponseMessage responseMessage = new ODataMessageWrapper(writeStream, content.Headers);

            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings()
            {
                BaseUri = GetBaseAddress(Request),
                Version = _version,
                Indent  = true,
                DisableMessageStreamDisposal = true,
                MessageQuotas = MessageWriterQuotas
            };

            // The MetadataDocumentUri is never required for errors. Additionally, it sometimes won't be available
            // for errors, such as when routing itself fails. In that case, the route data property is not
            // available on the request, and due to a bug with HttpRoute.GetVirtualPath (bug #669) we won't be able
            // to generate a metadata link.
            if (serializer.ODataPayloadKind != ODataPayloadKind.Error)
            {
                string metadataLink = urlHelper.ODataLink(new MetadataPathSegment());

                if (metadataLink == null)
                {
                    throw new SerializationException(SRResources.UnableToDetermineMetadataUrl);
                }

                string selectClause = GetSelectClause(Request);
                writerSettings.SetMetadataDocumentUri(new Uri(metadataLink), selectClause);
            }

            MediaTypeHeaderValue contentType = null;

            if (contentHeaders != null && contentHeaders.ContentType != null)
            {
                contentType = contentHeaders.ContentType;
            }

            using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, writerSettings, model))
            {
                ODataSerializerContext writeContext = new ODataSerializerContext()
                {
                    Request         = Request,
                    Url             = urlHelper,
                    EntitySet       = targetEntitySet,
                    Model           = model,
                    RootElementName = GetRootElementName(path) ?? "root",
                    SkipExpensiveAvailabilityChecks = serializer.ODataPayloadKind == ODataPayloadKind.Feed,
                    Path               = path,
                    MetadataLevel      = ODataMediaTypes.GetMetadataLevel(contentType),
                    SelectExpandClause = Request.GetSelectExpandClause()
                };

                serializer.WriteObject(value, messageWriter, writeContext);
            }
        }
        /// <summary>
        /// Gets the path for entity set.
        /// </summary>
        /// <param name="entitySet">The entity set.</param>
        /// <returns></returns>
        public static string GetPathForEntitySet(IEdmEntitySet entitySet)
        {
            Contract.Requires(entitySet != null);

            return(entitySet.Name);
        }
        private void WriteToStream(Type type, object value, Stream writeStream, HttpContent content, HttpContentHeaders contentHeaders)
        {
            IEdmModel model = Request.ODataProperties().Model;

            if (model == null)
            {
                throw Error.InvalidOperation(SRResources.RequestMustHaveModel);
            }

            ODataSerializer serializer = GetSerializer(type, value, model, _serializerProvider);

            UrlHelper urlHelper = Request.GetUrlHelper() ?? new UrlHelper(Request);

            ODataPath     path            = Request.ODataProperties().Path;
            IEdmEntitySet targetEntitySet = path == null ? null : path.EntitySet;

            // serialize a response
            HttpConfiguration configuration = Request.GetConfiguration();

            if (configuration == null)
            {
                throw Error.InvalidOperation(SRResources.RequestMustContainConfiguration);
            }

            IODataResponseMessage responseMessage = new ODataMessageWrapper(writeStream, content.Headers);

            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings(MessageWriterSettings)
            {
                PayloadBaseUri = GetBaseAddress(Request),
                Version        = _version,
            };

            string metadataLink = urlHelper.CreateODataLink(new MetadataPathSegment());

            if (metadataLink == null)
            {
                throw new SerializationException(SRResources.UnableToDetermineMetadataUrl);
            }

            string resourcePath = path != null?path.ToString() : String.Empty;

            Uri baseAddress = GetBaseAddress(Request);

            writerSettings.SetServiceDocumentUri(
                baseAddress,
                Request.ODataProperties().SelectExpandClause,
                resourcePath,
                isIndividualProperty: false);

            writerSettings.ODataUri = new ODataUri
            {
                ServiceRoot = baseAddress,

                // TODO: 1604 Convert webapi.odata's ODataPath to ODL's ODataPath, or use ODL's ODataPath.
            };

            MediaTypeHeaderValue contentType = null;

            if (contentHeaders != null && contentHeaders.ContentType != null)
            {
                contentType = contentHeaders.ContentType;
            }

            using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, writerSettings, model))
            {
                ODataSerializerContext writeContext = new ODataSerializerContext()
                {
                    Request         = Request,
                    RequestContext  = Request.GetRequestContext(),
                    Url             = urlHelper,
                    EntitySet       = targetEntitySet,
                    Model           = model,
                    RootElementName = GetRootElementName(path) ?? "root",
                    SkipExpensiveAvailabilityChecks = serializer.ODataPayloadKind == ODataPayloadKind.Feed,
                    Path               = path,
                    MetadataLevel      = ODataMediaTypes.GetMetadataLevel(contentType),
                    SelectExpandClause = Request.ODataProperties().SelectExpandClause
                };

                serializer.WriteObject(value, type, messageWriter, writeContext);
            }
        }
Exemple #50
0
        public void UnresolvedAnnotationTargetsTest()
        {
            string csdl = @"
<Schema Namespace=""DefaultNamespace"" xmlns=""http://docs.oasis-open.org/odata/ns/edm"">
    <Term Name=""Term"" Type=""Edm.Int32"" />
    <EntityType Name=""Entity"" >
        <Key>
            <PropertyRef Name=""ID"" />
        </Key>
        <Property Name=""ID"" Type=""Edm.Int32"" Nullable=""False"" />
    </EntityType>
    <Function Name=""Function"">
        <Parameter Name=""Parameter"" Type=""Edm.String"" />
        <ReturnType Type=""Edm.Int32"" />
    </Function>
    <EntityContainer Name=""Container"">
        <FunctionImport Name=""FunctionImport"" Function=""DefaultNamespace.Function"" />
    </EntityContainer>
    <Annotations Target=""DefaultNamespace.Container/BadEntitySet"">
        <Annotation Term=""AnnotationNamespace.Term"">
            <Int>42</Int>
        </Annotation>
    </Annotations>
    <Annotations Target=""DefaultNamespace.Entity/BadProperty"">
        <Annotation Term=""AnnotationNamespace.Term"">
            <Int>42</Int>
        </Annotation>
    </Annotations>
    <Annotations Target=""DefaultNamespace.Function(Edm.String)/BadParameter"">
        <Annotation Term=""AnnotationNamespace.Annotation"">
            <Int>42</Int>
        </Annotation>
    </Annotations>
    <Annotations Target=""DefaultNamespace.BadEntity/BadProperty"">
        <Annotation Term=""AnnotationNamespace.Term"">
            <Int>42</Int>
        </Annotation>
    </Annotations>
    <Annotations Target=""Impossible/Target/With/Too/Long/A/Path"">
        <Annotation Term=""AnnotationNamespace.Term"">
            <Int>42</Int>
        </Annotation>
    </Annotations>
</Schema>";

            IEdmModel model;
            IEnumerable <EdmError> errors;
            bool parsed = CsdlReader.TryParse(new XmlReader[] { XmlReader.Create(new StringReader(csdl)) }, out model, out errors);

            Assert.IsTrue(parsed, "parsed");
            Assert.IsTrue(errors.Count() == 0, "No errors");

            Assert.AreEqual(5, model.VocabularyAnnotations.Count(), "Correct number of annotations");
            IEdmEntitySet          badEntitySet           = model.VocabularyAnnotations.ElementAt(0).Target as IEdmEntitySet;
            IEdmStructuralProperty badProperty            = model.VocabularyAnnotations.ElementAt(1).Target as IEdmStructuralProperty;
            IEdmOperationParameter badOperationParameter  = model.VocabularyAnnotations.ElementAt(2).Target as IEdmOperationParameter;
            IEdmStructuralProperty badPropertyWithBadType = model.VocabularyAnnotations.ElementAt(3).Target as IEdmStructuralProperty;
            IEdmElement            badElement             = model.VocabularyAnnotations.ElementAt(4).Target as IEdmElement;

            Assert.IsNotNull(badEntitySet, "Target not null");
            Assert.IsNotNull(badProperty, "Target not null");
            Assert.IsNotNull(badOperationParameter, "Target not null");
            Assert.IsNotNull(badPropertyWithBadType, "Target not null");
            Assert.IsNotNull(badElement, "Target not null");

            Assert.IsTrue(badEntitySet.IsBad(), "Target is bad");
            Assert.IsTrue(badProperty.IsBad(), "Target is bad");
            Assert.AreEqual("BadUnresolvedProperty:BadProperty:[UnknownType Nullable=True]", badProperty.ToString(), "Correct bad property to string");
            Assert.AreEqual("BadUnresolvedProperty:[UnknownType Nullable=True]", badProperty.Type.ToString(), "Correct bad property to string");
            Assert.IsTrue(badOperationParameter.IsBad(), "Target is bad");
            Assert.IsTrue(badPropertyWithBadType.IsBad(), "Target is bad");
            Assert.IsTrue(badElement.IsBad(), "Target is bad");
        }
        /// <summary>
        /// Create the Swagger path for the Edm operation bound to the Edm entity.
        /// </summary>
        /// <param name="operation">The Edm operation.</param>
        /// <param name="entitySet">The entity set.</param>
        /// <param name="oDataRoute">The OData route.</param>
        /// <returns></returns>
        public static PathItem CreateSwaggerPathForOperationOfEntity(IEdmOperation operation, IEdmEntitySet entitySet, ODataRoute oDataRoute)
        {
            Contract.Requires(operation != null);
            Contract.Requires(entitySet != null);

            var isFunction        = operation is IEdmFunction;
            var swaggerParameters = new List <Parameter>();

            foreach (var key in entitySet.GetEntityType().GetKey())
            {
                Contract.Assume(key != null);
                string format;
                var    edmPrimitiveType = key.GetPropertyType().GetDefinition() as IEdmPrimitiveType;
                Contract.Assume(edmPrimitiveType != null);
                var type = GetPrimitiveTypeAndFormat(edmPrimitiveType, out format);
                swaggerParameters.Parameter(key.Name, "path", "key: " + key.Name, type, true, format);
            }

            var edmOperationParameters = operation.Parameters;

            Contract.Assume(edmOperationParameters != null);

            if (isFunction)
            {
                AddSwaggerParametersForFunction(swaggerParameters, operation);
            }
            else
            {
                AddSwaggerParametersForAction(swaggerParameters, operation);
            }

            var swaggerResponses = new Dictionary <string, Response>();

            if (operation.ReturnType != null)
            {
                swaggerResponses.Response("200", "Response from " + operation.Name, operation.ReturnType.GetDefinition());
            }

            var swaggerOperation = new Operation()
                                   .Summary("Call operation  " + operation.Name)
                                   .Description("Call operation  " + operation.Name)
                                   .Parameters(AddRoutePrefixParameters(oDataRoute))
                                   .Tags(entitySet.Name, isFunction ? "Function" : "Action");

            if (swaggerParameters.Count > 0)
            {
                swaggerOperation.Parameters(swaggerParameters);
            }
            swaggerOperation.Responses(swaggerResponses.DefaultErrorResponse());

            return(isFunction ? new PathItem
            {
                get = swaggerOperation
            } : new PathItem
            {
                post = swaggerOperation
            });
        }
Exemple #52
0
 internal FunctionImportEntitySetReferenceExpression(IEdmEntitySet referencedEntitySet) : base(referencedEntitySet)
 {
 }
            public override Expression Visit(Expression node)
            {
                if (node == null)
                {
                    return(null);
                }

                // Initialize and push the visited node
                var visited = node;

                this.context.PushVisitedNode(visited);

                // If visited node has already been processed,
                // skip normalization, inspection and filtering
                // and simply replace with the processed node
                if (this.processedExpressions.ContainsKey(visited))
                {
                    node = this.processedExpressions[visited];
                }
                else
                {
                    // Only visit the visited node's children if
                    // the visited node represents API data
                    if (!(this.context.ModelReference is DataSourceStubModelReference))
                    {
                        // Visit visited node's children
                        node = base.Visit(visited);
                    }

                    // Inspect the visited node
                    this.Inspect();

                    // Try to expand the visited node
                    // if it represents API data
                    if (this.context.ModelReference is DataSourceStubModelReference)
                    {
                        node = this.Expand(visited);
                    }

                    // Process the visited node
                    node = this.Process(visited, node);
                }

                if (visited == node)
                {
                    if (this.context.ModelReference is DataSourceStubModelReference)
                    {
                        // If no processing occurred on the visited node
                        // and it represents API data, then it must be
                        // in its most primitive form, so source the node
                        node = this.Source(node);
                    }

                    if (this.BaseQuery == null)
                    {
                        // The very first time control reaches here, the
                        // visited node represents the original starting
                        // point for the entire composed query, and thus
                        // it should produce a non-embedded expression.
                        var constant = node as ConstantExpression;
                        if (constant == null)
                        {
                            throw new NotSupportedException(Resources.OriginalExpressionShouldBeConstant);
                        }

                        this.BaseQuery = constant.Value as IQueryable;
                        if (this.BaseQuery == null)
                        {
                            throw new NotSupportedException(Resources.OriginalExpressionShouldBeQueryable);
                        }

                        node = this.BaseQuery.Expression;
                    }
                }

                // TODO GitHubIssue#28 : Support transformation between API types and data source proxy types
                this.context.PopVisitedNode();

                if (this.context.VisitedNode != null)
                {
                    this.EntitySet = this.context.ModelReference != null ?
                                     this.context.ModelReference.EntitySet : null;
                }

                return(node);
            }
        /// <summary>
        /// Create the Swagger path for the Edm operation bound to the Edm entity set.
        /// </summary>
        /// <param name="operation">The Edm operation.</param>
        /// <param name="entitySet">The entity set.</param>
        /// <param name="oDataRoute"></param>
        public static PathItem CreateSwaggerPathForOperationOfEntitySet(IEdmOperation operation, IEdmEntitySet entitySet, ODataRoute oDataRoute)
        {
            Contract.Requires(operation != null);
            Contract.Requires(entitySet != null);

            Contract.Assume(operation.Parameters != null);

            var isFunction        = operation is IEdmFunction;
            var swaggerParameters = new List <Parameter>();

            if (isFunction)
            {
                AddSwaggerParametersForFunction(swaggerParameters, operation);
            }
            else
            {
                AddSwaggerParametersForAction(swaggerParameters, operation);
            }

            var swaggerResponses = new Dictionary <string, Response>();

            if (operation.ReturnType != null)
            {
                swaggerResponses.Response("200", "Response from " + operation.Name, operation.ReturnType.GetDefinition());
            }

            var swaggerOperation = new Operation()
                                   .Summary("Call operation  " + operation.Name)
                                   .OperationId(operation.Name + (isFunction ? "_FunctionGet" : "_ActionPost"))
                                   .Description("Call operation  " + operation.Name)
                                   .OperationId(operation.Name + (isFunction ? "_FunctionGetById" : "_ActionPostById"))
                                   .Parameters(AddRoutePrefixParameters(oDataRoute))
                                   .Tags(entitySet.Name, isFunction ? "Function" : "Action");

            if (swaggerParameters.Count > 0)
            {
                swaggerOperation.Parameters(swaggerParameters);
            }
            swaggerOperation.Responses(swaggerResponses.DefaultErrorResponse());

            return(isFunction ? new PathItem
            {
                get = swaggerOperation
            } : new PathItem
            {
                post = swaggerOperation
            });
        }
        private void VerifyEntitySetPostOperation(string annotation, bool enableOperationId, bool hasStream)
        {
            // Arrange
            IEdmModel              model     = GetEdmModel(annotation, hasStream);
            IEdmEntitySet          entitySet = model.EntityContainer.FindEntitySet("Customers");
            OpenApiConvertSettings settings  = new OpenApiConvertSettings
            {
                EnableOperationId = enableOperationId
            };
            ODataContext context = new ODataContext(model, settings);
            ODataPath    path    = new ODataPath(new ODataNavigationSourceSegment(entitySet));

            // Act
            var post = _operationHandler.CreateOperation(context, path);

            // Assert
            Assert.NotNull(post);
            Assert.Equal("Add new entity to " + entitySet.Name, post.Summary);
            Assert.NotNull(post.Tags);
            var tag = Assert.Single(post.Tags);

            Assert.Equal("Customers.Customer", tag.Name);

            Assert.Empty(post.Parameters);
            Assert.NotNull(post.RequestBody);

            Assert.NotNull(post.Responses);
            Assert.Equal(2, post.Responses.Count);

            if (hasStream)
            {
                Assert.NotNull(post.RequestBody);

                if (!string.IsNullOrEmpty(annotation))
                {
                    // RequestBody
                    Assert.Equal(2, post.RequestBody.Content.Keys.Count);
                    Assert.True(post.RequestBody.Content.ContainsKey("application/todo"));
                    Assert.True(post.RequestBody.Content.ContainsKey(Constants.ApplicationJsonMediaType));

                    // Response
                    Assert.Equal(2, post.Responses[Constants.StatusCode201].Content.Keys.Count);
                    Assert.True(post.Responses[Constants.StatusCode201].Content.ContainsKey("application/todo"));
                    Assert.True(post.Responses[Constants.StatusCode201].Content.ContainsKey(Constants.ApplicationJsonMediaType));
                }
                else
                {
                    // RequestBody
                    Assert.Equal(2, post.RequestBody.Content.Keys.Count);
                    Assert.True(post.RequestBody.Content.ContainsKey(Constants.ApplicationOctetStreamMediaType));
                    Assert.True(post.RequestBody.Content.ContainsKey(Constants.ApplicationJsonMediaType));

                    // Response
                    Assert.Equal(2, post.Responses[Constants.StatusCode201].Content.Keys.Count);
                    Assert.True(post.Responses[Constants.StatusCode201].Content.ContainsKey(Constants.ApplicationOctetStreamMediaType));
                    Assert.True(post.Responses[Constants.StatusCode201].Content.ContainsKey(Constants.ApplicationJsonMediaType));
                }
            }
            else
            {
                // RequestBody
                Assert.NotNull(post.RequestBody);
                Assert.Equal(1, post.RequestBody.Content.Keys.Count);
                Assert.True(post.RequestBody.Content.ContainsKey(Constants.ApplicationJsonMediaType));

                // Response
                Assert.Equal(1, post.Responses[Constants.StatusCode201].Content.Keys.Count);
                Assert.True(post.Responses[Constants.StatusCode201].Content.ContainsKey(Constants.ApplicationJsonMediaType));
            }

            if (enableOperationId)
            {
                Assert.Equal("Customers.Customer.CreateCustomer", post.OperationId);
            }
            else
            {
                Assert.Null(post.OperationId);
            }
        }
        /// <summary>
        /// Create the Swagger path for the Edm entity.
        /// </summary>
        /// <param name="entitySet">The entity set.</param>
        /// <param name="oDataRoute">The OData route.</param>
        /// <returns></returns>
        public static PathItem CreateSwaggerPathForEntity(IEdmEntitySet entitySet, ODataRoute oDataRoute)
        {
            Contract.Requires(entitySet != null);
            Contract.Ensures(Contract.Result <PathItem>() != null);

            var keyParameters = new List <Parameter>();

            foreach (var key in entitySet.GetEntityType().GetKey())
            {
                Contract.Assume(key != null);

                // Create key parameters for primitive and enum types
                IEdmType keyDefinitionAsType = null;
                var      keyDefinition       = key.GetPropertyType().GetDefinition();

                if (EdmTypeKind.Primitive == keyDefinition.TypeKind)
                {
                    keyDefinitionAsType = keyDefinition as IEdmPrimitiveType;
                }
                else if (EdmTypeKind.Enum == keyDefinition.TypeKind)
                {
                    keyDefinitionAsType = keyDefinition as IEdmEnumType;
                }
                Contract.Assume(keyDefinitionAsType != null);

                keyParameters.Parameter(
                    key.Name,
                    "path",
                    "key: " + key.Name,
                    keyDefinitionAsType,
                    true);
            }
            return(new PathItem
            {
                get = new Operation()
                      .Summary("Get entity from " + entitySet.Name + " by key.")
                      .OperationId(entitySet.Name + "_GetById")
                      .Description("Returns the entity with the key from " + entitySet.Name)
                      .Tags(entitySet.Name)
                      .Parameters(AddQueryOptionParametersForEntity(keyParameters.DeepClone()))
                      .Parameters(AddRoutePrefixParameters(oDataRoute))
                      .Responses(new Dictionary <string, Response>().Response("200", "EntitySet " + entitySet.Name, entitySet.GetEntityType()).DefaultErrorResponse()),

                patch = new Operation()
                        .Summary("Update entity in EntitySet " + entitySet.Name)
                        .OperationId(entitySet.Name + "_PatchById")
                        .Description("Update entity in EntitySet " + entitySet.Name)
                        .Tags(entitySet.Name)
                        .Parameters(keyParameters.DeepClone()
                                    .Parameter(entitySet.GetEntityType().Name, "body", "The entity to patch", entitySet.GetEntityType(), true))
                        .Parameters(AddRoutePrefixParameters(oDataRoute))
                        .Responses(new Dictionary <string, Response>()
                                   .Response("204", "Empty response").DefaultErrorResponse()),

                put = new Operation()
                      .Summary("Replace entity in EntitySet " + entitySet.Name)
                      .OperationId(entitySet.Name + "_PutById")
                      .Description("Replace entity in EntitySet " + entitySet.Name)
                      .Tags(entitySet.Name)
                      .Parameters(keyParameters.DeepClone()
                                  .Parameter(entitySet.GetEntityType().Name, "body", "The entity to put", entitySet.GetEntityType(), true))
                      .Parameters(AddRoutePrefixParameters(oDataRoute))
                      .Responses(new Dictionary <string, Response>().Response("204", "Empty response").DefaultErrorResponse()),

                delete = new Operation()
                         .Summary("Delete entity in EntitySet " + entitySet.Name)
                         .OperationId(entitySet.Name + "_DeleteById")
                         .Description("Delete entity in EntitySet " + entitySet.Name)
                         .Tags(entitySet.Name)
                         .Parameters(keyParameters.DeepClone()
                                     .Parameter("If-Match", "header", "If-Match header", "string", false))
                         .Parameters(AddRoutePrefixParameters(oDataRoute))
                         .Responses(new Dictionary <string, Response>().Response("204", "Empty response").DefaultErrorResponse())
            });
        }
        internal EntitySetConfiguration(OeModelBoundFluentBuilder modelBuilder, IEdmEntitySet entitySet)
        {
            _modelBuilder = modelBuilder;

            EntityType = new EntityTypeConfiguration <TEntityType>(_modelBuilder, entitySet.EntityType());
        }
 private static OrderByClause ParseOrderBy(string text, IEdmModel edmModel, IEdmEntityType edmEntityType, IEdmEntitySet edmEntitySet = null)
 {
     return(new ODataQueryOptionParser(edmModel, edmEntityType, edmEntitySet, new Dictionary <string, string>()
     {
         { "$orderby", text }
     }).ParseOrderBy());
 }
        /// <inheritdoc/>
        protected override void SetOperations(OpenApiPathItem item)
        {
            IEdmEntitySet             entitySet = NavigationSource as IEdmEntitySet;
            IEdmVocabularyAnnotatable target    = entitySet;

            if (target == null)
            {
                target = NavigationSource as IEdmSingleton;
            }

            string navigationPropertyPath = String.Join("/",
                                                        Path.Segments.Where(s => !(s is ODataKeySegment || s is ODataNavigationSourceSegment)).Select(e => e.Identifier));

            NavigationRestrictionsType    navigation  = Context.Model.GetRecord <NavigationRestrictionsType>(target, CapabilitiesConstants.NavigationRestrictions);
            NavigationPropertyRestriction restriction = navigation?.RestrictedProperties?.FirstOrDefault(r => r.NavigationProperty == navigationPropertyPath);

            // verify using individual first
            if (restriction != null && restriction.Navigability != null && restriction.Navigability.Value == NavigationType.None)
            {
                return;
            }

            if (restriction == null || restriction.Navigability == null)
            {
                // if the individual has not navigability setting, use the global navigability setting
                if (navigation != null && navigation.Navigability != null && navigation.Navigability.Value == NavigationType.None)
                {
                    // Default navigability for all navigation properties of the annotation target.
                    // Individual navigation properties can override this value via `RestrictedProperties/Navigability`.
                    return;
                }
            }

            // contaiment: Get / (Post - Collection | Patch - Single)
            // non-containment: Get
            AddGetOperation(item, restriction);

            if (NavigationProperty.ContainsTarget)
            {
                if (NavigationProperty.TargetMultiplicity() == EdmMultiplicity.Many)
                {
                    if (LastSegmentIsKeySegment)
                    {
                        // Need to check this scenario is valid or not?
                        UpdateRestrictionsType update = restriction?.UpdateRestrictions;
                        if (update == null || update.IsUpdatable)
                        {
                            AddOperation(item, OperationType.Patch);
                        }
                    }
                    else
                    {
                        InsertRestrictionsType insert = restriction?.InsertRestrictions;
                        if (insert == null || insert.IsInsertable)
                        {
                            AddOperation(item, OperationType.Post);
                        }
                    }
                }
                else
                {
                    UpdateRestrictionsType update = restriction?.UpdateRestrictions;
                    if (update == null || update.IsUpdatable)
                    {
                        AddOperation(item, OperationType.Patch);
                    }
                }
            }

            AddDeleteOperation(item, restriction);
        }
Exemple #60
0
        static OpenTypeExtensionTestBase()
        {
            var model = new EdmModel();

            Model = model;

            var person   = new EdmEntityType("TestNS", "Person", null, false, true);
            var personId = person.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32);

            PersonNameProp = person.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            PersonPen      = person.AddStructuralProperty("pen", EdmPrimitiveTypeKind.Binary);
            person.AddKeys(personId);
            PersonType = person;

            var address = new EdmComplexType("TestNS", "Address", null, false, true);

            AddrType        = address;
            ZipCodeProperty = address.AddStructuralProperty("ZipCode", EdmPrimitiveTypeKind.String);
            AddrProperty    = person.AddStructuralProperty("Addr", new EdmComplexTypeReference(address, false));

            var pencil   = new EdmEntityType("TestNS", "Pencil");
            var pencilId = pencil.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);

            PencilId = pencilId;
            var pid = pencil.AddStructuralProperty("Pid", EdmPrimitiveTypeKind.Int32);

            pencil.AddKeys(pencilId);

            var starPencil = new EdmEntityType("TestNS", "StarPencil", pencil);

            model.AddElement(starPencil);
            var starPencilUpper = new EdmEntityType("TestNS", "STARPENCIL");

            model.AddElement(starPencilUpper);
            StarPencil = starPencil;

            var navInfo = new EdmNavigationPropertyInfo()
            {
                Name               = "Pen",
                ContainsTarget     = false,
                Target             = pencil,
                TargetMultiplicity = EdmMultiplicity.One
            };

            PersonNavPen = person.AddUnidirectionalNavigation(navInfo);

            var navInfo2 = new EdmNavigationPropertyInfo()
            {
                Name               = "Pen2",
                ContainsTarget     = true,
                Target             = pencil,
                TargetMultiplicity = EdmMultiplicity.One
            };

            PersonNavPen2 = person.AddUnidirectionalNavigation(navInfo2);

            var container = new EdmEntityContainer("Default", "Con1");
            var personSet = container.AddEntitySet("People", person);

            PencilSet = container.AddEntitySet("PencilSet", pencil);
            personSet.AddNavigationTarget(PersonNavPen, PencilSet);
            PeopleSet = personSet;

            var         pencilRef   = new EdmEntityTypeReference(pencil, false);
            EdmFunction findPencil1 = new EdmFunction("TestNS", "FindPencil", pencilRef, true, null, false);

            findPencil1.AddParameter("qid", new EdmEntityTypeReference(PersonType, false));
            model.AddElement(findPencil1);
            FindPencil1P = findPencil1;

            EdmFunction findPencil = new EdmFunction("TestNS", "FindPencil", pencilRef, true, null, false);

            findPencil.AddParameter("qid", new EdmEntityTypeReference(PersonType, false));
            findPencil.AddParameter("pid", EdmCoreModel.Instance.GetInt32(false));
            model.AddElement(findPencil);
            FindPencil2P = findPencil;

            EdmFunction findPencilsCon = new EdmFunction("TestNS", "FindPencilsCon", new EdmCollectionTypeReference(new EdmCollectionType(pencilRef)), true, null, false);

            FindPencilsCon = findPencilsCon;
            findPencilsCon.AddParameter("qid", new EdmEntityTypeReference(PersonType, false));
            model.AddElement(findPencilsCon);

            EdmFunction findPencilsConNT = new EdmFunction("TestNT", "FindPencilsCon", new EdmCollectionTypeReference(new EdmCollectionType(pencilRef)), true, null, false);

            FindPencilsConNT = findPencilsConNT;
            findPencilsConNT.AddParameter("qid", new EdmEntityTypeReference(PersonType, false));
            model.AddElement(findPencilsConNT);

            ChangeZip = new EdmAction("TestNS", "ChangeZip", null, true, null);
            ChangeZip.AddParameter("address", new EdmComplexTypeReference(address, false));
            ChangeZip.AddParameter("newZip", EdmCoreModel.Instance.GetString(false));
            model.AddElement(ChangeZip);

            GetZip = new EdmFunction("TestNS", "GetZip", EdmCoreModel.Instance.GetString(false), true, null, true);
            GetZip.AddParameter("address", new EdmComplexTypeReference(address, false));
            model.AddElement(GetZip);

            model.AddElement(person);
            model.AddElement(address);
            model.AddElement(pencil);
            model.AddElement(container);
        }