/// <summary> /// Verifies that calling WriteStart is valid. /// </summary> /// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param> /// <param name="collectionStart">The <see cref="ODataCollectionStart"/> representing the collection.</param> private void VerifyCanWriteStart(bool synchronousCall, ODataCollectionStart collectionStart) { ExceptionUtils.CheckArgumentNotNull(collectionStart, "collection"); this.VerifyNotDisposed(); this.VerifyCallAllowed(synchronousCall); }
public ODataJsonLightInheritComplexCollectionWriterTests() { collectionStartWithoutSerializationInfo = new ODataCollectionStart(); collectionStartWithSerializationInfo = new ODataCollectionStart(); collectionStartWithSerializationInfo.SetSerializationInfo(new ODataCollectionStartSerializationInfo { CollectionTypeName = "Collection(ns.Address)" }); address = new ODataComplexValue { Properties = new[] { new ODataProperty { Name = "Street", Value = "1 Microsoft Way" }, new ODataProperty { Name = "Zipcode", Value = 98052 }, new ODataProperty { Name = "State", Value = new ODataEnumValue("WA", "ns.StateEnum") }, new ODataProperty { Name = "City", Value = "Shanghai" } }, TypeName = "TestNamespace.DerivedAddress" }; items = new[] { address }; EdmComplexType addressType = new EdmComplexType("ns", "Address"); addressType.AddProperty(new EdmStructuralProperty(addressType, "Street", EdmCoreModel.Instance.GetString(isNullable: true))); addressType.AddProperty(new EdmStructuralProperty(addressType, "Zipcode", EdmCoreModel.Instance.GetInt32(isNullable: true))); var stateEnumType = new EdmEnumType("ns", "StateEnum", isFlags: true); stateEnumType.AddMember("IL", new EdmIntegerConstant(1)); stateEnumType.AddMember("WA", new EdmIntegerConstant(2)); addressType.AddProperty(new EdmStructuralProperty(addressType, "State", new EdmEnumTypeReference(stateEnumType, true))); EdmComplexType derivedAddressType = new EdmComplexType("ns", "DerivedAddress", addressType, false); derivedAddressType.AddProperty(new EdmStructuralProperty(derivedAddressType, "City", EdmCoreModel.Instance.GetString(isNullable: true))); addressTypeReference = new EdmComplexTypeReference(addressType, isNullable: false); derivedAddressTypeReference = new EdmComplexTypeReference(derivedAddressType, isNullable: false); }
public void PropertySettersNullTest() { ODataCollectionStart odataCollectionStart = new ODataCollectionStart() { Name = "DummyName" }; odataCollectionStart.Name = null; this.Assert.IsNull(odataCollectionStart.Name, "Expected null value for property 'Name'."); }
/// <summary> /// Start writing a collection - implementation of the actual functionality. /// </summary> /// <param name="collectionStart">The <see cref="ODataCollectionStart"/> representing the collection.</param> private void WriteStartImplementation(ODataCollectionStart collectionStart) { this.StartPayloadInStartState(); this.EnterScope(CollectionWriterState.Collection, collectionStart); this.InterceptException(() => { if (this.expectedItemType == null) { this.collectionValidator = new CollectionWithoutExpectedTypeValidator(/*expectedItemTypeName*/ null); } this.StartCollection(collectionStart); }); }
/// <summary> /// Start writing a collection. /// </summary> /// <param name="collection">The <see cref="ODataCollectionStart"/> representing the collection.</param> public override void WriteStart(ODataCollectionStart collection) { if (this.testConfiguration.Synchronous) { this.collectionWriter.WriteStart(collection); } else { #if WINDOWS_PHONE throw new TaupoNotSupportedException("This test is not supported in asynchronous mode in Silverlight or Windows Phone"); #else this.collectionWriter.WriteStartAsync(collection).Wait(); #endif } }
/// <summary> /// Writes the given <paramref name="graph"/> using the given <paramref name="writer"/>. /// </summary> /// <param name="writer">The <see cref="ODataCollectionWriter"/> to use.</param> /// <param name="graph">The collection to write.</param> /// <param name="collectionType">The EDM type of the collection.</param> /// <param name="writeContext">The serializer context.</param> public void WriteCollection(ODataCollectionWriter writer, object graph, IEdmTypeReference collectionType, ODataSerializerContext writeContext) { if (writer == null) { throw Error.ArgumentNull("writer"); } ODataCollectionStart collectionStart = new ODataCollectionStart { Name = writeContext.RootElementName }; if (writeContext.Request != null) { if (writeContext.Request.ODataProperties().NextLink != null) { collectionStart.NextPageLink = writeContext.Request.ODataProperties().NextLink; } if (writeContext.Request.ODataProperties().TotalCount != null) { collectionStart.Count = writeContext.Request.ODataProperties().TotalCount; } } writer.WriteStart(collectionStart); if (graph != null) { ODataCollectionValue collectionValue = CreateODataValue(graph, collectionType, writeContext) as ODataCollectionValue; if (collectionValue != null) { foreach (object item in collectionValue.Items) { writer.WriteItem(item); } } } writer.WriteEnd(); }
public void DefaultValuesAndPropertiesGetterAndSetterTest() { ODataCollectionStart odataCollectionStart = new ODataCollectionStart(); this.Assert.IsNull(odataCollectionStart.Name, "Expected null default value for property 'Name'."); }
/// <summary> /// Calls the base class method to process the instance collection. /// </summary> /// <param name="payloadElement">The complex instance collection to process.</param> public override void Visit(ComplexInstanceCollection payloadElement) { ODataCollectionStart collectionStart = new ODataCollectionStart(); this.items.Push(collectionStart); var annotation = new ODataCollectionItemsObjectModelAnnotation(); foreach (var complex in payloadElement) { this.items.Push(new ODataComplexValue() { TypeName = complex.FullTypeName }); this.Recurse(complex); annotation.Add(this.items.Pop()); } collectionStart.SetAnnotation<ODataCollectionItemsObjectModelAnnotation>(annotation); }
/// <summary> /// Provide additional serialization information to the <see cref="ODataCollectionWriter"/> for <paramref name="collectionStart"/>. /// </summary> /// <param name="collectionStart">The instance to set the serialization info.</param> /// <param name="serializationInfo">The serialization info to set.</param> public static void SetSerializationInfo(this ODataCollectionStart collectionStart, ODataCollectionStartSerializationInfo serializationInfo) { ExceptionUtils.CheckArgumentNotNull(collectionStart, "collectionStart"); collectionStart.SerializationInfo = serializationInfo; }
/// <summary> /// Asynchronously start writing a collection. /// </summary> /// <param name="collection">The <see cref="ODataCollectionStart"/> representing the collection.</param> /// <returns>A task instance that represents the asynchronous write operation.</returns> public sealed override Task WriteStartAsync(ODataCollectionStart collection) { this.VerifyCanWriteStart(false, collection); return TaskUtils.GetTaskForSynchronousOperation(() => this.WriteStartImplementation(collection)); }
/// <summary>Start writing a collection.</summary> /// <param name="collectionStart">The <see cref="T:Microsoft.OData.Core.ODataCollectionStart" /> representing the collection.</param> public abstract void WriteStart(ODataCollectionStart collectionStart);
/// <summary>Asynchronously start writing a collection.</summary> /// <returns>A task instance that represents the asynchronous write operation.</returns> /// <param name="collectionStart">The <see cref="T:Microsoft.OData.Core.ODataCollectionStart" /> representing the collection.</param> public abstract Task WriteStartAsync(ODataCollectionStart collectionStart);
private void WriteCollection(ODataMessageWriterTestWrapper messageWriter, ODataCollectionStart collection) { ODataCollectionWriter collectionWriter = messageWriter.CreateODataCollectionWriter(); this.WriteCollection(collectionWriter, collection); collectionWriter.Flush(); }
private void WriteCollection(ODataCollectionWriter collectionWriter, ODataCollectionStart collection) { collectionWriter.WriteStart(collection); var annotation = collection.GetAnnotation<ODataCollectionItemsObjectModelAnnotation>(); if (annotation != null) { foreach (var item in annotation) { collectionWriter.WriteItem(item); } } collectionWriter.WriteEnd(); }
public void ShouldWriteContextUriBasedOnSerializationInfoForComplexCollectionRequestWithoutUserModelWhenBothItemTypeAndSerializationInfoAreGiven() { ODataCollectionStart collectionStart = new ODataCollectionStart(); collectionStart.SetSerializationInfo(new ODataCollectionStartSerializationInfo { CollectionTypeName = "Collection(foo.bar)" }); WriteAndValidate(collectionStart, this.items, "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection(foo.bar)\",\"value\":[{\"Street\":\"1 Microsoft Way\",\"Zipcode\":98052,\"State\":\"WA\"}]}", writingResponse: false, itemTypeReference: this.addressTypeReference); }
private static void WriteAndValidateAsync(IEdmTypeReference itemTypeReference, ODataCollectionStart collectionStart, IEnumerable<object> items, string expectedPayload, bool writingResponse) { MemoryStream stream = new MemoryStream(); var outputContext = CreateJsonLightOutputContext(stream, writingResponse, synchronous: false); var collectionWriter = new ODataJsonLightCollectionWriter(outputContext, itemTypeReference); collectionWriter.WriteStartAsync(collectionStart).Wait(); foreach (object item in items) { collectionWriter.WriteItemAsync(item).Wait(); } collectionWriter.WriteEndAsync().Wait(); ValidateWrittenPayload(stream, expectedPayload); }
private static void WriteAndValidate(ODataCollectionStart collectionStart, IEnumerable<object> items, string expectedPayload, bool writingResponse = true, IEdmTypeReference itemTypeReference = null) { WriteAndValidateSync(itemTypeReference, collectionStart, items, expectedPayload, writingResponse); WriteAndValidateAsync(itemTypeReference, collectionStart, items, expectedPayload, writingResponse); }
public void ShouldBeAbleToClearTheCollectionStartSerializationInfo() { ODataCollectionStart collectionStart = new ODataCollectionStart(); ODataCollectionStartSerializationInfo serializationInfo = new ODataCollectionStartSerializationInfo { CollectionTypeName = "Collection(Edm.String)" }; collectionStart.SerializationInfo = serializationInfo; collectionStart.SetSerializationInfo(null); collectionStart.SerializationInfo.Should().BeNull(); }
public override void WriteStart(ODataCollectionStart collectionStart) { }
public void ShouldWriteCollectionOfTypeDefinitionItemType() { ODataCollectionStart collectionStart = new ODataCollectionStart(); WriteAndValidate(collectionStart, new object[] { 123 }, "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection(NS.Test)\",\"value\":[123]}", true, new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "Test", EdmPrimitiveTypeKind.Int32), false)); }
public override Task WriteStartAsync(ODataCollectionStart collectionStart) { return Task.Factory.StartNew(() => { }); }
/// <summary> /// Start writing a collection. /// </summary> /// <param name="collectionStart">The <see cref="ODataCollectionStart"/> representing the collection.</param> protected abstract void StartCollection(ODataCollectionStart collectionStart);
/// <summary> /// Start writing a collection. /// </summary> /// <param name="collectionStart">The <see cref="ODataCollectionStart"/> representing the collection.</param> public sealed override void WriteStart(ODataCollectionStart collectionStart) { this.VerifyCanWriteStart(true, collectionStart); this.WriteStartImplementation(collectionStart); }
/// <summary> /// Asynchronously start writing a collection. /// </summary> /// <param name="collection">The <see cref="ODataCollectionStart"/> representing the collection.</param> /// <returns>A task instance that represents the asynchronous write operation.</returns> public sealed override Task WriteStartAsync(ODataCollectionStart collection) { this.VerifyCanWriteStart(false, collection); return(TaskUtils.GetTaskForSynchronousOperation(() => this.WriteStartImplementation(collection))); }
/// <summary> /// Calls the base class method to process the primitive collection. /// </summary> /// <param name="payloadElement">The primitive collection to process.</param> public override void Visit(PrimitiveCollection payloadElement) { ODataCollectionStart collectionStart = new ODataCollectionStart(); var annotation = new ODataCollectionItemsObjectModelAnnotation(); foreach (var primitive in payloadElement) { annotation.Add(primitive.ClrValue); } collectionStart.SetAnnotation<ODataCollectionItemsObjectModelAnnotation>(annotation); }
/// <summary> /// Writes the given <paramref name="graph"/> using the given <paramref name="writer"/>. /// </summary> /// <param name="writer">The <see cref="ODataCollectionWriter"/> to use.</param> /// <param name="graph">The collection to write.</param> /// <param name="collectionType">The EDM type of the collection.</param> /// <param name="writeContext">The serializer context.</param> public void WriteCollection(ODataCollectionWriter writer, object graph, IEdmTypeReference collectionType, ODataSerializerContext writeContext) { if (writer == null) { throw Error.ArgumentNull("writer"); } ODataCollectionStart collectionStart = new ODataCollectionStart { Name = writeContext.RootElementName }; if (writeContext.Request != null) { if (writeContext.Request.ODataProperties().NextLink != null) { collectionStart.NextPageLink = writeContext.Request.ODataProperties().NextLink; } if (writeContext.Request.ODataProperties().TotalCount != null) { collectionStart.Count = writeContext.Request.ODataProperties().TotalCount; } } bool doNotSerializeIfNull = false; bool serializeAsEmptyIfNull = false; if (writeContext.Request != null) { var config = writeContext.Request.GetConfiguration(); if (config != null) { doNotSerializeIfNull = config.GetDoNotSerializeNullCollections(); serializeAsEmptyIfNull = config.GetSerializeNullCollectionsAsEmpty(); } } if (graph == null && doNotSerializeIfNull) { return; } writer.WriteStart(collectionStart); if (graph != null || !serializeAsEmptyIfNull) { ODataCollectionValue collectionValue = CreateODataValue(graph, collectionType, writeContext) as ODataCollectionValue; if (collectionValue != null) { foreach (object item in collectionValue.Items) { writer.WriteItem(item); } } } writer.WriteEnd(); }
/// <summary>Writes multiple top-level elements, possibly none.</summary> /// <param name="expanded">Expanded results for elements.</param> /// <param name="elements">Enumerator for elements to write.</param> protected override void WriteTopLevelElements(IExpandedResult expanded, QueryResultInfo elements) { Debug.Assert( !this.RequestDescription.IsSingleResult, "!this.RequestDescription.IsSingleResult -- otherwise WriteTopLevelElement should have been called"); if (this.RequestDescription.LinkUri) { bool needPop = this.PushSegmentForRoot(); this.WriteLinkCollection(elements); this.PopSegmentName(needPop); } else { MetadataProviderEdmModel model = this.Service.Provider.GetMetadataProviderEdmModel(); OperationWrapper operation = this.RequestDescription.LastSegmentInfo.Operation; IEdmOperation edmOperation = model.GetRelatedOperation(operation); Debug.Assert(edmOperation != null, "edmOperation != null"); IEdmCollectionTypeReference collectionType = (IEdmCollectionTypeReference)edmOperation.ReturnType; bool isJsonLightResponse = ContentTypeUtil.IsResponseMediaTypeJsonLight(this.Service, /*isEntryOrFeed*/ false); this.collectionWriter = this.writer.CreateODataCollectionWriter(isJsonLightResponse ? null : collectionType.ElementType()); ODataCollectionStart collectionStart = new ODataCollectionStart { Name = this.ComputeContainerName() }; collectionStart.SetSerializationInfo(new ODataCollectionStartSerializationInfo { CollectionTypeName = collectionType.FullName() }); this.collectionWriter.WriteStart(collectionStart); while (elements.HasMoved) { object element = elements.Current; ResourceType resourceType = element == null ? this.RequestDescription.TargetResourceType : WebUtil.GetResourceType(this.Provider, element); if (resourceType == null) { throw new InvalidOperationException(Microsoft.OData.Service.Strings.Serializer_UnsupportedTopLevelType(element.GetType())); } this.collectionWriter.WriteItem(this.GetPropertyValue(XmlConstants.XmlCollectionItemElementName, resourceType, element, false /*openProperty*/).FromODataValue()); elements.MoveNext(); } this.collectionWriter.WriteEnd(); this.collectionWriter.Flush(); } }
/// <summary> /// Asynchronously start writing a collection. /// </summary> /// <param name="collection">The <see cref="ODataCollectionStart"/> representing the collection.</param> /// <returns>A task instance that represents the asynchronous write operation.</returns> public override Task WriteStartAsync(ODataCollectionStart collection) { throw new NotImplementedException("Tests should always use synchronous APIs."); }
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\"]}" ); }
public void ShouldBeAbleToSetTheCollectionStartSerializationInfo() { ODataCollectionStart collectionStart = new ODataCollectionStart(); ODataCollectionStartSerializationInfo serializationInfo = new ODataCollectionStartSerializationInfo { CollectionTypeName = "Collection(Edm.String)" }; collectionStart.SetSerializationInfo(serializationInfo); collectionStart.SerializationInfo.Should().BeSameAs(serializationInfo); }
/// <summary> /// Writes collection value in body operation parameter. /// </summary> /// <param name="parameterWriter">The odata parameter writer.</param> /// <param name="operationParameter">The operation parameter.</param> /// <param name="edmCollectionType">The edm collection type.</param> private void WriteCollectionValueInBodyOperationParameter(ODataParameterWriter parameterWriter, BodyOperationParameter operationParameter, IEdmCollectionType edmCollectionType) { ClientEdmModel model = this.requestInfo.Model; if (edmCollectionType.ElementType.TypeKind() == EdmTypeKind.Entity) { ODataWriter feedWriter = parameterWriter.CreateFeedWriter(operationParameter.Name); feedWriter.WriteStart(new ODataFeed()); IEnumerator enumerator = ((ICollection)operationParameter.Value).GetEnumerator(); while (enumerator.MoveNext()) { Object collectionItem = enumerator.Current; if (collectionItem == null) { throw new NotSupportedException(Strings.Serializer_NullCollectionParamterItemValue(operationParameter.Name)); } IEdmType edmItemType = model.GetOrCreateEdmType(collectionItem.GetType()); Debug.Assert(edmItemType != null, "edmItemType != null"); if (edmItemType.TypeKind != EdmTypeKind.Entity) { throw new NotSupportedException(Strings.Serializer_InvalidCollectionParamterItemType(operationParameter.Name, edmItemType.TypeKind)); } Debug.Assert(model.GetClientTypeAnnotation(edmItemType).ElementType != null, "edmItemType.GetClientTypeAnnotation().ElementType != null"); ODataEntry entry = this.CreateODataEntryFromEntityOperationParameter(model.GetClientTypeAnnotation(edmItemType), collectionItem); Debug.Assert(entry != null, "entry != null"); feedWriter.WriteStart(entry); feedWriter.WriteEnd(); } feedWriter.WriteEnd(); feedWriter.Flush(); } else { ODataCollectionWriter collectionWriter = parameterWriter.CreateCollectionWriter(operationParameter.Name); ODataCollectionStart odataCollectionStart = new ODataCollectionStart(); collectionWriter.WriteStart(odataCollectionStart); IEnumerator enumerator = ((ICollection)operationParameter.Value).GetEnumerator(); while (enumerator.MoveNext()) { Object collectionItem = enumerator.Current; if (collectionItem == null) { collectionWriter.WriteItem(null); continue; } IEdmType edmItemType = model.GetOrCreateEdmType(collectionItem.GetType()); Debug.Assert(edmItemType != null, "edmItemType != null"); switch (edmItemType.TypeKind) { case EdmTypeKind.Complex: { Debug.Assert(model.GetClientTypeAnnotation(edmItemType).ElementType != null, "edmItemType.GetClientTypeAnnotation().ElementType != null"); ODataComplexValue complexValue = this.propertyConverter.CreateODataComplexValue(model.GetClientTypeAnnotation(edmItemType).ElementType, collectionItem, null /*propertyName*/, false /*isCollectionItem*/, null /*visitedComplexTypeObjects*/); Debug.Assert(complexValue != null, "complexValue != null"); collectionWriter.WriteItem(complexValue); break; } case EdmTypeKind.Primitive: { object primitiveItemValue = ODataPropertyConverter.ConvertPrimitiveValueToRecognizedODataType(collectionItem, collectionItem.GetType()); collectionWriter.WriteItem(primitiveItemValue); break; } case EdmTypeKind.Enum: { ODataEnumValue enumTmp = this.propertyConverter.CreateODataEnumValue(model.GetClientTypeAnnotation(edmItemType).ElementType, collectionItem, false); collectionWriter.WriteItem(enumTmp); break; } default: // EdmTypeKind.Entity // EdmTypeKind.Row // EdmTypeKind.EntityReference throw new NotSupportedException(Strings.Serializer_InvalidCollectionParamterItemType(operationParameter.Name, edmItemType.TypeKind)); } } collectionWriter.WriteEnd(); collectionWriter.Flush(); } }
public void ShouldWriteCountAndNextLinkAnnotationOfComplexCollectionPropertyIfSpecified() { ODataCollectionStart collectionStart = new ODataCollectionStart() { Count = 3, NextPageLink = new Uri("http://next-link") }; collectionStart.SetSerializationInfo(new ODataCollectionStartSerializationInfo { CollectionTypeName = "Collection(foo.bar)" }); WriteAndValidate(collectionStart, this.items, "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection(foo.bar)\",\"@odata.count\":3,\"@odata.nextLink\":\"http://next-link/\",\"value\":[{\"Street\":\"1 Microsoft Way\",\"Zipcode\":98052,\"State\":\"WA\"}]}", writingResponse: true, itemTypeReference: this.addressTypeReference); }