internal static void ODataValueToString(StringBuilder sb, ODataValue value) { if (value == null || value is ODataNullValue) { sb.Append("null"); } ODataCollectionValue collectionValue = value as ODataCollectionValue; if (collectionValue != null) { ODataCollectionValueToString(sb, collectionValue); } ODataResourceValue resourceValue = value as ODataResourceValue; if (resourceValue != null) { ODataResourceValueToString(sb, resourceValue); } ODataPrimitiveValue primitiveValue = value as ODataPrimitiveValue; if (primitiveValue != null) { if (primitiveValue.FromODataValue() is string) { sb.Append(string.Concat("\"", JsonValueUtils.GetEscapedJsonString(value.FromODataValue()?.ToString()), "\"")); } else { sb.Append(JsonValueUtils.GetEscapedJsonString(value.FromODataValue()?.ToString())); } } }
public void WritingMultipleInstanceAnnotationInResourceValueShouldWrite(string filter, string expect) { var complexType = new EdmComplexType("NS", "Address"); model.AddElement(complexType); settings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter(filter); var result = this.SetupSerializerAndRunTest(serializer => { var resourceValue = new ODataResourceValue { TypeName = "NS.Address", InstanceAnnotations = new Collection <ODataInstanceAnnotation> { new ODataInstanceAnnotation("Custom.Bool", new ODataPrimitiveValue(true)), new ODataInstanceAnnotation("Custom.Int", new ODataPrimitiveValue(123)), new ODataInstanceAnnotation("My.String", new ODataPrimitiveValue("annotation")), new ODataInstanceAnnotation("My.Bool", new ODataPrimitiveValue(false)) } }; var complexTypeRef = new EdmComplexTypeReference(complexType, false); serializer.WriteResourceValue(resourceValue, complexTypeRef, false, serializer.CreateDuplicatePropertyNameChecker()); }); Assert.Equal(expect, result); }
public void IfValueIsResourceThenODataValueShouldBeReferenceEqual() { ODataResourceValue resourceValue = new ODataResourceValue(); this.property.Value = resourceValue; this.property.ODataValue.Should().BeSameAs(resourceValue); }
public async Task WriteResourceValueAsync_WritesExpectedValue() { var resourceValue = new ODataResourceValue { Properties = new List <ODataProperty> { new ODataProperty { Name = "LuckyNumber", Value = new ODataPrimitiveValue(13) }, new ODataProperty { Name = "FavoriteColor", Value = new ODataEnumValue("Black") } } }; var result = await SetupJsonLightValueSerializerAndRunTestAsync( (jsonLightValueSerializer) => { return(jsonLightValueSerializer.WriteResourceValueAsync( resourceValue, /* metadataTypeReference */ null, /* isOpenProperty */ false, new NullDuplicatePropertyNameChecker())); }); Assert.Equal("{\"LuckyNumber\":13,\"FavoriteColor\":\"Black\"}", result); }
public void IfValueIsResourceThenODataValueShouldBeReferenceEqual() { ODataResourceValue resourceValue = new ODataResourceValue(); this.property.Value = resourceValue; Assert.Same(resourceValue, this.property.ODataValue); }
public async Task WriteResourceValueAsync_WritesExpectedValueForOpenProperty() { var resourceValue = new ODataResourceValue { Properties = new List <ODataProperty> { new ODataProperty { Name = "LuckyNumber", Value = new ODataPrimitiveValue(13) }, new ODataProperty { Name = "FavoriteColor", Value = new ODataEnumValue("Black") } }, TypeName = "NS.Attributes" }; var metadataTypeReference = new EdmComplexTypeReference(this.attributesComplexType, false); var result = await SetupJsonLightValueSerializerAndRunTestAsync( (jsonLightValueSerializer) => { return(jsonLightValueSerializer.WriteResourceValueAsync( resourceValue, metadataTypeReference, /* isOpenProperty */ true, new NullDuplicatePropertyNameChecker())); }); Assert.Equal("{\"@odata.type\":\"#NS.Attributes\",\"LuckyNumber\":13,\"FavoriteColor\":\"Black\"}", result); }
public void TestResourceValueWithInstanceAnnotationConvertToUriLiteral() { ODataResourceValue value = new ODataResourceValue { TypeName = "Fully.Qualified.Namespace.Person", Properties = new[] { new ODataProperty { Name = "ID", Value = 42 } }, InstanceAnnotations = new [] { new ODataInstanceAnnotation("Custom.Annotation", new ODataResourceValue { TypeName = "Fully.Qualified.Namespace.Dog", Properties = new [] { new ODataProperty { Name = "Color", Value = "Red" } } }) } }; string actual = ODataUriUtils.ConvertToUriLiteral(value, ODataVersion.V4, HardCodedTestModel.TestModel); Assert.Equal( "{" + "\"@odata.type\":\"#Fully.Qualified.Namespace.Person\"," + "\"@Custom.Annotation\":{\"@odata.type\":\"#Fully.Qualified.Namespace.Dog\",\"Color\":\"Red\"}," + "\"ID\":42" + "}", actual); }
public void ShouldWriteCollectionOfDerivedResourceValueItem() { EdmModel currentModel = new EdmModel(); EdmComplexType addressType = new EdmComplexType("ns", "Address"); addressType.AddProperty(new EdmStructuralProperty(addressType, "Street", EdmCoreModel.Instance.GetString(isNullable: true))); currentModel.AddElement(addressType); EdmComplexType homeAddressType = new EdmComplexType("ns", "HomeAddress", addressType); homeAddressType.AddProperty(new EdmStructuralProperty(homeAddressType, "City", EdmCoreModel.Instance.GetString(isNullable: true))); currentModel.AddElement(homeAddressType); this.model = currentModel; var address = new ODataResourceValue { TypeName = "ns.HomeAddress", Properties = new[] { new ODataProperty { Name = "Street", Value = "1 Microsoft Way" }, new ODataProperty { Name = "City", Value = "Redmond" }, } }; WriteAndValidate(new ODataCollectionStart(), new object[] { address }, "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection(ns.Address)\",\"value\":[{\"@odata.type\":\"#ns.HomeAddress\",\"Street\":\"1 Microsoft Way\",\"City\":\"Redmond\"}]}", true, new EdmComplexTypeReference(addressType, false)); }
/// <summary> /// Writes the ODataValue (primitive, collection or resource value) to the underlying json writer. /// </summary> /// <param name="jsonWriter">The <see cref="JsonWriter"/> to write to.</param> /// <param name="odataValue">value to write.</param> internal static void WriteODataValue(this IJsonWriter jsonWriter, ODataValue odataValue) { if (odataValue == null || odataValue is ODataNullValue) { jsonWriter.WriteValue((string)null); return; } object objectValue = odataValue.FromODataValue(); if (EdmLibraryExtensions.IsPrimitiveType(objectValue.GetType())) { jsonWriter.WritePrimitiveValue(objectValue); return; } ODataResourceValue resourceValue = odataValue as ODataResourceValue; if (resourceValue != null) { jsonWriter.StartObjectScope(); foreach (ODataProperty property in resourceValue.Properties) { jsonWriter.WriteName(property.Name); jsonWriter.WriteODataValue(property.ODataValue); } jsonWriter.EndObjectScope(); return; } ODataCollectionValue collectionValue = odataValue as ODataCollectionValue; if (collectionValue != null) { jsonWriter.StartArrayScope(); foreach (object item in collectionValue.Items) { // Will not be able to accurately serialize complex objects unless they are ODataValues. ODataValue collectionItem = item as ODataValue; if (item != null) { jsonWriter.WriteODataValue(collectionItem); } else { throw new ODataException(ODataErrorStrings.ODataJsonWriter_UnsupportedValueInCollection); } } jsonWriter.EndArrayScope(); return; } throw new ODataException( ODataErrorStrings.ODataJsonWriter_UnsupportedValueType(odataValue.GetType().FullName)); }
public void TestResourceValueWithNestedResourceValueConvertToUriLiteral() { ODataResourceValue value = new ODataResourceValue { TypeName = "Fully.Qualified.Namespace.Person", Properties = new[] { new ODataProperty { Name = "ID", Value = 42 }, new ODataProperty { Name = "SSN", Value = "777-42-9001" }, new ODataProperty { Name = "MyDog", Value = new ODataResourceValue { TypeName = "Fully.Qualified.Namespace.Dog", Properties = new [] { new ODataProperty { Name = "Color", Value = "Red" } } } } } }; string actual = ODataUriUtils.ConvertToUriLiteral(value, ODataVersion.V4, HardCodedTestModel.TestModel); Assert.Equal(@"{""@odata.type"":""#Fully.Qualified.Namespace.Person"",""ID"":42,""SSN"":""777-42-9001"",""MyDog"":{""Color"":""Red""}}", actual); }
private static void AssertODataResourceValueAreEqual(ODataResourceValue resourceValue1, ODataResourceValue resourceValue2) { Assert.NotNull(resourceValue1); Assert.NotNull(resourceValue2); Assert.Equal(resourceValue1.TypeName, resourceValue2.TypeName); AssertODataPropertiesAreEqual(resourceValue1.Properties, resourceValue2.Properties); }
public void TestCollectionResourceValueWithInstanceAnnotationConvertToUriLiteral() { ODataResourceValue person = new ODataResourceValue { TypeName = "Fully.Qualified.Namespace.Person", Properties = new[] { new ODataProperty { Name = "ID", Value = 42 } }, InstanceAnnotations = new[] { new ODataInstanceAnnotation("Custom.Annotation", new ODataResourceValue { TypeName = "Fully.Qualified.Namespace.Dog", Properties = new [] { new ODataProperty { Name = "Color", Value = "Red" } } }) } }; ODataResourceValue employee = new ODataResourceValue { TypeName = "Fully.Qualified.Namespace.Employee", Properties = new[] { new ODataProperty { Name = "ID", Value = 42 }, new ODataProperty { Name = "WorkEmail", Value = "*****@*****.**" } } }; ODataCollectionValue collection = new ODataCollectionValue { TypeName = "Collection(Fully.Qualified.Namespace.Person)", Items = new[] { person, employee } }; string actual = ODataUriUtils.ConvertToUriLiteral(collection, ODataVersion.V4, HardCodedTestModel.TestModel); Assert.Equal( "[" + "{\"@Custom.Annotation\":{\"@odata.type\":\"#Fully.Qualified.Namespace.Dog\",\"Color\":\"Red\"},\"ID\":42}," + "{\"@odata.type\":\"#Fully.Qualified.Namespace.Employee\",\"ID\":42,\"WorkEmail\":\"[email protected]\"}" + "]", actual); }
public void WritingResourceValueWithoutMetadataTypeAndWithoutTypeNameInRequestShouldFail() { var serializer = CreateODataJsonLightValueSerializer(false); var resourceValue = new ODataResourceValue(); Action test = () => serializer.WriteResourceValue(resourceValue, null, false, null); test.Throws <ODataException>(Strings.ODataJsonLightPropertyAndValueSerializer_NoExpectedTypeOrTypeNameSpecifiedForResourceValueRequest); }
/// <summary> /// Visits a resource value item. /// </summary> /// <param name="resourceValue">The resource value to visit.</param> protected virtual void VisitResourceValue(ODataResourceValue resourceValue) { var properties = resourceValue.Properties; if (properties != null) { foreach (var property in properties) { this.Visit(property); } } }
/// <summary> /// Asynchronously writes out the value of a resource (complex or entity). /// </summary> /// <param name="resourceValue">The resource (complex or entity) value to write.</param> /// <param name="metadataTypeReference">The metadata type for the resource value.</param> /// <param name="isOpenPropertyType">true if the type name belongs to an open (dynamic) property.</param> /// <param name="duplicatePropertyNamesChecker">The checker instance for duplicate property names.</param> /// <remarks>The current recursion depth should be a value, measured by the number of resource and collection values between /// this resource value and the top-level payload, not including this one.</remarks> /// <returns>A task that represents the asynchronous write operation.</returns> public virtual async Task WriteResourceValueAsync( ODataResourceValue resourceValue, IEdmTypeReference metadataTypeReference, bool isOpenPropertyType, IDuplicatePropertyNameChecker duplicatePropertyNamesChecker) { Debug.Assert(resourceValue != null, "resourceValue != null"); this.IncreaseRecursionDepth(); // Start the object scope which will represent the entire resource instance; await this.AsynchronousJsonWriter.StartObjectScopeAsync().ConfigureAwait(false); string typeName = resourceValue.TypeName; // In requests, we allow the property type reference to be null if the type name is specified in the OM if (metadataTypeReference == null && !this.WritingResponse && typeName == null && this.Model.IsUserModel()) { throw new ODataException(ODataErrorStrings.ODataJsonLightPropertyAndValueSerializer_NoExpectedTypeOrTypeNameSpecifiedForResourceValueRequest); } // Resolve the type name to the type; if no type name is specified we will use the type inferred from metadata. IEdmStructuredTypeReference resourceValueTypeReference = (IEdmStructuredTypeReference)TypeNameOracle.ResolveAndValidateTypeForResourceValue(this.Model, metadataTypeReference, resourceValue, isOpenPropertyType, this.WriterValidator); Debug.Assert( metadataTypeReference == null || resourceValueTypeReference == null || EdmLibraryExtensions.IsAssignableFrom(metadataTypeReference, resourceValueTypeReference), "Complex property types must be the same as or inherit from the ones from metadata (unless open)."); typeName = this.JsonLightOutputContext.TypeNameOracle.GetValueTypeNameForWriting(resourceValue, metadataTypeReference, resourceValueTypeReference, isOpenPropertyType); if (typeName != null) { await this.AsynchronousODataAnnotationWriter.WriteODataTypeInstanceAnnotationAsync(typeName) .ConfigureAwait(false); } // Write custom instance annotations await this.InstanceAnnotationWriter.WriteInstanceAnnotationsAsync(resourceValue.InstanceAnnotations) .ConfigureAwait(false); // Write the properties of the resource value as usual. Note we do not allow resource types to contain named stream properties. await this.PropertySerializer.WritePropertiesAsync( resourceValueTypeReference == null?null : resourceValueTypeReference.StructuredDefinition(), resourceValue.Properties, true /* isComplexValue */, duplicatePropertyNamesChecker, null).ConfigureAwait(false); // End the object scope which represents the resource instance; await this.AsynchronousJsonWriter.EndObjectScopeAsync().ConfigureAwait(false); this.DecreaseRecursionDepth(); }
/// <summary> /// Init the <see cref="ResourceExampleValue"/> /// </summary> /// <param name="record">The input record.</param> public override void Initialize(IEdmRecordExpression record) { // Load ExampleValue base.Initialize(record); // Value of PrimitiveExampleValue IEdmPropertyConstructor property = record.FindProperty("Value"); if (property != null) { Value = property.Value.Convert() as ODataResourceValue; } }
private ODataResourceValue CreateODataResourceValue(object graph, IEdmStructuredTypeReference expectedType, ODataSerializerContext writeContext) { List <ODataProperty> properties = new List <ODataProperty>(); ODataResourceValue resourceValue = new ODataResourceValue { TypeName = writeContext.GetEdmType(graph, graph.GetType()).FullName() }; IDelta delta = graph as IDelta; if (delta != null) { foreach (string propertyName in delta.GetChangedPropertyNames()) { SetDeltaPropertyValue(writeContext, properties, delta, propertyName); } foreach (string propertyName in delta.GetUnchangedPropertyNames()) { SetDeltaPropertyValue(writeContext, properties, delta, propertyName); } } else { HashSet <string> structuralPropertyNames = new HashSet <string>(); foreach (IEdmStructuralProperty structuralProperty in expectedType.DeclaredStructuralProperties()) { structuralPropertyNames.Add(structuralProperty.Name); } foreach (PropertyInfo property in graph.GetType().GetProperties()) { if (structuralPropertyNames.Contains(property.Name)) { object propertyValue = property.GetValue(graph); IEdmStructuredTypeReference expectedPropType = null; if (propertyValue == null) { expectedPropType = writeContext.GetEdmType(propertyValue, property.PropertyType) as IEdmStructuredTypeReference; } SetPropertyValue(writeContext, properties, expectedPropType, property.Name, propertyValue); } } } resourceValue.Properties = properties; return(resourceValue); }
/// <summary> /// Writes a resource property. /// </summary> /// <param name="property">The property to write out.</param> /// <param name="resourceValue">The resource value to be written</param> /// <param name="isOpenPropertyType">If the property is open.</param> private void WriteResourceProperty( ODataProperty property, ODataResourceValue resourceValue, bool isOpenPropertyType) { Debug.Assert(!this.currentPropertyInfo.IsTopLevel, "Resource property should not be top level"); this.JsonWriter.WriteName(property.Name); this.JsonLightValueSerializer.WriteResourceValue( resourceValue, this.currentPropertyInfo.MetadataType.TypeReference, isOpenPropertyType, this.CreateDuplicatePropertyNameChecker()); }
public async Task WriteEndAsync_WritesCollectionEnd() { var model = new EdmModel(); var productEntityType = CreateProductEntityType(); model.AddElement(productEntityType); var collectionStart = CreateProductCollectionStart(); var itemTypeReference = new EdmEntityTypeReference(productEntityType, true); var odataResource1 = new ODataResourceValue { Properties = new List <ODataProperty> { new ODataProperty { Name = "Id", Value = 1 }, new ODataProperty { Name = "Name", Value = "Pencil" } }, TypeName = "NS.Product" }; var odataResource2 = new ODataResourceValue { Properties = new List <ODataProperty> { new ODataProperty { Name = "Id", Value = 2 }, new ODataProperty { Name = "Name", Value = "Paper" } }, TypeName = "NS.Product" }; var result = await SetupJsonLightCollectionWriterAndRunTestAsync( async (jsonLightCollectionWriter) => { await jsonLightCollectionWriter.WriteStartAsync(collectionStart); await jsonLightCollectionWriter.WriteItemAsync(odataResource1); await jsonLightCollectionWriter.WriteItemAsync(odataResource2); await jsonLightCollectionWriter.WriteEndAsync(); }, model, itemTypeReference); Assert.Equal("{\"@odata.context\":\"http://odata.org/test/$metadata#Collection(NS.Product)\"," + "\"value\":[{\"Id\":1,\"Name\":\"Pencil\"},{\"Id\":2,\"Name\":\"Paper\"}]}", result); }
internal static ODataValue ReadODataValue(this IJsonReader jsonReader) { if (jsonReader.NodeType == JsonNodeType.PrimitiveValue) { object primitiveValue = jsonReader.ReadPrimitiveValue(); return(primitiveValue.ToODataValue()); } else if (jsonReader.NodeType == JsonNodeType.StartObject) { jsonReader.ReadStartObject(); ODataResourceValue resourceValue = new ODataResourceValue(); IList <ODataProperty> propertyList = new List <ODataProperty>(); while (jsonReader.NodeType != JsonNodeType.EndObject) { ODataProperty property = new ODataProperty(); property.Name = jsonReader.ReadPropertyName(); property.Value = jsonReader.ReadODataValue(); propertyList.Add(property); } resourceValue.Properties = propertyList; jsonReader.ReadEndObject(); return(resourceValue); } else if (jsonReader.NodeType == JsonNodeType.StartArray) { jsonReader.ReadStartArray(); ODataCollectionValue collectionValue = new ODataCollectionValue(); IList <object> propertyList = new List <object>(); while (jsonReader.NodeType != JsonNodeType.EndArray) { propertyList.Add(jsonReader.ReadODataValue()); } collectionValue.Items = propertyList; jsonReader.ReadEndArray(); return(collectionValue); } else { return(jsonReader.ReadAsUntypedOrNullValue()); } }
public void WriteTopLevelErrorWithResourceInstanceAnnotationNoTypeNameShouldThrow() { SetupSerializerAndRunTest(null, serializer => { ODataError error = new ODataError(); var instanceAnnotations = new Collection <ODataInstanceAnnotation>(); var resourceValue = new ODataResourceValue(); ODataInstanceAnnotation annotation = new ODataInstanceAnnotation("sample.complex", resourceValue); instanceAnnotations.Add(annotation); error.InstanceAnnotations = instanceAnnotations; Action writeError = () => serializer.WriteTopLevelError(error, false); writeError.Throws <ODataException>(Strings.WriterValidationUtils_MissingTypeNameWithMetadata); }); }
public void WritingResourceValueAndNestedResourceValueWithSimilarPropertiesShouldWrite() { var complexType = new EdmComplexType("NS", "Address"); complexType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String); complexType.AddStructuralProperty("City", EdmPrimitiveTypeKind.String); model.AddElement(complexType); var entityType = new EdmEntityType("NS", "Customer"); entityType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String); entityType.AddStructuralProperty("Location", new EdmComplexTypeReference(complexType, false)); model.AddElement(entityType); settings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*"); var result = this.SetupSerializerAndRunTest(serializer => { var resourceValue = new ODataResourceValue { TypeName = "NS.Customer", Properties = new[] { new ODataProperty { Name = "Name", Value = "MyName" }, new ODataProperty { Name = "Location", Value = new ODataResourceValue { TypeName = "NS.Address", Properties = new [] { new ODataProperty { Name = "Name", Value = "AddressName" }, new ODataProperty { Name = "City", Value = "MyCity" } } } } } }; var entityTypeRef = new EdmEntityTypeReference(entityType, false); serializer.WriteResourceValue(resourceValue, entityTypeRef, false, serializer.GetDuplicatePropertyNameChecker()); }); Assert.Equal(@"{""Name"":""MyName"",""Location"":{""Name"":""AddressName"",""City"":""MyCity""}}", result); }
public void ResourceCustomInstanceAnnotationOnErrorShouldRoundtrip() { var originalResourceValue = new ODataResourceValue { TypeName = "ns.ErrorDetails", Properties = new[] { new ODataProperty { Name = "ErrorDetailName", Value = "inner property value" } } }; var original = new KeyValuePair <string, ODataValue>("sample.error", originalResourceValue); var error = this.WriteThenReadErrorWithInstanceAnnotation(original); var annotation = RunBasicVerificationAndGetAnnotationValue("sample.error", error); var value = Assert.IsType <ODataResourceValue>(annotation); Assert.Equal("inner property value", value.Properties.First().Value); }
public static void AssertODataValueAreEqual(ODataValue value1, ODataValue value2) { if (value1.IsNullValue && value2.IsNullValue) { return; } ODataPrimitiveValue primitiveValue1 = value1 as ODataPrimitiveValue; ODataPrimitiveValue primitiveValue2 = value2 as ODataPrimitiveValue; if (primitiveValue1 != null && primitiveValue2 != null) { AssertODataPrimitiveValueAreEqual(primitiveValue1, primitiveValue2); } else { ODataResourceValue resourceValue1 = value1 as ODataResourceValue; ODataResourceValue resourceValue2 = value2 as ODataResourceValue; if (resourceValue1 != null && resourceValue2 != null) { AssertODataResourceValueAreEqual(resourceValue1, resourceValue2); return; } ODataEnumValue enumValue1 = value1 as ODataEnumValue; ODataEnumValue enumValue2 = value2 as ODataEnumValue; if (enumValue1 != null && enumValue2 != null) { AssertODataEnumValueAreEqual(enumValue1, enumValue2); } else { ODataCollectionValue collectionValue1 = value1 as ODataCollectionValue; ODataCollectionValue collectionValue2 = value2 as ODataCollectionValue; if (collectionValue1 != null && collectionValue2 != null) { AssertODataCollectionValueAreEqual(collectionValue1, collectionValue2); } else { ODataUntypedValue untyped1 = value1 as ODataUntypedValue; ODataUntypedValue untyped2 = value2 as ODataUntypedValue; Assert.Equal(untyped1.RawValue, untyped2.RawValue); } } } }
public void WriteTopLevelErrorWithResourceInstanceAnnotation() { var result = SetupSerializerAndRunTest(null, serializer => { ODataError error = new ODataError(); var instanceAnnotations = new Collection <ODataInstanceAnnotation>(); var resourceValue = new ODataResourceValue(); resourceValue.TypeName = "ns.ErrorDetails"; ODataInstanceAnnotation annotation = new ODataInstanceAnnotation("sample.complex", resourceValue); instanceAnnotations.Add(annotation); error.InstanceAnnotations = instanceAnnotations; serializer.WriteTopLevelError(error, false); }); Assert.Contains("\"@sample.complex\":{\"@odata.type\":\"#ns.ErrorDetails\"}", result); }
public async Task WriteODataValueAsyncWritesODataResourceValue() { var resourceValue = new ODataResourceValue { Properties = new List <ODataProperty> { new ODataProperty { Name = "Name", Value = "Sue" }, new ODataProperty { Name = "Age", Value = 19 } } }; await this.writer.WriteODataValueAsync(resourceValue); Assert.Equal("{\"Name\":\"Sue\",\"Age\":19}", this.builder.ToString()); }
/// <summary> /// Visits a resource value item. /// </summary> /// <param name="resourceValue">The resource value to visit.</param> protected override ODataPayloadElement VisitResourceValue(ODataResourceValue resourceValue) { if (resourceValue == null) { return(new ComplexInstance(null, true)); } else { ComplexInstance complexElement = new ComplexInstance(resourceValue.TypeName, false); foreach (ODataProperty childProperty in resourceValue.Properties) { complexElement.Add((PropertyInstance)this.Visit(childProperty)); } this.ConvertSerializationTypeNameAnnotation(resourceValue, complexElement); return(complexElement); } }
/// <summary> /// Writes a collection item (either primitive, enum or resource) /// </summary> /// <param name="item">The collection item to write.</param> /// <param name="expectedItemType">The expected type of the collection item or null if no expected item type exists.</param> protected override void WriteCollectionItem(object item, IEdmTypeReference expectedItemType) { if (item == null) { this.jsonLightOutputContext.WriterValidator.ValidateNullCollectionItem(expectedItemType); this.jsonLightOutputContext.JsonWriter.WriteValue((string)null); } else { ODataResourceValue resourceValue = item as ODataResourceValue; ODataEnumValue enumVal = null; if (resourceValue != null) { this.jsonLightCollectionSerializer.AssertRecursionDepthIsZero(); this.jsonLightCollectionSerializer.WriteResourceValue( resourceValue, expectedItemType, false /*isOpenPropertyType*/, this.DuplicatePropertyNameChecker); this.jsonLightCollectionSerializer.AssertRecursionDepthIsZero(); this.DuplicatePropertyNameChecker.Reset(); } else if ((enumVal = item as ODataEnumValue) != null) { if (enumVal.Value == null) { this.jsonLightCollectionSerializer.WriteNullValue(); } else { // write ODataEnumValue.Value as string value this.jsonLightCollectionSerializer.WritePrimitiveValue(enumVal.Value, EdmCoreModel.Instance.GetString(true)); } } else { Debug.Assert(!(item is ODataCollectionValue), "!(item is ODataCollectionValue)"); Debug.Assert(!(item is ODataStreamReferenceValue), "!(item is ODataStreamReferenceValue)"); this.jsonLightCollectionSerializer.WritePrimitiveValue(item, expectedItemType); } } }
public void WritingPropertyShouldWriteResourceInstanceAnnotation() { var resourceValue = new ODataResourceValue { TypeName = "TestNamespace.Address", Properties = new[] { new ODataProperty { Name = "City", Value = "Redmond" } } }; var property = new ODataProperty() { Name = "IntProp", Value = 12345, }; property.InstanceAnnotations.Add(new ODataInstanceAnnotation("Resource.Annotation", resourceValue)); var result = SerializeProperty(null, property); Assert.Equal("{\"[email protected]\":{\"@odata.type\":\"#TestNamespace.Address\",\"City\":\"Redmond\"},\"IntProp\":12345}", result); }
/// <inheritdoc/> public sealed override ODataValue CreateODataValue(object graph, IEdmTypeReference expectedType, ODataSerializerContext writeContext) { if (!expectedType.IsStructured()) { throw Error.InvalidOperation(SRResources.CannotWriteType, typeof(ODataResourceValueSerializer), expectedType.FullName()); } if (graph == null) { return(new ODataNullValue()); } ODataResourceValue value = CreateODataResourceValue(graph, expectedType as IEdmStructuredTypeReference, writeContext); if (value == null) { return(new ODataNullValue()); } return(value); }