Example #1
0
		public EdmEnumMember(IEdmEnumType declaringType, string name, IEdmPrimitiveValue value) : base(name)
		{
			EdmUtil.CheckArgumentNull<IEdmEnumType>(declaringType, "declaringType");
			EdmUtil.CheckArgumentNull<IEdmPrimitiveValue>(value, "value");
			this.declaringType = declaringType;
			this.@value = value;
		}
Example #2
0
        public void InitializeApiKeyWithRecordSuccess()
        {
            // Arrange
            EdmModel       model      = new EdmModel();
            IEdmType       edmType    = model.FindType("Org.OData.Authorization.V1.KeyLocation");
            IEdmEnumType   enumType   = edmType as IEdmEnumType;
            IEdmEnumMember enumMember = enumType.Members.FirstOrDefault(c => c.Name == "Header");

            Assert.NotNull(enumMember);

            IEdmRecordExpression record = new EdmRecordExpression(
                new EdmPropertyConstructor("Name", new EdmStringConstant("DelegatedWork")),
                new EdmPropertyConstructor("Description", new EdmStringConstant("Description of the authorization scheme")),
                new EdmPropertyConstructor("KeyName", new EdmStringConstant("keyName")),
                new EdmPropertyConstructor("Location", new EdmEnumMemberExpression(enumMember)));

            ApiKey apiKey = new ApiKey();

            Assert.Null(apiKey.Name);
            Assert.Null(apiKey.Description);
            Assert.Null(apiKey.Location);
            Assert.Null(apiKey.KeyName);

            // Act
            apiKey.Initialize(record);

            // Assert
            Assert.Equal("DelegatedWork", apiKey.Name);
            Assert.Equal("Description of the authorization scheme", apiKey.Description);
            Assert.Equal("keyName", apiKey.KeyName);
            Assert.Equal(KeyLocation.Header, apiKey.Location);
        }
Example #3
0
        /// <summary>
        /// Get cached values and names from hash table
        /// </summary>
        /// <param name="enumType">edm enum type</param>
        /// <param name="values">output values</param>
        /// <param name="names">output names</param>
        /// <param name="getValues">true if get values, false otherwise</param>
        /// <param name="getNames">true if get names, false otherwise</param>
        private static void GetCachedValuesAndNames(this IEdmEnumType enumType, out ulong[] values, out string[] names, bool getValues, bool getNames)
        {
            HashEntry hashEntry = GetHashEntry(enumType);

            values = hashEntry.Values;
            if (values != null)
            {
                getValues = false;
            }

            names = hashEntry.Names;
            if (names != null)
            {
                getNames = false;
            }

            if (!getValues && !getNames)
            {
                return;
            }

            GetEnumValuesAndNames(enumType, ref values, ref names, getValues, getNames);
            if (getValues)
            {
                hashEntry.Values = values;
            }

            if (getNames)
            {
                hashEntry.Names = names;
            }
        }
Example #4
0
        internal static IEdmTypeReference GetTypeReference(this IEdmType type, bool isNullable)
        {
            IEdmPrimitiveType primitiveType = type as IEdmPrimitiveType;

            if (primitiveType != null)
            {
                return(primitiveType.GetPrimitiveTypeReference(isNullable));
            }

            IEdmComplexType complexType = type as IEdmComplexType;

            if (complexType != null)
            {
                return(new EdmComplexTypeReference(complexType, isNullable));
            }

            IEdmEntityType entityType = type as IEdmEntityType;

            if (entityType != null)
            {
                return(new EdmEntityTypeReference(entityType, isNullable));
            }

            IEdmEnumType enumType = type as IEdmEnumType;

            if (enumType != null)
            {
                return(new EdmEnumTypeReference(enumType, isNullable));
            }

            throw new InvalidOperationException(Edm.Strings.EdmType_UnexpectedEdmType);
        }
Example #5
0
        public void CreateODataEnumValue_ReturnsCorrectEnumMember()
        {
            // Arrange
            var builder = new ODataConventionModelBuilder();

            builder.EnumType <BookCategory>().Namespace = "NS";
            IEdmModel    model    = builder.GetEdmModel();
            IEdmEnumType enumType = model.SchemaElements.OfType <IEdmEnumType>().Single();

            IServiceProvider serviceProvder = new Mock <IServiceProvider>().Object;
            var provider = new DefaultODataSerializerProvider(serviceProvder);
            ODataEnumSerializer    serializer   = new ODataEnumSerializer(provider);
            ODataSerializerContext writeContext = new ODataSerializerContext
            {
                Model = model
            };

            // Act
            ODataEnumValue value = serializer.CreateODataEnumValue(BookCategory.Newspaper,
                                                                   new EdmEnumTypeReference(enumType, false), writeContext);

            // Assert
            Assert.NotNull(value);
            Assert.Equal("news", value.Value);
        }
Example #6
0
        public void CreatePropertySchemaForNullableEnumPropertyReturnSchema()
        {
            // Arrange
            IEdmModel     model     = EdmModelHelper.BasicEdmModel;
            ODataContext  context   = new ODataContext(model);
            IEdmEnumType  enumType  = model.SchemaElements.OfType <IEdmEnumType>().First(e => e.Name == "Color");
            EdmEntityType entitType = new EdmEntityType("NS", "Entity");
            IEdmProperty  property  = new EdmStructuralProperty(entitType, "ColorEnumValue", new EdmEnumTypeReference(enumType, true), "yellow");

            // Act
            var schema = context.CreatePropertySchema(property);

            Assert.NotNull(schema);
            string json = schema.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0);

            _output.WriteLine(json);
            // Assert
            Assert.Equal(@"{
  ""anyOf"": [
    {
      ""$ref"": ""#/components/schemas/DefaultNs.Color""
    }
  ],
  ""default"": ""yellow"",
  ""nullable"": true
}".ChangeLineBreaks(), json);
        }
Example #7
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));
        }
Example #8
0
 protected virtual void ProcessEnumType(IEdmEnumType definition)
 {
     this.ProcessSchemaElement(definition);
     this.ProcessType(definition);
     this.ProcessSchemaType(definition);
     this.VisitEnumMembers(definition.Members);
 }
        /// <summary>
        /// Create a <see cref="OpenApiSchema"/> for a <see cref="IEdmEnumType"/>.
        /// An enumeration type is represented as a Schema Object of type string containing the OpenAPI Specification enum keyword.
        /// Its value is an array that contains a string with the member name for each enumeration member.
        /// </summary>
        /// <param name="context">The OData context.</param>
        /// <param name="enumType">The Edm enum type.</param>
        /// <returns>The created <see cref="OpenApiSchema"/>.</returns>
        public static OpenApiSchema CreateEnumTypeSchema(this ODataContext context, IEdmEnumType enumType)
        {
            Utils.CheckArgumentNull(context, nameof(context));
            Utils.CheckArgumentNull(enumType, nameof(enumType));

            OpenApiSchema schema = new OpenApiSchema
            {
                // An enumeration type is represented as a Schema Object of type string
                Type = "string",

                // containing the OpenAPI Specification enum keyword.
                Enum = new List <IOpenApiAny>(),

                // It optionally can contain the field description,
                // whose value is the value of the unqualified annotation Core.Description of the enumeration type.
                Description = context.Model.GetDescriptionAnnotation(enumType)
            };

            // Enum value is an array that contains a string with the member name for each enumeration member.
            foreach (IEdmEnumMember member in enumType.Members)
            {
                schema.Enum.Add(new OpenApiString(member.Name));
            }

            schema.Title = enumType.Name;
            return(schema);
        }
Example #10
0
 public EdmEnumMember(IEdmEnumType declaringType, string name, IEdmPrimitiveValue value) : base(name)
 {
     EdmUtil.CheckArgumentNull <IEdmEnumType>(declaringType, "declaringType");
     EdmUtil.CheckArgumentNull <IEdmPrimitiveValue>(value, "value");
     this.declaringType = declaringType;
     this.@value        = value;
 }
Example #11
0
        public void CreatePropertySchemaForNonNullableEnumPropertyReturnSchema(OpenApiSpecVersion specVersion)
        {
            // Arrange
            IEdmModel    model   = EdmModelHelper.BasicEdmModel;
            ODataContext context = new ODataContext(model);

            context.Settings.OpenApiSpecVersion = specVersion;

            IEdmEnumType  enumType  = model.SchemaElements.OfType <IEdmEnumType>().First(e => e.Name == "Color");
            EdmEntityType entitType = new EdmEntityType("NS", "Entity");
            IEdmProperty  property  = new EdmStructuralProperty(entitType, "ColorEnumValue", new EdmEnumTypeReference(enumType, false));

            // Act
            var schema = context.CreatePropertySchema(property);

            Assert.NotNull(schema);
            string json = schema.SerializeAsJson(specVersion);

            // Assert

            if (specVersion == OpenApiSpecVersion.OpenApi2_0)
            {
                Assert.Equal(@"{
  ""$ref"": ""#/definitions/DefaultNs.Color""
}".ChangeLineBreaks(), json);
            }
            else
            {
                Assert.Equal(@"{
  ""$ref"": ""#/components/schemas/DefaultNs.Color""
}".ChangeLineBreaks(), json);
            }
        }
        public void InitializSearchRestrictionsTypeWithRecordSuccess()
        {
            // Assert
            EdmModel     model             = new EdmModel();
            IEdmEnumType searchExpressions = model.FindType("Org.OData.Capabilities.V1.SearchExpressions") as IEdmEnumType;

            Assert.NotNull(searchExpressions);

            IEdmRecordExpression record = new EdmRecordExpression(
                new EdmPropertyConstructor("Searchable", new EdmBooleanConstant(false)),
                new EdmPropertyConstructor("UnsupportedExpressions", new EdmEnumMemberExpression(
                                               searchExpressions.Members.First(c => c.Name == "AND"),
                                               searchExpressions.Members.First(c => c.Name == "OR")))
                );

            // Act
            SearchRestrictionsType search = new SearchRestrictionsType();

            search.Initialize(record);

            // Assert
            Assert.False(search.Searchable);
            Assert.NotNull(search.UnsupportedExpressions);
            Assert.Equal(SearchExpressions.AND | SearchExpressions.OR, search.UnsupportedExpressions.Value);
        }
Example #13
0
        public void BoundAction_ForEnumTypeInODataModelBuilder()
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();
            EntityTypeConfiguration <EnumModel> entityTypeConfiguration = builder.EntityType <EnumModel>();
            ActionConfiguration actionConfiguration = entityTypeConfiguration.Action("BoundAction");

            actionConfiguration.CollectionParameter <Color>("Colors");
            actionConfiguration.ReturnsCollection <Color?>();
            builder.Add_Color_EnumType();

            // Act & Assert
            IEdmModel  model  = builder.GetEdmModel();
            IEdmAction action = model.FindDeclaredOperations("Default.BoundAction").Single() as IEdmAction;

            IEdmTypeReference colors     = action.Parameters.Single(p => p.Name == "Colors").Type;
            IEdmTypeReference returnType = action.ReturnType;
            IEdmEnumType      colorType  = model.SchemaElements.OfType <IEdmEnumType>().Single(e => e.Name == "Color");

            Assert.True(colors.IsCollection());
            Assert.Same(colorType, colors.AsCollection().ElementType().Definition);
            Assert.True(returnType.IsCollection());
            Assert.True(returnType.AsCollection().ElementType().IsNullable);
            Assert.Same(colorType, returnType.AsCollection().ElementType().Definition);
        }
        private EnumType ConvertToTaupoEnumType(IEdmEnumType edmEnum)
        {
            var taupoEnumType = new EnumType(edmEnum.Namespace, edmEnum.Name);

            if (edmEnum.IsFlags)
            {
                taupoEnumType.IsFlags = true;
            }

            if (edmEnum.UnderlyingType != null)
            {
                taupoEnumType.UnderlyingType = this.ConvertToClrType(edmEnum.UnderlyingType);
            }

            foreach (var edmEnumMember in edmEnum.Members)
            {
                var taupoEnumMember = new EnumMember(edmEnumMember.Name);

                if (edmEnumMember.Value != null)
                {
                    taupoEnumMember.Value = this.ConvertToClrObject(edmEnumMember.Value);
                }

                taupoEnumType.Add(taupoEnumMember);
            }

            return(taupoEnumType);
        }
Example #15
0
        private static EdmEntityObjectCollection GetCustomers()
        {
            if (_untypedSimpleOpenCustormers != null)
            {
                return(_untypedSimpleOpenCustormers);
            }

            IEdmModel       edmModel     = OpenEntityTypeTests.GetUntypedEdmModel();
            IEdmEntityType  customerType = edmModel.SchemaElements.OfType <IEdmEntityType>().First(c => c.Name == "UntypedSimpleOpenCustomer");
            EdmEntityObject customer     = new EdmEntityObject(customerType);

            customer.TrySetPropertyValue("CustomerId", 1);

            //Add Numbers primitive collection property
            customer.TrySetPropertyValue("DeclaredNumbers", new[] { 1, 2 });

            //Add Color, Colors enum(collection) property
            IEdmEnumType  colorType = edmModel.SchemaElements.OfType <IEdmEnumType>().First(c => c.Name == "Color");
            EdmEnumObject color     = new EdmEnumObject(colorType, "Red");
            EdmEnumObject color2    = new EdmEnumObject(colorType, "0");
            EdmEnumObject color3    = new EdmEnumObject(colorType, "Red");

            customer.TrySetPropertyValue("Color", color);

            List <IEdmEnumObject> colorList = new List <IEdmEnumObject>();

            colorList.Add(color);
            colorList.Add(color2);
            colorList.Add(color3);
            IEdmCollectionTypeReference enumCollectionType = new EdmCollectionTypeReference(new EdmCollectionType(colorType.ToEdmTypeReference(false)));
            EdmEnumObjectCollection     colors             = new EdmEnumObjectCollection(enumCollectionType, colorList);

            customer.TrySetPropertyValue("Colors", colors);
            customer.TrySetPropertyValue("DeclaredColors", colors);

            //Add Addresses complex(collection) property
            EdmComplexType addressType =
                edmModel.SchemaElements.OfType <IEdmComplexType>().First(c => c.Name == "Address") as EdmComplexType;
            EdmComplexObject address = new EdmComplexObject(addressType);

            address.TrySetPropertyValue("Street", "No1");
            EdmComplexObject address2 = new EdmComplexObject(addressType);

            address2.TrySetPropertyValue("Street", "No2");

            List <IEdmComplexObject> addressList = new List <IEdmComplexObject>();

            addressList.Add(address);
            addressList.Add(address2);
            IEdmCollectionTypeReference complexCollectionType = new EdmCollectionTypeReference(new EdmCollectionType(addressType.ToEdmTypeReference(false)));
            EdmComplexObjectCollection  addresses             = new EdmComplexObjectCollection(complexCollectionType, addressList);

            customer.TrySetPropertyValue("DeclaredAddresses", addresses);

            EdmEntityObjectCollection customers = new EdmEntityObjectCollection(new EdmCollectionTypeReference(new EdmCollectionType(customerType.ToEdmTypeReference(false))));

            customers.Add(customer);
            _untypedSimpleOpenCustormers = customers;
            return(_untypedSimpleOpenCustormers);
        }
        public void InitializNavigationRestrictionsTypeWithRecordSuccess()
        {
            // Assert
            EdmModel     model          = new EdmModel();
            IEdmEnumType navigationType = model.FindType("Org.OData.Capabilities.V1.NavigationType") as IEdmEnumType;

            Assert.NotNull(navigationType);

            IEdmRecordExpression restriction1 = new EdmRecordExpression(
                new EdmPropertyConstructor("NavigationProperty", new EdmNavigationPropertyPathExpression("abc")),
                new EdmPropertyConstructor("Navigability", new EdmEnumMemberExpression(navigationType.Members.First(c => c.Name == "Single"))),
                new EdmPropertyConstructor("SkipSupported", new EdmBooleanConstant(false)));

            IEdmRecordExpression restriction2 = new EdmRecordExpression(
                new EdmPropertyConstructor("NavigationProperty", new EdmNavigationPropertyPathExpression("xyz")),
                new EdmPropertyConstructor("Navigability", new EdmEnumMemberExpression(navigationType.Members.First(c => c.Name == "None"))),
                new EdmPropertyConstructor("OptimisticConcurrencyControl", new EdmBooleanConstant(true)));

            IEdmRecordExpression record = new EdmRecordExpression(
                new EdmPropertyConstructor("Navigability", new EdmEnumMemberExpression(navigationType.Members.First(c => c.Name == "Recursive"))),
                new EdmPropertyConstructor("RestrictedProperties", new EdmCollectionExpression(restriction1, restriction2))
                );

            // Act
            NavigationRestrictionsType navigation = new NavigationRestrictionsType();

            navigation.Initialize(record);

            // Assert
            VerifyNavigationRestrictions(navigation);
        }
Example #17
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);
        }
Example #18
0
 private static bool IsEquivalentTo(this IEdmEnumType thisType, IEdmEnumType otherType)
 {
     // ODataLib requires to register signatures for custom uri functions in static class
     // If we generate multiple models that use the same enum we will have different object refs
     return(thisType.FullName() == otherType.FullName() &&
            thisType.UnderlyingType.IsEquivalentTo(otherType.UnderlyingType) &&
            thisType.IsFlags == otherType.IsFlags);
 }
Example #19
0
 /// <summary>
 /// Determine if the underlying type of the enum type is integer type (byte, sbyte, int16, int32, int64).
 /// </summary>
 /// <param name="enumType">The enum type.</param>
 /// <returns>True if the underlying type of enum type is integer type.</returns>
 internal static bool IsEnumIntegerType(IEdmEnumType enumType)
 {
     return(enumType.UnderlyingType.PrimitiveKind == EdmPrimitiveTypeKind.Byte ||
            enumType.UnderlyingType.PrimitiveKind == EdmPrimitiveTypeKind.SByte ||
            enumType.UnderlyingType.PrimitiveKind == EdmPrimitiveTypeKind.Int16 ||
            enumType.UnderlyingType.PrimitiveKind == EdmPrimitiveTypeKind.Int32 ||
            enumType.UnderlyingType.PrimitiveKind == EdmPrimitiveTypeKind.Int64);
 }
Example #20
0
        internal static bool TryBindIdentifier(string identifier, IEdmEnumTypeReference typeReference, IEdmModel modelWhenNoTypeReference, 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);

            Debug.Assert((typeReference == null) || (modelWhenNoTypeReference == null), "((typeReference == null) || (modelWhenNoTypeReference == null)");

            // validate typeReference but allow type name not found in model for delayed throwing.
            if ((typeReference != null) && !string.Equals(namespaceAndType, typeReference.FullName()))
            {
                return(false);
            }

            // get the type
            IEdmEnumType enumType = typeReference != null
                ?
                                    (IEdmEnumType)typeReference.Definition
                :
                                    UriEdmHelpers.FindEnumTypeFromModel(modelWhenNoTypeReference, namespaceAndType);

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

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

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

            if (!TryParseEnum(enumType, enumValueString, out enumValue))
            {
                return(false);
            }

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

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

            return(true);
        }
Example #21
0
        private bool TryGetEnumType(string typeName, out IEdmEnumType enumType)
        {
            enumType = _model.SchemaElements
                       .Where(x => x.SchemaElementKind == EdmSchemaElementKind.TypeDefinition && (x as IEdmType).TypeKind == EdmTypeKind.Enum)
                       .Select(x => x as IEdmEnumType)
                       .BestMatch(x => x.Name, typeName, NameMatchResolver);

            return(enumType != null);
        }
        internal static void Compile(IEdmEnumType type, ModuleBuilder moduleBuilder, string moduleName)
        {
            var typeBuilder = CreateType(type, moduleBuilder, moduleName);

            foreach (var enumMember in type.Members)
            {
                GenerateEnum(enumMember, typeBuilder, moduleBuilder);
            }
        }
Example #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EdmEnumObject"/> class.
 /// </summary>
 /// <param name="edmType">The <see cref="IEdmEnumTypeReference"/> of this object.</param>
 /// <param name="value">The value of the enumeration type.</param>
 /// <param name="isNullable">true if this object can be nullable; otherwise, false.</param>
 public EdmEnumObject(IEdmEnumType edmType, string value, bool isNullable)
 {
     if (edmType == null)
     {
         throw Error.ArgumentNull("edmType");
     }
     _edmType = edmType;
     Value = value;
     IsNullable = isNullable;
 }
 internal void WriteEnumTypeElementHeader(IEdmEnumType enumType)
 {
     this.xmlWriter.WriteStartElement("EnumType");
     this.WriteRequiredAttribute <string>("Name", enumType.Name, new Func <string, string>(EdmValueWriter.StringAsXml));
     if (enumType.UnderlyingType.PrimitiveKind != EdmPrimitiveTypeKind.Int32)
     {
         this.WriteRequiredAttribute <IEdmPrimitiveType>("UnderlyingType", enumType.UnderlyingType, new Func <IEdmPrimitiveType, string>(this.TypeDefinitionAsXml));
     }
     this.WriteOptionalAttribute <bool>("IsFlags", enumType.IsFlags, false, new Func <bool, string>(EdmValueWriter.BooleanAsXml));
 }
Example #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EdmEnumObject"/> class.
 /// </summary>
 /// <param name="edmType">The <see cref="IEdmEnumTypeReference"/> of this object.</param>
 /// <param name="value">The value of the enumeration type.</param>
 /// <param name="isNullable">true if this object can be nullable; otherwise, false.</param>
 public EdmEnumObject(IEdmEnumType edmType, string value, bool isNullable)
 {
     if (edmType == null)
     {
         throw Error.ArgumentNull("edmType");
     }
     _edmType   = edmType;
     Value      = value;
     IsNullable = isNullable;
 }
Example #26
0
        /// <summary>
        /// For enum without flags, use a binary search
        /// </summary>
        /// <param name="enumType">edm enum type</param>
        /// <param name="value">input integer value</param>
        /// <returns>string</returns>
        private static string ToStringNoFlags(this IEdmEnumType enumType, Int64 value)
        {
            ulong[]  values;
            string[] names;
            enumType.GetCachedValuesAndNames(out values, out names, true, true);
            ulong num   = (ulong)value;
            int   index = Array.BinarySearch(values, num);

            return(index >= 0 ? names[index] : value.ToString(CultureInfo.InvariantCulture));
        }
Example #27
0
        private static CsdlExpressionBase AdjustStringConstantUsingTermType(CsdlExpressionBase expression, IEdmTypeReference termType)
        {
            if (expression == null || termType == null)
            {
                return(expression);
            }

            switch (expression.ExpressionKind)
            {
            case EdmExpressionKind.Collection:
                if (termType.IsCollection())
                {
                    IEdmTypeReference          elementType   = termType.AsCollection().ElementType();
                    IList <CsdlExpressionBase> newElements   = new List <CsdlExpressionBase>();
                    CsdlCollectionExpression   collectionExp = (CsdlCollectionExpression)expression;

                    foreach (CsdlExpressionBase exp in collectionExp.ElementValues)
                    {
                        if (exp != null && exp.ExpressionKind == EdmExpressionKind.StringConstant)
                        {
                            newElements.Add(AdjustStringConstantUsingTermType(exp, elementType));
                        }
                        else
                        {
                            newElements.Add(exp);
                        }
                    }

                    return(new CsdlCollectionExpression(collectionExp.Type, newElements, collectionExp.Location as CsdlLocation));
                }

                break;

            case EdmExpressionKind.StringConstant:
                CsdlConstantExpression constantExp = (CsdlConstantExpression)expression;
                switch (termType.TypeKind())
                {
                case EdmTypeKind.Primitive:
                    IEdmPrimitiveTypeReference primitiveTypeReference = (IEdmPrimitiveTypeReference)termType;
                    return(BuildPrimitiveExpression(primitiveTypeReference, constantExp));

                case EdmTypeKind.Path:
                    IEdmPathType pathType = (IEdmPathType)termType.Definition;
                    return(BuildPathExpression(pathType, constantExp));

                case EdmTypeKind.Enum:
                    IEdmEnumType enumType = (IEdmEnumType)termType.Definition;
                    return(BuildEnumExpression(enumType, constantExp));
                }

                break;
            }

            return(expression);
        }
Example #28
0
        public static ConstantNode ShouldBeEnumNode(this QueryNode node, IEdmEnumType enumType, Int64 value)
        {
            Assert.NotNull(node);
            var enumNode = Assert.IsType <ConstantNode>(node);

            Assert.Equal(enumType.FullTypeName(), enumNode.TypeReference.FullName());
            Assert.Equal(value + "", ((ODataEnumValue)enumNode.Value).Value);
            Assert.Equal(enumType.FullTypeName(), ((ODataEnumValue)enumNode.Value).TypeName);

            return(enumNode);
        }
        private void FillStockContentsForEnum(IEdmEnumType edmType, IEdmModel edmModel, EdmModel stockModel)
        {
            var stockType = (IEdmEnumType)stockModel.FindType(edmType.FullName());

            this.SetImmediateAnnotations(edmType, stockType, edmModel, stockModel);

            foreach (var edmMember in edmType.Members)
            {
                ConvertToStockMember((IEdmEnumMember)edmMember, edmModel, stockModel);
            }
        }
Example #30
0
		public BadEnumMember(IEdmEnumType declaringType, string name, IEnumerable<EdmError> errors) : base(errors)
		{
			string str = name;
			string empty = str;
			if (str == null)
			{
				empty = string.Empty;
			}
			this.name = empty;
			this.declaringType = declaringType;
		}
        internal void WriteEnumTypeElementHeader(IEdmEnumType enumType)
        {
            this.xmlWriter.WriteStartElement(CsdlConstants.Element_EnumType);
            this.WriteRequiredAttribute(CsdlConstants.Attribute_Name, enumType.Name, EdmValueWriter.StringAsXml);
            if (enumType.UnderlyingType.PrimitiveKind != EdmPrimitiveTypeKind.Int32)
            {
                this.WriteRequiredAttribute(CsdlConstants.Attribute_UnderlyingType, enumType.UnderlyingType, this.TypeDefinitionAsXml);
            }

            this.WriteOptionalAttribute(CsdlConstants.Attribute_IsFlags, enumType.IsFlags, CsdlConstants.Default_IsFlags, EdmValueWriter.BooleanAsXml);
        }
Example #32
0
 private static HashEntry GetHashEntry(IEdmEnumType enumType)
 {
     try
     {
         return(EnumHelper.fieldInfoHash.GetOrAdd(enumType, type => new HashEntry(null, null)));
     }
     catch (OverflowException)
     {
         EnumHelper.fieldInfoHash.Clear();
         return(EnumHelper.fieldInfoHash.GetOrAdd(enumType, type => new HashEntry(null, null)));
     }
 }
Example #33
0
        /// <summary>
        /// For enum with flags, use a sequential search for bit masks, and then check if any residual
        /// </summary>
        /// <param name="enumType">edm enum type</param>
        /// <param name="value">input integer value</param>
        /// <returns>string separated by comma</returns>
        private static string ToStringWithFlags(this IEdmEnumType enumType, Int64 value)
        {
            string[] strArray;
            ulong[]  numArray;
            ulong    num = (ulong)value;

            enumType.GetCachedValuesAndNames(out numArray, out strArray, true, true);
            int           index     = numArray.Length - 1;
            StringBuilder builder   = new StringBuilder();
            bool          flag      = true;
            ulong         num3      = num;
            const int     Zero      = 0;
            const ulong   UlongZero = 0L;

            while (index >= Zero)
            {
                if ((index == Zero) && (numArray[index] == UlongZero))
                {
                    break;
                }

                if ((num & numArray[index]) == numArray[index])
                {
                    num -= numArray[index];
                    if (!flag)
                    {
                        builder.Insert(Zero, ", ");
                    }

                    builder.Insert(Zero, strArray[index]);
                    flag = false;
                }

                index--;
            }

            if (num != UlongZero)
            {
                return(value.ToString(CultureInfo.InvariantCulture));
            }

            if (num3 != UlongZero)
            {
                return(builder.ToString());
            }

            if ((numArray.Length > Zero) && (numArray[Zero] == UlongZero))
            {
                return(strArray[Zero]);
            }

            return(Zero.ToString(CultureInfo.InvariantCulture));
        }
Example #34
0
		public UnresolvedEnumMember(string name, IEdmEnumType declaringType, EdmLocation location)
			: base(new EdmError[] { new EdmError(location, EdmErrorCode.BadUnresolvedEnumMember, Strings.Bad_UnresolvedEnumMember(name)) })
		{
			this.@value = new Cache<UnresolvedEnumMember, IEdmPrimitiveValue>();
			UnresolvedEnumMember unresolvedEnumMember = this;
			string str = name;
			string empty = str;
			if (str == null)
			{
				empty = string.Empty;
			}
			unresolvedEnumMember.name = empty;
			this.declaringType = declaringType;
		}
Example #35
0
        static CapabilitiesHelpers()
        {
            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ODataSamples.Services.Core.Vocabularies.CapabilitiesVocabularies.xml"))
            {
                IEnumerable<EdmError> errors;
                CsdlReader.TryParse(new[] { XmlReader.Create(stream) }, out Instance, out errors);
            }

            ConformanceLevelTerm = Instance.FindDeclaredValueTerm(CapabilitiesConformanceLevel);
            SupportedFormatsTerm = Instance.FindDeclaredValueTerm(CapabilitiesSupportedFormats);
            AsynchronousRequestsSupportedTerm = Instance.FindDeclaredValueTerm(CapabilitiesAsynchronousRequestsSupported);
            BatchContinueOnErrorSupportedTerm = Instance.FindDeclaredValueTerm(CapabilitiesBatchContinueOnErrorSupported);
            ChangeTrackingTerm = Instance.FindDeclaredValueTerm(CapabilitiesChangeTracking);
            NavigationRestrictionsTerm = Instance.FindDeclaredValueTerm(CapabilitiesNavigationRestrictions);
            FilterFunctionsTerm = Instance.FindDeclaredValueTerm(CapabilitiesFilterFunctions);
            SearchRestrictionsTerm = Instance.FindDeclaredValueTerm(CapabilitiesSearchRestrictions);
            InsertRestrictionsTerm = Instance.FindDeclaredValueTerm(CapabilitiesInsertRestrictions);
            UpdateRestrictionsTerm = Instance.FindDeclaredValueTerm(CapabilitiesUpdateRestrictions);
            DeleteRestrictionsTerm = Instance.FindDeclaredValueTerm(CapabilitiesDeleteRestrictions);
            ConformanceLevelTypeType = (IEdmEnumType)Instance.FindDeclaredType(CapabilitiesConformanceLevelType);
            NavigationTypeType = (IEdmEnumType)Instance.FindDeclaredType(CapabilitiesNavigationType);
            SearchExpressionsType = (IEdmEnumType)Instance.FindDeclaredType(CapabilitiesSearchExpressions);
        }
        internal void WriteEnumType(IEdmEnumType enumType)
        {
            WriteSummaryCommentForEnumType(Context.EnableNamingAlias ? Customization.CustomizeNaming(enumType.Name) : enumType.Name);
            if (enumType.IsFlags)
            {
                WriteEnumFlags();
            }

            var underlyingType = string.Empty;
            if (enumType.UnderlyingType != null && enumType.UnderlyingType.PrimitiveKind != EdmPrimitiveTypeKind.Int32)
            {
                underlyingType = Utils.GetClrTypeName(enumType.UnderlyingType, this);
                underlyingType = EnumUnderlyingTypeMarker + underlyingType;
            }

            WriteEnumDeclaration(Context.EnableNamingAlias ? GetFixedName(Customization.CustomizeNaming(enumType.Name)) : GetFixedName(enumType.Name), enumType.Name, underlyingType);
            WriteMembersForEnumType(enumType.Members);
            WriteEnumEnd();
        }
Example #37
0
  /// <summary>
 /// Initializes a new instance of the <see cref="EdmEnumObject"/> class.
 /// </summary>
 /// <param name="edmType">The <see cref="IEdmEnumType"/> of this object.</param>
 /// <param name="value">The value of the enumeration type.</param>
 public EdmEnumObject(IEdmEnumType edmType, string value)
     : this(edmType, value, isNullable: false)
 {
 }
 public CustomEnumMember(IEdmEnumType declaringType, string name, IEdmPrimitiveValue value)
     : base(name)
 {
     this.declaringType = declaringType;
     this.value = value;
 }
 public UnresolvedEnumMember(string name, IEdmEnumType declaringType, EdmLocation location)
     : base(new EdmError[] { new EdmError(location, EdmErrorCode.BadUnresolvedEnumMember, Edm.Strings.Bad_UnresolvedEnumMember(name)) })
 {
     this.name = name ?? string.Empty;
     this.declaringType = declaringType;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="EdmEnumTypeReference"/> class.
 /// </summary>
 /// <param name="enumType">The definition refered to by this reference.</param>
 /// <param name="isNullable">Denotes whether the type can be nullable.</param>
 public EdmEnumTypeReference(IEdmEnumType enumType, bool isNullable)
     : base(enumType, isNullable)
 {
 }
Example #41
0
        private static void GetEnumValuesAndNames(IEdmEnumType enumType, ref ulong[] values, ref string[] names, bool getValues, bool getNames)
        {
            Dictionary<string, ulong> dict = new Dictionary<string, ulong>();
            foreach (var member in enumType.Members)
            {
                EdmIntegerConstant intValue = member.Value as EdmIntegerConstant;
                if (intValue != null)
                {
                    dict.Add(member.Name, (ulong)intValue.Value);
                }
            }

            Dictionary<string, ulong> sortedDict = dict.OrderBy(d => d.Value).ToDictionary(d => d.Key, d => d.Value);
            values = sortedDict.Select(d => d.Value).ToArray();
            names = sortedDict.Select(d => d.Key).ToArray();
        }
Example #42
0
        private static HashEntry GetHashEntry(IEdmEnumType enumType)
        {
            if (fieldInfoHash.Count > MaxHashElements)
            {
                lock (fieldInfoHash)
                {
                    if (fieldInfoHash.Count > MaxHashElements)
                    {
                        fieldInfoHash.Clear();
                    }
                }
            }

            return EdmUtil.DictionaryGetOrUpdate(fieldInfoHash, enumType, type => new HashEntry(null, null));
        }
 /// <summary>
 /// Constructs an Enum type reference from definition
 /// </summary>
 /// <param name="definition">The Enum type definition</param>
 /// <returns>The Enum type reference</returns>
 public static IEdmEnumTypeReference EnumTypeReference(IEdmEnumType definition)
 {
     return new EdmEnumTypeReference(definition, true);
 }
 private static IEdmEnumType GetCapabilitiesNavigationType(this EdmModel model)
 {
     return _navigationType ??
            (_navigationType = model.FindType(CapabilitiesVocabularyConstants.NavigationType) as IEdmEnumType);
 }
        private EnumType ConvertToTaupoEnumType(IEdmEnumType edmEnum)
        {
            var taupoEnumType = new EnumType(edmEnum.Namespace, edmEnum.Name);
            if (edmEnum.IsFlags)
            {
                taupoEnumType.IsFlags = true;
            }

            if (edmEnum.UnderlyingType != null)
            {
                taupoEnumType.UnderlyingType = this.ConvertToClrType(edmEnum.UnderlyingType);
            }

            foreach (var edmEnumMember in edmEnum.Members)
            {
                var taupoEnumMember = new EnumMember(edmEnumMember.Name);

                if (edmEnumMember.Value != null)
                {
                    taupoEnumMember.Value = this.ConvertToClrObject(edmEnumMember.Value);
                }

                taupoEnumType.Add(taupoEnumMember);
            }

            return taupoEnumType;
        }
 protected override void ProcessEnumType(IEdmEnumType element)
 {
     base.ProcessEnumType(element);
     this.CheckSchemaElementReference(element.UnderlyingType);
 }
        private bool TryGetEnumType(string typeName, out IEdmEnumType enumType)
        {
            enumType = _model.SchemaElements
                .Where(x => x.SchemaElementKind == EdmSchemaElementKind.TypeDefinition && (x as IEdmType).TypeKind == EdmTypeKind.Enum)
                .Select(x => x as IEdmEnumType)
                .BestMatch(x => x.Name, typeName, _session.Pluralizer);

            return enumType != null;
        }
        /// <summary>
        /// Parse string or integer to enum value
        /// </summary>
        /// <param name="enumType">edm enum type</param>
        /// <param name="value">input string value</param>
        /// <param name="enumValue">output edm enum value</param>
        /// <returns>true if parse succeeds, false if fails</returns>
        private static bool TryParseEnum(IEdmEnumType enumType, string value, out ODataEnumValue enumValue)
        {
            long parsedValue;
            bool success = enumType.TryParseEnum(value, true, out parsedValue);
            enumValue = null;
            if (success)
            {
                enumValue = new ODataEnumValue(parsedValue.ToString(CultureInfo.InvariantCulture), enumType.FullTypeName());
            }

            return success;
        }
        private void FillStockContentsForEnum(IEdmEnumType edmType, IEdmModel edmModel, EdmModel stockModel)
        {
            var stockType = (IEdmEnumType)stockModel.FindType(edmType.FullName());
            this.SetImmediateAnnotations(edmType, stockType, edmModel, stockModel);

            foreach (var edmMember in edmType.Members)
            {
                ConvertToStockMember((IEdmEnumMember)edmMember, edmModel, stockModel);
            }
        }
 /// <summary>
 /// Deterine if the underlying type of the enum type is interger type (byte, sbyte, int16, int32, int64).
 /// </summary>
 /// <param name="enumType">The enum type.</param>
 /// <returns>True if the underlying type of enum type is integer type.</returns>
 internal static bool IsEnumIntergeType(IEdmEnumType enumType)
 {
     return enumType.UnderlyingType.PrimitiveKind == EdmPrimitiveTypeKind.Byte ||
            enumType.UnderlyingType.PrimitiveKind == EdmPrimitiveTypeKind.SByte ||
            enumType.UnderlyingType.PrimitiveKind == EdmPrimitiveTypeKind.Int16 ||
            enumType.UnderlyingType.PrimitiveKind == EdmPrimitiveTypeKind.Int32 ||
            enumType.UnderlyingType.PrimitiveKind == EdmPrimitiveTypeKind.Int64;
 }
Example #51
0
        /// <summary>
        /// Parse string or integer to enum value
        /// </summary>
        /// <param name="enumType">edm enum type</param>
        /// <param name="value">input string value</param>
        /// <param name="enumValue">output edm enum value</param>
        /// <returns>true if parse succeeds, false if fails</returns>
        internal static bool TryParseEnum(IEdmEnumType enumType, string value, out ODataEnumValue enumValue)
        {
            long parsedValue;
            bool success = enumType.TryParseEnum(value, true, out parsedValue);
            enumValue = null;
            if (success)
            {
                // ODataEnumValue.Value will always be numeric string like '3', '10' instead of 'Cyan', 'Solid,Yellow', etc.
                // so user code can easily Enum.Parse() them into CLR value.
                enumValue = new ODataEnumValue(parsedValue.ToString(CultureInfo.InvariantCulture), enumType.ODataFullName());
            }

            return success;
        }
Example #52
0
 public BadEnumMember(IEdmEnumType declaringType, string name, IEnumerable<EdmError> errors)
     : base(errors)
 {
     this.name = name ?? string.Empty;
     this.declaringType = declaringType;
 }
Example #53
0
 public TestEdmEnumObject(IEdmEnumType edmType, string value)
     : base(edmType, value)
 {
 }