コード例 #1
0
        private IEdmModel CreateTestMetadata(out IEdmEntityType entityType, out IEdmComplexType complexType)
        {
            EdmModel model = new EdmModel();

            EdmEntityType modelEntityType = model.EntityType("EntityType", "TestNS")
                                            .KeyProperty("Id", EdmCoreModel.Instance.GetInt32(false) as EdmTypeReference);

            EdmComplexType modelComplexType = model.ComplexType("ComplexType", "TestNS")
                                              .Property("EntityProp", modelEntityType.ToTypeReference() as EdmTypeReference)
                                              .Property("EntityCollectionProp", EdmCoreModel.GetCollection(modelEntityType.ToTypeReference()) as EdmTypeReference);

            EdmEntityContainer container = new EdmEntityContainer("TestNS", "TestContainer");

            container.AddFunctionAndFunctionImport(model, "FunctionImport1", EdmCoreModel.Instance.GetInt32(false));
            container.AddFunctionAndFunctionImport(model, "PrimitiveValueFunctionImport", EdmCoreModel.Instance.GetInt32(false));
            container.AddFunctionAndFunctionImport(model, "EntityValueFunctionImport", modelEntityType.ToTypeReference());
            container.AddFunctionAndFunctionImport(model, "CollectionOfEntitiesFunctionImport", EdmCoreModel.GetCollection(modelEntityType.ToTypeReference()));
            model.AddElement(container);

            model.Fixup();

            entityType = (IEdmEntityType)model.FindType("TestNS.EntityType");
            ExceptionUtilities.Assert(entityType != null, "entityType != null");

            complexType = (IEdmComplexType)model.FindType("TestNS.ComplexType");
            ExceptionUtilities.Assert(complexType != null, "complexType != null");

            return(model);
        }
コード例 #2
0
        public void TestCollectionValue()
        {
            var constant = new EdmCollectionValue(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(false)), new IEdmDelayedValue[] { new EdmStringConstant("foo") });

            Assert.AreEqual(EdmValueKind.Collection, constant.ValueKind, "Invalid value kind.");
        }
コード例 #3
0
        public CustomersModelWithInheritance()
        {
            EdmModel model = new EdmModel();

            // Enum type simpleEnum
            EdmEnumType simpleEnum = new EdmEnumType("NS", "SimpleEnum");

            simpleEnum.AddMember(new EdmEnumMember(simpleEnum, "First", new EdmEnumMemberValue(0)));
            simpleEnum.AddMember(new EdmEnumMember(simpleEnum, "Second", new EdmEnumMemberValue(1)));
            simpleEnum.AddMember(new EdmEnumMember(simpleEnum, "Third", new EdmEnumMemberValue(2)));
            model.AddElement(simpleEnum);

            // complex type address
            EdmComplexType address = new EdmComplexType("NS", "Address");

            address.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String);
            address.AddStructuralProperty("City", EdmPrimitiveTypeKind.String);
            address.AddStructuralProperty("State", EdmPrimitiveTypeKind.String);
            address.AddStructuralProperty("ZipCode", EdmPrimitiveTypeKind.String);
            address.AddStructuralProperty("CountryOrRegion", EdmPrimitiveTypeKind.String);
            model.AddElement(address);

            // open complex type "Account"
            EdmComplexType account = new EdmComplexType("NS", "Account", null, false, true);

            account.AddStructuralProperty("Bank", EdmPrimitiveTypeKind.String);
            account.AddStructuralProperty("CardNum", EdmPrimitiveTypeKind.Int64);
            account.AddStructuralProperty("BankAddress", new EdmComplexTypeReference(address, isNullable: true));
            model.AddElement(account);

            EdmComplexType specialAccount = new EdmComplexType("NS", "SpecialAccount", account, false, true);

            specialAccount.AddStructuralProperty("SpecialCard", EdmPrimitiveTypeKind.String);
            model.AddElement(specialAccount);

            // entity type customer
            EdmEntityType customer = new EdmEntityType("NS", "Customer");

            customer.AddKeys(customer.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            IEdmProperty customerName = customer.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);

            customer.AddStructuralProperty("SimpleEnum", simpleEnum.ToEdmTypeReference(isNullable: false));
            customer.AddStructuralProperty("Address", new EdmComplexTypeReference(address, isNullable: true));
            customer.AddStructuralProperty("Account", new EdmComplexTypeReference(account, isNullable: true));
            IEdmTypeReference primitiveTypeReference = EdmCoreModel.Instance.GetPrimitive(
                EdmPrimitiveTypeKind.String,
                isNullable: true);
            var city = customer.AddStructuralProperty(
                "City",
                primitiveTypeReference,
                defaultValue: null);

            model.AddElement(customer);

            // derived entity type special customer
            EdmEntityType specialCustomer = new EdmEntityType("NS", "SpecialCustomer", customer);

            specialCustomer.AddStructuralProperty("SpecialCustomerProperty", EdmPrimitiveTypeKind.Guid);
            specialCustomer.AddStructuralProperty("SpecialAddress", new EdmComplexTypeReference(address, isNullable: true));
            model.AddElement(specialCustomer);

            // entity type order (open entity type)
            EdmEntityType order = new EdmEntityType("NS", "Order", null, false, true);

            // EdmEntityType order = new EdmEntityType("NS", "Order");
            order.AddKeys(order.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            order.AddStructuralProperty("City", EdmPrimitiveTypeKind.String);
            order.AddStructuralProperty("Amount", EdmPrimitiveTypeKind.Int32);
            model.AddElement(order);

            // derived entity type special order
            EdmEntityType specialOrder = new EdmEntityType("NS", "SpecialOrder", order, false, true);

            specialOrder.AddStructuralProperty("SpecialOrderProperty", EdmPrimitiveTypeKind.Guid);
            model.AddElement(specialOrder);

            // test entity
            EdmEntityType testEntity = new EdmEntityType("Microsoft.AspNet.OData.Test.Query.Expressions", "TestEntity");

            testEntity.AddStructuralProperty("SampleProperty", EdmPrimitiveTypeKind.Binary);
            model.AddElement(testEntity);

            // containment
            // my order
            EdmEntityType myOrder = new EdmEntityType("NS", "MyOrder");

            myOrder.AddKeys(myOrder.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            myOrder.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            model.AddElement(myOrder);

            // order line
            EdmEntityType orderLine = new EdmEntityType("NS", "OrderLine");

            orderLine.AddKeys(orderLine.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            orderLine.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            model.AddElement(orderLine);

            EdmNavigationProperty orderLinesNavProp = myOrder.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo
            {
                Name = "OrderLines",
                TargetMultiplicity = EdmMultiplicity.Many,
                Target             = orderLine,
                ContainsTarget     = true,
            });

            EdmNavigationProperty nonContainedOrderLinesNavProp = myOrder.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo
            {
                Name = "NonContainedOrderLines",
                TargetMultiplicity = EdmMultiplicity.Many,
                Target             = orderLine,
                ContainsTarget     = false,
            });

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

            tag.AddParameter("entity", new EdmEntityTypeReference(orderLine, false));
            model.AddElement(tag);

            // entity sets
            EdmEntityContainer container = new EdmEntityContainer("NS", "ModelWithInheritance");

            model.AddElement(container);
            EdmEntitySet customers = container.AddEntitySet("Customers", customer);
            EdmEntitySet orders    = container.AddEntitySet("Orders", order);
            EdmEntitySet myOrders  = container.AddEntitySet("MyOrders", myOrder);

            // singletons
            EdmSingleton vipCustomer = container.AddSingleton("VipCustomer", customer);
            EdmSingleton mary        = container.AddSingleton("Mary", customer);
            EdmSingleton rootOrder   = container.AddSingleton("RootOrder", order);

            // annotations
            model.SetOptimisticConcurrencyAnnotation(customers, new[] { city });

            // containment
            IEdmContainedEntitySet orderLines = (IEdmContainedEntitySet)myOrders.FindNavigationTarget(orderLinesNavProp);

            // no-containment
            IEdmNavigationSource nonContainedOrderLines = myOrders.FindNavigationTarget(nonContainedOrderLinesNavProp);

            // actions
            EdmAction upgrade = new EdmAction("NS", "upgrade", returnType: null, isBound: true, entitySetPathExpression: null);

            upgrade.AddParameter("entity", new EdmEntityTypeReference(customer, false));
            model.AddElement(upgrade);

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

            specialUpgrade.AddParameter("entity", new EdmEntityTypeReference(specialCustomer, false));
            model.AddElement(specialUpgrade);

            // actions bound to collection
            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);

            EdmAction upgradeSpecialAll = new EdmAction("NS", "UpgradeSpecialAll", returnType: null, isBound: true, entitySetPathExpression: null);

            upgradeSpecialAll.AddParameter("entityset",
                                           new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(specialCustomer, false))));
            model.AddElement(upgradeSpecialAll);

            // functions
            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 IsUpgraded = new EdmFunction(
                "NS",
                "IsUpgraded",
                returnType,
                isBound: true,
                entitySetPathExpression: null,
                isComposable: false);

            IsUpgraded.AddParameter("entity", new EdmEntityTypeReference(customer, false));
            model.AddElement(IsUpgraded);

            EdmFunction orderByCityAndAmount = new EdmFunction(
                "NS",
                "OrderByCityAndAmount",
                stringType,
                isBound: true,
                entitySetPathExpression: null,
                isComposable: false);

            orderByCityAndAmount.AddParameter("entity", new EdmEntityTypeReference(customer, false));
            orderByCityAndAmount.AddParameter("city", stringType);
            orderByCityAndAmount.AddParameter("amount", intType);
            model.AddElement(orderByCityAndAmount);

            EdmFunction getOrders = new EdmFunction(
                "NS",
                "GetOrders",
                EdmCoreModel.GetCollection(order.ToEdmTypeReference(false)),
                isBound: true,
                entitySetPathExpression: null,
                isComposable: true);

            getOrders.AddParameter("entity", new EdmEntityTypeReference(customer, false));
            getOrders.AddParameter("parameter", intType);
            model.AddElement(getOrders);

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

            IsSpecialUpgraded.AddParameter("entity", new EdmEntityTypeReference(specialCustomer, false));
            model.AddElement(IsSpecialUpgraded);

            EdmFunction getSalary = new EdmFunction(
                "NS",
                "GetSalary",
                stringType,
                isBound: true,
                entitySetPathExpression: null,
                isComposable: false);

            getSalary.AddParameter("entity", new EdmEntityTypeReference(customer, false));
            model.AddElement(getSalary);

            getSalary = new EdmFunction(
                "NS",
                "GetSalary",
                stringType,
                isBound: true,
                entitySetPathExpression: null,
                isComposable: false);
            getSalary.AddParameter("entity", new EdmEntityTypeReference(specialCustomer, false));
            model.AddElement(getSalary);

            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 isCustomerLocal = new EdmFunction(
                "NS",
                "IsLocal",
                returnType,
                isBound: true,
                entitySetPathExpression: null,
                isComposable: false);

            isCustomerLocal.AddParameter("entity", new EdmEntityTypeReference(customer, false));
            model.AddElement(isCustomerLocal);

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

            entityFunction.AddParameter("entity", new EdmEntityTypeReference(customer, false));
            entityFunction.AddParameter("customer", new EdmEntityTypeReference(customer, false));
            model.AddElement(entityFunction);

            EdmFunction getOrder = new EdmFunction(
                "NS",
                "GetOrder",
                order.ToEdmTypeReference(false),
                isBound: true,
                entitySetPathExpression: null,
                isComposable: true); // Composable

            getOrder.AddParameter("entity", new EdmEntityTypeReference(customer, false));
            getOrder.AddParameter("orderId", intType);
            model.AddElement(getOrder);

            // functions bound to collection
            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 isSpecialAllUpgraded = new EdmFunction("NS", "IsSpecialAllUpgraded", returnType, isBound: true,
                                                               entitySetPathExpression: null, isComposable: false);

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

            // navigation properties
            EdmNavigationProperty ordersNavProp = customer.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo
            {
                Name = "Orders",
                TargetMultiplicity = EdmMultiplicity.Many,
                Target             = order
            });

            mary.AddNavigationTarget(ordersNavProp, orders);
            vipCustomer.AddNavigationTarget(ordersNavProp, orders);
            customers.AddNavigationTarget(ordersNavProp, orders);
            orders.AddNavigationTarget(
                order.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name = "Customer",
                TargetMultiplicity = EdmMultiplicity.ZeroOrOne,
                Target             = customer
            }),
                customers);

            // navigation properties on derived types.
            EdmNavigationProperty specialOrdersNavProp = specialCustomer.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo
            {
                Name = "SpecialOrders",
                TargetMultiplicity = EdmMultiplicity.Many,
                Target             = order
            });

            vipCustomer.AddNavigationTarget(specialOrdersNavProp, orders);
            customers.AddNavigationTarget(specialOrdersNavProp, orders);
            orders.AddNavigationTarget(
                specialOrder.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name = "SpecialCustomer",
                TargetMultiplicity = EdmMultiplicity.ZeroOrOne,
                Target             = customer
            }),
                customers);
            model.SetAnnotationValue <BindableOperationFinder>(model, new BindableOperationFinder(model));

            // set properties
            Model                     = model;
            Container                 = container;
            Customer                  = customer;
            Order                     = order;
            Address                   = address;
            Account                   = account;
            SpecialCustomer           = specialCustomer;
            SpecialOrder              = specialOrder;
            Orders                    = orders;
            Customers                 = customers;
            VipCustomer               = vipCustomer;
            Mary                      = mary;
            RootOrder                 = rootOrder;
            OrderLine                 = orderLine;
            OrderLines                = orderLines;
            NonContainedOrderLines    = nonContainedOrderLines;
            UpgradeCustomer           = upgrade;
            UpgradeSpecialCustomer    = specialUpgrade;
            CustomerName              = customerName;
            IsCustomerUpgraded        = isCustomerUpgradedWithParam;
            IsSpecialCustomerUpgraded = IsSpecialUpgraded;
            Tag = tag;
        }
コード例 #4
0
        private IEdmModel CreateEdmModel()
        {
            var model = new EdmModel();

            EdmComplexType simpleComplexType = new EdmComplexType(DefaultNamespaceName, "SimplexComplexType");

            simpleComplexType.AddProperty(new EdmStructuralProperty(simpleComplexType, "Name", StringTypeRef));
            model.AddElement(simpleComplexType);

            EdmComplexType simpleComplexType2 = new EdmComplexType(DefaultNamespaceName, "SimplexComplexType2");

            simpleComplexType2.AddProperty(new EdmStructuralProperty(simpleComplexType2, "Value", Int32NullableTypeRef));
            model.AddElement(simpleComplexType2);

            EdmComplexType nestedComplexType = new EdmComplexType(DefaultNamespaceName, "NestedComplexType");

            nestedComplexType.AddProperty(new EdmStructuralProperty(nestedComplexType, "InnerComplexProperty", new EdmComplexTypeReference(simpleComplexType2, isNullable: false)));
            model.AddElement(nestedComplexType);

            EdmComplexType ratingComplexType = new EdmComplexType(DefaultNamespaceName, "RatingComplexType");

            ratingComplexType.AddProperty(new EdmStructuralProperty(ratingComplexType, "Rating", Int32NullableTypeRef));
            model.AddElement(ratingComplexType);

            EdmEntityType entityType = new EdmEntityType(DefaultNamespaceName, "EntityType");

            EdmEntityType expandedEntryType = new EdmEntityType(DefaultNamespaceName, "ExpandedEntryType");

            expandedEntryType.AddKeys(expandedEntryType.AddStructuralProperty("Id", Int32TypeRef));
            expandedEntryType.AddStructuralProperty("ExpandedEntryName", StringTypeRef);
            expandedEntryType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "ExpandedEntry_DeferredNavigation", Target = entityType, TargetMultiplicity = EdmMultiplicity.One
            });
            expandedEntryType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "ExpandedEntry_ExpandedFeed", Target = entityType, TargetMultiplicity = EdmMultiplicity.Many
            });
            model.AddElement(expandedEntryType);

            entityType.AddKeys(entityType.AddStructuralProperty("Id", Int32TypeRef));
            entityType.AddStructuralProperty("StringProperty", StringTypeRef);
            entityType.AddStructuralProperty("NumberProperty", Int32TypeRef);
            entityType.AddStructuralProperty("SimpleComplexProperty", new EdmComplexTypeReference(simpleComplexType, isNullable: false));
            entityType.AddStructuralProperty("DeepComplexProperty", new EdmComplexTypeReference(nestedComplexType, isNullable: false));
            entityType.AddStructuralProperty("PrimitiveCollection", EdmCoreModel.GetCollection(StringTypeRef));
            entityType.AddStructuralProperty("ComplexCollection", EdmCoreModel.GetCollection(new EdmComplexTypeReference(ratingComplexType, isNullable: false)));
            entityType.AddStructuralProperty("NamedStream", EdmPrimitiveTypeKind.Stream, false);
            entityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "DeferredNavigation", Target = entityType, TargetMultiplicity = EdmMultiplicity.One
            });
            entityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "AssociationLink", Target = entityType, TargetMultiplicity = EdmMultiplicity.One
            });
            entityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "ExpandedEntry", Target = expandedEntryType, TargetMultiplicity = EdmMultiplicity.One
            });
            entityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "ExpandedFeed", Target = entityType, TargetMultiplicity = EdmMultiplicity.Many
            });
            model.AddElement(entityType);

            EdmEntityType wrappingEntityType = new EdmEntityType(DefaultNamespaceName, "WrappingEntityType");

            wrappingEntityType.AddKeys(wrappingEntityType.AddStructuralProperty("Wrapping_ID", Int32TypeRef));
            wrappingEntityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "Wrapping_ExpandedEntry", Target = entityType, TargetMultiplicity = EdmMultiplicity.One
            });
            model.AddElement(wrappingEntityType);

            var container = new EdmEntityContainer(DefaultNamespaceName, "DefaultContainer");

            model.AddElement(container);

            container.AddEntitySet("EntitySet", entityType);
            container.AddEntitySet("WrappingEntitySet", wrappingEntityType);

            return(model);
        }
コード例 #5
0
        public IEnumerable <PayloadReaderTestDescriptor> CreateInvalidCollectionsWithTypeNames(bool expectedTypeWillBeUsed)
        {
            EdmModel       model           = new EdmModel();
            EdmComplexType itemComplexType = model.ComplexType("ItemComplexType");

            model.ComplexType("ExtraComplexType");
            model = model.Fixup();

            // Add invalid cases
            var testDescriptors = new[]
            {
                // Invalid collection type name
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue("")
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false))),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", string.Empty),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName(""))
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false))),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", EntityModelUtils.GetCollectionTypeName("")),
                },
                // Invalid collection type name
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue("collection(Edm.Int32)")
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false))),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", "collection(Edm.Int32)"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue("foo")
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false))),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", "foo"),
                },

                // Non existant type name
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("TestModel.NonExistant"))
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false))),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", EntityModelUtils.GetCollectionTypeName("TestModel.NonExistant")),
                },

                // Type of the item differs from the type of the collection
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.String"))
                                     .Item(-42)
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(true))),
                    PayloadEdmModel        = model,
                    ExpectedResultCallback = tc =>
                                             new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_CannotConvertPrimitiveValue", "-42", "Edm.String")
                    },
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(EntityModelUtils.GetCollectionTypeName("TestModel.ItemComplexType"))
                                     .Item(PayloadBuilder.ComplexValue("TestModel.ExtraComplexType"))
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(itemComplexType.ToTypeReference())),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatibleType", "TestModel.ExtraComplexType", "TestModel.ItemComplexType"),
                }
            };

            if (expectedTypeWillBeUsed)
            {
                testDescriptors = testDescriptors.Concat(new[]
                {
                    // Type differs from the declared/expected type
                    new PayloadReaderTestDescriptor(this.Settings)
                    {
                        PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.String"))
                                         .WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false))),
                        PayloadEdmModel   = model,
                        ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatibleType", EntityModelUtils.GetCollectionTypeName("Edm.String"), EntityModelUtils.GetCollectionTypeName("Edm.Int32")),
                    },
                }).ToArray();
            }

            foreach (var testDescriptor in testDescriptors)
            {
                testDescriptor.PayloadNormalizers.Add((tc) => tc.Format == ODataFormat.Json ? AddJsonLightTypeAnnotationToCollectionsVisitor.Normalize : (Func <ODataPayloadElement, ODataPayloadElement>)null);
            }

            return(testDescriptors);
        }
コード例 #6
0
        public void CollectionEntityTypeTypeReferenceFullNameTest()
        {
            var entityTypeCollection = EdmCoreModel.GetCollection(new EdmEntityTypeReference(new EdmEntityType("n", "type"), false));

            entityTypeCollection.Definition.FullTypeName().Should().Be("Collection(n.type)");
        }
コード例 #7
0
        /// <summary>
        /// Creates a test model to test our conversion of OData instances into EDM values.
        /// </summary>
        /// <returns>Returns a model suitable for testing EDM values over OData instances.</returns>
        public static IEdmModel BuildEdmValueModel()
        {
            EdmModel model       = new EdmModel();
            var      complexType = new EdmComplexType(DefaultNamespaceName, "ComplexType");

            complexType.AddStructuralProperty("IntProp", Int32TypeRef);
            complexType.AddStructuralProperty("StringProp", EdmCoreModel.Instance.GetString(isNullable: false));
            complexType.AddStructuralProperty("ComplexProp", new EdmComplexTypeReference(complexType, isNullable: true));
            model.AddElement(complexType);

            #region Entity types
            var entityContainer = new EdmEntityContainer(DefaultNamespaceName, "TestContainer");
            model.AddElement(entityContainer);

            // Entity type with a single primitive property
            var singlePrimitivePropertyEntityType = new EdmEntityType(DefaultNamespaceName, "SinglePrimitivePropertyEntityType");
            singlePrimitivePropertyEntityType.AddKeys(singlePrimitivePropertyEntityType.AddStructuralProperty("ID", Int32TypeRef));
            singlePrimitivePropertyEntityType.AddStructuralProperty("Int32Prop", Int32NullableTypeRef);
            entityContainer.AddEntitySet("SinglePrimitivePropertyEntityType", singlePrimitivePropertyEntityType);
            model.AddElement(singlePrimitivePropertyEntityType);

            // Entity type with all primitive properties
            var allPrimitivePropertiesEntityType = new EdmEntityType(DefaultNamespaceName, "AllPrimitivePropertiesEntityType");
            allPrimitivePropertiesEntityType.AddKeys(allPrimitivePropertiesEntityType.AddStructuralProperty("ID", Int32TypeRef));
            allPrimitivePropertiesEntityType.AddStructuralProperty("BoolProp", EdmPrimitiveTypeKind.Boolean, isNullable: false);
            allPrimitivePropertiesEntityType.AddStructuralProperty("Int16Prop", EdmPrimitiveTypeKind.Int16, isNullable: false);
            allPrimitivePropertiesEntityType.AddStructuralProperty("Int32Prop", EdmPrimitiveTypeKind.Int32, isNullable: false);
            allPrimitivePropertiesEntityType.AddStructuralProperty("Int64Prop", EdmPrimitiveTypeKind.Int64, isNullable: false);
            allPrimitivePropertiesEntityType.AddStructuralProperty("ByteProp", EdmPrimitiveTypeKind.Byte, isNullable: false);
            allPrimitivePropertiesEntityType.AddStructuralProperty("SByteProp", EdmPrimitiveTypeKind.SByte, isNullable: false);
            allPrimitivePropertiesEntityType.AddStructuralProperty("SingleProp", EdmPrimitiveTypeKind.Single, isNullable: false);
            allPrimitivePropertiesEntityType.AddStructuralProperty("DoubleProp", EdmPrimitiveTypeKind.Double, isNullable: false);
            allPrimitivePropertiesEntityType.AddStructuralProperty("DecimalProp", EdmPrimitiveTypeKind.Decimal, isNullable: false);
            allPrimitivePropertiesEntityType.AddStructuralProperty("DateTimeOffsetProp", EdmPrimitiveTypeKind.DateTimeOffset, isNullable: false);
            allPrimitivePropertiesEntityType.AddStructuralProperty("TimeProp", EdmPrimitiveTypeKind.Duration, isNullable: false);
            allPrimitivePropertiesEntityType.AddStructuralProperty("GuidProp", EdmPrimitiveTypeKind.Guid, isNullable: false);
            allPrimitivePropertiesEntityType.AddStructuralProperty("StringProp", EdmPrimitiveTypeKind.String, isNullable: false);
            allPrimitivePropertiesEntityType.AddStructuralProperty("BinaryProp", EdmPrimitiveTypeKind.Binary, isNullable: false);
            entityContainer.AddEntitySet("AllPrimitivePropertiesEntityType", allPrimitivePropertiesEntityType);
            model.AddElement(allPrimitivePropertiesEntityType);

            // Entity type with a single complex property
            var singleComplexPropertyEntityType = new EdmEntityType(DefaultNamespaceName, "SingleComplexPropertyEntityType");
            singleComplexPropertyEntityType.AddKeys(singleComplexPropertyEntityType.AddStructuralProperty("ID", Int32TypeRef));
            singleComplexPropertyEntityType.AddStructuralProperty("ComplexProp", new EdmComplexTypeReference(complexType, isNullable: true));
            entityContainer.AddEntitySet("SingleComplexPropertyEntityType", singleComplexPropertyEntityType);
            model.AddElement(singleComplexPropertyEntityType);

            // Entity type with a single primitive collection property
            var singlePrimitiveCollectionPropertyEntityType = new EdmEntityType(DefaultNamespaceName, "SinglePrimitiveCollectionPropertyEntityType");
            singlePrimitiveCollectionPropertyEntityType.AddKeys(singlePrimitiveCollectionPropertyEntityType.AddStructuralProperty("ID", Int32TypeRef));
            singlePrimitiveCollectionPropertyEntityType.AddStructuralProperty("PrimitiveCollectionProp", EdmCoreModel.GetCollection(Int32TypeRef));
            entityContainer.AddEntitySet("SinglePrimitiveCollectionPropertyEntityType", singlePrimitiveCollectionPropertyEntityType);
            model.AddElement(singlePrimitiveCollectionPropertyEntityType);

            // Entity type with a single primitive collection property
            var singleComplexCollectionPropertyEntityType = new EdmEntityType(DefaultNamespaceName, "SingleComplexCollectionPropertyEntityType");
            singleComplexCollectionPropertyEntityType.AddKeys(singleComplexCollectionPropertyEntityType.AddStructuralProperty("ID", Int32TypeRef));
            singleComplexCollectionPropertyEntityType.AddStructuralProperty("ComplexCollectionProp", EdmCoreModel.GetCollection(new EdmComplexTypeReference(complexType, isNullable: true)));
            entityContainer.AddEntitySet("SingleComplexCollectionPropertyEntityType", singleComplexCollectionPropertyEntityType);
            model.AddElement(singleComplexCollectionPropertyEntityType);

            // Entity type with different property kinds
            var differentPropertyKindsEntityType = new EdmEntityType(DefaultNamespaceName, "DifferentPropertyKindsEntityType");
            differentPropertyKindsEntityType.AddKeys(differentPropertyKindsEntityType.AddStructuralProperty("ID", Int32TypeRef));
            differentPropertyKindsEntityType.AddStructuralProperty("ComplexProp", new EdmComplexTypeReference(complexType, isNullable: true));
            differentPropertyKindsEntityType.AddStructuralProperty("PrimitiveCollectionProp", EdmCoreModel.GetCollection(Int32TypeRef));
            differentPropertyKindsEntityType.AddStructuralProperty("Int32Prop", EdmPrimitiveTypeKind.Int32, isNullable: false);
            differentPropertyKindsEntityType.AddStructuralProperty("ComplexCollectionProp", EdmCoreModel.GetCollection(new EdmComplexTypeReference(complexType, isNullable: true)));
            entityContainer.AddEntitySet("DifferentPropertyKindsEntityType", differentPropertyKindsEntityType);
            model.AddElement(differentPropertyKindsEntityType);
            #endregion Entity types

            #region Complex types
            // Empty complex type
            model.AddElement(new EdmComplexType(DefaultNamespaceName, "EmptyComplexType"));

            // Complex type with a single primitive property
            var singlePrimitivePropertyComplexType = new EdmComplexType(DefaultNamespaceName, "SinglePrimitivePropertyComplexType");
            singlePrimitivePropertyComplexType.AddStructuralProperty("Int32Prop", Int32NullableTypeRef);
            model.AddElement(singlePrimitivePropertyComplexType);

            // Complex type with all primitive properties
            var allPrimitivePropertiesComplexType = new EdmComplexType(DefaultNamespaceName, "AllPrimitivePropertiesComplexType");
            allPrimitivePropertiesComplexType.AddStructuralProperty("BoolProp", EdmPrimitiveTypeKind.Boolean, isNullable: false);
            allPrimitivePropertiesComplexType.AddStructuralProperty("Int16Prop", EdmPrimitiveTypeKind.Int16, isNullable: false);
            allPrimitivePropertiesComplexType.AddStructuralProperty("Int32Prop", EdmPrimitiveTypeKind.Int32, isNullable: false);
            allPrimitivePropertiesComplexType.AddStructuralProperty("Int64Prop", EdmPrimitiveTypeKind.Int64, isNullable: false);
            allPrimitivePropertiesComplexType.AddStructuralProperty("ByteProp", EdmPrimitiveTypeKind.Byte, isNullable: false);
            allPrimitivePropertiesComplexType.AddStructuralProperty("SByteProp", EdmPrimitiveTypeKind.SByte, isNullable: false);
            allPrimitivePropertiesComplexType.AddStructuralProperty("SingleProp", EdmPrimitiveTypeKind.Single, isNullable: false);
            allPrimitivePropertiesComplexType.AddStructuralProperty("DoubleProp", EdmPrimitiveTypeKind.Double, isNullable: false);
            allPrimitivePropertiesComplexType.AddStructuralProperty("DecimalProp", EdmPrimitiveTypeKind.Decimal, isNullable: false);
            allPrimitivePropertiesComplexType.AddStructuralProperty("DateTimeOffsetProp", EdmPrimitiveTypeKind.DateTimeOffset, isNullable: false);
            allPrimitivePropertiesComplexType.AddStructuralProperty("TimeProp", EdmPrimitiveTypeKind.Duration, isNullable: false);
            allPrimitivePropertiesComplexType.AddStructuralProperty("GuidProp", EdmPrimitiveTypeKind.Guid, isNullable: false);
            allPrimitivePropertiesComplexType.AddStructuralProperty("StringProp", EdmPrimitiveTypeKind.String, isNullable: false);
            allPrimitivePropertiesComplexType.AddStructuralProperty("BinaryProp", EdmPrimitiveTypeKind.Binary, isNullable: false);
            model.AddElement(allPrimitivePropertiesComplexType);

            // Complex type with a single complex property
            var singleComplexPropertyComplexType = new EdmComplexType(DefaultNamespaceName, "SingleComplexPropertyComplexType");
            singleComplexPropertyComplexType.AddStructuralProperty("ComplexProp", new EdmComplexTypeReference(complexType, isNullable: true));
            model.AddElement(singleComplexPropertyComplexType);

            // Complex type with a single primitive collection property
            var singlePrimitiveCollectionPropertyComplexType = new EdmComplexType(DefaultNamespaceName, "SinglePrimitiveCollectionPropertyComplexType");
            singlePrimitiveCollectionPropertyComplexType.AddStructuralProperty("PrimitiveCollectionProp", EdmCoreModel.GetCollection(Int32TypeRef));
            model.AddElement(singlePrimitiveCollectionPropertyComplexType);

            // Complex type with a single primitive collection property
            var singleComplexCollectionPropertyComplexType = new EdmComplexType(DefaultNamespaceName, "SingleComplexCollectionPropertyComplexType");
            singleComplexCollectionPropertyComplexType.AddStructuralProperty("ComplexCollectionProp", EdmCoreModel.GetCollection(new EdmComplexTypeReference(complexType, isNullable: true)));
            model.AddElement(singleComplexCollectionPropertyComplexType);

            // Complex type with different property kinds
            var differentPropertyKindsComplexType = new EdmComplexType(DefaultNamespaceName, "DifferentPropertyKindsComplexType");
            differentPropertyKindsComplexType.AddStructuralProperty("ComplexProp", new EdmComplexTypeReference(complexType, isNullable: true));
            differentPropertyKindsComplexType.AddStructuralProperty("PrimitiveCollectionProp", EdmCoreModel.GetCollection(Int32TypeRef));
            differentPropertyKindsComplexType.AddStructuralProperty("Int32Prop", EdmPrimitiveTypeKind.Int32);
            differentPropertyKindsComplexType.AddStructuralProperty("ComplexCollectionProp", EdmCoreModel.GetCollection(new EdmComplexTypeReference(complexType, isNullable: true)));
            model.AddElement(differentPropertyKindsComplexType);
            #endregion Complex types

            return(model);
        }
コード例 #8
0
        public void StreamPropertiesNegativeTests()
        {
            EdmModel model = new EdmModel();

            EdmComplexType edmComplexType = new EdmComplexType("TestModel", "MyComplexType");

            edmComplexType.AddStructuralProperty("Stream1", EdmCoreModel.Instance.GetStream(false));
            model.AddElement(edmComplexType);

            EdmEntityType edmEntityType = new EdmEntityType("TestModel", "EntityTypeForStreams");

            edmEntityType.AddStructuralProperty("Complex", new EdmComplexTypeReference(edmComplexType, false));
            edmEntityType.AddStructuralProperty("Collection", EdmCoreModel.GetCollection(new EdmComplexTypeReference(edmComplexType, false)));
            edmEntityType.AddStructuralProperty("Int32Collection", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false)));
            edmEntityType.AddStructuralProperty("NamedStreamCollection", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetStream(false)));
            model.AddElement(edmEntityType);

            var edmEntityContainer = new EdmEntityContainer("TestModel", "DefaultContainer");

            model.AddElement(edmEntityContainer);

            var entitySet = edmEntityContainer.AddEntitySet("EntitySetForStreams", edmEntityType);

            var testCases = new[] {
                // Note that negative test cases to validate the content of an ODataStreamReferenceValue are in WriteInputValidationTests.cs.
                // TODO: We need to add these test cases for writing top level properties and metadata as well.
                new { // named stream properties are not allowed on complex types
                    NamedStreamProperty = new ODataProperty()
                    {
                        Name  = "Complex",
                        Value = new ODataComplexValue()
                        {
                            TypeName   = "TestModel.MyComplexType",
                            Properties = new[]
                            {
                                new ODataProperty()
                                {
                                    Name  = "Stream1",
                                    Value = new ODataStreamReferenceValue()
                                    {
                                        EditLink = new Uri("someUri", UriKind.RelativeOrAbsolute)
                                    }
                                }
                            }
                        }
                    },
                    ExpectedExceptionWithoutModel = ODataExpectedExceptions.ODataException("ODataWriter_StreamPropertiesMustBePropertiesOfODataEntry"),
                    ExpectedExceptionWithModel    = ODataExpectedExceptions.ODataException("ODataWriter_StreamPropertiesMustBePropertiesOfODataEntry"),
                },
                new { // named stream properties are not allowed on complex collection types
                    NamedStreamProperty = new ODataProperty()
                    {
                        Name  = "Collection",
                        Value = new ODataCollectionValue()
                        {
                            TypeName = EntityModelUtils.GetCollectionTypeName("TestModel.MyComplexType"),
                            Items    = new[]
                            {
                                new ODataComplexValue()
                                {
                                    TypeName   = "TestModel.MyComplexType",
                                    Properties = new[]
                                    {
                                        new ODataProperty()
                                        {
                                            Name  = "Stream1",
                                            Value = new ODataStreamReferenceValue()
                                            {
                                                EditLink = new Uri("someUri", UriKind.RelativeOrAbsolute)
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    },
                    ExpectedExceptionWithoutModel = ODataExpectedExceptions.ODataException("ODataWriter_StreamPropertiesMustBePropertiesOfODataEntry"),
                    ExpectedExceptionWithModel    = ODataExpectedExceptions.ODataException("ODataWriter_StreamPropertiesMustBePropertiesOfODataEntry"),
                },
                // TODO: Add the following case for the top-level collection writer as well.
                new { // named stream collection properties are not allowed.
                    NamedStreamProperty = new ODataProperty()
                    {
                        Name  = "Int32Collection",
                        Value = new ODataCollectionValue()
                        {
                            TypeName = EntityModelUtils.GetCollectionTypeName("Edm.Int32"),
                            Items    = new[]
                            {
                                new ODataStreamReferenceValue()
                                {
                                    EditLink = new Uri("someUri", UriKind.RelativeOrAbsolute)
                                }
                            }
                        }
                    },
                    ExpectedExceptionWithoutModel = ODataExpectedExceptions.ODataException("ValidationUtils_StreamReferenceValuesNotSupportedInCollections"),
                    ExpectedExceptionWithModel    = ODataExpectedExceptions.ODataException("ValidationUtils_StreamReferenceValuesNotSupportedInCollections"),
                },
                new { // named stream collection properties are not allowed - with valid type.
                    NamedStreamProperty = new ODataProperty()
                    {
                        Name  = "NamedStreamCollection",
                        Value = new ODataCollectionValue()
                        {
                            TypeName = EntityModelUtils.GetCollectionTypeName("Edm.Stream"),
                            Items    = new[]
                            {
                                new ODataStreamReferenceValue()
                                {
                                    EditLink = new Uri("someUri", UriKind.RelativeOrAbsolute)
                                }
                            }
                        }
                    },
                    ExpectedExceptionWithoutModel = ODataExpectedExceptions.ODataException("ValidationUtils_StreamReferenceValuesNotSupportedInCollections"),
                    ExpectedExceptionWithModel    = ODataExpectedExceptions.ODataException("EdmLibraryExtensions_CollectionItemCanBeOnlyPrimitiveEnumComplex"),
                },
            };

            var testDescriptors = testCases.SelectMany(testCase =>
            {
                ODataEntry entry = new ODataEntry()
                {
                    TypeName          = "TestModel.EntityTypeForStreams",
                    Properties        = new ODataProperty[] { testCase.NamedStreamProperty },
                    SerializationInfo = new ODataFeedAndEntrySerializationInfo()
                    {
                        NavigationSourceEntityTypeName = "TestModel.EntityTypeForStreams",
                        ExpectedTypeName     = "TestModel.EntityTypeForStreams",
                        NavigationSourceName = "MySet"
                    }
                };
                return(new []
                {
                    new PayloadWriterTestDescriptor <ODataItem>(
                        this.Settings,
                        entry,
                        testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = testCase.ExpectedExceptionWithoutModel
                    })
                    {
                        Model = null,
                    },
                    new PayloadWriterTestDescriptor <ODataItem>(
                        this.Settings,
                        entry,
                        testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = testCase.ExpectedExceptionWithModel
                    })
                    {
                        Model = model,
                        PayloadEdmElementContainer = entitySet,
                        PayloadEdmElementType = edmEntityType,
                    },
                });
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                if (testDescriptor.Model == null && testConfiguration.Format == ODataFormat.Json)
                {
                    return;
                }

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
コード例 #9
0
        private void InitializeEdmModel()
        {
            this.edmModel = new EdmModel();

            EdmEntityContainer defaultContainer = new EdmEntityContainer("TestModel", "DefaultContainer");

            this.edmModel.AddElement(defaultContainer);

            addressType = new EdmComplexType("TestModel", "Address");
            addressType.AddStructuralProperty("Street", EdmCoreModel.Instance.GetString(/*isNullable*/ false));
            addressType.AddStructuralProperty("Zip", EdmCoreModel.Instance.GetString(/*isNullable*/ false));

            this.cityType = new EdmEntityType("TestModel", "City", baseType: null, isAbstract: false, isOpen: true);
            EdmStructuralProperty cityIdProperty = cityType.AddStructuralProperty("Id", EdmCoreModel.Instance.GetInt32(/*isNullable*/ false));

            cityType.AddKeys(cityIdProperty);
            cityType.AddStructuralProperty("Name", EdmCoreModel.Instance.GetString(/*isNullable*/ false));
            cityType.AddStructuralProperty("Size", EdmCoreModel.Instance.GetInt32(/*isNullable*/ false));
            cityType.AddStructuralProperty("Restaurants", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(/*isNullable*/ false)));
            cityType.AddStructuralProperty("Address", new EdmComplexTypeReference(addressType, true));
            this.edmModel.AddElement(cityType);

            this.capitolCityType = new EdmEntityType("TestModel", "CapitolCity", cityType);
            capitolCityType.AddStructuralProperty("CapitolType", EdmCoreModel.Instance.GetString(/*isNullable*/ false));
            this.edmModel.AddElement(capitolCityType);

            this.districtType = new EdmEntityType("TestModel", "District");
            EdmStructuralProperty districtIdProperty = districtType.AddStructuralProperty("Id", EdmCoreModel.Instance.GetInt32(/*isNullable*/ false));

            districtType.AddKeys(districtIdProperty);
            districtType.AddStructuralProperty("Name", EdmCoreModel.Instance.GetString(/*isNullable*/ false));
            districtType.AddStructuralProperty("Zip", EdmCoreModel.Instance.GetInt32(/*isNullable*/ false));
            this.edmModel.AddElement(districtType);

            cityType.AddBidirectionalNavigation(
                new EdmNavigationPropertyInfo {
                Name = "Districts", Target = districtType, TargetMultiplicity = EdmMultiplicity.Many
            },
                new EdmNavigationPropertyInfo {
                Name = "City", Target = cityType, TargetMultiplicity = EdmMultiplicity.One
            });

            cityType.NavigationProperties().Single(np => np.Name == "Districts");
            capitolCityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "CapitolDistrict", Target = districtType, TargetMultiplicity = EdmMultiplicity.One
            });
            capitolCityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "OutlyingDistricts", Target = districtType, TargetMultiplicity = EdmMultiplicity.Many
            });

            this.citySet     = defaultContainer.AddEntitySet("Cities", cityType);
            this.districtSet = defaultContainer.AddEntitySet("Districts", districtType);

            this.singletonCity = defaultContainer.AddSingleton("SingletonCity", cityType);

            // operations
            var cityReference       = new EdmEntityTypeReference(cityType, true);
            var districtReference   = new EdmEntityTypeReference(districtType, true);
            IEdmPathExpression path = new EdmPathExpression("binding/Districts");
            var function            = new EdmFunction("TestModel", "GetOneDistrict", districtReference, true, path, true /*isComposable*/);

            function.AddParameter("binding", cityReference);
            edmModel.AddElement(function);
        }
コード例 #10
0
        public void ComplexValueIgnorePropertyNullValuesTest()
        {
            var versions = new Version[] {
                null,
                new Version(4, 0),
            };

            EdmModel        edmModel          = new EdmModel();
            IEdmComplexType countryRegionType = edmModel.ComplexType("CountryRegion")
                                                .Property("Name", EdmPrimitiveTypeKind.String)
                                                .Property("CountryRegionCode", EdmPrimitiveTypeKind.String);
            IEdmComplexType countryRegionNullType = edmModel.ComplexType("CountryRegionNull")
                                                    .Property("Name", EdmPrimitiveTypeKind.String)
                                                    .Property("CountryRegionCode", EdmPrimitiveTypeKind.String);
            IEdmComplexType addressType = edmModel.ComplexType("Address")
                                          .Property("Street", EdmPrimitiveTypeKind.String)
                                          .Property("StreetNull", EdmCoreModel.Instance.GetString(true) as EdmTypeReference)
                                          .Property("Numbers", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false)) as EdmTypeReference)
                                          .Property("CountryRegion", new EdmComplexTypeReference(countryRegionType, false))
                                          .Property("CountryRegionNull", new EdmComplexTypeReference(countryRegionNullType, true));

            edmModel.EntityType("Customer")
            .KeyProperty("ID", EdmCoreModel.Instance.GetInt32(false) as EdmTypeReference)
            .Property("Address", new EdmComplexTypeReference(addressType, false));
            edmModel.Fixup();

            this.CombinatorialEngineProvider.RunCombinations(
                new ODataNullValueBehaviorKind[] { ODataNullValueBehaviorKind.Default, ODataNullValueBehaviorKind.DisableValidation, ODataNullValueBehaviorKind.IgnoreValue },
                versions,
                versions,
                TestReaderUtils.ODataBehaviorKinds,
                (nullPropertyValueReaderBehavior, dataServiceVersion, edmVersion, behaviorKind) =>
            {
                edmModel.SetEdmVersion(edmVersion);

                // Now we set the 'IgnoreNullValues' annotation on all properties
                IEdmComplexType edmAddressType = (IEdmComplexType)edmModel.FindType("TestModel.Address");
                foreach (IEdmStructuralProperty edmProperty in edmAddressType.StructuralProperties())
                {
                    edmModel.SetNullValueReaderBehavior(edmProperty, nullPropertyValueReaderBehavior);
                }

                EntityInstance customerPayload = PayloadBuilder.Entity("TestModel.Customer")
                                                 .PrimitiveProperty("ID", 1)
                                                 .Property("Address", PayloadBuilder.ComplexValue("TestModel.Address")
                                                           .PrimitiveProperty("Street", "One Microsoft Way")
                                                           .PrimitiveProperty("StreetNull", "One Microsoft Way")
                                                           .Property("Numbers", PayloadBuilder.PrimitiveMultiValue("Collection(Edm.Int32)").Item(1).Item(2))
                                                           .Property("CountryRegion", PayloadBuilder.ComplexValue("TestModel.CountryRegion")
                                                                     .PrimitiveProperty("Name", "Austria")
                                                                     .PrimitiveProperty("CountryRegionCode", "AUT"))
                                                           .Property("CountryRegionNull", PayloadBuilder.ComplexValue("TestModel.CountryRegionNull")
                                                                     .PrimitiveProperty("Name", "Austria")
                                                                     .PrimitiveProperty("CountryRegionCode", "AUT")));

                var testCases = new[]
                {
                    // Complex types that are not nullable should not allow null values.
                    // Null primitive property in the payload and non-nullable property in the model
                    new IgnoreNullValueTestCase
                    {
                        PropertyName = "Street",
                        ExpectedResponseException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_NullNamedValueForNonNullableType", "Street", "Edm.String"),
                    },
                    // Null complex property in the payload and non-nullable property in the model
                    new IgnoreNullValueTestCase
                    {
                        PropertyName = "CountryRegion",
                        ExpectedResponseException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_NullNamedValueForNonNullableType", "CountryRegion", "TestModel.CountryRegion"),
                    },
                    // Null collection property in the payload and non-nullable property in the model
                    new IgnoreNullValueTestCase
                    {
                        PropertyName = "Numbers",
                        ExpectedResponseException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_NullNamedValueForNonNullableType", "Numbers", "Collection(Edm.Int32)"),
                    },
                    // Complex types that are nullable should allow null values.
                    // Null primitive property in the payload and nullable property in the model
                    new IgnoreNullValueTestCase
                    {
                        PropertyName = "StreetNull",
                    },
                    // Null complex property in the payload and nullable property in the model
                    new IgnoreNullValueTestCase
                    {
                        PropertyName = "CountryRegionNull",
                    },
                };

                Func <IgnoreNullValueTestCase, ReaderTestConfiguration, PayloadReaderTestDescriptor> createTestDescriptor =
                    (testCase, testConfig) =>
                {
                    EntityInstance payloadValue         = customerPayload.DeepCopy();
                    ComplexInstance payloadAddressValue = ((ComplexProperty)payloadValue.GetProperty("Address")).Value;
                    SetToNull(payloadAddressValue, testCase.PropertyName);

                    ComplexInstance resultValue = payloadValue;
                    if (testConfig.IsRequest && nullPropertyValueReaderBehavior == ODataNullValueBehaviorKind.IgnoreValue)
                    {
                        resultValue = customerPayload.DeepCopy();
                        ComplexInstance resultAddressValue = ((ComplexProperty)resultValue.GetProperty("Address")).Value;
                        resultAddressValue.Remove(resultAddressValue.GetProperty(testCase.PropertyName));
                    }

                    return(new PayloadReaderTestDescriptor(this.Settings)
                    {
                        PayloadElement = payloadValue,
                        PayloadEdmModel = edmModel,
                        ExpectedResultPayloadElement =
                            tc =>
                        {
                            if (tc.Format == ODataFormat.Json)
                            {
                                // under the client knob ODL will compute edit links, ids, etc
                                // so we need to update the expected payload
                                if (tc.RunBehaviorKind == TestODataBehaviorKind.WcfDataServicesClient)
                                {
                                    var entity = resultValue as EntityInstance;
                                    if (entity != null)
                                    {
                                        if (!tc.IsRequest)
                                        {
                                            entity.Id = "http://odata.org/test/Customer(1)";
                                            entity.EditLink = "http://odata.org/test/Customer(1)";
                                            entity.WithSelfLink("http://odata.org/test/Customer(1)");
                                        }
                                    }
                                }

                                var tempDescriptor = new PayloadReaderTestDescriptor(this.Settings)
                                {
                                    PayloadElement = resultValue,
                                    PayloadEdmModel = edmModel,
                                };

                                JsonLightPayloadElementFixup.Fixup(tempDescriptor);
                                return tempDescriptor.PayloadElement;
                            }

                            return resultValue;
                        },
                        ExpectedException = (testConfig.IsRequest && nullPropertyValueReaderBehavior != ODataNullValueBehaviorKind.Default) ? null : testCase.ExpectedResponseException
                    });
                };

                this.CombinatorialEngineProvider.RunCombinations(
                    testCases,
                    this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                    (testCase, testConfiguration) =>
                {
                    testConfiguration = testConfiguration.CloneAndApplyBehavior(behaviorKind);
                    testConfiguration.MessageReaderSettings.BaseUri = null;

                    PayloadReaderTestDescriptor testDescriptor = createTestDescriptor(testCase, testConfiguration);
                    testDescriptor.RunTest(testConfiguration);
                });
            });
        }
コード例 #11
0
        /// <summary>
        /// Gets the data type of a property value specified in the property instance payload element.
        /// </summary>
        /// <param name="propertyInstance">The property instance payload element to inspect.</param>
        /// <returns>The data type of the property value (can be used to define the metadata for this property).</returns>
        public static IEdmTypeReference GetPayloadEdmElementPropertyValueType(PropertyInstance propertyInstance)
        {
            ExceptionUtilities.CheckArgumentNotNull(propertyInstance, "propertyInstance");

            IEdmTypeReference result = GetEdmTypeFromEntityModelTypeAnnotation(propertyInstance);

            if (result == null)
            {
                switch (propertyInstance.ElementType)
                {
                case ODataPayloadElementType.NullPropertyInstance:
                    NullPropertyInstance nullPropertyInstance = (NullPropertyInstance)propertyInstance;
                    if (nullPropertyInstance.FullTypeName != null)
                    {
                        result = GetPrimitiveEdmType(nullPropertyInstance.FullTypeName);
                        if (result == null)
                        {
                            result = CreateComplexTypeReference(nullPropertyInstance.FullTypeName);
                        }
                    }

                    break;

                case ODataPayloadElementType.PrimitiveProperty:
                    result = GetEdmTypeFromEntityModelTypeAnnotation(((PrimitiveProperty)propertyInstance).Value);
                    if (result == null)
                    {
                        result = GetPrimitiveEdmType(((PrimitiveProperty)propertyInstance).Value.FullTypeName);
                    }

                    break;

                case ODataPayloadElementType.ComplexProperty:
                    result = GetEdmTypeFromEntityModelTypeAnnotation(((ComplexProperty)propertyInstance).Value);
                    if (result == null)
                    {
                        result = CreateComplexTypeReference(((ComplexProperty)propertyInstance).Value.FullTypeName);
                    }

                    break;

                case ODataPayloadElementType.NamedStreamInstance:
                    result = EdmCoreModel.Instance.GetStream(isNullable: false);

                    break;

                case ODataPayloadElementType.PrimitiveMultiValueProperty:
                    PrimitiveMultiValue primitiveMultiValue = ((PrimitiveMultiValueProperty)propertyInstance).Value;
                    result = GetEdmTypeFromEntityModelTypeAnnotation(primitiveMultiValue);
                    if (result == null && primitiveMultiValue.FullTypeName != null)
                    {
                        string itemTypeName = EntityModelUtils.GetCollectionItemTypeName(primitiveMultiValue.FullTypeName);
                        if (itemTypeName != null)
                        {
                            result = EdmCoreModel.GetCollection(GetPrimitiveEdmType(itemTypeName));
                        }
                    }

                    break;

                case ODataPayloadElementType.ComplexMultiValueProperty:
                    ComplexMultiValue complexMultiValue = ((ComplexMultiValueProperty)propertyInstance).Value;
                    result = GetEdmTypeFromEntityModelTypeAnnotation(complexMultiValue);
                    if (result == null && complexMultiValue.FullTypeName != null)
                    {
                        string itemTypeName = EntityModelUtils.GetCollectionItemTypeName(complexMultiValue.FullTypeName);
                        if (itemTypeName != null)
                        {
                            return(EdmCoreModel.GetCollection(CreateComplexTypeReference(itemTypeName)));
                        }
                    }

                    break;

                case ODataPayloadElementType.PrimitiveCollection:
                case ODataPayloadElementType.ComplexInstanceCollection:
                    ExceptionUtilities.Assert(false, "Primitive and complex collections cannot be used in properties but only at the top-level.");
                    return(null);

                default:
                    ExceptionUtilities.Assert(false, "GetPayloadElementPropertyValueType doesn't support '{0}' yet.", propertyInstance.ElementType);
                    return(null);
                }
            }

            // Use the expected type if there's any since it also specifies metadata
            if (result == null)
            {
                ExpectedTypeODataPayloadElementAnnotation expectedTypeAnnotation = propertyInstance.GetAnnotation <ExpectedTypeODataPayloadElementAnnotation>();
                if (expectedTypeAnnotation != null && expectedTypeAnnotation.ExpectedType != null)
                {
                    result = expectedTypeAnnotation.EdmExpectedType;
                }
            }

            return(result);
        }
コード例 #12
0
        public void DuplicatePropertyNamesTest()
        {
            PropertyInstance primitiveProperty = PayloadBuilder.PrimitiveProperty("DuplicateProperty", 42);
            PropertyInstance complexProperty   = PayloadBuilder.Property("DuplicateProperty",
                                                                         PayloadBuilder.ComplexValue("TestModel.DuplicateComplexType").PrimitiveProperty("Name", "foo"));
            PropertyInstance collectionProperty = PayloadBuilder.Property("DuplicateProperty",
                                                                          PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.String")).WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(false))));

            PropertyInstance[] allProperties = new[] { primitiveProperty, complexProperty, collectionProperty };
            PropertyInstance[] propertiesWithPossibleDuplication = new[] { primitiveProperty, complexProperty };
            PropertyInstance[] propertiesWithNoDuplication       = new[] { collectionProperty };

            IEnumerable <DuplicatePropertySet> duplicatePropertySets;

            // Those which may allow duplication
            duplicatePropertySets = propertiesWithPossibleDuplication
                                    .Variations(2).Select(properties => new DuplicatePropertySet {
                Properties = properties, DuplicationPotentiallyAllowed = true
            });

            // Then for each in those which don't allow duplication try it against all the others
            duplicatePropertySets = duplicatePropertySets.Concat(propertiesWithNoDuplication.SelectMany(
                                                                     propertyWithNoDuplication => allProperties.SelectMany(otherProperty =>
                                                                                                                           new[]
            {
                new DuplicatePropertySet {
                    Properties = new [] { propertyWithNoDuplication, otherProperty }, DuplicationPotentiallyAllowed = false
                },
                new DuplicatePropertySet {
                    Properties = new [] { otherProperty, propertyWithNoDuplication }, DuplicationPotentiallyAllowed = false
                },
            })));

            this.CombinatorialEngineProvider.RunCombinations(
                duplicatePropertySets,
                new bool[] { false, true },
                new bool[] { true, false },
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                (duplicatePropertySet, allowDuplicateProperties, useMetadata, testConfiguration) =>
            {
                EdmModel model  = new EdmModel();
                var complexType = model.ComplexType("DuplicateComplexType");
                complexType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
                model.Fixup();

                PropertyInstance firstProperty  = duplicatePropertySet.Properties.ElementAt(0);
                PropertyInstance secondProperty = duplicatePropertySet.Properties.ElementAt(1);

                // Non-metadata reading is not possible in JSON
                if (!useMetadata && (testConfiguration.Format == ODataFormat.Json))
                {
                    return;
                }

                // If we will have metadata then we can only allow combinations of the same kind
                if (useMetadata)
                {
                    if (firstProperty.ElementType != secondProperty.ElementType)
                    {
                        return;
                    }
                }

                // Copy the test config
                testConfiguration = new ReaderTestConfiguration(testConfiguration);
                if (allowDuplicateProperties)
                {
                    testConfiguration.MessageReaderSettings.EnableODataServerBehavior();
                }

                // Create a descriptor with the first property
                PayloadReaderTestDescriptor testDescriptor = new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement  = firstProperty,
                    PayloadEdmModel = useMetadata ? model : null
                };

                // Now generate entity around it
                testDescriptor = testDescriptor.InComplexValue(5, 5);

                // Now add the second property to it
                ((ComplexInstance)testDescriptor.PayloadElement).Add(secondProperty);

                // [Astoria-ODataLib-Integration] Parsing of URLs on OData recognized places may fail, but Astoria server doesn't
                // Server does not read named stream links for Atom payload therefore the expected payload needs to be normalized
                if (testConfiguration.Format == ODataFormat.Atom)
                {
                    testDescriptor.ExpectedResultNormalizers.Add(config => (payloadElement => WcfDsServerPayloadElementNormalizer.Normalize(payloadElement, ODataFormat.Atom, testDescriptor.PayloadEdmModel as EdmModel)));
                }

                // We expect failure only if we don't allow duplicates or if the property kind doesn't allow duplicates ever
                if ((!duplicatePropertySet.DuplicationPotentiallyAllowed || !allowDuplicateProperties))
                {
                    testDescriptor.ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_DuplicatePropertyNamesNotAllowed", "DuplicateProperty");
                }

                IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new PayloadReaderTestDescriptor[]
                {
                    testDescriptor.InProperty("TopLevelProperty"),
                    testDescriptor.InProperty("ComplexProperty").InEntity(2, 2),
                    testDescriptor.InCollection(5, 5).InProperty("TopLevelCollection"),
                };

                this.CombinatorialEngineProvider.RunCombinations(
                    testDescriptors,
                    td =>
                {
                    var property = td.PayloadElement as PropertyInstance;
                    if (property != null && testConfiguration.Format == ODataFormat.Atom)
                    {
                        property.Name = null;
                    }
                    td.RunTest(testConfiguration);
                });
            });
        }
コード例 #13
0
 public static IEdmCollectionTypeReference GetDocEntityCollectionTypeRef(this IEdmModel model) =>
 EdmCoreModel.GetCollection(model.GetDocTypeRef());
コード例 #14
0
ファイル: TrippinDomain.cs プロジェクト: karataliu/RESTier
        public Task ExtendModelAsync(
            ModelContext context,
            CancellationToken cancellationToken)
        {
            var entityContainer = (EdmEntityContainer)context.Model.EntityContainer;
            var personType      = (IEdmEntityType)context.Model
                                  .FindDeclaredType("Microsoft.Restier.WebApi.Test.Services.Trippin.Models.Person");
            var personTypeReference = new EdmEntityTypeReference(personType, false);

            entityContainer.AddSingleton("Me", personType);

            var people = entityContainer.FindEntitySet("People");

            var getNumberOfFriends = new EdmFunction(
                "Microsoft.Restier.WebApi.Test.Services.Trippin.Models",
                "GetNumberOfFriends",
                EdmCoreModel.Instance.GetInt32(false),
                isBound: true,
                entitySetPathExpression: null,
                isComposable: true);

            getNumberOfFriends.AddParameter("person", personTypeReference);
            context.Model.AddElement(getNumberOfFriends);

            var getPersonWithMostFriends = new EdmFunction(
                "Microsoft.Restier.WebApi.Test.Services.Trippin.Models",
                "GetPersonWithMostFriends",
                personTypeReference,
                isBound: false,
                entitySetPathExpression: null,
                isComposable: true);

            context.Model.AddElement(getPersonWithMostFriends);
            entityContainer.AddFunctionImport(
                "GetPersonWithMostFriends",
                getPersonWithMostFriends,
                new EdmEntitySetReferenceExpression(people));

            var getPeopleWithFriendsAtLeast = new EdmFunction(
                "Microsoft.Restier.WebApi.Test.Services.Trippin.Models",
                "GetPeopleWithFriendsAtLeast",
                EdmCoreModel.GetCollection(personTypeReference),
                isBound: false,
                entitySetPathExpression: null,
                isComposable: true);

            getPeopleWithFriendsAtLeast.AddParameter("n", EdmCoreModel.Instance.GetInt32(false));
            context.Model.AddElement(getPeopleWithFriendsAtLeast);
            entityContainer.AddFunctionImport(
                "GetPeopleWithFriendsAtLeast",
                getPeopleWithFriendsAtLeast,
                new EdmEntitySetReferenceExpression(people));

            var cleanUpExpiredTrips = new EdmAction(
                "Microsoft.Restier.WebApi.Test.Services.Trippin.Models",
                "CleanUpExpiredTrips",
                returnType: null,
                isBound: false,
                entitySetPathExpression: null);

            context.Model.AddElement(cleanUpExpiredTrips);
            entityContainer.AddActionImport(
                "CleanUpExpiredTrips",
                cleanUpExpiredTrips,
                null);

            var tripType = (IEdmEntityType)context.Model
                           .FindDeclaredType("Microsoft.Restier.WebApi.Test.Services.Trippin.Models.Trip");
            var tripTypeReference = new EdmEntityTypeReference(tripType, false);

            var endTrip = new EdmAction(
                "Microsoft.Restier.WebApi.Test.Services.Trippin.Models",
                "EndTrip",
                tripTypeReference,
                isBound: true,
                entitySetPathExpression: new EdmPathExpression("trip"));

            endTrip.AddParameter("trip", tripTypeReference);
            context.Model.AddElement(endTrip);

            return(Task.FromResult <object>(null));
        }
コード例 #15
0
        public void CollectionUnNamedStructuralType()
        {
            var fakeStructuredCollectionType = EdmCoreModel.GetCollection(new FakeEdmStructuredTypeReference(new FakeStructuredType(false, false, null)));

            fakeStructuredCollectionType.Definition.FullTypeName().Should().BeNull();
        }
コード例 #16
0
        private IEdmModel CollectionOfPrimitiveTypeTermModel()
        {
            var model = new EdmModel();

            var collectionOfPrimitiveTypeEntity = new EdmEntityType("NS", "CollectionOfPrimitiveTypeEntity");

            collectionOfPrimitiveTypeEntity.AddKeys(collectionOfPrimitiveTypeEntity.AddStructuralProperty("KeyProperty", EdmCoreModel.Instance.GetInt32(false)));
            model.AddElement(collectionOfPrimitiveTypeEntity);

            // Collection of Boolean
            var collectionOfBooleanProperty = collectionOfPrimitiveTypeEntity.AddStructuralProperty("CollectionOfBooleanProperty", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetBoolean(true)));
            var collectionOfBooleanTerm     = new EdmTerm("NS", "CollectionOfBooleanTerm", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetBoolean(true)));

            model.AddElement(collectionOfBooleanTerm);
            var collectionOfBooleanAnnotation = new EdmVocabularyAnnotation(collectionOfBooleanProperty, collectionOfBooleanTerm, new EdmCollectionExpression(
                                                                                new EdmBooleanConstant(true),
                                                                                new EdmBooleanConstant(false)));

            model.AddVocabularyAnnotation(collectionOfBooleanAnnotation);

            // Collection of Integer
            var collectionOfIntegerProperty = collectionOfPrimitiveTypeEntity.AddStructuralProperty("CollectionOfIntegerProperty", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(true)));
            var collectionOfIntegerTerm     = new EdmTerm("NS", "CollectionOfIntegerTerm", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(true)));

            model.AddElement(collectionOfIntegerTerm);
            var collectionOfIntegerAnnotation = new EdmVocabularyAnnotation(collectionOfIntegerProperty, collectionOfIntegerTerm, new EdmCollectionExpression(
                                                                                new EdmIntegerConstant(1),
                                                                                new EdmIntegerConstant(2),
                                                                                new EdmIntegerConstant(3)));

            model.AddVocabularyAnnotation(collectionOfIntegerAnnotation);

            // Collection of Floating
            var collectionOfFloatingProperty = collectionOfPrimitiveTypeEntity.AddStructuralProperty("CollectionOfFloatingProperty", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetDouble(true)));
            var collectionOfFloatingTerm     = new EdmTerm("NS", "CollectionOfFloatingTerm", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetDouble(true)));

            model.AddElement(collectionOfFloatingTerm);
            var collectionOfFloatingAnnotation = new EdmVocabularyAnnotation(collectionOfFloatingProperty, collectionOfFloatingTerm, new EdmCollectionExpression(
                                                                                 new EdmFloatingConstant(1.23),
                                                                                 new EdmFloatingConstant(99.99)));

            model.AddVocabularyAnnotation(collectionOfFloatingAnnotation);

            // Collection of Guid
            var collectionOfGuidProperty = collectionOfPrimitiveTypeEntity.AddStructuralProperty("CollectionOfGuidProperty", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetGuid(true)));
            var collectionOfGuidTerm     = new EdmTerm("NS", "CollectionOfGuidTerm", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetGuid(true)));

            model.AddElement(collectionOfGuidTerm);
            var collectionOfGuidAnnotation = new EdmVocabularyAnnotation(collectionOfGuidProperty, collectionOfGuidTerm, new EdmCollectionExpression(new EdmGuidConstant(new Guid("00000000-0000-0000-0000-000000000000"))));

            model.AddVocabularyAnnotation(collectionOfGuidAnnotation);

            // Collection of Binary
            var collectionOfBinaryProperty = collectionOfPrimitiveTypeEntity.AddStructuralProperty("CollectionOfBinaryProperty", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetBinary(true)));
            var collectionOfBinaryTerm     = new EdmTerm("NS", "CollectionOfBinaryTerm", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetBinary(true)));

            model.AddElement(collectionOfBinaryTerm);
            var collectionOfBinaryAnnotation = new EdmVocabularyAnnotation(collectionOfBinaryProperty, collectionOfBinaryTerm, new EdmCollectionExpression(
                                                                               new EdmBinaryConstant(new byte[] { 0x41, 0x42 }),
                                                                               new EdmBinaryConstant(new byte[] { 0x61, 0x62 }),
                                                                               new EdmBinaryConstant(new byte[] { 0x4A, 0x4B, 0x6A, 0x6B })));

            model.AddVocabularyAnnotation(collectionOfBinaryAnnotation);

            // Collection of Decimal
            var collectionOfDecimalProperty = collectionOfPrimitiveTypeEntity.AddStructuralProperty("CollectionOfDecimalProperty", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetDecimal(true)));
            var collectionOfDecimalTerm     = new EdmTerm("NS", "CollectionOfDecimalTerm", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetDecimal(true)));

            model.AddElement(collectionOfDecimalTerm);
            var collectionOfDecimalAnnotation = new EdmVocabularyAnnotation(collectionOfDecimalProperty, collectionOfDecimalTerm, new EdmCollectionExpression(
                                                                                new EdmDecimalConstant(-1.0000000000m),
                                                                                new EdmDecimalConstant(1234567890m),
                                                                                new EdmDecimalConstant(99.9999999999m)));

            collectionOfDecimalAnnotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            model.AddVocabularyAnnotation(collectionOfDecimalAnnotation);

            // Collection of String
            var collectionOfStringProperty = collectionOfPrimitiveTypeEntity.AddStructuralProperty("CollectionOfStringProperty", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(true)));
            var collectionOfStringTerm     = new EdmTerm("NS", "CollectionOfStringTerm", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(true)));

            model.AddElement(collectionOfStringTerm);
            var collectionOfStringAnnotation = new EdmVocabularyAnnotation(collectionOfStringProperty, collectionOfStringTerm, new EdmCollectionExpression(
                                                                               new EdmStringConstant("12345"),
                                                                               new EdmStringConstant("abcdABCD"),
                                                                               new EdmStringConstant("Hello World!")));

            collectionOfStringAnnotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            model.AddVocabularyAnnotation(collectionOfStringAnnotation);

            // Collection of DateTimeOffset
            var collectionOfDateTimeOffsetProperty = collectionOfPrimitiveTypeEntity.AddStructuralProperty("CollectionOfDateTimeOffsetProperty", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetDateTimeOffset(true)));
            var collectionOfDateTimeOffsetTerm     = new EdmTerm("NS", "CollectionOfDateTimeOffsetTerm", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetDateTimeOffset(true)));

            model.AddElement(collectionOfDateTimeOffsetTerm);
            var collectionOfDateTimeOffsetAnnotation = new EdmVocabularyAnnotation(collectionOfDateTimeOffsetProperty, collectionOfDateTimeOffsetTerm, new EdmCollectionExpression(
                                                                                       new EdmDateTimeOffsetConstant(new DateTimeOffset(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))),
                                                                                       new EdmDateTimeOffsetConstant(new DateTimeOffset(new DateTime(2000, 12, 31, 23, 59, 59, DateTimeKind.Utc)))));

            collectionOfDateTimeOffsetAnnotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            model.AddVocabularyAnnotation(collectionOfDateTimeOffsetAnnotation);

            // Collection of Duration
            var collectionOfDurationProperty = collectionOfPrimitiveTypeEntity.AddStructuralProperty("CollectionOfDurationProperty", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetDuration(true)));
            var collectionOfDurationTerm     = new EdmTerm("NS", "CollectionOfDurationTerm", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetDuration(true)));

            model.AddElement(collectionOfDurationTerm);
            var collectionOfDurationAnnotation = new EdmVocabularyAnnotation(collectionOfDurationProperty, collectionOfDurationTerm, new EdmCollectionExpression(
                                                                                 new EdmDurationConstant(new TimeSpan(1, 2, 3, 4)),
                                                                                 new EdmDurationConstant(new TimeSpan(23, 59, 59))));

            collectionOfDurationAnnotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            model.AddVocabularyAnnotation(collectionOfDurationAnnotation);

            return(model);
        }
コード例 #17
0
        public void CollectionPrimitiveTypeReferenceFullNameTest()
        {
            var collectionPrimitives = EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt16(true));

            collectionPrimitives.Definition.FullTypeName().Should().Be("Collection(Edm.Int16)");
        }
コード例 #18
0
        private IEdmModel CollectionOfEntityTypeTermModel()
        {
            var model = new EdmModel();

            var entityTypeElement = new EdmEntityType("NS", "EntityTypeElement");

            entityTypeElement.AddKeys(entityTypeElement.AddStructuralProperty("KeyProperty", EdmCoreModel.Instance.GetInt32(false)));
            entityTypeElement.AddStructuralProperty("IntegerProperty", EdmCoreModel.Instance.GetInt32(true));
            entityTypeElement.AddStructuralProperty("StringProperty", EdmCoreModel.Instance.GetString(true));
            model.AddElement(entityTypeElement);

            var collectionOfEntityTypeTerm = new EdmTerm("NS", "CollectionOfEntityTypeTerm", EdmCoreModel.GetCollection(new EdmEntityTypeReference(entityTypeElement, true)));

            model.AddElement(collectionOfEntityTypeTerm);

            var inlineCollectionOfEntityTypeAnnotation = new EdmVocabularyAnnotation(entityTypeElement, collectionOfEntityTypeTerm, new EdmCollectionExpression(
                                                                                         new EdmRecordExpression(
                                                                                             new EdmPropertyConstructor("KeyProperty", new EdmIntegerConstant(1)),
                                                                                             new EdmPropertyConstructor("IntegerProperty", new EdmIntegerConstant(111)),
                                                                                             new EdmPropertyConstructor("StringProperty", new EdmStringConstant("Inline String 111"))),
                                                                                         new EdmRecordExpression(
                                                                                             new EdmPropertyConstructor("KeyProperty", new EdmIntegerConstant(2)),
                                                                                             new EdmPropertyConstructor("IntegerProperty", new EdmIntegerConstant(222)),
                                                                                             new EdmPropertyConstructor("StringProperty", new EdmStringConstant("Inline String 222"))),
                                                                                         new EdmRecordExpression(
                                                                                             new EdmPropertyConstructor("KeyProperty", new EdmIntegerConstant(3)),
                                                                                             new EdmPropertyConstructor("IntegerProperty", new EdmIntegerConstant(333)),
                                                                                             new EdmPropertyConstructor("StringProperty", new EdmStringConstant("Inline String 333")))));

            inlineCollectionOfEntityTypeAnnotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            model.AddVocabularyAnnotation(inlineCollectionOfEntityTypeAnnotation);

            var outlineCollectionOfEntityTypeAnnotation = new EdmVocabularyAnnotation(collectionOfEntityTypeTerm, collectionOfEntityTypeTerm, new EdmCollectionExpression(
                                                                                          new EdmRecordExpression(
                                                                                              new EdmPropertyConstructor("KeyProperty", new EdmIntegerConstant(4)),
                                                                                              new EdmPropertyConstructor("IntegerProperty", new EdmIntegerConstant(444)),
                                                                                              new EdmPropertyConstructor("StringProperty", new EdmStringConstant("Inline String 444"))),
                                                                                          new EdmRecordExpression(
                                                                                              new EdmPropertyConstructor("KeyProperty", new EdmIntegerConstant(5)),
                                                                                              new EdmPropertyConstructor("IntegerProperty", new EdmIntegerConstant(555)),
                                                                                              new EdmPropertyConstructor("StringProperty", new EdmStringConstant("Inline String 555")))));

            model.AddVocabularyAnnotation(outlineCollectionOfEntityTypeAnnotation);

            return(model);
        }
コード例 #19
0
        /// <summary>
        /// Build a test model shared across several tests.
        /// </summary>
        /// <returns>Returns the test model.</returns>
        public static EdmModel BuildTestModel()
        {
            // The metadata model
            var model = new EdmModel();

            var addressType = new EdmComplexType(DefaultNamespaceName, "Address");

            addressType.AddStructuralProperty("Street", StringNullableTypeRef);
            addressType.AddStructuralProperty("Zip", Int32TypeRef);
            addressType.AddStructuralProperty("SubAddress", new EdmComplexTypeReference(addressType, isNullable: false));
            model.AddElement(addressType);

            var officeType = new EdmEntityType(DefaultNamespaceName, "OfficeType");

            officeType.AddKeys(officeType.AddStructuralProperty("Id", Int32TypeRef));
            officeType.AddStructuralProperty("Address", new EdmComplexTypeReference(addressType, isNullable: false));
            model.AddElement(officeType);

            var officeWithNumberType = new EdmEntityType(DefaultNamespaceName, "OfficeWithNumberType", officeType);

            officeWithNumberType.AddStructuralProperty("Number", Int32TypeRef);
            model.AddElement(officeWithNumberType);

            var cityType = new EdmEntityType(DefaultNamespaceName, "CityType");

            cityType.AddKeys(cityType.AddStructuralProperty("Id", Int32TypeRef));
            cityType.AddStructuralProperty("Name", StringNullableTypeRef);
            cityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "CityHall", Target = officeType, TargetMultiplicity = EdmMultiplicity.Many
            });
            cityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "DOL", Target = officeType, TargetMultiplicity = EdmMultiplicity.Many
            });
            cityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "PoliceStation", Target = officeType, TargetMultiplicity = EdmMultiplicity.One
            });
            cityType.AddStructuralProperty("Skyline", EdmPrimitiveTypeKind.Stream, isNullable: false);
            cityType.AddStructuralProperty("MetroLanes", EdmCoreModel.GetCollection(StringNullableTypeRef));
            model.AddElement(cityType);

            var metropolitanCityType = new EdmEntityType(DefaultNamespaceName, "MetropolitanCityType", cityType);

            metropolitanCityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "ContainedOffice", Target = officeType, TargetMultiplicity = EdmMultiplicity.Many, ContainsTarget = true
            });
            officeType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "ContainedCity", Target = metropolitanCityType, TargetMultiplicity = EdmMultiplicity.One, ContainsTarget = true
            });
            model.AddElement(metropolitanCityType);

            var cityWithMapType = new EdmEntityType(DefaultNamespaceName, "CityWithMapType", cityType, false, false, true);

            model.AddElement(cityWithMapType);

            var cityOpenType = new EdmEntityType(DefaultNamespaceName, "CityOpenType", cityType, isAbstract: false, isOpen: true);

            model.AddElement(cityOpenType);

            var personType = new EdmEntityType(DefaultNamespaceName, "Person");

            personType.AddKeys(personType.AddStructuralProperty("Id", Int32TypeRef));
            personType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "Friend", Target = personType, TargetMultiplicity = EdmMultiplicity.Many
            });
            model.AddElement(personType);

            var employeeType = new EdmEntityType(DefaultNamespaceName, "Employee", personType);

            employeeType.AddStructuralProperty("CompanyName", StringNullableTypeRef);
            model.AddElement(employeeType);

            var managerType = new EdmEntityType(DefaultNamespaceName, "Manager", employeeType);

            managerType.AddStructuralProperty("Level", Int32TypeRef);
            model.AddElement(managerType);

            var container = new EdmEntityContainer(DefaultNamespaceName, "DefaultContainer");

            model.AddElement(container);

            container.AddEntitySet("Offices", officeType);
            container.AddEntitySet("Cities", cityType);
            container.AddEntitySet("MetropolitanCities", metropolitanCityType);
            container.AddEntitySet("Persons", personType);
            container.AddEntitySet("Employee", employeeType);
            container.AddEntitySet("Manager", managerType);
            container.AddSingleton("Boss", personType);

            // Fixup will set DefaultContainer\TopLevelEntitySet\AssociationSet
            model.Fixup();

            // NOTE: Function import parameters and return types must be nullable as per current CSDL spec
            var serviceOp = container.AddFunctionAndFunctionImport(model, "ServiceOperation1", Int32NullableTypeRef, null, false /*isComposable*/, false /*isBound*/);

            serviceOp.Function.AsEdmFunction().AddParameter("a", Int32NullableTypeRef);
            serviceOp.Function.AsEdmFunction().AddParameter("b", StringNullableTypeRef);

            container.AddFunctionAndFunctionImport(model, "PrimitiveResultOperation", Int32NullableTypeRef, null, false /*isComposable*/, false /*isBound*/);
            container.AddFunctionAndFunctionImport(model, "ComplexResultOperation", new EdmComplexTypeReference(addressType, isNullable: true), null, false /*isComposable*/, false /*isBound*/);
            container.AddFunctionAndFunctionImport(model, "PrimitiveCollectionResultOperation", EdmCoreModel.GetCollection(Int32NullableTypeRef), null, false /*isComposable*/, false /*isBound*/);
            container.AddFunctionAndFunctionImport(model, "ComplexCollectionResultOperation", EdmCoreModel.GetCollection(new EdmComplexTypeReference(addressType, isNullable: true)), null, false /*isComposable*/, false /*isBound*/);

            // Overload with 0 Param
            container.AddFunctionAndFunctionImport(model, "FunctionImportWithOverload", Int32NullableTypeRef, null, false /*isComposable*/, false /*isBound*/);

            // Overload with 1 Param
            var overloadWithOneParam = container.AddFunctionAndFunctionImport(model, "FunctionImportWithOverload", Int32NullableTypeRef, null, false /*isComposable*/, false /*isBound*/);

            overloadWithOneParam.Function.AsEdmFunction().AddParameter("p1", new EdmEntityTypeReference(cityWithMapType, isNullable: true));

            // Overload with 2 Params
            var overloadWithTwoParams = container.AddFunctionAndFunctionImport(model, "FunctionImportWithOverload", Int32NullableTypeRef, null, false /*isComposable*/, false /*isBound*/);

            overloadWithTwoParams.Function.AsEdmFunction().AddParameter("p1", new EdmEntityTypeReference(cityType, isNullable: true));
            overloadWithTwoParams.Function.AsEdmFunction().AddParameter("p2", StringNullableTypeRef);

            // Overload with 5 Params
            var overloadWithFiveParams = container.AddFunctionAndFunctionImport(model, "FunctionImportWithOverload", Int32NullableTypeRef, null, false /*isComposable*/, false /*isBound*/);

            overloadWithFiveParams.Function.AsEdmFunction().AddParameter("p1", EdmCoreModel.GetCollection(new EdmEntityTypeReference(cityType, isNullable: true)));
            overloadWithFiveParams.Function.AsEdmFunction().AddParameter("p2", EdmCoreModel.GetCollection(StringNullableTypeRef));
            overloadWithFiveParams.Function.AsEdmFunction().AddParameter("p3", StringNullableTypeRef);
            overloadWithFiveParams.Function.AsEdmFunction().AddParameter("p4", new EdmComplexTypeReference(addressType, isNullable: true));
            overloadWithFiveParams.Function.AsEdmFunction().AddParameter("p5", EdmCoreModel.GetCollection(new EdmComplexTypeReference(addressType, isNullable: true)));

            return(model);
        }
コード例 #20
0
        public void FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingTypeShouldFilterReturnTypeClosestToTypeCollectionA()
        {
            EdmEntityType aType  = new EdmEntityType("N", "A");
            EdmEntityType bType  = new EdmEntityType("N", "B", aType);
            EdmEntityType cType  = new EdmEntityType("N", "C", bType);
            EdmAction     action = new EdmAction("namespace", "action", null, true, null);

            action.AddParameter("bindingParameter", EdmCoreModel.GetCollection(new EdmEntityTypeReference(aType, false)));
            EdmAction action2 = new EdmAction("namespace", "action", null, true, null);

            action2.AddParameter("bindingParameter", EdmCoreModel.GetCollection(new EdmEntityTypeReference(bType, false)));
            var filteredResults = new IEdmOperation[] { action, action2 }.FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingType(EdmCoreModel.GetCollection(new EdmEntityTypeReference(cType, false)).Definition).ToList();

            filteredResults.Should().HaveCount(1);
            filteredResults[0].Should().BeSameAs(action2);
        }
コード例 #21
0
        public void CollectionValueTest()
        {
            EdmModel model       = new EdmModel();
            var      complexType = new EdmComplexType("TestModel", "ComplexType").Property("Name", EdmPrimitiveTypeKind.String, true);

            model.AddElement(complexType);
            var owningType = new EdmEntityType("TestModel", "OwningType");

            owningType.AddKeys(owningType.AddStructuralProperty("ID", EdmCoreModel.Instance.GetInt32(false)));
            owningType.AddStructuralProperty("PrimitiveCollection", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false)));
            model.AddElement(owningType);
            model.Fixup();

            var primitiveMultiValue = PayloadBuilder.PrimitiveMultiValue("Collection(Edm.Int32)").Item(42).Item(43);

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new[]
            {
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "null collection in request - should fail.",
                    PayloadEdmModel  = model,
                    PayloadElement   = PayloadBuilder.Property("PrimitiveCollection",
                                                               PayloadBuilder.PrimitiveMultiValue("Collection(Edm.Int32)"))
                                       .JsonRepresentation("{\"value\":null }")
                                       .ExpectedProperty(owningType, "PrimitiveCollection"),
                    SkipTestConfiguration = tc => !tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ReaderValidationUtils_NullNamedValueForNonNullableType", "value", "Collection(Edm.Int32)")
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "null collection in response - should fail.",
                    PayloadEdmModel  = model,
                    PayloadElement   = PayloadBuilder.Property("PrimitiveCollection",
                                                               PayloadBuilder.PrimitiveMultiValue("Collection(Edm.Int32)"))
                                       .JsonRepresentation(
                        "{" +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Collection(Edm.Int32)\"," +
                        "\"value\":null" +
                        "}")
                                       .ExpectedProperty(owningType, "PrimitiveCollection"),
                    SkipTestConfiguration = tc => tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ReaderValidationUtils_NullNamedValueForNullableType", "value", "Collection(Edm.Int32)")
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "Primitive value for collection - should fail.",
                    PayloadEdmModel  = model,
                    PayloadElement   = PayloadBuilder.Property("PrimitiveCollection",
                                                               PayloadBuilder.PrimitiveMultiValue("Collection(Edm.Int32)")
                                                               .JsonRepresentation("42"))
                                       .ExpectedProperty(owningType, "PrimitiveCollection"),
                    ExpectedException = ODataExpectedExceptions.ODataException("JsonReaderExtensions_UnexpectedNodeDetected", "StartArray", "PrimitiveValue")
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "Object value for collection - should fail.",
                    PayloadEdmModel  = model,
                    PayloadElement   = PayloadBuilder.Property("PrimitiveCollection",
                                                               PayloadBuilder.PrimitiveMultiValue("Collection(Edm.Int32)")
                                                               .JsonRepresentation("{}"))
                                       .ExpectedProperty(owningType, "PrimitiveCollection"),
                    ExpectedException = ODataExpectedExceptions.ODataException("JsonReaderExtensions_UnexpectedNodeDetectedWithPropertyName", "StartArray", "StartObject", "value")
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "Simple primitive collection.",
                    PayloadEdmModel  = model,
                    PayloadElement   = PayloadBuilder.Property("PrimitiveCollection",
                                                               primitiveMultiValue
                                                               .JsonRepresentation("[42,43]")
                                                               .AddAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    }))
                                       .ExpectedProperty(owningType, "PrimitiveCollection"),
                    ExpectedResultPayloadElement = tc => tc.IsRequest
                        ? PayloadBuilder.Property(string.Empty, primitiveMultiValue)
                        : PayloadBuilder.Property("PrimitiveCollection", primitiveMultiValue)
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                // These descriptors are already tailored specifically for Json Light and
                // do not require normalization.
                testDescriptor.TestDescriptorNormalizers.Clear();
                testDescriptor.RunTest(testConfiguration);
            });
        }
コード例 #22
0
        public void TopLevelPropertyTest()
        {
            var injectedProperties = new[]
            {
                new
                {
                    InjectedJSON      = string.Empty,
                    ExpectedException = (ExpectedException)null
                },
                new
                {
                    InjectedJSON      = "\"@custom.annotation\": null",
                    ExpectedException = (ExpectedException)null
                },
                new
                {
                    InjectedJSON      = "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataAnnotationNamespacePrefix + "unknown\": { }",
                    ExpectedException = (ExpectedException)null
                },
                new
                {
                    InjectedJSON      = "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\": { }",
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_UnexpectedAnnotationProperties", JsonLightConstants.ODataContextAnnotationName)
                },
                new
                {
                    InjectedJSON      = "\"@custom.annotation\": null, \"@custom.annotation\": 42",
                    ExpectedException = (ExpectedException)null
                },
            };

            var payloads = new[]
            {
                new
                {
                    Json = "{{ " +
                           "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " +
                           "\"value\": null" +
                           "{1}{0}" +
                           "}}",
                },
                new
                {
                    Json = "{{ " +
                           "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " +
                           "{0}{1}" +
                           "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" +
                           "}}",
                },
                new
                {
                    Json = "{{ " +
                           "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " +
                           "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" +
                           "{1}{0}" +
                           "}}",
                },
            };

            EdmModel model     = new EdmModel();
            var      container = new EdmEntityContainer("TestModel", "DefaultContainer");

            model.AddElement(container);

            var owningType = new EdmEntityType("TestModel", "OwningType");

            owningType.AddKeys(owningType.AddStructuralProperty("ID", EdmCoreModel.Instance.GetInt32(false)));
            owningType.AddStructuralProperty("TopLevelProperty", EdmCoreModel.Instance.GetInt32(true));
            owningType.AddStructuralProperty("TopLevelSpatialProperty", EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.GeographyPoint, false));
            owningType.AddStructuralProperty("TopLevelCollectionProperty", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false)));
            model.AddElement(owningType);

            IEdmEntityType         edmOwningType                 = (IEdmEntityType)model.FindDeclaredType("TestModel.OwningType");
            IEdmStructuralProperty edmTopLevelProperty           = (IEdmStructuralProperty)edmOwningType.FindProperty("TopLevelProperty");
            IEdmStructuralProperty edmTopLevelSpatialProperty    = (IEdmStructuralProperty)edmOwningType.FindProperty("TopLevelSpatialProperty");
            IEdmStructuralProperty edmTopLevelCollectionProperty = (IEdmStructuralProperty)edmOwningType.FindProperty("TopLevelCollectionProperty");

            PayloadReaderTestDescriptor.ReaderMetadata readerMetadata           = new PayloadReaderTestDescriptor.ReaderMetadata(edmTopLevelProperty);
            PayloadReaderTestDescriptor.ReaderMetadata spatialReaderMetadata    = new PayloadReaderTestDescriptor.ReaderMetadata(edmTopLevelSpatialProperty);
            PayloadReaderTestDescriptor.ReaderMetadata collectionReaderMetadata = new PayloadReaderTestDescriptor.ReaderMetadata(edmTopLevelCollectionProperty);

            var testDescriptors = payloads.SelectMany(payload => injectedProperties.Select(injectedProperty =>
            {
                return(new NativeInputReaderTestDescriptor()
                {
                    PayloadKind = ODataPayloadKind.Property,
                    InputCreator = (tc) =>
                    {
                        string input = string.Format(payload.Json, injectedProperty.InjectedJSON, string.IsNullOrEmpty(injectedProperty.InjectedJSON) ? string.Empty : ",");
                        return input;
                    },
                    PayloadEdmModel = model,

                    // We use payload expected result just as a convenient way to run the reader for the Property payload kind.
                    // We validate whether the reading succeeds or fails, but not the actual read values (at least not here).
                    ExpectedResultCallback = (tc) =>
                                             new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ReaderMetadata = readerMetadata,
                        ExpectedException = injectedProperty.ExpectedException,
                    }
                });
            }));

            var explicitPayloads = new[]
            {
                new
                {
                    Description = "Custom property annotation - should be ignored.",
                    Json        = "{ " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("value", "custom.annotation") + "\": null," +
                                  "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" +
                                  "}",
                    ReaderMetadata    = readerMetadata,
                    ExpectedException = (ExpectedException)null
                },
                new
                {
                    Description = "Duplicate custom property annotation - should not fail.",
                    Json        = "{ " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("value", "custom.annotation") + "\": null," +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("value", "custom.annotation") + "\": 42," +
                                  "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" +
                                  "}",
                    ReaderMetadata    = readerMetadata,
                    ExpectedException = (ExpectedException)null
                },
                new
                {
                    Description = "Unrecognized odata property annotation - should be ignored.",
                    Json        = "{ " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("value", JsonLightConstants.ODataAnnotationNamespacePrefix + "unknown") + "\": null," +
                                  "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" +
                                  "}",
                    ReaderMetadata    = readerMetadata,
                    ExpectedException = (ExpectedException)null
                },
                new
                {
                    Description = "Custom property annotation after the property - should fail.",
                    Json        = "{ " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " +
                                  "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42," +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("value", "custom.annotation") + "\": null" +
                                  "}",
                    ReaderMetadata    = readerMetadata,
                    ExpectedException = ODataExpectedExceptions.ODataException("PropertyAnnotationAfterTheProperty", "custom.annotation", "value")
                },
                new
                {
                    Description = "OData property annotation.",
                    Json        = "{ " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Edm.Int32\"," +
                                  "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" +
                                  "}",
                    ReaderMetadata    = readerMetadata,
                    ExpectedException = (ExpectedException)null
                },
                new
                {
                    Description = "Duplicate odata.type property should fail.",
                    Json        = "{ " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Edm.Int32\"," +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Edm.String\"," +
                                  "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" +
                                  "}",
                    ReaderMetadata    = readerMetadata,
                    ExpectedException = ODataExpectedExceptions.ODataException("DuplicateAnnotationNotAllowed", JsonLightConstants.ODataTypeAnnotationName)
                },
                new
                {
                    Description = "Type information for top-level property - correct.",
                    Json        = "{ " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Edm.Int32\"," +
                                  "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" +
                                  "}",
                    ReaderMetadata    = readerMetadata,
                    ExpectedException = (ExpectedException)null
                },
                new
                {
                    Description = "Type information for top-level property - different kind - should fail.",
                    Json        = "{ " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Collection(Edm.Int32)\"," +
                                  "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" +
                                  "}",
                    ReaderMetadata    = readerMetadata,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectTypeKind", "Collection(Edm.Int32)", "Primitive", "Collection")
                },
                new
                {
                    Description = "Unknown type information for top-level null - should fail.",
                    Json        = "{ " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Unknown\"," +
                                  "\"" + JsonLightConstants.ODataValuePropertyName + "\": null" +
                                  "}",
                    ReaderMetadata    = readerMetadata,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectTypeKind", "Unknown", "Primitive", "Complex")
                },
                new
                {
                    Description = "Type information for top-level spatial - should work.",
                    Json        = "{ " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.GeographyPoint\", " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Edm.GeographyPoint\"," +
                                  "\"" + JsonLightConstants.ODataValuePropertyName + "\":" + SpatialUtils.GetSpatialStringValue(ODataFormat.Json, GeographyFactory.Point(33.1, -110.0).Build()) +
                                  "}",
                    ReaderMetadata    = spatialReaderMetadata,
                    ExpectedException = (ExpectedException)null
                },
            };

            testDescriptors = testDescriptors.Concat(explicitPayloads.Select(payload =>
            {
                return(new NativeInputReaderTestDescriptor()
                {
                    PayloadKind = ODataPayloadKind.Property,
                    InputCreator = (tc) =>
                    {
                        return payload.Json;
                    },
                    PayloadEdmModel = model,

                    // We use payload expected result just as a convenient way to run the reader for the Property payload kind
                    // since the reading should always fail, we don't need anything to compare the results to.
                    ExpectedResultCallback = (tc) =>
                                             new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ReaderMetadata = payload.ReaderMetadata,
                        ExpectedException = payload.ExpectedException,
                    },
                    DebugDescription = payload.Description
                });
            }));

            // Add a test descriptor to verify that we ignore odata.context in requests
            testDescriptors = testDescriptors.Concat(
                new NativeInputReaderTestDescriptor[]
            {
                new NativeInputReaderTestDescriptor()
                {
                    DebugDescription = "Top-level property with invalid name.",
                    PayloadKind      = ODataPayloadKind.Property,
                    InputCreator     = tc =>
                    {
                        return("{ " +
                               "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " +
                               "\"TopLevelProperty\": 42" +
                               "}");
                    },
                    PayloadEdmModel        = model,
                    ExpectedResultCallback = tc =>
                                             new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ReaderMetadata    = readerMetadata,
                        ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_InvalidTopLevelPropertyName", "TopLevelProperty", "value")
                    },
                    SkipTestConfiguration = tc => !tc.IsRequest
                }
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration);
            });
        }
コード例 #23
0
        /// <summary>
        /// Creates a set of models.
        /// </summary>
        /// <returns>List of interesting models.</returns>
        public static IEnumerable <IEdmModel> CreateModels()
        {
            //
            // NOTE: we only create a few models here since we mostly rely on EdmLib to test
            //       model serialization/deserialization for us
            //
            // Empty model
            EdmModel emptyModel = new EdmModel();

            emptyModel.AddElement(new EdmEntityContainer("DefaultNamespace", "DefaultContainer"));
            yield return(emptyModel.Fixup());

            // Model with a single entity type
            EdmModel modelWithSingleEntityType = new EdmModel();
            var      singletonEntityType       = new EdmEntityType(DefaultNamespaceName, "SingletonEntityType");

            singletonEntityType.AddKeys(singletonEntityType.AddStructuralProperty("Id", Int32TypeRef));
            singletonEntityType.AddStructuralProperty("Name", StringNullableTypeRef);
            modelWithSingleEntityType.AddElement(singletonEntityType);
            modelWithSingleEntityType.Fixup();
            yield return(modelWithSingleEntityType);

            // Model with a single complex type
            EdmModel modelWithSingleComplexType = new EdmModel();
            var      singletonComplexType       = new EdmComplexType(DefaultNamespaceName, "SingletonComplexType");

            singletonComplexType.AddStructuralProperty("City", StringNullableTypeRef);
            modelWithSingleComplexType.AddElement(singletonComplexType);
            modelWithSingleComplexType.Fixup();
            yield return(modelWithSingleComplexType);

            // Model with a collection property
            EdmModel modelWithCollectionProperty = new EdmModel();
            var      complexTypeWithCollection   = new EdmComplexType(DefaultNamespaceName, "ComplexTypeWithCollection");

            complexTypeWithCollection.AddStructuralProperty("Cities", EdmCoreModel.GetCollection(StringNullableTypeRef));
            modelWithCollectionProperty.AddElement(complexTypeWithCollection);
            modelWithCollectionProperty.Fixup();
            yield return(modelWithCollectionProperty);

            // Model with an open type
            EdmModel modelWithOpenType = new EdmModel();
            var      openType          = new EdmEntityType(DefaultNamespaceName, "OpenEntityType", baseType: null, isAbstract: false, isOpen: true);

            openType.AddKeys(openType.AddStructuralProperty("Id", Int32TypeRef));
            modelWithOpenType.AddElement(openType);

            var containerForModelWithOpenType = new EdmEntityContainer(DefaultNamespaceName, "DefaultContainer");

            containerForModelWithOpenType.AddEntitySet("OpenEntityType", openType);
            modelWithOpenType.AddElement(containerForModelWithOpenType);
            yield return(modelWithOpenType);

            // Model with a named stream
            EdmModel modelWithNamedStream  = new EdmModel();
            var      namedStreamEntityType = new EdmEntityType(DefaultNamespaceName, "NamedStreamEntityType");

            namedStreamEntityType.AddKeys(namedStreamEntityType.AddStructuralProperty("Id", Int32TypeRef));
            namedStreamEntityType.AddStructuralProperty("NamedStream", EdmPrimitiveTypeKind.Stream, isNullable: false);
            modelWithNamedStream.AddElement(namedStreamEntityType);

            var containerForModelWithNamedStream = new EdmEntityContainer(DefaultNamespaceName, "DefaultContainer");

            containerForModelWithNamedStream.AddEntitySet("NamedStreamEntityType", namedStreamEntityType);
            modelWithNamedStream.AddElement(containerForModelWithNamedStream);
            yield return(modelWithNamedStream);

            // OData Shared Test Model
            yield return(BuildTestModel());

            // Model with OData-specific attribute annotations
            yield return(BuildODataAnnotationTestModel(true));

#if !NETCOREAPP1_0
            // Astoria Default Test Model
            yield return(BuildDefaultAstoriaTestModel());
#endif
        }
コード例 #24
0
        public void CollectionWithHeterogenousItemsErrorTest()
        {
            EdmModel model = new EdmModel();

            var complexType1 = model.ComplexType("ComplexTypeWithStringAndInteger32")
                               .Property("Property1", EdmCoreModel.Instance.GetString(true) as EdmTypeReference)
                               .Property("Property2", EdmCoreModel.Instance.GetInt32(false) as EdmTypeReference);

            var complexType2 = model.ComplexType("ComplexTypeWithStringAndDateTime")
                               .Property("Property1", EdmCoreModel.Instance.GetString(true) as EdmTypeReference)
                               .Property("Property2", EdmPrimitiveTypeKind.DateTimeOffset);

            model.Fixup();

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new[]
            {
                // Primitive collection containing items of different primitive types
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement         = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.Int32")).Item(1).Item(true).Item(2).WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false))),
                    PayloadEdmModel        = model,
                    ExpectedResultCallback = tc => new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_CannotConvertPrimitiveValue", "True", "Edm.Int32")
                    }
                },
                // Complex collection containing items of different complex type (correct type attribute value)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(EntityModelUtils.GetCollectionTypeName(complexType1.FullName()))
                                     .Item(PayloadBuilder.ComplexValue(complexType1.FullName()).PrimitiveProperty("Property1", "Foo").PrimitiveProperty("Property2", -1))
                                     .Item(PayloadBuilder.ComplexValue(complexType2.FullName()).PrimitiveProperty("Property1", "Foo").PrimitiveProperty("Property2", DateTimeOffset.Now))
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(complexType1.ToTypeReference())),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatibleType", "TestModel.ComplexTypeWithStringAndDateTime", "TestModel.ComplexTypeWithStringAndInteger32"),
                },
                // Complex collection containing items of different complex type (incorrect type attribute value)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(EntityModelUtils.GetCollectionTypeName(complexType2.FullName()))
                                     .Item(PayloadBuilder.ComplexValue(complexType2.FullName()).PrimitiveProperty("Property1", "Foo").PrimitiveProperty("Property2", -1))
                                     .Item(PayloadBuilder.ComplexValue(complexType2.FullName()).PrimitiveProperty("Property1", "Foo").PrimitiveProperty("Property2", DateTimeOffset.Now))
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(complexType2.ToTypeReference())),
                    PayloadEdmModel        = model,
                    ExpectedResultCallback = tc => new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_CannotConvertPrimitiveValue", "-1", "Edm.DateTimeOffset")
                    }
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor = testDescriptor.InProperty("RootProperty");
                testDescriptor.RunTest(testConfiguration);
            });
        }