Exemplo n.º 1
0
        public void VisitEdmEntityContainer_visits_function_imports()
        {
            var functionPayload =
                new EdmFunctionPayload
                    {
                        IsFunctionImport = true
                    };

            var functionImport =
                new EdmFunction("f", "N", DataSpace.CSpace, functionPayload);

            var model = new EdmModel(DataSpace.CSpace);
            model.Container.AddFunctionImport(functionImport);

            var visitorMock =
                new Mock<EdmModelVisitor>
                    {
                        CallBase = true
                    };

            visitorMock.Object.VisitEdmModel(model);

            visitorMock.Verify(v => v.VisitFunctionImports(model.Container, It.IsAny<IEnumerable<EdmFunction>>()), Times.Once());
            visitorMock.Verify(v => v.VisitFunctionImport(functionImport), Times.Once());
        }
        /// <summary>
        ///     Serialize the <see cref = "EdmModel" /> to the XmlWriter.
        /// </summary>
        /// <param name = "model"> The EdmModel to serialize, mut have only one <see cref = "EdmNamespace" /> and one <see cref = "EdmEntityContainer" /> </param>
        /// <param name = "xmlWriter"> The XmlWriter to serialize to </param>
        public bool Serialize(EdmModel model, XmlWriter xmlWriter)
        {
            Contract.Requires(model != null);
            Contract.Requires(xmlWriter != null);

            if (model.Namespaces.Count != 1
                || model.Containers.Count != 1)
            {
                Validator_OnError(
                    this,
                    new DataModelErrorEventArgs
                        {
                            ErrorMessage = Strings.Serializer_OneNamespaceAndOneContainer,
                            ErrorCode = XmlErrorCode.Serializer_OneNamespaceAndOneContainer
                        });
            }

            // validate the model first
            var validator = new DataModelValidator();
            validator.OnError += Validator_OnError;
            validator.Validate(model, true);

            if (_isModelValid)
            {
                var visitor = new EdmModelCsdlSerializationVisitor(xmlWriter, model.Version);
                visitor.Visit(model);
            }
            return _isModelValid;
        }
        internal void Visit(EdmModel model)
        {
            DebugCheck.NotNull(model);

            EvaluateItem(model);

            VisitEdmModel(model);
        }
Exemplo n.º 4
0
 public Task<IEdmModel> GetModelAsync(ModelContext context, CancellationToken cancellationToken)
 {
     var model = new EdmModel();
     var dummyType = new EdmEntityType("NS", "Dummy");
     model.AddElement(dummyType);
     var container = new EdmEntityContainer("NS", "DefaultContainer");
     container.AddEntitySet("Test", dummyType);
     model.AddElement(container);
     return Task.FromResult((IEdmModel) model);
 }
        private static DbDatabaseMapping InitializeDatabaseMapping(EdmModel model)
        {
            Contract.Requires(model != null);

            var databaseMapping = new DbDatabaseMapping().Initialize(
                model, new DbDatabaseMetadata().Initialize(model.Version));

            databaseMapping.EntityContainerMappings.Single().EntityContainer = model.Containers.Single();

            return databaseMapping;
        }
        internal void Visit(EdmModel edmModel)
        {
            Contract.Assert(edmModel.Namespaces.Count == 1, "Expected exactly 1 namespace");

            var namespaceName = edmModel.Namespaces.First().Name;

            _schemaWriter.WriteSchemaElementHeader(namespaceName);

            base.VisitEdmModel(edmModel);

            _schemaWriter.WriteEndElement();
        }
        public DbDatabaseMapping Generate(EdmModel model)
        {
            Contract.Requires(model != null);

            var databaseMapping = InitializeDatabaseMapping(model);

            GenerateEntityTypes(model, databaseMapping);
            GenerateDiscriminators(databaseMapping);
            GenerateAssociationTypes(model, databaseMapping);

            return databaseMapping;
        }
        public void Validate(EdmModel model, bool validateSyntax)
        {
            var context = new EdmModelValidationContext(model, validateSyntax);

            context.OnError += OnError;

            var modelVisitor
                = new EdmModelValidationVisitor(
                    context,
                    EdmModelRuleSet.CreateEdmModelRuleSet(model.SchemaVersion, validateSyntax));

            modelVisitor.Visit(model);
        }
        private void GenerateEntityTypes(EdmModel model, DbDatabaseMapping databaseMapping)
        {
            Contract.Requires(model != null);
            Contract.Requires(databaseMapping != null);

            foreach (var entityType in model.GetEntityTypes())
            {
                if (!entityType.IsAbstract)
                {
                    new EntityTypeMappingGenerator(_providerManifest).
                        Generate(entityType, databaseMapping);
                }
            }
        }
Exemplo n.º 10
0
        public void VisitEdmModel_should_visit_edm_functions()
        {
            var visitorMock
                = new Mock<EdmModelVisitor>
                      {
                          CallBase = true
                      };

            var function = new EdmFunction("F", "N", DataSpace.SSpace);
            var model = new EdmModel(DataSpace.SSpace);
            model.AddItem(function);

            visitorMock.Object.VisitEdmModel(model);

            visitorMock.Verify(v => v.VisitFunctions(It.IsAny<IEnumerable<EdmFunction>>()), Times.Once());
            visitorMock.Verify(v => v.VisitMetadataItem(function), Times.Once());
            visitorMock.Verify(v => v.VisitEdmFunction(function), Times.Once());
        }
        internal static DbDatabaseMapping Initialize(
            this DbDatabaseMapping databaseMapping, EdmModel model, DbDatabaseMetadata database)
        {
            Contract.Requires(databaseMapping != null);
            Contract.Requires(databaseMapping != null);
            Contract.Requires(database != null);

            databaseMapping.Model = model;
            databaseMapping.Database = database;
            var entityContainerMapping
                = new DbEntityContainerMapping
                    {
                        EntityContainer = model.Containers.Single()
                    };
            databaseMapping.EntityContainerMappings.Add(entityContainerMapping);

            return databaseMapping;
        }
Exemplo n.º 12
0
        private IEdmModel GetModel()
        {
            if (_model != null)
            {
                return(_model);
            }

            var model = new EdmModel();

            // EntityContainer: Service
            var container = new EdmEntityContainer("ns", "Service");

            model.AddElement(container);

            // EntityType: Address
            var address   = new EdmEntityType("ns", "Address");
            var addressId = address.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);

            address.AddKeys(addressId);
            model.AddElement(address);

            // EntitySet: Addresses
            var addresses = container.AddEntitySet("Addresses", address);

            // EntityType: PaymentInstrument
            var paymentInstrument   = new EdmEntityType("ns", "PaymentInstrument");
            var paymentInstrumentId = paymentInstrument.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);

            paymentInstrument.AddKeys(paymentInstrumentId);
            var billingAddresses = paymentInstrument.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name               = "BillingAddresses",
                Target             = address,
                TargetMultiplicity = EdmMultiplicity.Many
            });

            paymentInstrument.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name               = "ContainedBillingAddresses",
                Target             = address,
                TargetMultiplicity = EdmMultiplicity.Many,
                ContainsTarget     = true
            });
            model.AddElement(paymentInstrument);

            // EntityType: Account
            var account   = new EdmEntityType("ns", "Account");
            var accountId = account.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);

            account.AddKeys(accountId);
            var myPaymentInstruments = account.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name               = "MyPaymentInstruments",
                Target             = paymentInstrument,
                TargetMultiplicity = EdmMultiplicity.Many,
                ContainsTarget     = true
            });

            model.AddElement(account);

            // EntitySet: Accounts
            var accounts = container.AddEntitySet("Accounts", account);

            var paymentInstruments = accounts.FindNavigationTarget(myPaymentInstruments) as EdmNavigationSource;

            Assert.NotNull(paymentInstruments);
            paymentInstruments.AddNavigationTarget(billingAddresses, addresses);

            // EntityType: Person
            var person   = new EdmEntityType("ns", "Person");
            var personId = person.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);

            person.AddKeys(personId);
            var myAccounts = person.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name               = "MyAccounts",
                Target             = account,
                TargetMultiplicity = EdmMultiplicity.Many
            });
            var myPermanentAccount = person.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name               = "MyPermanentAccount",
                Target             = account,
                TargetMultiplicity = EdmMultiplicity.One
            });
            var myLatestAccount = person.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name               = "MyLatestAccount",
                Target             = account,
                TargetMultiplicity = EdmMultiplicity.One
            });

            person.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name               = "MyAddresses",
                Target             = address,
                TargetMultiplicity = EdmMultiplicity.Many,
                ContainsTarget     = true
            });
            model.AddElement(person);

            // EntityType: Benefit
            var benefit   = new EdmEntityType("ns", "Benefit");
            var benefitId = benefit.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);

            benefit.AddKeys(benefitId);
            model.AddElement(benefit);

            // EntityType: SpecialPerson
            var specialPerson = new EdmEntityType("ns", "SpecialPerson", person);

            specialPerson.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name               = "Benefits",
                Target             = benefit,
                TargetMultiplicity = EdmMultiplicity.Many,
                ContainsTarget     = true
            });
            model.AddElement(specialPerson);

            // EntityType: VIP
            var vip = new EdmEntityType("ns", "VIP", specialPerson);

            vip.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name               = "MyBenefits",
                Target             = benefit,
                TargetMultiplicity = EdmMultiplicity.Many,
                ContainsTarget     = true
            });
            model.AddElement(vip);

            // EntitySet: People
            var people = container.AddEntitySet("People", person);

            people.AddNavigationTarget(myAccounts, accounts);
            people.AddNavigationTarget(myLatestAccount, accounts);

            // EntityType: Club
            var club   = new EdmEntityType("ns", "Club");
            var clubId = club.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);

            club.AddKeys(clubId);
            var members = club.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name               = "Members",
                Target             = person,
                TargetMultiplicity = EdmMultiplicity.Many,
                ContainsTarget     = true
            });

            // EntityType: SeniorClub
            var seniorClub = new EdmEntityType("ns", "SeniorClub", club);

            model.AddElement(seniorClub);

            // EntitySet: Clubs
            var clubs         = container.AddEntitySet("Clubs", club);
            var membersInClub = clubs.FindNavigationTarget(members) as EdmNavigationSource;

            membersInClub.AddNavigationTarget(myAccounts, accounts);

            // Singleton: PermanentAccount
            var permanentAccount = container.AddSingleton("PermanentAccount", account);

            people.AddNavigationTarget(myPermanentAccount, permanentAccount);

            _model = model;

            return(_model);
        }
 /// <summary>
 /// Normalizes the payload for WCF DS Server mode.
 /// </summary>
 /// <param name="payloadElement">The payload element to normalize.</param>
 /// <param name="format">The format ot use.</param>
 /// <returns>The normalized payload element.</returns>
 public static ODataPayloadElement Normalize(ODataFormat format, EdmModel payloadEdmModel, ODataPayloadElement payloadElement)
 {
     new WcfDsServerPayloadElementNormalizer(format, payloadEdmModel).Recurse(payloadElement);
     return(payloadElement);
 }
Exemplo n.º 14
0
 private static IEdmEnumType GetCapabilitiesNavigationType(this EdmModel model)
 {
     return(_navigationType ??
            (_navigationType = model.FindType(CapabilitiesVocabularyConstants.NavigationType) as IEdmEnumType));
 }
Exemplo n.º 15
0
 public TestModelProducer(EdmModel model)
 {
     this.model = model;
 }
Exemplo n.º 16
0
            /// <inheritdoc/>
            public async Task<IEdmModel> GetModelAsync(ModelContext context, CancellationToken cancellationToken)
            {
                Ensure.NotNull(context, "context");

                IEdmModel modelReturned = await GetModelReturnedByInnerHandlerAsync(context, cancellationToken);
                if (modelReturned == null)
                {
                    // There is no model returned so return an empty model.
                    var emptyModel = new EdmModel();
                    emptyModel.EnsureEntityContainer(ModelCache.targetType);
                    return emptyModel;
                }

                EdmModel edmModel = modelReturned as EdmModel;
                if (edmModel == null)
                {
                    // The model returned is not an EDM model.
                    return modelReturned;
                }

                ModelCache.ScanForDeclaredPublicProperties();
                ModelCache.BuildEntitySetsAndSingletons(edmModel);
                ModelCache.AddNavigationPropertyBindings(edmModel);
                return edmModel;
            }
Exemplo n.º 17
0
        public async Task ParseBatchRequestsAsync_Returns_RequestsFromMultipartContent()
        {
            // Arrange
            DefaultODataBatchHandler batchHandler = new DefaultODataBatchHandler();
            string batchRequest = @"
--7289e6c2-adbd-4dd8-bfb1-f36099442947
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 1430195875

GET / HTTP/1.1
Host: example.com


--7289e6c2-adbd-4dd8-bfb1-f36099442947
Content-Type: multipart/mixed;boundary=e58fa556-67f1-4180-b04e-e28df22ac4d9

--e58fa556-67f1-4180-b04e-e28df22ac4d9
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 675766617

POST /values HTTP/1.1
Host: example.com


--e58fa556-67f1-4180-b04e-e28df22ac4d9--

--7289e6c2-adbd-4dd8-bfb1-f36099442947--
";

            HttpContext httpContext = HttpContextHelper.Create("Post", "http://example.com/$batch");

            byte[] requestBytes = Encoding.UTF8.GetBytes(batchRequest);
            httpContext.Request.Body          = new MemoryStream(requestBytes);
            httpContext.Request.ContentType   = "multipart/mixed;boundary=7289e6c2-adbd-4dd8-bfb1-f36099442947";
            httpContext.Request.ContentLength = requestBytes.Length;

            IEdmModel model = new EdmModel();

            httpContext.ODataFeature().PrefixName = "odata";
            httpContext.RequestServices = BuildServiceProvider(opt => opt.AddModel("odata", model));
            httpContext.Response.Body   = new MemoryStream();
            batchHandler.PrefixName     = "odata";

            // Act
            IList <ODataBatchRequestItem> requests = await batchHandler.ParseBatchRequestsAsync(httpContext);

            // Assert
            Assert.Equal(2, requests.Count);

            var operationContext = Assert.IsType <OperationRequestItem>(requests[0]).Context;

            Assert.Equal("GET", operationContext.Request.Method);
            Assert.Equal("http://example.com/", operationContext.Request.GetDisplayUrl());

            var changeSetContexts = Assert.IsType <ChangeSetRequestItem>(requests[1]).Contexts;
            var changeSetContext  = Assert.Single(changeSetContexts);

            Assert.Equal("POST", changeSetContext.Request.Method);
            Assert.Equal("http://example.com/values", changeSetContext.Request.GetDisplayUrl());
        }
        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 = "Invalid type information for top-level null - we don't allow null collections - should fail.",
                    Json        = "{ " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Collection(Edm.Int32)\", " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Collection(Edm.Int32)\"," +
                                  "\"" + JsonLightConstants.ODataValuePropertyName + "\": null" +
                                  "}",
                    ReaderMetadata    = collectionReaderMetadata,
                    ExpectedException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_NullNamedValueForNonNullableType", "value", "Collection(Edm.Int32)")
                },
                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);
            });
        }
Exemplo n.º 19
0
        private PayloadWriterTestDescriptor <ODataItem>[] CreateFeedQueryCountDescriptors()
        {
            Func <long?, ODataResourceSet> feedCreator = (c) =>
            {
                ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed();
                feed.Count = c;
                return(feed);
            };

            long?[] counts = new long?[] { 0, 1, 2, 1000, -1 - 10, long.MaxValue, long.MinValue, null };

            EdmModel      model = new EdmModel();
            ODataResource entry = ObjectModelUtils.CreateDefaultEntryWithAtomMetadata("DefaultEntitySet", "DefaultEntityType", model);

            var container  = model.FindEntityContainer("DefaultContainer");
            var entitySet  = container.FindEntitySet("DefaultEntitySet") as EdmEntitySet;
            var entityType = model.FindType("TestModel.DefaultEntityType") as EdmEntityType;

            var descriptors = counts.Select(count => new PayloadWriterTestDescriptor <ODataItem>(this.Settings, feedCreator(count),
                                                                                                 (testConfiguration) =>
            {
                if (testConfiguration.IsRequest && count.HasValue)
                {
                    return(new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = ODataExpectedExceptions.ODataException("ODataWriterCore_QueryCountInRequest")
                    });
                }

                if (testConfiguration.Format == ODataFormat.Json)
                {
                    if (count.HasValue)
                    {
                        return(new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            Json = "$(Indent)$(Indent)\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataCountAnnotationName + "\":\"" + count + "\"",
                            FragmentExtractor = (result) => result.Object().Property(JsonLightConstants.ODataCountAnnotationName)
                        });
                    }
                    else
                    {
                        return(new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            Json = string.Join("$(NL)",
                                               "[",
                                               string.Empty,
                                               "]"),
                            FragmentExtractor = (result) =>
                            {
                                return JsonLightWriterUtils.GetTopLevelFeedItemsArray(testConfiguration, result).RemoveAllAnnotations(true);
                            }
                        });
                    }
                }
                else
                {
                    string formatName = testConfiguration.Format == null ? "null" : testConfiguration.Format.GetType().Name;
                    throw new NotSupportedException("Invalid format detected: " + formatName);
                }
            })
            {
                Model = model,
                PayloadEdmElementContainer = entitySet,
                PayloadEdmElementType      = entityType,
            });

            return(descriptors.ToArray());
        }
Exemplo n.º 20
0
        private PayloadWriterTestDescriptor <ODataItem>[] CreateFeedNextLinkDescriptors()
        {
            string[] nextLinkUris = new string[]
            {
                "http://my.customers.com/?skiptoken=1234",
                "http://my.customers.com/?",
                "http://my.customers.com/",
                "http://my.customers.com/?$filter=3.14E%2B%20ne%20null",
                "http://my.customers.com/?$filter='foo%20%26%20'%20ne%20null",
                "http://my.customers.com/?$filter=not%20endswith(Name,'%2B')",
                "http://my.customers.com/?$filter=geo.distance(Point,%20geometry'SRID=0;Point(6.28E%2B3%20-2.1e%2B4)')%20eq%20null",
            };

            Func <string, ODataResourceSet> feedCreator = (nextLink) =>
            {
                ODataResourceSet resourceCollection = ObjectModelUtils.CreateDefaultFeed();
                resourceCollection.NextPageLink = new Uri(nextLink);
                return(resourceCollection);
            };

            EdmModel model = new EdmModel();

            ODataResourceSet dummyFeed = ObjectModelUtils.CreateDefaultFeed("CustomersSet", "CustomerType", model);

            var container    = model.FindEntityContainer("DefaultContainer");
            var customerSet  = container.FindEntitySet("CustomersSet") as EdmEntitySet;
            var customerType = model.FindType("TestModel.CustomerType") as EdmEntityType;

            return(nextLinkUris.Select(nextLink => new PayloadWriterTestDescriptor <ODataItem>(
                                           this.Settings,
                                           feedCreator(nextLink),
                                           (testConfiguration) =>
            {
                if (testConfiguration.IsRequest)
                {
                    return new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = ODataExpectedExceptions.ODataException("WriterValidationUtils_NextPageLinkInRequest")
                    };
                }

                if (testConfiguration.Format == ODataFormat.Json)
                {
                    return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        Json = "\"" + JsonLightConstants.ODataNextLinkAnnotationName + "\":\"" + nextLink + "\"",
                        FragmentExtractor = (result) => result.Object().Property(JsonLightConstants.ODataNextLinkAnnotationName)
                    };
                }
                else
                {
                    string formatName = testConfiguration.Format == null ? "null" : testConfiguration.Format.GetType().Name;
                    throw new NotSupportedException("Invalid format detected: " + formatName);
                }
            })
            {
                Model = model,
                PayloadEdmElementContainer = customerSet,
                PayloadEdmElementType = customerType,
            }).ToArray());
        }
 public PrimitiveValuesRoundtripJsonLightTests()
 {
     model = new EdmModel();
 }
        public void UnsignedIntAndTypeDefinitionRoundtripJsonLightIntegrationTest()
        {
            var model = new EdmModel();

            var uint16    = new EdmTypeDefinition("MyNS", "UInt16", EdmPrimitiveTypeKind.Double);
            var uint16Ref = new EdmTypeDefinitionReference(uint16, false);

            model.AddElement(uint16);
            model.SetPrimitiveValueConverter(uint16Ref, UInt16ValueConverter.Instance);

            var uint64    = new EdmTypeDefinition("MyNS", "UInt64", EdmPrimitiveTypeKind.String);
            var uint64Ref = new EdmTypeDefinitionReference(uint64, false);

            model.AddElement(uint64);
            model.SetPrimitiveValueConverter(uint64Ref, UInt64ValueConverter.Instance);

            var guidType = new EdmTypeDefinition("MyNS", "Guid", EdmPrimitiveTypeKind.Int64);
            var guidRef  = new EdmTypeDefinitionReference(guidType, true);

            model.AddElement(guidType);

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

            personType.AddKeys(personType.AddStructuralProperty("ID", uint64Ref));
            personType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            personType.AddStructuralProperty("FavoriteNumber", uint16Ref);
            personType.AddStructuralProperty("Age", model.GetUInt32("MyNS", true));
            personType.AddStructuralProperty("Guid", guidRef);
            personType.AddStructuralProperty("Weight", EdmPrimitiveTypeKind.Double);
            personType.AddStructuralProperty("Money", EdmPrimitiveTypeKind.Decimal);
            model.AddElement(personType);

            var container = new EdmEntityContainer("MyNS", "Container");
            var peopleSet = container.AddEntitySet("People", personType);

            model.AddElement(container);

            var stream = new MemoryStream();
            IODataResponseMessage message = new InMemoryMessage {
                Stream = stream
            };

            message.StatusCode = 200;

            var writerSettings = new ODataMessageWriterSettings();

            writerSettings.SetServiceDocumentUri(new Uri("http://host/service"));

            var messageWriter = new ODataMessageWriter(message, writerSettings, model);
            var entryWriter   = messageWriter.CreateODataEntryWriter(peopleSet);

            var entry = new ODataEntry
            {
                TypeName   = "MyNS.Person",
                Properties = new[]
                {
                    new ODataProperty
                    {
                        Name  = "ID",
                        Value = UInt64.MaxValue
                    },
                    new ODataProperty
                    {
                        Name  = "Name",
                        Value = "Foo"
                    },
                    new ODataProperty
                    {
                        Name  = "FavoriteNumber",
                        Value = (UInt16)250
                    },
                    new ODataProperty
                    {
                        Name  = "Age",
                        Value = (UInt32)123
                    },
                    new ODataProperty
                    {
                        Name  = "Guid",
                        Value = Int64.MinValue
                    },
                    new ODataProperty
                    {
                        Name  = "Weight",
                        Value = 123.45
                    },
                    new ODataProperty
                    {
                        Name  = "Money",
                        Value = Decimal.MaxValue
                    }
                }
            };

            entryWriter.WriteStart(entry);
            entryWriter.WriteEnd();
            entryWriter.Flush();

            stream.Position = 0;

            StreamReader reader  = new StreamReader(stream);
            string       payload = reader.ReadToEnd();

            payload.Should().Be("{\"@odata.context\":\"http://host/service/$metadata#People/$entity\",\"ID\":\"18446744073709551615\",\"Name\":\"Foo\",\"FavoriteNumber\":250.0,\"Age\":123,\"Guid\":-9223372036854775808,\"Weight\":123.45,\"Money\":79228162514264337593543950335}");

            stream  = new MemoryStream(Encoding.Default.GetBytes(payload));
            message = new InMemoryMessage {
                Stream = stream
            };
            message.StatusCode = 200;

            var readerSettings = new ODataMessageReaderSettings();

            var messageReader = new ODataMessageReader(message, readerSettings, model);
            var entryReader   = messageReader.CreateODataEntryReader(peopleSet, personType);

            Assert.True(entryReader.Read());
            var entryReaded = entryReader.Item as ODataEntry;

            var propertiesReaded = entryReaded.Properties.ToList();
            var propertiesGiven  = entry.Properties.ToList();

            Assert.Equal(propertiesReaded.Count, propertiesGiven.Count);
            for (int i = 0; i < propertiesReaded.Count; ++i)
            {
                Assert.Equal(propertiesReaded[i].Name, propertiesGiven[i].Name);
                Assert.Equal(propertiesReaded[i].Value.GetType(), propertiesGiven[i].Value.GetType());
                Assert.Equal(propertiesReaded[i].Value, propertiesGiven[i].Value);
            }
        }
Exemplo n.º 23
0
 /// <summary>
 /// Add default container into the model
 ///     * add top level EntitySet
 ///     * add NavigationPropertyBinding
 /// </summary>
 /// <param name="model">The Model to run the fixup operations on.</param>
 public static void AddDefaultContainerFixup(this EdmModel model)
 {
     AddDefaultContainerFixup(model, ModelNamespace);
 }
Exemplo n.º 24
0
        /// <summary>
        /// Gets the <see cref="EntityType"/> of the specified entry or feed payload element.
        /// </summary>
        /// <param name="payloadElement">The payload element to get the entity type for.</param>
        /// <param name="model">The model to find the entity type in.</param>
        /// <returns>The <see cref="EntityType"/> of the <paramref name="payloadElement"/>.</returns>
        public static IEdmEntityType GetPayloadElementEntityType(ODataAnnotatable payloadElement, EdmModel model)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");
            ExceptionUtilities.CheckArgumentNotNull(model, "model");

            ExceptionUtilities.Assert(
                payloadElement is ODataEntry || payloadElement is ODataFeed,
                "Can only determine entity type for entry or feed payloads.");

            ODataFeed feed = payloadElement as ODataFeed;

            if (feed != null)
            {
                // A feed doesn't know it's type. If it doesn't have any entries we can't determine the type.
                var feedentry = feed.GetAnnotation <ODataFeedEntriesObjectModelAnnotation>().FirstOrDefault();
                if (feedentry != null)
                {
                    return(model.FindDeclaredType(feedentry.TypeName) as IEdmEntityType);
                }

                return(null);
            }

            ODataEntry entry = payloadElement as ODataEntry;

            if (entry != null)
            {
                return(model.FindDeclaredType(entry.TypeName) as IEdmEntityType);
            }

            return(null);
        }
Exemplo n.º 25
0
        public void GetTypeMappingCache_ReturnsNewInstance_IfNotSet()
        {
            IEdmModel model = new EdmModel();

            Assert.NotNull(model.GetTypeMappingCache());
        }
        private static IDictionary <string, EdmNavigationSource> GetNavigationSourceMap(this EdmModel model, ODataModelBuilder builder,
                                                                                        Dictionary <Type, IEdmType> edmTypeMap, IEnumerable <NavigationSourceAndAnnotations> navigationSourceAndAnnotations)
        {
            // index the navigation source by name
            Dictionary <string, EdmNavigationSource> edmNavigationSourceMap = navigationSourceAndAnnotations.ToDictionary(e => e.NavigationSource.Name, e => e.NavigationSource);

            // apply the annotations
            foreach (NavigationSourceAndAnnotations navigationSourceAndAnnotation in navigationSourceAndAnnotations)
            {
                EdmNavigationSource navigationSource = navigationSourceAndAnnotation.NavigationSource;
                model.SetAnnotationValue <NavigationSourceUrlAnnotation>(navigationSource, navigationSourceAndAnnotation.Url);
                model.SetNavigationSourceLinkBuilder(navigationSource, navigationSourceAndAnnotation.LinkBuilder);

                AddNavigationBindings(navigationSourceAndAnnotation.Configuration, navigationSource, navigationSourceAndAnnotation.LinkBuilder,
                                      builder, edmTypeMap, edmNavigationSourceMap);
            }

            return(edmNavigationSourceMap);
        }
Exemplo n.º 27
0
        public void WriteEntityReferenceLinkAfterFeedJsonLightErrorTest()
        {
            EdmModel model = new EdmModel();

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

            model.AddElement(container);

            var customerType = new EdmEntityType("TestModel", "Customer");
            var orderType    = new EdmEntityType("TestModel", "Order");
            var orderNavProp = customerType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "Orders", Target = orderType, TargetMultiplicity = EdmMultiplicity.Many
            });
            var bestFriendNavProp = customerType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "BestFriend", Target = customerType, TargetMultiplicity = EdmMultiplicity.One
            });
            var customerSet = container.AddEntitySet("Customers", customerType);
            var orderSet    = container.AddEntitySet("Order", orderType);

            customerSet.AddNavigationTarget(orderNavProp, orderSet);
            customerSet.AddNavigationTarget(bestFriendNavProp, customerSet);
            model.AddElement(customerType);
            model.AddElement(orderType);

            ODataResource expandedOrderInstance = ObjectModelUtils.CreateDefaultEntryWithAtomMetadata();

            expandedOrderInstance.TypeName = "TestModel.Order";

            var testCases = new WriterNavigationLinkTests.NavigationLinkTestCase[]
            {
                // Entity reference link after empty feed in collection navigation link
                new WriterNavigationLinkTests.NavigationLinkTestCase
                {
                    Items = new ODataItem[] {
                        new ODataNestedResourceInfo()
                        {
                            IsCollection = true, Name = "Orders", Url = new Uri("http://odata.org/nav")
                        },
                        ObjectModelUtils.CreateDefaultFeedWithAtomMetadata(),
                        null,
                        new ODataEntityReferenceLink()
                        {
                            Url = new Uri("http://odata.org/singleton")
                        },
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightWriter_EntityReferenceLinkAfterResourceSetInRequest")
                },
                // Entity reference link after non-empty feed in collection navigation link
                new WriterNavigationLinkTests.NavigationLinkTestCase
                {
                    Items = new ODataItem[] {
                        new ODataNestedResourceInfo()
                        {
                            IsCollection = true, Name = "Orders", Url = new Uri("http://odata.org/nav")
                        },
                        ObjectModelUtils.CreateDefaultFeedWithAtomMetadata(),
                        expandedOrderInstance,
                        null,
                        null,
                        new ODataEntityReferenceLink()
                        {
                            Url = new Uri("http://odata.org/singleton")
                        },
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightWriter_EntityReferenceLinkAfterResourceSetInRequest")
                },
                // Entity reference link before and after empty feed in collection navigation link
                new WriterNavigationLinkTests.NavigationLinkTestCase
                {
                    Items = new ODataItem[] {
                        new ODataNestedResourceInfo()
                        {
                            IsCollection = true, Name = "Orders", Url = new Uri("http://odata.org/nav")
                        },
                        new ODataEntityReferenceLink()
                        {
                            Url = new Uri("http://odata.org/singleton")
                        },
                        ObjectModelUtils.CreateDefaultFeedWithAtomMetadata(),
                        null,
                        new ODataEntityReferenceLink()
                        {
                            Url = new Uri("http://odata.org/singleton")
                        },
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightWriter_EntityReferenceLinkAfterResourceSetInRequest")
                },
                // Entity reference link after two empty feeds in collection navigation link
                new WriterNavigationLinkTests.NavigationLinkTestCase
                {
                    Items = new ODataItem[] {
                        new ODataNestedResourceInfo()
                        {
                            IsCollection = true, Name = "Orders", Url = new Uri("http://odata.org/nav")
                        },
                        new ODataEntityReferenceLink()
                        {
                            Url = new Uri("http://odata.org/singleton")
                        },
                        ObjectModelUtils.CreateDefaultFeedWithAtomMetadata(),
                        null,
                        ObjectModelUtils.CreateDefaultFeedWithAtomMetadata(),
                        null,
                        new ODataEntityReferenceLink()
                        {
                            Url = new Uri("http://odata.org/singleton")
                        },
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightWriter_EntityReferenceLinkAfterResourceSetInRequest")
                },
            };

            IEnumerable <PayloadWriterTestDescriptor <ODataItem> > testDescriptors =
                testCases.Select(testCase => testCase.ToEdmTestDescriptor(this.Settings, model, customerSet, customerType));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.JsonLightFormatConfigurations.Where(tc => tc.IsRequest),
                (testDescriptor, testConfiguration) =>
            {
                TestWriterUtils.WriteAndVerifyODataEdmPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
        public ODataJsonLightReaderEnumIntegrationTests()
        {
            EdmModel tmpModel = new EdmModel();

            // enum without flags
            var enumType = new EdmEnumType("NS", "Color");
            var red      = new EdmEnumMember(enumType, "Red", new EdmEnumMemberValue(1));

            enumType.AddMember(red);
            enumType.AddMember("Green", new EdmEnumMemberValue(2));
            enumType.AddMember("Blue", new EdmEnumMemberValue(3));
            tmpModel.AddElement(enumType);

            // enum with flags
            var enumFlagsType = new EdmEnumType("NS", "ColorFlags", isFlags: true);

            enumFlagsType.AddMember("Red", new EdmEnumMemberValue(1));
            enumFlagsType.AddMember("Green", new EdmEnumMemberValue(2));
            enumFlagsType.AddMember("Blue", new EdmEnumMemberValue(4));
            tmpModel.AddElement(enumFlagsType);

            this.entityType = new EdmEntityType("NS", "MyEntityType", isAbstract: false, isOpen: true, baseType: null);
            EdmStructuralProperty floatId = new EdmStructuralProperty(this.entityType, "FloatId", EdmCoreModel.Instance.GetSingle(false));

            this.entityType.AddKeys(floatId);
            this.entityType.AddProperty(floatId);
            var enumTypeReference = new EdmEnumTypeReference(enumType, true);

            this.entityType.AddProperty(new EdmStructuralProperty(this.entityType, "Color", enumTypeReference));
            var enumFlagsTypeReference = new EdmEnumTypeReference(enumFlagsType, false);

            this.entityType.AddProperty(new EdmStructuralProperty(this.entityType, "ColorFlags", enumFlagsTypeReference));

            // enum in complex type
            EdmComplexType myComplexType = new EdmComplexType("NS", "MyComplexType");

            myComplexType.AddProperty(new EdmStructuralProperty(myComplexType, "MyColorFlags", enumFlagsTypeReference));
            myComplexType.AddProperty(new EdmStructuralProperty(myComplexType, "Height", EdmCoreModel.Instance.GetDouble(false)));
            tmpModel.AddElement(myComplexType);
            this.entityType.AddProperty(new EdmStructuralProperty(this.entityType, "MyComplexType", new EdmComplexTypeReference(myComplexType, true)));

            // enum in derived complex type
            EdmComplexType myDerivedComplexType = new EdmComplexType("NS", "MyDerivedComplexType", myComplexType, false);

            myDerivedComplexType.AddProperty(new EdmStructuralProperty(myDerivedComplexType, "MyDerivedColorFlags", new EdmEnumTypeReference(enumFlagsType, false)));
            tmpModel.AddElement(myDerivedComplexType);

            // enum in collection type
            EdmCollectionType myCollectionType = new EdmCollectionType(enumFlagsTypeReference);

            this.entityType.AddProperty(new EdmStructuralProperty(this.entityType, "MyCollectionType", new EdmCollectionTypeReference(myCollectionType)));

            tmpModel.AddElement(this.entityType);

            var defaultContainer = new EdmEntityContainer("NS", "DefaultContainer_sub");

            this.entitySet = new EdmEntitySet(defaultContainer, "MySet", this.entityType);
            defaultContainer.AddEntitySet(this.entitySet.Name, this.entityType);
            tmpModel.AddElement(defaultContainer);

            this.userModel = TestUtils.WrapReferencedModelsToMainModel("NS", "DefaultContainer", tmpModel);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Creates a test model shared among parameter reader/writer tests.
        /// </summary>
        /// <returns>Returns a model with function imports.</returns>
        public static IEdmModel BuildModelWithFunctionImport()
        {
            EdmCoreModel       coreModel            = EdmCoreModel.Instance;
            EdmModel           model                = new EdmModel();
            const string       defaultNamespaceName = "TestModel";
            EdmEntityContainer container            = new EdmEntityContainer(defaultNamespaceName, "TestContainer");

            model.AddElement(container);

            EdmComplexType complexType = new EdmComplexType(defaultNamespaceName, "ComplexType");

            complexType.AddProperty(new EdmStructuralProperty(complexType, "PrimitiveProperty", coreModel.GetString(false)));
            complexType.AddProperty(new EdmStructuralProperty(complexType, "ComplexProperty", complexType.ToTypeReference(false)));
            model.AddElement(complexType);

            EdmEnumType enumType = new EdmEnumType(defaultNamespaceName, "EnumType");

            model.AddElement(enumType);

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

            entityType.AddKeys(new IEdmStructuralProperty[] { new EdmStructuralProperty(entityType, "ID", coreModel.GetInt32(false)) });
            entityType.AddProperty(new EdmStructuralProperty(entityType, "ComplexProperty", complexType.ToTypeReference()));

            container.AddActionAndActionImport(model, "FunctionImport_Primitive", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("primitive", coreModel.GetString(false));
            container.AddActionAndActionImport(model, "FunctionImport_NullablePrimitive", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("nullablePrimitive", coreModel.GetString(true));
            EdmCollectionType stringCollectionType = new EdmCollectionType(coreModel.GetString(true));

            container.AddActionAndActionImport(model, "FunctionImport_PrimitiveCollection", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("primitiveCollection", stringCollectionType.ToTypeReference(false));
            container.AddActionAndActionImport(model, "FunctionImport_Complex", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("complex", complexType.ToTypeReference(true));
            EdmCollectionType complexCollectionType = new EdmCollectionType(complexType.ToTypeReference());

            container.AddActionAndActionImport(model, "FunctionImport_ComplexCollection", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("complexCollection", complexCollectionType.ToTypeReference());
            container.AddActionAndActionImport(model, "FunctionImport_Entry", null /*returnType*/, null /*entitySet*/, true /*bindable*/).Action.AsEdmAction().AddParameter("entry", entityType.ToTypeReference());
            EdmCollectionType entityCollectionType = new EdmCollectionType(entityType.ToTypeReference());

            container.AddActionAndActionImport(model, "FunctionImport_Feed", null /*returnType*/, null /*entitySet*/, true /*bindable*/).Action.AsEdmAction().AddParameter("feed", entityCollectionType.ToTypeReference());
            container.AddActionAndActionImport(model, "FunctionImport_Stream", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("stream", coreModel.GetStream(false));
            container.AddActionAndActionImport(model, "FunctionImport_Enum", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("enum", enumType.ToTypeReference());

            var functionImport_PrimitiveTwoParameters = container.AddActionAndActionImport(model, "FunctionImport_PrimitiveTwoParameters", null /*returnType*/, null /*entitySet*/, false /*bindable*/);

            functionImport_PrimitiveTwoParameters.Action.AsEdmAction().AddParameter("p1", coreModel.GetInt32(false));
            functionImport_PrimitiveTwoParameters.Action.AsEdmAction().AddParameter("p2", coreModel.GetString(false));

            container.AddActionAndActionImport(model, "FunctionImport_Int", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("p1", coreModel.GetInt32(false));
            container.AddActionAndActionImport(model, "FunctionImport_Double", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("p1", coreModel.GetDouble(false));
            EdmCollectionType int32CollectionType = new EdmCollectionType(coreModel.GetInt32(false));

            container.AddActionAndActionImport(model, "FunctionImport_NonNullablePrimitiveCollection", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("p1", int32CollectionType.ToTypeReference(false));

            EdmComplexType complexType2 = new EdmComplexType(defaultNamespaceName, "ComplexTypeWithNullableProperties");

            complexType2.AddProperty(new EdmStructuralProperty(complexType2, "StringProperty", coreModel.GetString(true)));
            complexType2.AddProperty(new EdmStructuralProperty(complexType2, "IntegerProperty", coreModel.GetInt32(true)));
            model.AddElement(complexType2);

            var functionImport_MultipleNullableParameters = container.AddActionAndActionImport(model, "FunctionImport_MultipleNullableParameters", null /*returnType*/, null /*entitySet*/, false /*bindable*/);
            var function_MultipleNullableParameters       = functionImport_MultipleNullableParameters.Action.AsEdmAction();

            function_MultipleNullableParameters.AddParameter("p1", coreModel.GetBinary(true /*isNullable*/));
            function_MultipleNullableParameters.AddParameter("p2", coreModel.GetBoolean(true /*isNullable*/));
            function_MultipleNullableParameters.AddParameter("p3", coreModel.GetByte(true /*isNullable*/));
            function_MultipleNullableParameters.AddParameter("p5", coreModel.GetDateTimeOffset(true /*isNullable*/));
            function_MultipleNullableParameters.AddParameter("p6", coreModel.GetDecimal(true /*isNullable*/));
            function_MultipleNullableParameters.AddParameter("p7", coreModel.GetDouble(true /*isNullable*/));
            function_MultipleNullableParameters.AddParameter("p8", coreModel.GetGuid(true /*isNullable*/));
            function_MultipleNullableParameters.AddParameter("p9", coreModel.GetInt16(true /*isNullable*/));
            function_MultipleNullableParameters.AddParameter("p10", coreModel.GetInt32(true /*isNullable*/));
            function_MultipleNullableParameters.AddParameter("p11", coreModel.GetInt64(true /*isNullable*/));
            function_MultipleNullableParameters.AddParameter("p12", coreModel.GetSByte(true /*isNullable*/));
            function_MultipleNullableParameters.AddParameter("p13", coreModel.GetSingle(true /*isNullable*/));
            function_MultipleNullableParameters.AddParameter("p14", coreModel.GetSpatial(EdmPrimitiveTypeKind.GeographyPoint, true /*isNullable*/));
            function_MultipleNullableParameters.AddParameter("p15", coreModel.GetString(true /*isNullable*/));
            function_MultipleNullableParameters.AddParameter("p16", complexType2.ToTypeReference(true /*isNullable*/));

            return(model);
        }
 private static void AddSelfAndAllDerivedTypes(
     EdmModel model, EdmEntityType entityType, List<EdmEntityType> entityTypes)
 {
     entityTypes.Add(entityType);
     foreach (var derivedType in model.GetEntityTypes().Where(et => et.BaseType == entityType))
     {
         AddSelfAndAllDerivedTypes(model, derivedType, entityTypes);
     }
 }
        public void SpatialPropertyErrorTest()
        {
            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.GetSpatial(EdmPrimitiveTypeKind.GeographyPoint, true));
            model.AddElement(owningType);

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

            PayloadReaderTestDescriptor.ReaderMetadata readerMetadata = new PayloadReaderTestDescriptor.ReaderMetadata(edmTopLevelProperty);
            string pointValue = SpatialUtils.GetSpatialStringValue(ODataFormat.Json, GeographyFactory.Point(33.1, -110.0).Build(), "Edm.GeographyPoint");

            var explicitPayloads = new[]
            {
                new
                {
                    Description = "Spatial value with type information and odata.type annotation - should fail.",
                    Json        = "{ " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.GeographyPoint\", " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"Edm.GeographyPoint\"," +
                                  "\"" + JsonLightConstants.ODataValuePropertyName + "\":" + pointValue +
                                  "}",
                    ReaderMetadata    = readerMetadata,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_ODataTypeAnnotationInPrimitiveValue", JsonLightConstants.ODataTypeAnnotationName)
                },
                new
                {
                    Description = "Spatial value with odata.type annotation - should fail.",
                    Json        = "{ " +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.GeographyPoint\", " +
                                  "\"" + JsonLightConstants.ODataValuePropertyName + "\":" + pointValue +
                                  "}",
                    ReaderMetadata    = readerMetadata,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_ODataTypeAnnotationInPrimitiveValue", JsonLightConstants.ODataTypeAnnotationName)
                },
            };

            var testDescriptors = explicitPayloads.Select(payload =>
            {
                return(new NativeInputReaderTestDescriptor()
                {
                    DebugDescription = payload.Description,
                    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,
                    },
                });
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration);
            });
        }
        private void BuildOperations(EdmModel model, string modelNamespace)
        {
            foreach (OperationMethodInfo operationMethodInfo in this.operationInfos)
            {
                // With this method, if return type is nullable type,it will get underlying type
                var returnType = TypeHelper.GetUnderlyingTypeOrSelf(operationMethodInfo.Method.ReturnType);
                var returnTypeReference = returnType.GetReturnTypeReference(model);
                bool isBound = operationMethodInfo.IsBound;
                var bindingParameter = operationMethodInfo.Method.GetParameters().FirstOrDefault();

                if (bindingParameter == null && isBound)
                {
                    // Ignore the method which is marked as bounded but no parameters
                    continue;
                }

                string namespaceName = GetNamespaceName(operationMethodInfo, modelNamespace);

                EdmOperation operation = null;
                EdmPathExpression path = null;
                if (isBound)
                {
                    // Unbound actions or functions should not have EntitySetPath attribute
                    path = BuildBoundOperationReturnTypePathExpression(returnTypeReference, bindingParameter);
                }

                if (operationMethodInfo.HasSideEffects)
                {
                    operation = new EdmAction(
                        namespaceName,
                        operationMethodInfo.Name,
                        returnTypeReference,
                        isBound,
                        path);
                }
                else
                {
                    operation = new EdmFunction(
                        namespaceName,
                        operationMethodInfo.Name,
                        returnTypeReference,
                        isBound,
                        path,
                        operationMethodInfo.IsComposable);
                }

                BuildOperationParameters(operation, operationMethodInfo.Method, model);
                model.AddElement(operation);

                if (!isBound)
                {
                    // entitySetReferenceExpression refer to an entity set containing entities returned
                    // by this function/action import.
                    var entitySetExpression = BuildEntitySetExpression(
                        model, operationMethodInfo.EntitySet, returnTypeReference);
                    var entityContainer = model.EnsureEntityContainer(this.targetType);
                    if (operationMethodInfo.HasSideEffects)
                    {
                        entityContainer.AddActionImport(operation.Name, (EdmAction)operation, entitySetExpression);
                    }
                    else
                    {
                        entityContainer.AddFunctionImport(
                            operation.Name, (EdmFunction)operation, entitySetExpression);
                    }
                }
            }
        }
Exemplo n.º 33
0
        protected virtual void VisitEdmModel(EdmModel item)
        {
            VisitEdmNamedMetadataItem(item);
            if (item != null)
            {
                if (item.HasNamespaces)
                {
                    VisitNamespaces(item, item.Namespaces);
                }

                if (item.HasContainers)
                {
                    VisitEntityContainers(item, item.Containers);
                }
            }
        }
Exemplo n.º 34
0
        private void BuildEntitySetsAndSingletons(EdmModel model)
        {
            foreach (var property in this.publicProperties)
            {
                var resourceAttribute = property.GetCustomAttributes<ResourceAttribute>(true).FirstOrDefault();
                if (resourceAttribute == null)
                {
                    continue;
                }

                bool isSingleton = resourceAttribute.IsSingleton;
                if ((!isSingleton && !IsEntitySetProperty(property))
                    || (isSingleton && !IsSingletonProperty(property)))
                {
                    // This means property type is not IQueryable<T> when indicating an entityset
                    // or not non-generic type when indicating a singleton
                    continue;
                }

                var propertyType = property.PropertyType;
                if (!isSingleton)
                {
                    propertyType = propertyType.GetGenericArguments()[0];
                }

                var entityType = model.FindDeclaredType(propertyType.FullName) as IEdmEntityType;
                if (entityType == null)
                {
                    // Skip property whose entity type has not been declared yet.
                    continue;
                }

                var container = model.EnsureEntityContainer(this.targetType);
                if (!isSingleton)
                {
                    if (container.FindEntitySet(property.Name) == null)
                    {
                        container.AddEntitySet(property.Name, entityType);
                    }

                    // If ODataConventionModelBuilder is used to build the model, and a entity set is added,
                    // i.e. the entity set is already in the container,
                    // we should add it into entitySetProperties and addedNavigationSources
                    if (!this.entitySetProperties.Contains(property))
                    {
                        this.entitySetProperties.Add(property);
                        this.addedNavigationSources.Add(container.FindEntitySet(property.Name) as EdmEntitySet);
                    }
                }
                else
                {
                    if (container.FindSingleton(property.Name) == null)
                    {
                        container.AddSingleton(property.Name, entityType);
                    }

                    if (!this.singletonProperties.Contains(property))
                    {
                        this.singletonProperties.Add(property);
                        this.addedNavigationSources.Add(container.FindSingleton(property.Name) as EdmSingleton);
                    }
                }
            }
        }
Exemplo n.º 35
0
 protected virtual void VisitNamespaces(EdmModel model, IEnumerable<EdmNamespace> namespaces)
 {
     VisitCollection(namespaces, VisitEdmNamespace);
 }
Exemplo n.º 36
0
 public void Apply(EntitySet entitySet, EdmModel model)
 {
     entitySet.Name = entitySet.Name + "Foo";
 }
            public Task<IEdmModel> GetModelAsync(ModelContext context, CancellationToken cancellationToken)
            {
                var model = new EdmModel();
                var entityType = new EdmEntityType(
                    "TestNamespace", "TestName");
                var entityContainer = new EdmEntityContainer(
                    "TestNamespace", "Entities");
                entityContainer.AddEntitySet("TestEntitySet", entityType);
                model.AddElement(entityType);
                model.AddElement(entityContainer);

                return Task.FromResult<IEdmModel>(model);
            }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="format">The format to use.</param>
 /// <param name="payloadEdmModel">Model for the payload.</param>
 private WcfDsServerPayloadElementNormalizer(ODataFormat format, EdmModel payloadEdmModel)
 {
     this.format          = format;
     this.payloadEdmModel = payloadEdmModel;
 }
        public ODataJsonLightWriterComplexIntegrationTests()
        {
            // Initialize open EntityType: EntityType.
            EdmModel edmModel = new EdmModel();

            EdmEntityType edmEntityType = new EdmEntityType("TestNamespace", "EntityType", baseType: null, isAbstract: false, isOpen: true);

            edmEntityType.AddStructuralProperty("DeclaredProperty", EdmPrimitiveTypeKind.Guid);
            edmEntityType.AddStructuralProperty("DeclaredGeometryProperty", EdmPrimitiveTypeKind.Geometry);
            edmEntityType.AddStructuralProperty("DeclaredSingleProperty", EdmPrimitiveTypeKind.Single);
            edmEntityType.AddStructuralProperty("DeclaredDoubleProperty", EdmPrimitiveTypeKind.Double);
            edmEntityType.AddStructuralProperty("TimeOfDayProperty", EdmPrimitiveTypeKind.TimeOfDay);
            edmEntityType.AddStructuralProperty("DateProperty", EdmPrimitiveTypeKind.Date);

            edmModel.AddElement(edmEntityType);

            this.model      = TestUtils.WrapReferencedModelsToMainModel(edmModel);
            this.entityType = edmEntityType;

            // Initialize derived ComplexType: Address and HomeAddress
            this.addressType = new EdmComplexType("TestNamespace", "Address", baseType: null, isAbstract: false, isOpen: false);
            this.addressType.AddStructuralProperty("City", EdmPrimitiveTypeKind.String);
            this.derivedAddressType = new EdmComplexType("TestNamespace", "HomeAddress", baseType: this.addressType, isAbstract: false, isOpen: false);
            this.derivedAddressType.AddStructuralProperty("FamilyName", EdmPrimitiveTypeKind.String);

            // Initialize open ComplexType: OpenAddress.
            this.openAddressType = new EdmComplexType("TestNamespace", "OpenAddress", baseType: null, isAbstract: false, isOpen: true);
            this.openAddressType.AddStructuralProperty("CountryRegion", EdmPrimitiveTypeKind.String);

            edmModel.AddElement(this.addressType);
            edmModel.AddElement(this.derivedAddressType);
            edmModel.AddElement(this.openAddressType);

            this.address = new ODataResource()
            {
                TypeName = "TestNamespace.Address", Properties = new ODataProperty[] { new ODataProperty {
                                                                                           Name = "City", Value = "Shanghai"
                                                                                       } }
            };
            this.homeAddress = new ODataResource {
                TypeName = "TestNamespace.HomeAddress", Properties = new ODataProperty[] { new ODataProperty {
                                                                                               Name = "FamilyName", Value = "Green"
                                                                                           }, new ODataProperty {
                                                                                               Name = "City", Value = "Shanghai"
                                                                                           } }
            };
            this.addressWithInstanceAnnotation = new ODataResource()
            {
                TypeName   = "TestNamespace.Address",
                Properties = new ODataProperty[]
                {
                    new ODataProperty {
                        Name = "City", Value = "Shanghai"
                    }
                },
                InstanceAnnotations = new Collection <ODataInstanceAnnotation>
                {
                    new ODataInstanceAnnotation("Is.ReadOnly", new ODataPrimitiveValue(true))
                }
            };
            this.homeAddressWithInstanceAnnotations = new ODataResource()
            {
                TypeName   = "TestNamespace.HomeAddress",
                Properties = new ODataProperty[]
                {
                    new ODataProperty
                    {
                        Name  = "FamilyName",
                        Value = "Green",
                        InstanceAnnotations = new Collection <ODataInstanceAnnotation>
                        {
                            new ODataInstanceAnnotation("FamilyName.annotation", new ODataPrimitiveValue(true))
                        }
                    },
                    new ODataProperty
                    {
                        Name  = "City",
                        Value = "Shanghai",
                        InstanceAnnotations = new Collection <ODataInstanceAnnotation>
                        {
                            new ODataInstanceAnnotation("City.annotation1", new ODataPrimitiveValue(true)),
                            new ODataInstanceAnnotation("City.annotation2", new ODataPrimitiveValue(123))
                        }
                    }
                },
                InstanceAnnotations = new Collection <ODataInstanceAnnotation>
                {
                    new ODataInstanceAnnotation("Is.AutoComputable", new ODataPrimitiveValue(true)),
                    new ODataInstanceAnnotation("Is.ReadOnly", new ODataPrimitiveValue(false))
                }
            };
        }
        private void GenerateAssociationTypes(EdmModel model, DbDatabaseMapping databaseMapping)
        {
            Contract.Requires(model != null);
            Contract.Requires(databaseMapping != null);

            foreach (var associationType in model.GetAssociationTypes())
            {
                new AssociationTypeMappingGenerator(_providerManifest)
                    .Generate(associationType, databaseMapping);
            }
        }
Exemplo n.º 41
0
        public async Task ProcessBatchAsync_ContinueOnError(bool enableContinueOnError, string preferenceHeader, bool hasThirdResponse)
        {
            // Arrange
            RequestDelegate handler = async context =>
            {
                HttpRequest request         = context.Request;
                string      responseContent = request.GetDisplayUrl();
                string      content         = request.ReadBody();
                if (!string.IsNullOrEmpty(content))
                {
                    responseContent += "," + content;
                }

                HttpResponse response = context.Response;
                if (content.Equals("foo"))
                {
                    response.StatusCode = StatusCodes.Status400BadRequest;
                }

                await response.WriteAsync(responseContent);
            };

            DefaultODataBatchHandler batchHandler = new DefaultODataBatchHandler();

            HttpContext httpContext = HttpContextHelper.Create("Post", "http://example.com/$batch");

            string batchRequest = @"--d3df74a8-8212-4c2a-b4fb-d713a4ba383e
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 1948857409

GET / HTTP/1.1
Host: example.com


--d3df74a8-8212-4c2a-b4fb-d713a4ba383e
Content-Type: multipart/mixed; boundary=""3c4d5753-d325-4806-8c80-38f4a5fbe523""

--3c4d5753-d325-4806-8c80-38f4a5fbe523
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 1856004745

POST /values HTTP/1.1
Host: example.com
Content-Type: text/plain; charset=utf-8

foo
--3c4d5753-d325-4806-8c80-38f4a5fbe523--

--d3df74a8-8212-4c2a-b4fb-d713a4ba383e
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: -2010824035

POST /values HTTP/1.1
Host: example.com
Content-Type: text/plain; charset=utf-8

bar
--d3df74a8-8212-4c2a-b4fb-d713a4ba383e--
";

            byte[] requestBytes = Encoding.UTF8.GetBytes(batchRequest);
            httpContext.Request.Body          = new MemoryStream(requestBytes);
            httpContext.Request.ContentType   = "multipart/mixed;boundary=\"d3df74a8-8212-4c2a-b4fb-d713a4ba383e\"";
            httpContext.Request.ContentLength = 827;

            IEdmModel model = new EdmModel();

            httpContext.ODataFeature().PrefixName = "odata";
            httpContext.RequestServices = BuildServiceProvider(opt => opt.AddModel("odata", model).EnableContinueOnErrorHeader = enableContinueOnError);

            if (preferenceHeader != null)
            {
                httpContext.Request.Headers.Add("prefer", preferenceHeader);
            }

            httpContext.Response.Body = new MemoryStream();
            batchHandler.PrefixName   = "odata";

            // Act
            await batchHandler.ProcessBatchAsync(httpContext, handler);

            string responseBody = httpContext.Response.ReadBody();

            // Assert
            Assert.NotNull(responseBody);

            // #1 response
            Assert.Contains("http://example.com/", responseBody);

            // #2 bad response
            Assert.Contains("Bad Request", responseBody);
            Assert.Contains("http://example.com/values,foo", responseBody);

            // #3 response
            if (hasThirdResponse)
            {
                Assert.Contains("http://example.com/values,bar", responseBody);
            }
            else
            {
                Assert.DoesNotContain("http://example.com/values,bar", responseBody);
            }
        }
        private static void AddProcedures(this EdmModel model, IEnumerable <ProcedureConfiguration> configurations, EdmEntityContainer container,
                                          Dictionary <Type, IEdmType> edmTypeMap, IDictionary <string, EdmNavigationSource> edmNavigationSourceMap)
        {
            Contract.Assert(model != null, "Model can't be null");

            ValidateActionOverload(configurations.OfType <ActionConfiguration>());

            foreach (ProcedureConfiguration procedure in configurations)
            {
                IEdmTypeReference returnReference = GetEdmTypeReference(
                    edmTypeMap,
                    procedure.ReturnType,
                    procedure.ReturnType != null && EdmLibHelpers.IsNullable(procedure.ReturnType.ClrType));
                IEdmExpression     expression     = GetEdmEntitySetExpression(edmNavigationSourceMap, procedure);
                IEdmPathExpression pathExpression = procedure.EntitySetPath != null
                    ? new EdmPathExpression(procedure.EntitySetPath)
                    : null;

                EdmOperationImport operationImport;

                switch (procedure.Kind)
                {
                case ProcedureKind.Action:
                    operationImport = CreateActionImport(procedure, container, returnReference, expression, pathExpression);
                    break;

                case ProcedureKind.Function:
                    operationImport = CreateFunctionImport((FunctionConfiguration)procedure, container, returnReference, expression, pathExpression);
                    break;

                case ProcedureKind.ServiceOperation:
                    Contract.Assert(false, "ServiceOperations are not supported.");
                    goto default;

                default:
                    Contract.Assert(false, "Unsupported ProcedureKind");
                    return;
                }

                EdmOperation operation = (EdmOperation)operationImport.Operation;
                if (procedure.IsBindable && procedure.Title != null & procedure.Title != procedure.Name)
                {
                    model.SetOperationTitleAnnotation(operation, new OperationTitleAnnotation(procedure.Title));
                }

                if (procedure.IsBindable &&
                    procedure.NavigationSource != null &&
                    edmNavigationSourceMap.ContainsKey(procedure.NavigationSource.Name))
                {
                    model.SetAnnotationValue(operation, new ReturnedEntitySetAnnotation(procedure.NavigationSource.Name));
                }

                AddProcedureParameters(operation, procedure, edmTypeMap);

                if (procedure.IsBindable)
                {
                    AddProcedureLinkBuilder(model, operation, procedure);
                    ValidateProcedureEntitySetPath(model, operationImport, procedure);
                }
                else
                {
                    container.AddElement(operationImport);
                }

                model.AddElement(operation);
            }
        }
Exemplo n.º 43
0
        public async Task ProcessBatchAsync_DoesNotCopyContentHeadersToGetAndDelete()
        {
            // Arrange
            string batchRequest = @"
--40e2c6b6-e6ce-43aa-9985-ddc12dc4bb9b
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 483818399

GET / HTTP/1.1
Host: example.com


--40e2c6b6-e6ce-43aa-9985-ddc12dc4bb9b
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 1035669256

DELETE / HTTP/1.1
Host: example.com


--40e2c6b6-e6ce-43aa-9985-ddc12dc4bb9b
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 632310651

POST /values HTTP/1.1
Host: example.com
Content-Type: text/plain; charset=utf-8

bar
--40e2c6b6-e6ce-43aa-9985-ddc12dc4bb9b--
";

            RequestDelegate handler = async context =>
            {
                HttpRequest request         = context.Request;
                string      responseContent = $"{request.Method},{request.ContentLength},{request.ContentType}";
                await context.Response.WriteAsync(responseContent);
            };

            HttpContext httpContext = HttpContextHelper.Create("Post", "http://example.com/$batch");

            byte[] requestBytes = Encoding.UTF8.GetBytes(batchRequest);
            httpContext.Request.Body          = new MemoryStream(requestBytes);
            httpContext.Request.ContentType   = "multipart/mixed;boundary=40e2c6b6-e6ce-43aa-9985-ddc12dc4bb9b";
            httpContext.Request.ContentLength = requestBytes.Length;

            IEdmModel model = new EdmModel();

            httpContext.ODataFeature().PrefixName = "odata";
            httpContext.RequestServices = BuildServiceProvider(opt => opt.AddModel("odata", model));

            DefaultODataBatchHandler batchHandler = new DefaultODataBatchHandler();

            httpContext.Response.Body = new MemoryStream();
            batchHandler.PrefixName   = "odata";

            // Act
            await batchHandler.ProcessBatchAsync(httpContext, handler);

            string responseBody = httpContext.Response.ReadBody();

            // Assert
            Assert.NotNull(responseBody);
            Assert.Contains("GET,,", responseBody);
            Assert.Contains("DELETE,,", responseBody);
            Assert.Contains("POST,3,text/plain; charset=utf-8", responseBody);
        }
Exemplo n.º 44
0
 internal EdmModelParentMap(EdmModel edmModel)
 {
     model = edmModel;
 }
        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.Test.AspNet.OData.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;
        }
Exemplo n.º 46
0
 static FallbackModel()
 {
     var builder = new ODataConventionModelBuilder();
     builder.Namespace = "Microsoft.Restier.Publishers.OData.Test";
     builder.EntitySet<Order>("Orders");
     builder.EntitySet<Person>("People");
     Model = (EdmModel)builder.GetEdmModel();
 }
Exemplo n.º 47
0
        public void AutoComputeETagWithOptimisticConcurrencyControlAnnotationForDerivedType()
        {
            const string expected = "{" +
                                    "\"@odata.context\":\"http://example.com/$metadata#Managers/$entity\"," +
                                    "\"@odata.id\":\"Managers(123)\"," +
                                    "\"@odata.etag\":\"W/\\\"'lucy',10\\\"\"," +
                                    "\"@odata.editLink\":\"Managers(123)\"," +
                                    "\"@odata.mediaEditLink\":\"Managers(123)/$value\"," +
                                    "\"ID\":123," +
                                    "\"Name\":\"lucy\"," +
                                    "\"Class\":12306," +
                                    "\"Alias\":\"lily\"," +
                                    "\"TeamSize\":10}";
            EdmModel model = new EdmModel();

            EdmEntityType personType = new EdmEntityType("MyNs", "Person", null, false, false, true);

            personType.AddKeys(personType.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            var nameProperty = personType.AddStructuralProperty("Name", EdmCoreModel.Instance.GetString(isNullable: true));

            personType.AddStructuralProperty("Class", EdmPrimitiveTypeKind.Int32);
            personType.AddStructuralProperty("Alias", EdmCoreModel.Instance.GetString(isNullable: true), null, EdmConcurrencyMode.Fixed);
            EdmEntityType managerType = new EdmEntityType("MyNs", "Manager", personType, false, false, true);
            var           tsProperty  = managerType.AddStructuralProperty("TeamSize", EdmPrimitiveTypeKind.Int32);

            var container = new EdmEntityContainer("MyNs", "Container");

            model.AddElement(personType);
            model.AddElement(managerType);
            container.AddEntitySet("Managers", managerType);
            model.AddElement(container);

            IEdmEntitySet managerSet = model.FindDeclaredEntitySet("Managers");

            model.SetOptimisticConcurrencyControlAnnotation(managerSet, new[] { nameProperty, tsProperty });

            ODataEntry entry = new ODataEntry
            {
                Properties = new[]
                {
                    new ODataProperty {
                        Name = "ID", Value = 123
                    },
                    new ODataProperty {
                        Name = "Name", Value = "lucy"
                    },
                    new ODataProperty {
                        Name = "Class", Value = 12306
                    },
                    new ODataProperty {
                        Name = "Alias", Value = "lily"
                    },
                    new ODataProperty {
                        Name = "TeamSize", Value = 10
                    },
                }
            };

            string actual = GetWriterOutputForContentTypeAndKnobValue(entry, model, managerSet, managerType);

            Assert.Equal(expected, actual);
        }
Exemplo n.º 48
0
 protected virtual void VisitEntityContainers(EdmModel model, IEnumerable<EdmEntityContainer> entityContainers)
 {
     VisitCollection(entityContainers, VisitEdmEntityContainer);
 }
        public void Build_builds_valid_DbDatabaseMapping_for_functions()
        {
            var rowTypeProperty = CreateStoreProperty("p1", "int");

            var complexTypeProperty =
                EdmProperty.Create(
                    "p2",
                    TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32)));

            var functionImportReturnComplexType =
                ComplexType.Create(
                    "CT",
                    "entityModel",
                    DataSpace.CSpace,
                    new[] { complexTypeProperty }, null);

            var storeFunction = EdmFunction.Create(
                "f_s",
                "storeModel",
                DataSpace.SSpace,
                new EdmFunctionPayload
            {
                IsComposable     = true,
                IsFunctionImport = false,
                ReturnParameters =
                    new[]
                {
                    FunctionParameter.Create(
                        "ReturnType",
                        RowType.Create(new[] { rowTypeProperty }, null).GetCollectionType(),
                        ParameterMode.ReturnValue)
                }
            },
                null);

            var functionImport =
                EdmFunction.Create(
                    "f_c",
                    "entityModel",
                    DataSpace.CSpace,
                    new EdmFunctionPayload
            {
                IsComposable     = true,
                IsFunctionImport = true,
                ReturnParameters =
                    new[]
                {
                    FunctionParameter.Create(
                        "ReturnType",
                        functionImportReturnComplexType.GetCollectionType(),
                        ParameterMode.ReturnValue)
                }
            },
                    null);

            var modelContainer = EntityContainer.Create("C_C", DataSpace.CSpace, new EntitySet[0], new[] { functionImport }, null);
            var storeContainer = EntityContainer.Create("C_S", DataSpace.SSpace, new EntitySet[0], null, null);

            var storeModel = EdmModel.CreateStoreModel(storeContainer, null, null);

            storeModel.AddItem(storeFunction);

            var mappingContext = new SimpleMappingContext(storeModel, true);

            mappingContext.AddMapping(rowTypeProperty, complexTypeProperty);
            mappingContext.AddMapping(storeFunction, functionImport);
            mappingContext.AddMapping(storeContainer, modelContainer);

            var entityModel = DbDatabaseMappingBuilder.Build(mappingContext).ConceptualModel;

            Assert.NotNull(entityModel);
            Assert.Equal(new[] { "f_c" }, entityModel.Containers.Single().FunctionImports.Select(f => f.Name));
            Assert.Equal(new[] { "CT" }, entityModel.ComplexTypes.Select(t => t.Name));
        }
Exemplo n.º 50
0
        public ODataWriterDerivedTypeConstraintTests()
        {
            // Create the basic model
            edmModel = new EdmModel();

            // Entity Type
            edmCustomerType = new EdmEntityType("NS", "Customer");
            edmCustomerType.AddKeys(edmCustomerType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));

            edmVipCustomerType = new EdmEntityType("NS", "VipCustomer", edmCustomerType);
            edmVipCustomerType.AddStructuralProperty("Vip", EdmPrimitiveTypeKind.String);

            edmNormalCustomerType = new EdmEntityType("NS", "NormalCustomer", edmCustomerType);
            edmNormalCustomerType.AddStructuralProperty("Email", EdmPrimitiveTypeKind.String);

            edmModel.AddElements(new[] { edmCustomerType, edmVipCustomerType, edmNormalCustomerType });

            // Complex type
            edmAddressType = new EdmComplexType("NS", "Address");
            edmAddressType.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String);

            edmUsAddressType = new EdmComplexType("NS", "UsAddress", edmAddressType);
            edmUsAddressType.AddStructuralProperty("ZipCode", EdmPrimitiveTypeKind.Int32);

            edmCnAddressType = new EdmComplexType("NS", "CnAddress", edmAddressType);
            edmCnAddressType.AddStructuralProperty("PostCode", EdmPrimitiveTypeKind.String);

            edmModel.AddElements(new[] { edmAddressType, edmUsAddressType, edmCnAddressType });

            // EntityContainer
            EdmEntityContainer container = new EdmEntityContainer("NS", "Default");

            edmMe        = container.AddSingleton("Me", edmCustomerType);
            edmCustomers = container.AddEntitySet("Customers", edmCustomerType);
            edmModel.AddElement(container);

            // resource
            odataCustomerResource = new ODataResource
            {
                TypeName   = "NS.Customer",
                Properties = new[] { new ODataProperty {
                                         Name = "Id", Value = 7
                                     } }
            };

            odataVipResource = new ODataResource
            {
                TypeName   = "NS.VipCustomer",
                Properties = new[] { new ODataProperty {
                                         Name = "Id", Value = 8
                                     }, new ODataProperty {
                                         Name = "Vip", Value = "Boss"
                                     } }
            };

            odataNormalResource = new ODataResource
            {
                TypeName   = "NS.NormalCustomer",
                Properties = new[] { new ODataProperty {
                                         Name = "Id", Value = 9
                                     }, new ODataProperty {
                                         Name = "Email", Value = "*****@*****.**"
                                     } }
            };

            odataAddressResource = new ODataResource
            {
                TypeName   = "NS.Address",
                Properties = new[] { new ODataProperty {
                                         Name = "Street", Value = "Way"
                                     } }
            };

            odataUsAddressResource = new ODataResource
            {
                TypeName   = "NS.UsAddress",
                Properties = new[] { new ODataProperty {
                                         Name = "Street", Value = "RedWay"
                                     }, new ODataProperty {
                                         Name = "ZipCode", Value = 98052
                                     } }
            };

            odataCnAddressResource = new ODataResource
            {
                TypeName   = "NS.CnAddress",
                Properties = new[] { new ODataProperty {
                                         Name = "Street", Value = "ShaWay"
                                     }, new ODataProperty {
                                         Name = "PostCode", Value = "201100"
                                     } }
            };
        }
        private IEdmModel GetModel()
        {
            if (myModel == null)
            {
                myModel = new EdmModel();

                EdmComplexType shippingAddress = new EdmComplexType("MyNS", "ShippingAddress");
                shippingAddress.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String);
                shippingAddress.AddStructuralProperty("City", EdmPrimitiveTypeKind.String);
                shippingAddress.AddStructuralProperty("Region", EdmPrimitiveTypeKind.String);
                shippingAddress.AddStructuralProperty("PostalCode", EdmPrimitiveTypeKind.String);
                myModel.AddElement(shippingAddress);

                EdmComplexTypeReference shippingAddressReference = new EdmComplexTypeReference(shippingAddress, true);

                EdmEntityType orderType = new EdmEntityType("MyNS", "Order");
                orderType.AddKeys(orderType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));
                orderType.AddStructuralProperty("ShippingAddress", shippingAddressReference);
                myModel.AddElement(orderType);

                EdmEntityType customer = new EdmEntityType("MyNS", "Customer");
                customer.AddStructuralProperty("ContactName", EdmPrimitiveTypeKind.String);
                var customerId = customer.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);
                customer.AddKeys(customerId);
                customer.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
                {
                    Name               = "Orders",
                    Target             = orderType,
                    TargetMultiplicity = EdmMultiplicity.Many,
                });
                myModel.AddElement(customer);

                var productType = new EdmEntityType("MyNS", "Product");
                var productId   = productType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);
                productType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
                productType.AddKeys(productId);
                myModel.AddElement(productType);

                var physicalProductType = new EdmEntityType("MyNS", "PhysicalProduct", productType);
                physicalProductType.AddStructuralProperty("Material", EdmPrimitiveTypeKind.String);
                myModel.AddElement(physicalProductType);

                var productDetailType = new EdmEntityType("MyNS", "ProductDetail");
                var productDetailId   = productDetailType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);
                productDetailType.AddStructuralProperty("Detail", EdmPrimitiveTypeKind.String);
                productDetailType.AddKeys(productDetailId);
                myModel.AddElement(productDetailType);

                var productDetailItemType = new EdmEntityType("MyNS", "ProductDetailItem");
                var productDetailItemId   = productDetailItemType.AddStructuralProperty("ItemId", EdmPrimitiveTypeKind.Int32);
                productDetailItemType.AddStructuralProperty("Description", EdmPrimitiveTypeKind.String);
                productDetailItemType.AddKeys(productDetailItemId);
                myModel.AddElement(productDetailItemType);

                productType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
                {
                    Name               = "Details",
                    Target             = productDetailType,
                    TargetMultiplicity = EdmMultiplicity.Many,
                    ContainsTarget     = true,
                });
                productDetailType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
                {
                    Name               = "Items",
                    Target             = productDetailItemType,
                    TargetMultiplicity = EdmMultiplicity.Many,
                    ContainsTarget     = true,
                });

                var favouriteProducts = customer.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
                {
                    Name               = "FavouriteProducts",
                    Target             = productType,
                    TargetMultiplicity = EdmMultiplicity.Many,
                });
                var productBeingViewed = customer.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
                {
                    Name               = "ProductBeingViewed",
                    Target             = productType,
                    TargetMultiplicity = EdmMultiplicity.ZeroOrOne,
                });

                EdmEntityContainer container = new EdmEntityContainer("MyNS", "Example30");
                var products  = container.AddEntitySet("Products", productType);
                var customers = container.AddEntitySet("Customers", customer);
                customers.AddNavigationTarget(favouriteProducts, products);
                customers.AddNavigationTarget(productBeingViewed, products);
                container.AddEntitySet("Orders", orderType);
                myModel.AddElement(container);
            }
            return(myModel);
        }
 internal EdmModelParentMap(EdmModel edmModel)
 {
     model = edmModel;
 }
Exemplo n.º 53
0
        protected virtual async Task BatchCore()
        {
            var actionDescriptors    = GetService <IActionDescriptorCollectionProvider>().ActionDescriptors;
            var actionInvokerFactory = GetService <IActionInvokerFactory>();

            String basePath = "";

            if (base.HttpContext.Request.PathBase.HasValue)
            {
                basePath = base.HttpContext.Request.PathBase;
            }
            else
            {
                int i = base.HttpContext.Request.Path.Value.IndexOf('/', 1);
                if (i > 0)
                {
                    basePath = base.HttpContext.Request.Path.Value.Substring(0, i);
                }
            }
            Uri baseUri = UriHelper.GetBaseUri(base.Request);

            OeBatchMessage batchMessage = OeBatchMessage.CreateBatchMessage(EdmModel, baseUri, base.HttpContext.Request.Body, base.HttpContext.Request.ContentType);
            OeDataAdapter  dataAdapter  = null;
            Object         dataContext  = null;

            try
            {
                IEdmModel refModel = null;
                foreach (OeOperationMessage operation in batchMessage.Changeset)
                {
                    if (dataContext == null)
                    {
                        refModel    = EdmModel.GetEdmModel(operation.EntitySet.Container);
                        dataAdapter = refModel.GetDataAdapter(operation.EntitySet.Container);
                        dataContext = dataAdapter.CreateDataContext();
                    }

                    OeEntitySetAdapter entitySetAdapter = refModel.GetEntitySetAdapter(operation.EntitySet);
                    String             path             = basePath + "/" + entitySetAdapter.EntitySetName;

                    List <ActionDescriptor> candidates = OeRouter.SelectCandidates(actionDescriptors.Items, base.RouteData.Values, path, operation.Method);
                    if (candidates.Count > 1)
                    {
                        throw new AmbiguousActionException(String.Join(Environment.NewLine, candidates.Select(c => c.DisplayName)));
                    }
                    if (candidates.Count == 0)
                    {
                        throw new InvalidOperationException("Action " + operation.Method + " for controller " + basePath + " not found");
                    }

                    Object entity;
                    if (operation.Method == ODataConstants.MethodPatch)
                    {
                        var properties = new Dictionary <String, Object>();
                        foreach (ODataProperty odataProperty in operation.Entry.Properties)
                        {
                            PropertyInfo propertyInfo = entitySetAdapter.EntityType.GetProperty(odataProperty.Name);
                            properties[odataProperty.Name] = OeEdmClrHelper.GetClrValue(propertyInfo.PropertyType, odataProperty.Value);
                        }
                        entity = properties;
                    }
                    else
                    {
                        entity = OeEdmClrHelper.CreateEntity(entitySetAdapter.EntityType, operation.Entry);
                    }

                    var modelState = new OeBatchFilterAttributeAttribute.BatchModelStateDictionary()
                    {
                        Entity      = entity,
                        DataContext = new OeDataContext(entitySetAdapter, refModel, dataContext, operation)
                    };
                    OnBeforeInvokeController(modelState.DataContext, operation.Entry);

                    var            actionContext = new ActionContext(base.HttpContext, base.HttpContext.GetRouteData(), candidates[0], modelState);
                    IActionInvoker actionInvoker = actionInvokerFactory.CreateInvoker(actionContext);
                    await actionInvoker.InvokeAsync();
                }

                await SaveChangesAsync(dataContext).ConfigureAwait(false);
            }
            finally
            {
                if (dataContext != null)
                {
                    dataAdapter.CloseDataContext(dataContext);
                }
            }

            base.HttpContext.Response.ContentType = base.HttpContext.Request.ContentType;
            var batchWriter = new OeBatchWriter(EdmModel, baseUri);

            batchWriter.Write(base.HttpContext.Response.Body, batchMessage);
        }