Exemplo n.º 1
0
        public ODataResource CreateEntry(Object entity)
        {
            var odataProperties = new ODataProperty[Accessors.Length];

            for (int i = 0; i < Accessors.Length; i++)
            {
                OePropertyAccessor accessor = Accessors[i];
                Object             value    = accessor.Accessor(entity);

                ODataValue odataValue = null;
                if (value == null)
                {
                    odataValue = new ODataNullValue();
                }
                else if (value.GetType().IsEnum)
                {
                    odataValue = new ODataEnumValue(value.ToString());
                }
                else if (value is DateTime dateTime)
                {
                    switch (dateTime.Kind)
                    {
                    case DateTimeKind.Unspecified:
                        value = new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc));
                        break;

                    case DateTimeKind.Utc:
                        value = new DateTimeOffset(dateTime);
                        break;

                    case DateTimeKind.Local:
                        value = new DateTimeOffset(dateTime.ToUniversalTime());
                        break;

                    default:
                        throw new ArgumentOutOfRangeException("unknown DateTimeKind " + dateTime.Kind.ToString());
                    }
                    odataValue = new ODataPrimitiveValue(value);
                }
                else
                {
                    odataValue = new ODataPrimitiveValue(value);
                }

                odataValue.TypeAnnotation = accessor.TypeAnnotation;
                odataProperties[i]        = new ODataProperty()
                {
                    Name = accessor.Name, Value = odataValue
                };
            }

            return(new ODataResource
            {
                TypeName = _typeName,
                Properties = odataProperties
            });
        }
Exemplo n.º 2
0
        internal static object ConvertValue(
            object odataValue,
            Type expectedReturnType,
            IEdmTypeReference propertyType,
            IEdmModel model,
            ApiContext apiContext)
        {
            ODataDeserializerContext readContext = new ODataDeserializerContext
            {
                Model = model
            };

            ODataDeserializerProvider deserializerProvider = apiContext.GetApiService <ODataDeserializerProvider>();

            if (odataValue == null)
            {
                return(null);
            }

            ODataNullValue nullValue = odataValue as ODataNullValue;

            if (nullValue != null)
            {
                return(null);
            }

            ODataComplexValue complexValue = odataValue as ODataComplexValue;

            if (complexValue != null)
            {
                ODataEdmTypeDeserializer deserializer
                    = deserializerProvider.GetEdmTypeDeserializer(propertyType.AsComplex());
                return(deserializer.ReadInline(complexValue, propertyType, readContext));
            }

            ODataEnumValue enumValue = odataValue as ODataEnumValue;

            if (enumValue != null)
            {
                ODataEdmTypeDeserializer deserializer
                    = deserializerProvider.GetEdmTypeDeserializer(propertyType.AsEnum());
                return(deserializer.ReadInline(enumValue, propertyType, readContext));
            }

            ODataCollectionValue collection = odataValue as ODataCollectionValue;

            if (collection != null)
            {
                ODataEdmTypeDeserializer deserializer
                    = deserializerProvider.GetEdmTypeDeserializer(propertyType as IEdmCollectionTypeReference);
                var collectionResult = deserializer.ReadInline(collection, propertyType, readContext);

                return(ConvertCollectionType(collectionResult, expectedReturnType));
            }

            return(odataValue);
        }
Exemplo n.º 3
0
        public void ConvertEnumValue_ThrowsValidationException_NonEnumType()
        {
            // Arrange & Act & Assert
            ODataEnumValue enumValue = new ODataEnumValue("Red");

            ExceptionAssert.Throws <InvalidOperationException>(
                () => EnumDeserializationHelpers.ConvertEnumValue(enumValue, typeof(int)),
                "The type 'Int32' must be an enum or Nullable<T> where T is an enum type.");
        }
Exemplo n.º 4
0
        /// <summary>
        /// Converts an enum value to a string for use in a Url.
        /// </summary>
        /// <param name="value">Value to convert.</param>
        /// <param name="version">OData version to be compliant with.</param>
        /// <returns>A string representation of <paramref name="value"/> to be added to a Url.</returns>
        internal static string ConvertToUriEnumLiteral(ODataEnumValue value, ODataVersion version)
        {
            ExceptionUtils.CheckArgumentNotNull(value, "value");
            ExceptionUtils.CheckArgumentNotNull(value.TypeName, "value.TypeName");
            ExceptionUtils.CheckArgumentNotNull(value.Value, "value.Value");

            // not URL-encode the resulting string:
            return string.Format(CultureInfo.InvariantCulture, "{0}'{1}'", value.TypeName, value.Value);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Converts an enum value to a string for use in a Url.
        /// </summary>
        /// <param name="value">Value to convert.</param>
        /// <param name="version">OData version to be compliant with.</param>
        /// <returns>A string representation of <paramref name="value"/> to be added to a Url.</returns>
        internal static string ConvertToUriEnumLiteral(ODataEnumValue value, ODataVersion version)
        {
            ExceptionUtils.CheckArgumentNotNull(value, "value");
            ExceptionUtils.CheckArgumentNotNull(value.TypeName, "value.TypeName");
            ExceptionUtils.CheckArgumentNotNull(value.Value, "value.Value");

            // not URL-encode the resulting string:
            return(string.Format(CultureInfo.InvariantCulture, "{0}'{1}'", value.TypeName, value.Value));
        }
Exemplo n.º 6
0
 public void SetCoverColors(ODataCollectionValue values)
 {
     this.CoverColors = new Collection <Color>();
     foreach (var item in values.Items)
     {
         ODataEnumValue enumItem = item as ODataEnumValue;
         this.CoverColors.Add((Color)Enum.Parse(typeof(Color), enumItem.Value));
     }
 }
Exemplo n.º 7
0
        public void ConvertEnumValue_ReturnEnumValue_ForEnumType()
        {
            // Arrange
            object value = new ODataEnumValue("Red");
            Type   type  = typeof(Color);

            // Act & Assert
            Assert.Equal(Enum.ToObject(typeof(Color), Color.Red), EnumDeserializationHelpers.ConvertEnumValue(value, type));
        }
        public void EnumTypeCollectionRoundtripJsonLightTest()
        {
            ODataEnumValue       subject0 = new ODataEnumValue("Red", "NS.ColorFlags");
            ODataEnumValue       subject1 = new ODataEnumValue("123", "NS.ColorFlags");
            ODataCollectionValue complexCollectionValue = new ODataCollectionValue {
                TypeName = "Collection(NS.ColorFlags)", Items = new[] { subject0, subject1 }
            };

            this.VerifyNonPrimitiveTypeRoundtrip(complexCollectionValue, "ClothesColors");
        }
Exemplo n.º 9
0
        /// <summary>
        /// Writes a enum property.
        /// </summary>
        /// <param name="enumValue">The enum value to be written.</param>
        /// <param name="isOpenPropertyType">If the property is open.</param>
        private void WriteEnumProperty(
            ODataEnumValue enumValue,
            bool isOpenPropertyType)
        {
            ResolveEnumValueTypeName(enumValue, isOpenPropertyType);

            this.WritePropertyTypeName();
            this.JsonWriter.WriteName(this.currentPropertyInfo.WireName);
            this.JsonLightValueSerializer.WriteEnumValue(enumValue, this.currentPropertyInfo.MetadataType.TypeReference);
        }
Exemplo n.º 10
0
        private static ODataResource CreateEntry(Object entity, PropertyInfo[] structuralProperties)
        {
            Type clrEntityType   = entity.GetType();
            var  odataProperties = new ODataProperty[structuralProperties.Length];

            for (int i = 0; i < odataProperties.Length; i++)
            {
                Object     value      = structuralProperties[i].GetValue(entity);
                ODataValue odataValue = null;
                if (value == null)
                {
                    odataValue = new ODataNullValue();
                }
                else if (value.GetType().IsEnum)
                {
                    odataValue = new ODataEnumValue(value.ToString());
                }
                else if (value is DateTime dateTime)
                {
                    switch (dateTime.Kind)
                    {
                    case DateTimeKind.Unspecified:
                        value = new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc));
                        break;

                    case DateTimeKind.Utc:
                        value = new DateTimeOffset(dateTime);
                        break;

                    case DateTimeKind.Local:
                        value = new DateTimeOffset(dateTime.ToUniversalTime());
                        break;

                    default:
                        throw new ArgumentOutOfRangeException("unknown DateTimeKind " + dateTime.Kind.ToString());
                    }
                    odataValue = new ODataPrimitiveValue(value);
                }
                else
                {
                    odataValue = new ODataPrimitiveValue(value);
                }

                odataProperties[i] = new ODataProperty()
                {
                    Name = structuralProperties[i].Name, Value = odataValue
                };
            }

            return(new ODataResource
            {
                TypeName = clrEntityType.FullName,
                Properties = odataProperties
            });
        }
Exemplo n.º 11
0
        public void ConvertEnumValue_Throws_ForNonEnumType()
        {
            // Arrange
            object value = new ODataEnumValue("Red");
            Type   type  = typeof(int);

            // Act & Assert
            Assert.Throws <InvalidOperationException>(
                () => EnumDeserializationHelpers.ConvertEnumValue(value, type),
                "The type 'Int32' must be an enum or Nullable<T> where T is an enum type.");
        }
Exemplo n.º 12
0
        public void ConvertEnumValue_Throws_ForNullTypeParameter()
        {
            // Arrange
            object value = new ODataEnumValue("Red");
            Type   type  = null;

            // Act & Assert
            ExceptionAssert.ThrowsArgumentNull(
                () => EnumDeserializationHelpers.ConvertEnumValue(value, type),
                "type");
        }
Exemplo n.º 13
0
        public void ConvertEnumValue_Returns_ForODataEnumValue()
        {
            // Arrange & Act & Assert
            ODataEnumValue enumValue = new ODataEnumValue("Red");

            Assert.Equal(EnumColor.Red, EnumDeserializationHelpers.ConvertEnumValue(enumValue, typeof(EnumColor)));

            // Arrange & Act & Assert
            enumValue = new ODataEnumValue("Green");
            Assert.Equal(EnumColor.Green, EnumDeserializationHelpers.ConvertEnumValue(enumValue, typeof(EnumColor)));
        }
        /// <summary>
        /// Generates a string to be used as the skip token value within the next link.
        /// </summary>
        /// <param name="lastMember"> Object based on which SkipToken value will be generated.</param>
        /// <param name="model">The edm model.</param>
        /// <param name="orderByNodes">List of orderByNodes used to generate the skiptoken value.</param>
        /// <returns>Value for the skiptoken to be used in the next link.</returns>
        private static string GenerateSkipTokenValue(Object lastMember, IEdmModel model, IList <OrderByNode> orderByNodes)
        {
            if (lastMember == null)
            {
                return(String.Empty);
            }

            IEnumerable <IEdmProperty> propertiesForSkipToken = GetPropertiesForSkipToken(lastMember, model, orderByNodes);
            StringBuilder skipTokenBuilder = new StringBuilder(String.Empty);

            if (propertiesForSkipToken == null)
            {
                return(skipTokenBuilder.ToString());
            }

            int    count = 0;
            string uriLiteral;
            object value;
            int    lastIndex         = propertiesForSkipToken.Count() - 1;
            IEdmStructuredObject obj = lastMember as IEdmStructuredObject;

            foreach (IEdmProperty edmProperty in propertiesForSkipToken)
            {
                bool   islast          = count == lastIndex;
                string clrPropertyName = EdmLibHelpers.GetClrPropertyName(edmProperty, model);
                if (obj != null)
                {
                    obj.TryGetPropertyValue(clrPropertyName, out value);
                }
                else
                {
                    value = lastMember.GetType().GetProperty(clrPropertyName).GetValue(lastMember);
                }

                if (value == null)
                {
                    uriLiteral = ODataUriUtils.ConvertToUriLiteral(value, ODataVersion.V401);
                }
                else if (edmProperty.Type.IsEnum())
                {
                    ODataEnumValue enumValue = new ODataEnumValue(value.ToString(), value.GetType().FullName);
                    uriLiteral = ODataUriUtils.ConvertToUriLiteral(enumValue, ODataVersion.V401, model);
                }
                else
                {
                    uriLiteral = ODataUriUtils.ConvertToUriLiteral(value, ODataVersion.V401, model);
                }

                skipTokenBuilder.Append(edmProperty.Name).Append(propertyDelimiter).Append(uriLiteral).Append(islast ? String.Empty : CommaDelimiter.ToString());
                count++;
            }

            return(skipTokenBuilder.ToString());
        }
Exemplo n.º 15
0
 public void QuerySingletonEnumProperty()
 {
     foreach (var mimeType in mimeTypes)
     {
         ODataProperty property = this.QueryProperty("Company/CompanyCategory", mimeType);
         if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
         {
             ODataEnumValue enumValue = (ODataEnumValue)property.Value;
             Assert.AreEqual("IT", enumValue.Value);
         }
     }
 }
Exemplo n.º 16
0
        public void UpdateEnumProperty()
        {
            // query an entry
            ODataEntry productEntry = this.QueryEntityItem("Products(5)") as ODataEntry;

            // send a request to update an entry property
            productEntry = new ODataEntry()
            {
                TypeName   = NameSpacePrefix + "Product",
                Properties = new[]
                {
                    new ODataProperty {
                        Name = "SkinColor", Value = new ODataEnumValue("Green")
                    },
                    new ODataProperty {
                        Name = "UserAccess", Value = new ODataEnumValue("Read")
                    }
                }
            };

            var settings = new ODataMessageWriterSettings();

            settings.PayloadBaseUri = ServiceBaseUri;
            settings.AutoComputePayloadMetadataInJson = true;

            var productType = Model.FindDeclaredType(NameSpacePrefix + "Product") as IEdmEntityType;
            var productSet  = Model.EntityContainer.FindEntitySet("Products");

            foreach (var mimeType in mimeTypes)
            {
                var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri + "Products(5)"));
                requestMessage.SetHeader("Content-Type", mimeType);
                requestMessage.SetHeader("Accept", mimeType);
                requestMessage.Method = "PATCH";

                using (var messageWriter = new ODataMessageWriter(requestMessage, settings, Model))
                {
                    var odataWriter = messageWriter.CreateODataEntryWriter(productSet, productType);
                    odataWriter.WriteStart(productEntry);
                    odataWriter.WriteEnd();
                }

                var responseMessage = requestMessage.GetResponse();

                // verify the update
                Assert.AreEqual(204, responseMessage.StatusCode);
                ODataEntry     updatedProduct = this.QueryEntityItem("Products(5)") as ODataEntry;
                ODataEnumValue skinColor      = updatedProduct.Properties.Single(p => p.Name == "SkinColor").Value as ODataEnumValue;
                ODataEnumValue userAccess     = updatedProduct.Properties.Single(p => p.Name == "UserAccess").Value as ODataEnumValue;
                Assert.AreEqual("Green", skinColor.Value);
                Assert.AreEqual("Read", userAccess.Value);
            }
        }
        /// <summary>
        /// Read an enumeration value from the reader.
        /// </summary>
        /// <param name="actualValueTypeReference">The thpe of the value to read.</param>
        /// <returns>An ODataEnumValue with the value read from the payload.</returns>
        private ODataEnumValue ReadEnumValue(IEdmEnumTypeReference actualValueTypeReference)
        {
            Debug.Assert(actualValueTypeReference != null, "actualValueTypeReference != null");
            Debug.Assert(actualValueTypeReference.TypeKind() == EdmTypeKind.Enum, "Only Enum values can be read by this method.");
            this.AssertXmlCondition(XmlNodeType.Element, XmlNodeType.Attribute);

            ODataEnumValue result = AtomValueUtils.ReadEnumValue(this.XmlReader, actualValueTypeReference);

            this.AssertXmlCondition(true, XmlNodeType.EndElement);
            Debug.Assert(result != null, "The method should never return null since it doesn't handle null values.");
            return(result);
        }
Exemplo n.º 18
0
 public void FlagsEnumAsTopLevelValue_StrAsValue_StrAsTypeName_anyContentType()
 {
     WriteToMessageWriterAndVerifyPayload(
         contentType: "*/*",
         writerAction: (writer) =>
     {
         ODataEnumValue enumValue = new ODataEnumValue(Color.Red.ToString(), "NS.EnumUndefinedTypename");
         writer.WriteValue(enumValue);
     },
         expectedPayload: Color.Red.ToString()
         );
 }
Exemplo n.º 19
0
        /// <inheritdoc />
        public override object ReadInline(object item, IEdmTypeReference edmType, ODataDeserializerContext readContext)
        {
            if (item == null)
            {
                return(null);
            }

            if (readContext == null)
            {
                throw Error.ArgumentNull(nameof(readContext));
            }

            ODataProperty property = item as ODataProperty;

            if (property != null)
            {
                item = property.Value;
            }

            IEdmEnumTypeReference enumTypeReference = edmType.AsEnum();
            ODataEnumValue        enumValue         = item as ODataEnumValue;

            if (readContext.IsNoClrType)
            {
                Contract.Assert(edmType.TypeKind() == EdmTypeKind.Enum);
                return(new EdmEnumObject(enumTypeReference, enumValue.Value));
            }

            IEdmEnumType enumType = enumTypeReference.EnumDefinition();

            // Enum member supports model alias case. So, try to use the Edm member name to retrieve the Enum value.
            var memberMapAnnotation = readContext.Model.GetClrEnumMemberAnnotation(enumType);

            if (memberMapAnnotation != null)
            {
                if (enumValue != null)
                {
                    IEdmEnumMember enumMember = enumType.Members.FirstOrDefault(m => m.Name == enumValue.Value);
                    if (enumMember != null)
                    {
                        var clrMember = memberMapAnnotation.GetClrEnumMember(enumMember);
                        if (clrMember != null)
                        {
                            return(clrMember);
                        }
                    }
                }
            }

            Type clrType = readContext.Model.GetClrType(edmType);

            return(EnumDeserializationHelpers.ConvertEnumValue(item, clrType));
        }
Exemplo n.º 20
0
 public void FlagsEnumAsTopLevelValue_StrAsValue_StrAsTypeName_textplainContentType()
 {
     WriteToMessageWriterAndVerifyPayload(
         contentType: "text/plain", // can't be full/minimal/none metadata
         writerAction: (writer) =>
     {
         ODataEnumValue enumValue = new ODataEnumValue(Color.Red.ToString(), "NS.EnumUndefinedTypename");
         writer.WriteValue(enumValue);
     },
         expectedPayload: Color.Red.ToString()
         );
 }
        public override ODataEnumValue CreateODataEnumValue(object graph, IEdmEnumTypeReference enumType, ODataSerializerContext writeContext)
        {
            ODataEnumValue result = base.CreateODataEnumValue(graph, enumType, writeContext);

            if (!string.IsNullOrEmpty(result?.Value) && !string.IsNullOrEmpty(result.TypeName))
            {
                // EnumKey >> "Namespace.EnumType'EnumKey'"
                result = new ODataEnumValue($"{result.TypeName}'{result.Value}'");
            }

            return(result);
        }
Exemplo n.º 22
0
        public void MaterializeEnumTypeShouldWork()
        {
            ODataEnumValue enumValue = new ODataEnumValue("blue");
            ODataProperty  property  = new ODataProperty {
                Name = "enumProperty", Value = enumValue
            };
            var enumPolicy = new EnumValueMaterializationPolicy(new TestMaterializerContext());
            var result     = enumPolicy.MaterializeEnumTypeProperty(typeof(Color), property);

            property.GetMaterializedValue().Should().Be(Color.Blue);
            result.Should().Be(Color.Blue);
        }
Exemplo n.º 23
0
        /// <summary>
        /// ConstantExpression visit method
        /// </summary>
        /// <param name="c">The ConstantExpression expression to visit</param>
        /// <returns>The visited ConstantExpression expression </returns>
        internal override Expression VisitConstant(ConstantExpression c)
        {
            if (c.Value == null)
            {
                this.builder.Append(UriHelper.NULL);
                return(c);
            }

            // DEVNOTE:
            // Rather than forcing every other codepath to have the 'Try...' pattern for formatting,
            // we catch the InvalidOperationException here to change the exception type.
            // This is exceedingly rare, and not a scenario where performance is meaningful, so the
            // reduced complexity in all other call sites is worth the extra logic here.
            string               result;
            BinaryExpression     b = this.parent as BinaryExpression;
            MethodCallExpression m = this.parent as MethodCallExpression;

            if ((b != null && HasEnumInBinaryExpression(b)) || (m != null && m.Method.Name == "HasFlag"))
            {
                c = this.ConvertConstantExpressionForEnum(c);
                ClientEdmModel       model          = this.context.Model;
                IEdmType             edmType        = model.GetOrCreateEdmType(c.Type.IsEnum() ? c.Type : c.Type.GetGenericArguments()[0]);
                ClientTypeAnnotation typeAnnotation = model.GetClientTypeAnnotation(edmType);
                string         typeNameInEdm        = this.context.ResolveNameFromTypeInternal(typeAnnotation.ElementType);
                MemberInfo     member      = typeAnnotation.ElementType.GetField(c.Value.ToString());
                string         memberValue = ClientTypeUtil.GetServerDefinedName(member);
                ODataEnumValue enumValue   = new ODataEnumValue(memberValue, typeNameInEdm ?? typeAnnotation.ElementTypeName);
                result = ODataUriUtils.ConvertToUriLiteral(enumValue, CommonUtil.ConvertToODataVersion(this.uriVersion), null);
            }
            else
            {
                try
                {
                    result = LiteralFormatter.ForConstants.Format(c.Value);
                }
                catch (InvalidOperationException)
                {
                    if (this.cantTranslateExpression)
                    {
                        // there's already a problem in the parents.
                        // we should just return here, because caller somewhere up the stack will throw a better exception
                        return(c);
                    }

                    throw new NotSupportedException(Strings.ALinq_CouldNotConvert(c.Value));
                }
            }

            Debug.Assert(result != null, "result != null");
            this.builder.Append(result);
            return(c);
        }
        private static bool ApplyDynamicProperty(ODataProperty property, IEdmStructuredType structuredType,
                                                 object resource, ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext)
        {
            PropertyInfo propertyInfo = EdmLibHelpers.GetDynamicPropertyDictionary(structuredType,
                                                                                   readContext.Model);

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

            IDictionary <string, object> dynamicPropertyDictionary = propertyInfo.GetValue(resource)
                                                                     as IDictionary <string, object>;

            if (dynamicPropertyDictionary == null)
            {
                dynamicPropertyDictionary = new Dictionary <string, object>();
                propertyInfo.SetValue(resource, dynamicPropertyDictionary);
            }

            if (dynamicPropertyDictionary.ContainsKey(property.Name))
            {
                throw Error.InvalidOperation(SRResources.DuplicateDynamicPropertyNameFound,
                                             property.Name, structuredType.FullTypeName());
            }

            EdmTypeKind       propertyKind;
            IEdmTypeReference propertyType = null;
            object            value        = ConvertValue(property.Value, ref propertyType, deserializerProvider, readContext, out propertyKind);

            if (propertyKind == EdmTypeKind.Collection)
            {
                throw Error.InvalidOperation(SRResources.CollectionNotAllowedAsDynamicProperty, property.Name);
            }

            if (propertyKind == EdmTypeKind.Enum)
            {
                ODataEnumValue enumValue = (ODataEnumValue)value;
                IEdmModel      model     = readContext.Model;
                IEdmType       edmType   = model.FindType(enumValue.TypeName);
                if (edmType == null)
                {
                    return(false);
                }

                Type enumType = EdmLibHelpers.GetClrType(edmType, model);
                value = Enum.Parse(enumType, enumValue.Value);
            }

            dynamicPropertyDictionary.Add(property.Name, value);
            return(true);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Materializes the enum data value.
        /// </summary>
        /// <param name="valueType">Type of the collection item.</param>
        /// <param name="property">The ODataProperty.</param>
        /// <returns>Materialized enum data CLR value.</returns>
        public object MaterializeEnumTypeProperty(Type valueType, ODataProperty property)
        {
            object         materializedValue = null;
            ODataEnumValue value             = property.Value as ODataEnumValue;

            this.MaterializeODataEnumValue(valueType, value.TypeName, value.Value, () => "TODO: Is this reachable?", out materializedValue);
            if (!property.HasMaterializedValue())
            {
                property.SetMaterializedValue(materializedValue);
            }

            return(materializedValue);
        }
Exemplo n.º 26
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>
        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);
        }
Exemplo n.º 27
0
        public override object ReadInline(object item, IEdmTypeReference edmType, ODataDeserializerContext readContext)
        {
            ODataEnumValue valueItem = item as ODataEnumValue;

            if (valueItem != null && !string.IsNullOrEmpty(valueItem.Value) && !string.IsNullOrEmpty(valueItem.TypeName))
            {
                // "Namespace.EnumType'EnumKey'" >> EnumKey
                valueItem = new ODataEnumValue(valueItem.Value.Replace(valueItem.TypeName, string.Empty).Replace("'", string.Empty));
            }
            object result = base.ReadInline(valueItem, edmType, readContext);

            return(result);
        }
 /// <summary>
 /// Write enum value
 /// </summary>
 /// <param name="value">enum value</param>
 /// <param name="expectedTypeReference">expected type reference</param>
 public virtual void WriteEnumValue(
     ODataEnumValue value,
     IEdmTypeReference expectedTypeReference)
 {
     if (value.Value == null)
     {
         this.WriteNullValue();
     }
     else
     {
         this.JsonWriter.WritePrimitiveValue(value.Value);
     }
 }
        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);
        }
 /// <summary>
 /// Asynchronously writes enum value
 /// </summary>
 /// <param name="value">enum value</param>
 /// <param name="expectedTypeReference">expected type reference</param>
 /// <returns>A task that represents the asynchronous write operation.</returns>
 public virtual Task WriteEnumValueAsync(
     ODataEnumValue value,
     IEdmTypeReference expectedTypeReference)
 {
     if (value.Value == null)
     {
         return(this.WriteNullValueAsync());
     }
     else
     {
         return(this.AsynchronousJsonWriter.WritePrimitiveValueAsync(value.Value));
     }
 }
Exemplo n.º 31
0
        private static string TranslateNode(object node, string functionName, string parameterName)
        {
            // If the function parameter is null, for example myFunction(param=null),
            // the input node here is not null, it is a contant node with a value as "null".
            // However, if a function call (or key) using parameter alias but without providing the parameter alias value,
            // the input node here is a null.
            if (node == null)
            {
                // We can't throw ODataException here because ODataException will be caught and return 404 response with empty message.
                throw new InvalidOperationException(Error.Format(SRResources.MissingConvertNode, parameterName, functionName));
            }

            ConstantNode constantNode = node as ConstantNode;

            if (constantNode != null)
            {
                UriTemplateExpression uriTemplateExpression = constantNode.Value as UriTemplateExpression;
                if (uriTemplateExpression != null)
                {
                    return(uriTemplateExpression.LiteralText);
                }

                // Make the enum prefix free to work.
                ODataEnumValue enumValue = constantNode.Value as ODataEnumValue;
                if (enumValue != null)
                {
                    return(ODataUriUtils.ConvertToUriLiteral(enumValue, ODataVersion.V4));
                }

                return(constantNode.LiteralText);
            }

            ConvertNode convertNode = node as ConvertNode;

            if (convertNode != null)
            {
                return(TranslateNode(convertNode.Source, functionName, parameterName));
            }

            ParameterAliasNode parameterAliasNode = node as ParameterAliasNode;

            if (parameterAliasNode != null)
            {
                return(parameterAliasNode.Alias);
            }

            //return node.ToString();
            throw Error.NotSupported(SRResources.CannotRecognizeNodeType, typeof(ODataPathSegmentHandler),
                                     node.GetType().FullName);
        }
 /// <summary>
 /// Write enum value
 /// </summary>
 /// <param name="value">enum value</param>
 /// <param name="expectedTypeReference">expected type reference</param>
 public void WriteEnumValue(ODataEnumValue value, IEdmTypeReference expectedTypeReference)
 {
     throw new NotImplementedException();
 }
        public void FlagsEnumAsCollectionItemAsTopLevelValue_StrAsValue_StrAsTypeName_MinimalMetadata_CollecionWriter()
        {
            ODataCollectionStart collectionStart = new ODataCollectionStart();
            collectionStart.SetSerializationInfo(new ODataCollectionStartSerializationInfo { CollectionTypeName = "Collection(NS.ColorFlags)" });
            ODataEnumValue[] items = new ODataEnumValue[] 
            {
                new ODataEnumValue(ColorFlags.Red.ToString(), "NS.ColorFlags"),
                new ODataEnumValue(null, "NS.ColorFlags_Undefined"),
                new ODataEnumValue("Red,Green", "NS.ColorFlags"),
                new ODataEnumValue("Red|Green", "NS.ColorFlags"),
                new ODataEnumValue(ColorFlags.Green.ToString(), "NS.ColorFlags")
            };

            EdmEnumTypeReference enumRef = new EdmEnumTypeReference((IEdmEnumType)this.userModel.FindType("NS.ColorFlags"), true);
            WriteToMessageWriterAndVerifyPayload(
                contentType: "application/json;odata.metadata=minimal;",
                writerAction: (writer) =>
                {
                    ODataCollectionWriter collectionWriter = writer.CreateODataCollectionWriter(enumRef);
                    collectionWriter.WriteStart(collectionStart);
                    foreach (object item in items)
                    {
                        collectionWriter.WriteItem(item);
                    }

                    collectionWriter.WriteEnd();
                },
                expectedPayload: "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection(NS.ColorFlags)\",\"value\":[\"Red\",null,\"Red,Green\",\"Red|Green\",\"Green\"]}"
            );
        }
        /// <summary>
        /// Writes a enum property.
        /// </summary>
        /// <param name="property">The property to write out.</param>
        /// <param name="enumValue">The enum value to be written.</param>
        /// <param name="propertyTypeReference">The metadata type reference of the property.</param>
        /// <param name="isTopLevel">true when writing a top-level property; false for nested properties.</param>
        /// <param name="isOpenPropertyType">If the property is open.</param>
        private void WriteEnumProperty(
            ODataProperty property,
            ODataEnumValue enumValue,
            IEdmTypeReference propertyTypeReference,
            bool isTopLevel,
            bool isOpenPropertyType)
        {
            string wirePropertyName = GetWirePropertyName(isTopLevel, property.Name);

            IEdmTypeReference typeFromValue = TypeNameOracle.ResolveAndValidateTypeForEnumValue(this.Model, enumValue, isOpenPropertyType);

            // This is a work around, needTypeOnWire always = true for client side: 
            // ClientEdmModel's reflection can't know a property is open type even if it is, so here 
            // make client side always write 'odata.type' for enum.
            bool needTypeOnWire = string.Equals(this.JsonLightOutputContext.Model.GetType().Name, "ClientEdmModel", StringComparison.OrdinalIgnoreCase);
            string typeNameToWrite = this.JsonLightOutputContext.TypeNameOracle.GetValueTypeNameForWriting(
                enumValue, propertyTypeReference, typeFromValue, needTypeOnWire || isOpenPropertyType);

            this.WritePropertyTypeName(wirePropertyName, typeNameToWrite, isTopLevel);
            this.JsonWriter.WriteName(wirePropertyName);
            this.JsonLightValueSerializer.WriteEnumValue(enumValue, propertyTypeReference);
        }
Exemplo n.º 35
0
 public void IfValueIsEnumThenODataValueShouldBeReferenceEqual()
 {
     var enumValue = new ODataEnumValue(Color.Green.ToString());
     this.property.Value = enumValue;
     this.property.ODataValue.Should().BeSameAs(enumValue);
 }
 /// <summary>
 /// Write enum value
 /// </summary>
 /// <param name="value">enum value</param>
 /// <param name="expectedTypeReference">expected type reference</param>
 public void WriteEnumValue(
     ODataEnumValue value,
     IEdmTypeReference expectedTypeReference)
 {
     if (value.Value == null)
     {
         this.WriteNullValue();
     }
     else
     {
         this.JsonWriter.WritePrimitiveValue(value.Value);
     }
 }
Exemplo n.º 37
0
 public void TestEnumConvertToUriLiteral_EnumValue()
 {
     var val = new ODataEnumValue(11L + "", "Fully.Qualified.Namespace.ColorPattern");
     string enumValStr = ODataUriUtils.ConvertToUriLiteral(val, ODataVersion.V4);
     enumValStr.Should().Be("Fully.Qualified.Namespace.ColorPattern'11'");
 }
Exemplo n.º 38
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>
        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;
        }
 public void FlagsEnumAsTopLevelValue_StrAsValue_StrAsTypeName_anyContentType()
 {
     WriteToMessageWriterAndVerifyPayload(
         contentType: "*/*",
         writerAction: (writer) =>
         {
             ODataEnumValue enumValue = new ODataEnumValue(Color.Red.ToString(), "NS.EnumUndefinedTypename");
             writer.WriteValue(enumValue);
         },
         expectedPayload: Color.Red.ToString()
     );
 }
 public void FlagsEnumAsTopLevelValue_StrAsValue_StrAsTypeName_textplainContentType()
 {
     WriteToMessageWriterAndVerifyPayload(
         contentType: "text/plain", // can't be full/minimal/none metadata
         writerAction: (writer) =>
         {
             ODataEnumValue enumValue = new ODataEnumValue(Color.Red.ToString(), "NS.EnumUndefinedTypename");
             writer.WriteValue(enumValue);
         },
         expectedPayload: Color.Red.ToString()
     );
 }
        public void EnumTypeCollectionRoundtripJsonLightTest()
        {
            ODataEnumValue subject0 = new ODataEnumValue("Red", "NS.ColorFlags");
            ODataEnumValue subject1 = new ODataEnumValue("123", "NS.ColorFlags");
            ODataCollectionValue complexCollectionValue = new ODataCollectionValue { TypeName = "Collection(NS.ColorFlags)", Items = new[] { subject0, subject1 } };

            this.VerifyNonPrimitiveTypeRoundtrip(complexCollectionValue, "ClothesColors");
        }
        /// <summary>
        /// Writes an enumeration value.
        /// </summary>
        /// <param name="value">The value to write.</param>
        /// <param name="collectionValidator">The collection validator instance.</param>
        /// <param name="expectedTypeReference">The expected type of the enumeration value.</param>
        /// <param name="typeNameAnnotation">The optional type name annotation provided by the user on the OM for this enumeration value. The annotation value will override whatever type name is being written.</param>
        internal void WriteEnumValue(
            ODataEnumValue value,
            CollectionWithoutExpectedTypeValidator collectionValidator,
            IEdmTypeReference expectedTypeReference,
            SerializationTypeNameAnnotation typeNameAnnotation)
        {
            Debug.Assert(value != null, "value != null");

            // write type name without validation:
            // TODO: consider adding a overloaded GetValueTypeNameForWriting() without out parameter.
            string collectionItemTypeName;
            string typeName = this.AtomOutputContext.TypeNameOracle.GetValueTypeNameForWriting(value, expectedTypeReference, typeNameAnnotation, collectionValidator, out collectionItemTypeName);
            Debug.Assert(collectionItemTypeName == null, "collectionItemTypeName == null");
            if (typeName != null)
            {
                Debug.Assert(typeName != EdmConstants.EdmStringTypeName, "Enum typeName != EdmConstants.StringTypeName");
                this.WritePropertyTypeAttribute(typeName);
            }

            // write string value without validation:
            AtomValueUtils.WritePrimitiveValue(this.XmlWriter, value.Value);
        }
Exemplo n.º 43
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;
        }