Пример #1
0
        private IEdmProperty CreateStructuralTypeEnumPropertyBody(EdmStructuredType type, StructuralTypeConfiguration config, EnumPropertyConfiguration enumProperty)
        {
            Type     enumPropertyType = TypeHelper.GetUnderlyingTypeOrSelf(enumProperty.RelatedClrType);
            IEdmType edmType          = GetEdmType(enumPropertyType);

            if (edmType == null)
            {
                throw Error.InvalidOperation(SRResources.EnumTypeDoesNotExist, enumPropertyType.Name);
            }

            IEdmEnumType      enumType          = (IEdmEnumType)edmType;
            IEdmTypeReference enumTypeReference = new EdmEnumTypeReference(enumType, enumProperty.OptionalProperty);

            // Set concurrency token if is entity type, and concurrency token is true
            EdmConcurrencyMode enumConcurrencyMode = EdmConcurrencyMode.None;

            if (config.Kind == EdmTypeKind.Entity && enumProperty.ConcurrencyToken)
            {
                enumConcurrencyMode = EdmConcurrencyMode.Fixed;
            }

            return(type.AddStructuralProperty(
                       enumProperty.Name,
                       enumTypeReference,
                       defaultValue: null,
                       concurrencyMode: enumConcurrencyMode));
        }
Пример #2
0
        public static void SetSearchRestrictionsCapabilitiesAnnotation(this EdmModel model, IEdmEntitySet entitySet, bool searchable, CapabilitiesSearchExpressions unsupported)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }
            if (entitySet == null)
            {
                throw new ArgumentNullException("entitySet");
            }

            var target     = entitySet;
            var term       = SearchRestrictionsTerm;
            var name       = new EdmEnumTypeReference(SearchExpressionsType, false).ToStringLiteral((long)unsupported);
            var properties = new IEdmPropertyConstructor[]
            {
                new EdmPropertyConstructor("Searchable", new EdmBooleanConstant(searchable)),
                new EdmPropertyConstructor("UnsupportedExpressions", new EdmEnumMemberReferenceExpression(SearchExpressionsType.Members.Single(m => m.Name == name))),
            };
            var record = new EdmRecordExpression(properties);

            var annotation = new EdmAnnotation(target, term, record);

            annotation.SetSerializationLocation(model, entitySet.ToSerializationLocation());
            model.AddVocabularyAnnotation(annotation);
        }
        public void CreateODataCollectionValue_CanSerialize_IEdmObjects()
        {
            // Arrange
            Mock <IEdmEnumObject> edmEnumObject = new Mock <IEdmEnumObject>();

            IEdmEnumObject[]       collection        = { edmEnumObject.Object };
            ODataSerializerContext serializerContext = new ODataSerializerContext();
            IEdmEnumTypeReference  elementType       = new EdmEnumTypeReference(new EdmEnumType("NS", "EnumType"), isNullable: true);

            edmEnumObject.Setup(s => s.GetEdmType()).Returns(elementType);

            Mock <ODataSerializerProvider> serializerProvider = new Mock <ODataSerializerProvider>();
            Mock <ODataEnumSerializer>     elementSerializer  = new Mock <ODataEnumSerializer>(MockBehavior.Strict, serializerProvider.Object);

            serializerProvider.Setup(s => s.GetEdmTypeSerializer(elementType)).Returns(elementSerializer.Object);
            elementSerializer.Setup(s => s.CreateODataEnumValue(collection[0], elementType, serializerContext)).Returns(new ODataEnumValue("1", "NS.EnumType")).Verifiable();

            ODataCollectionSerializer serializer = new ODataCollectionSerializer(serializerProvider.Object);

            // Act
            serializer.CreateODataCollectionValue(collection, elementType, serializerContext);

            // Assert
            elementSerializer.Verify();
        }
        public void ParseWithCustomFunction_EnumParameter()
        {
            try
            {
                var enumType = new EdmEnumType("Fully.Qualified.Namespace", "NonFlagShape", EdmPrimitiveTypeKind.SByte, false);
                enumType.AddMember("Rectangle", new EdmEnumMemberValue(1));
                enumType.AddMember("Triangle", new EdmEnumMemberValue(2));
                enumType.AddMember("foursquare", new EdmEnumMemberValue(3));
                var enumTypeRef = new EdmEnumTypeReference(enumType, false);

                FunctionSignatureWithReturnType signature =
                    new FunctionSignatureWithReturnType(EdmCoreModel.Instance.GetBoolean(false), enumTypeRef);

                CustomUriFunctions.AddCustomUriFunction("enumFunc", signature);

                var            fullUri = new Uri("http://www.odata.com/OData/People" + "?$filter=enumFunc('Rectangle')");
                ODataUriParser parser  = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://www.odata.com/OData/"), fullUri);

                var enumFuncWithArgs = parser.ParseFilter().Expression.ShouldBeSingleValueFunctionCallQueryNode("enumFunc").Parameters.ToList();
                enumFuncWithArgs[0].ShouldBeEnumNode(enumType, "Rectangle");
            }
            finally
            {
                Assert.True(CustomUriFunctions.RemoveCustomUriFunction("enumFunc"));
            }
        }
Пример #5
0
        public async Task WriteItemAsync_WritesEnumCollectionItem(string enumValue, string expected)
        {
            var model = new EdmModel();

            var colorEnumType = new EdmEnumType("NS", "Color");

            colorEnumType.AddMember(new EdmEnumMember(colorEnumType, "Black", new EdmEnumMemberValue(0)));
            colorEnumType.AddMember(new EdmEnumMember(colorEnumType, "White", new EdmEnumMemberValue(0)));
            model.AddElement(colorEnumType);

            var collectionStart = new ODataCollectionStart
            {
                SerializationInfo = new ODataCollectionStartSerializationInfo
                {
                    CollectionTypeName = "Collection(NS.Color)"
                }
            };
            var itemTypeReference = new EdmEnumTypeReference(colorEnumType, true);

            var result = await SetupJsonLightCollectionWriterAndRunTestAsync(
                async (jsonLightCollectionWriter) =>
            {
                await jsonLightCollectionWriter.WriteStartAsync(collectionStart);
                await jsonLightCollectionWriter.WriteItemAsync(new ODataEnumValue(enumValue));
                await jsonLightCollectionWriter.WriteEndAsync();
            },
                model,
                itemTypeReference);

            Assert.Equal("{\"@odata.context\":\"http://odata.org/test/$metadata#Collection(NS.Color)\"," +
                         $"\"value\":[{expected}]}}", result);
        }
Пример #6
0
        private static object ConvertEnumValue(ODataEnumValue enumValue, ref IEdmTypeReference propertyType,
                                               IODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext)
        {
            IEdmEnumTypeReference edmEnumType;

            if (propertyType == null)
            {
                // dynamic enum property
                Contract.Assert(!String.IsNullOrEmpty(enumValue.TypeName),
                                "ODataLib should have verified that dynamic enum value has a type name since we provided metadata.");
                IEdmModel model   = readContext.Model;
                IEdmType  edmType = model.FindType(enumValue.TypeName);
                Contract.Assert(edmType.TypeKind == EdmTypeKind.Enum, "ODataLib should have verified that enum value has a enum resource type.");
                edmEnumType  = new EdmEnumTypeReference(edmType as IEdmEnumType, isNullable: true);
                propertyType = edmEnumType;
            }
            else
            {
                edmEnumType = propertyType.AsEnum();
            }

            IODataEdmTypeDeserializer deserializer = deserializerProvider.GetEdmTypeDeserializer(edmEnumType);

            return(deserializer.ReadInline(enumValue, propertyType, readContext));
        }
Пример #7
0
        public void CreateEdmTypeSchemaReturnSchemaForEnumType(bool isNullable)
        {
            // Arrange
            IEdmModel    model    = EdmModelHelper.TripServiceModel;
            IEdmEnumType enumType = model.SchemaElements.OfType <IEdmEnumType>().First(c => c.Name == "PersonGender");

            Assert.NotNull(enumType); // guard
            IEdmEnumTypeReference enumTypeReference = new EdmEnumTypeReference(enumType, isNullable);
            ODataContext          context           = new ODataContext(model);

            // Act
            var schema = context.CreateEdmTypeSchema(enumTypeReference);

            // & Assert
            Assert.NotNull(schema);
            Assert.Equal(isNullable, schema.Nullable);
            Assert.Null(schema.Reference);
            Assert.NotNull(schema.AnyOf);
            Assert.NotEmpty(schema.AnyOf);
            var anyOf = Assert.Single(schema.AnyOf);

            Assert.NotNull(anyOf.Reference);
            Assert.Equal(ReferenceType.Schema, anyOf.Reference.Type);
            Assert.Equal(enumType.FullTypeName(), anyOf.Reference.Id);
        }
Пример #8
0
        public static IEdmTypeReference GetEdmTypeReference(this IEdmModel edmModel, Type clrType)
        {
            IEdmTypeReference edmTypeRef;
            bool nullable;
            Type underlyingType = Nullable.GetUnderlyingType(clrType);

            if (underlyingType == null)
            {
                nullable = clrType.IsClass;
            }
            else
            {
                clrType  = underlyingType;
                nullable = true;
            }

            IEdmPrimitiveType primitiveEdmType = PrimitiveTypeHelper.GetPrimitiveType(clrType);

            if (primitiveEdmType == null)
            {
                var edmEnumType = (IEdmEnumType)edmModel.FindType(clrType.FullName);
                edmTypeRef = new EdmEnumTypeReference(edmEnumType, nullable);
            }
            else
            {
                edmTypeRef = EdmCoreModel.Instance.GetPrimitive(primitiveEdmType.PrimitiveKind, nullable);
            }

            return(edmTypeRef);
        }
Пример #9
0
        public void CreateCollectionWriterWithEnumAsItemType()
        {
            var writer            = new ODataMessageWriter(new DummyRequestMessage());
            var entityElementType = new EdmEnumTypeReference(new EdmEnumType("FakeNS", "FakeEnum"), true);
            var collectionWriter  = writer.CreateODataCollectionWriter(entityElementType);

            Assert.True(collectionWriter != null, "CreateODataCollectionWriter with enum item type failed.");
        }
Пример #10
0
        private static void VerifyEnumVsStringFilterExpressionReverse(FilterClause filter)
        {
            var enumtypeRef = new EdmEnumTypeReference(UriEdmHelpers.FindEnumTypeFromModel(HardCodedTestModel.TestModel, "Fully.Qualified.Namespace.ColorPattern"), true);
            var bin         = filter.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal).And;

            bin.Right.ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPet2PetColorPatternProperty());
            bin.Left.ShouldBeEnumNode(new ODataEnumValue("2", enumtypeRef.ODataFullName()));
        }
Пример #11
0
        private EdmStructuralProperty?BuildStructuralProperty(Dictionary <Type, EntityTypeInfo> entityTypes,
                                                              Dictionary <Type, EdmEnumType> enumTypes, Dictionary <Type, EdmComplexType> complexTypes, PropertyInfo clrProperty)
        {
            bool isNullable           = !_metadataProvider.IsRequired(clrProperty);
            IEdmTypeReference?typeRef = PrimitiveTypeHelper.GetPrimitiveTypeRef(clrProperty, isNullable);

            if (typeRef == null)
            {
                Type?underlyingType = null;
                if (clrProperty.PropertyType.IsEnum ||
                    (underlyingType = Nullable.GetUnderlyingType(clrProperty.PropertyType)) != null && underlyingType.IsEnum)
                {
                    Type clrPropertyType = underlyingType ?? clrProperty.PropertyType;
                    if (!enumTypes.TryGetValue(clrPropertyType, out EdmEnumType? edmEnumType))
                    {
                        edmEnumType = OeEdmModelBuilder.CreateEdmEnumType(clrPropertyType);
                        enumTypes.Add(clrPropertyType, edmEnumType);
                    }
                    typeRef = new EdmEnumTypeReference(edmEnumType, underlyingType != null);
                }
                else
                {
                    if (complexTypes.TryGetValue(clrProperty.PropertyType, out EdmComplexType? edmComplexType))
                    {
                        typeRef = new EdmComplexTypeReference(edmComplexType, clrProperty.PropertyType.IsClass);
                    }
                    else
                    {
                        FKeyInfo?fkeyInfo = FKeyInfo.Create(_metadataProvider, entityTypes, this, clrProperty);
                        if (fkeyInfo != null)
                        {
                            _navigationClrProperties.Add(fkeyInfo);
                        }
                        return(null);
                    }
                }
            }
            else
            {
                if (clrProperty.PropertyType == typeof(DateTime?) && enumTypes.ContainsKey(typeof(DateTime?)))
                {
                    var edmType = enumTypes[typeof(DateTime?)];
                    typeRef = new EdmEnumTypeReference(edmType, true);
                }
            }

            EdmStructuralProperty edmProperty = clrProperty is Infrastructure.OeShadowPropertyInfo ?
                                                new OeEdmStructuralShadowProperty(EdmType, clrProperty.Name, typeRef, clrProperty) :
                                                new EdmStructuralProperty(EdmType, clrProperty.Name, typeRef);

            EdmType.AddProperty(edmProperty);
            if (_metadataProvider.IsKey(clrProperty))
            {
                _keyProperties.Add(new KeyValuePair <PropertyInfo, EdmStructuralProperty>(clrProperty, edmProperty));
            }

            return(edmProperty);
        }
Пример #12
0
        public void CloneForEnumTypeShouldBeExpect(bool nullable)
        {
            EdmEnumType          enumType          = new EdmEnumType("NS", "MyEnum");
            EdmEnumTypeReference enumTypeReference = new EdmEnumTypeReference(enumType, isNullable: nullable);

            IEdmTypeReference clonedType = enumTypeReference.Clone(nullable);

            Assert.IsType <EdmEnumTypeReference>(clonedType);
            Assert.Equal(nullable, clonedType.IsNullable);
        }
Пример #13
0
        public void CloneForEnumTypeShouldBeExpect(bool nullable)
        {
            EdmEnumType          enumType          = new EdmEnumType("NS", "MyEnum");
            EdmEnumTypeReference enumTypeReference = new EdmEnumTypeReference(enumType, isNullable: nullable);

            IEdmTypeReference clonedType = enumTypeReference.Clone(nullable);

            clonedType.Should().BeOfType <EdmEnumTypeReference>();
            clonedType.IsNullable.Should().Be(nullable);
        }
Пример #14
0
        private void BuildProperty(Dictionary <Type, EntityTypeInfo> entityTypes,
                                   Dictionary <Type, EdmEnumType> enumTypes, Dictionary <Type, EdmComplexType> complexTypes, PropertyDescriptor clrProperty)
        {
            IEdmTypeReference typeRef = PrimitiveTypeHelper.GetPrimitiveTypeRef(clrProperty);

            if (typeRef == null)
            {
                EdmEnumType edmEnumType;
                Type        underlyingType = null;
                if (clrProperty.PropertyType.GetTypeInfo().IsEnum ||
                    (underlyingType = Nullable.GetUnderlyingType(clrProperty.PropertyType)) != null && underlyingType.GetTypeInfo().IsEnum)
                {
                    Type clrPropertyType = underlyingType ?? clrProperty.PropertyType;
                    if (!enumTypes.TryGetValue(clrPropertyType, out edmEnumType))
                    {
                        edmEnumType = CreateEdmEnumType(clrPropertyType);
                        enumTypes.Add(clrPropertyType, edmEnumType);
                    }
                    typeRef = new EdmEnumTypeReference(edmEnumType, underlyingType != null);
                }
                else
                {
                    EdmComplexType edmComplexType;
                    if (complexTypes.TryGetValue(clrProperty.PropertyType, out edmComplexType))
                    {
                        typeRef = new EdmComplexTypeReference(edmComplexType, clrProperty.PropertyType.GetTypeInfo().IsClass);
                    }
                    else
                    {
                        FKeyInfo fkeyInfo = FKeyInfo.Create(_metadataProvider, entityTypes, this, clrProperty);
                        if (fkeyInfo != null)
                        {
                            _navigationClrProperties.Add(fkeyInfo);
                        }
                        return;
                    }
                }
            }
            else
            {
                if (clrProperty.PropertyType == typeof(DateTime?) && enumTypes.ContainsKey(typeof(DateTime?))) //zzz
                {
                    var edmType = enumTypes[typeof(DateTime?)];
                    typeRef = new EdmEnumTypeReference(edmType, true);
                }
            }

            var edmProperty = new EdmStructuralProperty(_edmType, clrProperty.Name, typeRef);

            _edmType.AddProperty(edmProperty);
            if (_metadataProvider.IsKey(clrProperty))
            {
                _keyProperties.Add(new KeyValuePair <PropertyDescriptor, EdmStructuralProperty>(clrProperty, edmProperty));
            }
        }
        public ODataAtomReaderEnumIntegrationTests()
        {
            this.userModel = new EdmModel();

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

            enumType.AddMember(red);
            enumType.AddMember("Green", new EdmIntegerConstant(2));
            enumType.AddMember("Blue", new EdmIntegerConstant(3));
            this.userModel.AddElement(enumType);

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

            enumFlagsType.AddMember("Red", new EdmIntegerConstant(1));
            enumFlagsType.AddMember("Green", new EdmIntegerConstant(2));
            enumFlagsType.AddMember("Blue", new EdmIntegerConstant(4));
            this.userModel.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)));
            this.userModel.AddElement(myComplexType);
            this.entityType.AddProperty(new EdmStructuralProperty(this.entityType, "MyComplexType", new EdmComplexTypeReference(myComplexType, true)));

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

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

            this.userModel.AddElement(this.entityType);

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

            this.entitySet = new EdmEntitySet(defaultContainer, "MySet", this.entityType);
            defaultContainer.AddEntitySet(this.entitySet.Name, this.entityType);
            this.userModel.AddElement(defaultContainer);
        }
        public void CreateEdmTypeSchemaReturnSchemaForEnumType(bool isNullable, OpenApiSpecVersion specVersion)
        {
            // Arrange
            IEdmModel    model    = EdmModelHelper.TripServiceModel;
            IEdmEnumType enumType = model.SchemaElements.OfType <IEdmEnumType>().First(c => c.Name == "PersonGender");

            Assert.NotNull(enumType); // guard
            IEdmEnumTypeReference enumTypeReference = new EdmEnumTypeReference(enumType, isNullable);
            ODataContext          context           = new ODataContext(model);

            context.Settings.OpenApiSpecVersion = specVersion;

            // Act
            var schema = context.CreateEdmTypeSchema(enumTypeReference);

            // & Assert
            Assert.NotNull(schema);


            if (specVersion == OpenApiSpecVersion.OpenApi2_0)
            {
                Assert.NotNull(schema.Reference);
                Assert.Null(schema.AnyOf);
                Assert.Equal(ReferenceType.Schema, schema.Reference.Type);
                Assert.Equal(enumType.FullTypeName(), schema.Reference.Id);
                Assert.Equal(isNullable, schema.Nullable);
            }
            else
            {
                if (isNullable)
                {
                    Assert.NotNull(schema.AnyOf);
                    Assert.NotEmpty(schema.AnyOf);
                    Assert.Null(schema.Reference);
                    Assert.Equal(2, schema.AnyOf.Count);
                    var anyOfRef = schema.AnyOf.FirstOrDefault();
                    Assert.NotNull(anyOfRef.Reference);
                    Assert.Equal(ReferenceType.Schema, anyOfRef.Reference.Type);
                    Assert.Equal(enumType.FullTypeName(), anyOfRef.Reference.Id);
                    var anyOfNull = schema.AnyOf.Skip(1).FirstOrDefault();
                    Assert.NotNull(anyOfNull.Type);
                    Assert.Equal("object", anyOfNull.Type);
                    Assert.True(anyOfNull.Nullable);
                }
                else
                {
                    Assert.Null(schema.AnyOf);
                    Assert.NotNull(schema.Reference);
                    Assert.Equal(ReferenceType.Schema, schema.Reference.Type);
                    Assert.Equal(enumType.FullTypeName(), schema.Reference.Id);
                }
            }
        }
Пример #17
0
        public void GetEdmType_Returns_EdmTypeInitializedByCtor()
        {
            // Arrange
            IEdmTypeReference           elementType    = new EdmEnumTypeReference(new EdmEnumType("NS", "Enum"), isNullable: false);
            IEdmCollectionTypeReference collectionType = new EdmCollectionTypeReference(new EdmCollectionType(elementType));

            // Act
            var edmObject = new EdmEnumObjectCollection(collectionType);

            // Assert
            Assert.Same(collectionType, edmObject.GetEdmType());
        }
Пример #18
0
        public void GetEdmTypeDeserializer_ReturnODataEnumDeserializer_ForEnumType()
        {
            // Arrange
            IEdmTypeReference edmType = new EdmEnumTypeReference(new EdmEnumType("TestModel", "Color"), isNullable: false);

            // Act
            ODataEdmTypeDeserializer deserializer = _deserializerProvider.GetEdmTypeDeserializer(edmType);

            // Assert
            Assert.NotNull(deserializer);
            Assert.IsType <ODataEnumDeserializer>(deserializer);
        }
        public static IEdmModel InterfaceCriticalKindValueMismatchOnlyUsingEnumTypeReferenceModel()
        {
            var model = new EdmModel();

            var badType    = new CustomEnumType("NS", "Enum", EdmTypeKind.Complex);
            var badTypeRef = new EdmEnumTypeReference(badType, true);
            var valueTerm  = new EdmTerm("NS", "Note", badTypeRef);

            model.AddElement(valueTerm);

            return(model);
        }
        public static IEdmModel InterfaceCriticalPropertyValueMustNotBeNullUsingEnumTypeReferenceModel()
        {
            var model = new EdmModel();

            var badType    = new CustomEnumType("NS", "Enum", (IEdmPrimitiveType)null);
            var badTypeRef = new EdmEnumTypeReference(badType, true);
            var valueTerm  = new EdmTerm("NS", "Note", badTypeRef);

            model.AddElement(valueTerm);

            return(model);
        }
        public void GetODataSerializer_Enum()
        {
            var serializerProvider        = new DefaultODataSerializerProvider(_edmModel);
            IEdmTypeReference edmEnumType = new EdmEnumTypeReference(new EdmEnumType("ODataDemo", "SupplierRating"), isNullable: false);
            var serializer = serializerProvider.GetEdmTypeSerializer(edmEnumType);

            Assert.NotNull(serializer);
            var enumSerializer = Assert.IsType <ODataEnumSerializer>(serializer);

            Assert.Equal(enumSerializer.EdmType, edmEnumType);
            Assert.Equal(enumSerializer.ODataPayloadKind, ODataPayloadKind.Property);
            Assert.Equal(enumSerializer.SerializerProvider, serializerProvider);
        }
        public async Task WriteEnumValueAsync_WritesNullForEnumValueAsNull()
        {
            var colorEnumValue            = new ODataEnumValue(null);
            var colorEdmEnumTypeReference = new EdmEnumTypeReference(this.colorEnumType, false);

            var result = await SetupJsonLightValueSerializerAndRunTestAsync(
                (jsonLightValueSerializer) =>
            {
                return(jsonLightValueSerializer.WriteEnumValueAsync(colorEnumValue, colorEdmEnumTypeReference));
            });

            Assert.Equal("null", result);
        }
        public static IEdmModel InterfaceCriticalPropertyValueMustNotBeNullUsingEnumMemberDeclaredTypeModel()
        {
            var model = new EdmModel();

            var enumType = new EdmEnumType("NS", "Enum");

            enumType.AddMember(new CustomEnumMember(null, "foo", new EdmIntegerConstant(5)));
            var enumTypeRef = new EdmEnumTypeReference(enumType, true);
            var valueTerm   = new EdmTerm("NS", "Note", enumTypeRef);

            model.AddElement(valueTerm);

            return(model);
        }
Пример #24
0
        /// <summary>
        /// Set Org.OData.Capabilities.V1.NavigationRestrictions to target.
        /// </summary>
        /// <param name="model">The model referenced to.</param>
        /// <param name="target">The target entity set to set the inline annotation.</param>
        /// <param name="navigability">This entity set supports navigability.</param>
        /// <param name="restrictedProperties">These properties have navigation restrictions on.</param>
        public static void SetNavigationRestrictionsAnnotation(this EdmModel model, IEdmEntitySet target,
                                                               CapabilitiesNavigationType navigability,
                                                               IEnumerable <Tuple <IEdmNavigationProperty, CapabilitiesNavigationType> > restrictedProperties)
        {
            if (model == null)
            {
                throw Error.ArgumentNull("model");
            }

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

            IEdmEnumType navigationType = model.GetCapabilitiesNavigationType();

            if (navigationType == null)
            {
                return;
            }

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

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

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

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

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

            model.SetVocabularyAnnotation(target, properties, CapabilitiesVocabularyConstants.NavigationRestrictions);
        }
Пример #25
0
        public void AddTypeNameAnnotationAsNeeded_DoesNotAddAnnotation()
        {
            // Arrange
            ODataEnumValue        enumValue = new ODataEnumValue("value");
            IEdmEnumTypeReference enumType  = new EdmEnumTypeReference(
                new EdmEnumType("TestModel", "EnumType"), isNullable: false);

            // Act
            ODataEnumSerializer.AddTypeNameAnnotationAsNeeded(enumValue, enumType, ODataMetadataLevel.Minimal);

            // Assert
            ODataTypeAnnotation annotation = enumValue.TypeAnnotation;

            Assert.Null(annotation);
        }
Пример #26
0
        public void CreateODataValue_RetrunsNull_IfGraphNull()
        {
            // Arrange
            ODataSerializerContext  writeContext = new ODataSerializerContext();
            ODataSerializerProvider provider     = new Mock <ODataSerializerProvider>().Object;
            ODataEnumSerializer     serializer   = new ODataEnumSerializer(provider);
            IEdmEnumType            enumType     = new EdmEnumType("NS", "Enum");
            IEdmTypeReference       expectedType = new EdmEnumTypeReference(enumType, false);

            // Act
            ODataValue actual = serializer.CreateODataValue(graph: null, expectedType: expectedType, writeContext);

            // Assert
            Assert.IsType <ODataNullValue>(actual);
        }
        internal static bool TryBindIdentifier(string identifier, IEdmModel model, out QueryNode boundEnum)
        {
            boundEnum = null;
            string text = identifier;

            // parse the string, e.g., NS.Color'Green'
            // get type information, and also convert Green into an ODataEnumValue

            // find the first ', before that, it is namespace.type
            int indexOfSingleQuote = text.IndexOf('\'');

            if (indexOfSingleQuote < 0)
            {
                return(false);
            }

            string namespaceAndType = text.Substring(0, indexOfSingleQuote);

            // find the type from edm model
            IEdmEnumType enumType = UriEdmHelpers.FindEnumTypeFromModel(model, namespaceAndType);

            if (enumType == null)
            {
                return(false);
            }

            // now, find out the value
            UriPrimitiveTypeParser.TryRemovePrefix(namespaceAndType, ref text);
            UriPrimitiveTypeParser.TryRemoveQuotes(ref text);

            // parse string or int value to edm enum value
            string         enumValueString = text;
            ODataEnumValue enumValue;

            enumType.TryParseEnum(enumValueString, out enumValue);

            if (enumValue == null)
            {
                return(false);
            }

            // create an enum node, enclosing an odata enum value
            EdmEnumTypeReference enumTypeReference = new EdmEnumTypeReference(enumType, false);

            boundEnum = new ConstantNode(enumValue, identifier, enumTypeReference);

            return(true);
        }
Пример #28
0
        private IEdmProperty CreateStructuralTypeCollectionPropertyBody(EdmStructuredType type, CollectionPropertyConfiguration collectionProperty)
        {
            IEdmTypeReference elementTypeReference = null;
            Type clrType = TypeHelper.GetUnderlyingTypeOrSelf(collectionProperty.ElementType);

            if (clrType.GetTypeInfo().IsEnum)
            {
                IEdmType edmType = GetEdmType(clrType);

                if (edmType == null)
                {
                    throw Error.InvalidOperation(SRResources.EnumTypeDoesNotExist, clrType.Name);
                }

                IEdmEnumType enumElementType = (IEdmEnumType)edmType;
                bool         isNullable      = collectionProperty.ElementType != clrType;
                elementTypeReference = new EdmEnumTypeReference(enumElementType, isNullable);
            }
            else
            {
                IEdmType edmType = GetEdmType(collectionProperty.ElementType);
                if (edmType != null)
                {
                    IEdmComplexType elementType = edmType as IEdmComplexType;
                    // Work around for primitive types (ex: Int32 would be typed to System.Int32 instead of EdmInt)
                    if (elementType != null)
                    {
                        elementTypeReference = new EdmComplexTypeReference(elementType, collectionProperty.OptionalProperty);
                    }
                    else
                    {
                        elementTypeReference =
                            EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(collectionProperty.ElementType);
                    }
                }
                else
                {
                    elementTypeReference =
                        EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(collectionProperty.ElementType);
                }

                Contract.Assert(elementTypeReference != null);
            }

            return(type.AddStructuralProperty(
                       collectionProperty.Name,
                       new EdmCollectionTypeReference(new EdmCollectionType(elementTypeReference))));
        }
Пример #29
0
        public void AddTypeNameAnnotationAsNeeded_AddsNullAnnotation_InNoMetadataMode()
        {
            // Arrange
            ODataEnumValue        enumValue = new ODataEnumValue("value");
            IEdmEnumTypeReference enumType  = new EdmEnumTypeReference(
                new EdmEnumType("TestModel", "EnumType"), isNullable: false);

            // Act
            ODataEnumSerializer.AddTypeNameAnnotationAsNeeded(enumValue, enumType, ODataMetadataLevel.NoMetadata);

            // Assert
            SerializationTypeNameAnnotation annotation = enumValue.GetAnnotation <SerializationTypeNameAnnotation>();

            Assert.NotNull(annotation);
            Assert.Null(annotation.TypeName);
        }
Пример #30
0
        public void AddTypeNameAnnotationAsNeeded_AddAnnotation_InFullMetadataMode()
        {
            // Arrange
            ODataEnumValue        enumValue = new ODataEnumValue("value");
            IEdmEnumTypeReference enumType  = new EdmEnumTypeReference(
                new EdmEnumType("TestModel", "EnumType"), isNullable: false);

            // Act
            ODataEnumSerializer.AddTypeNameAnnotationAsNeeded(enumValue, enumType, ODataMetadataLevel.Full);

            // Assert
            ODataTypeAnnotation annotation = enumValue.TypeAnnotation;

            Assert.NotNull(annotation);
            Assert.Equal("TestModel.EnumType", annotation.TypeName);
        }