Example #1
0
        /// <summary>
        /// Creates an <see cref="ODataCollectionWriter"/> to write the value of a collection parameter.
        /// </summary>
        /// <param name="parameterName">The name of the collection parameter to write.</param>
        /// <param name="expectedItemType">The type reference of the expected item type or null if no expected item type exists.</param>
        /// <returns>The newly created <see cref="ODataCollectionWriter"/>.</returns>
        private ODataCollectionWriter CreateCollectionWriterImplementation(string parameterName, IEdmTypeReference expectedItemType)
        {
            Debug.Assert(this.State == ParameterWriterState.CanWriteParameter, "this.State == ParameterWriterState.CanWriteParameter");
            ODataCollectionWriter collectionWriter = this.CreateFormatCollectionWriter(parameterName, expectedItemType);

            this.ReplaceScope(ParameterWriterState.ActiveSubWriter);
            return(collectionWriter);
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="collectionWriter">The writer to wrap.</param>
        /// <param name="testConfiguration">The test configuration to use.</param>
        public ODataCollectionWriterTestWrapper(ODataCollectionWriter collectionWriter, WriterTestConfiguration testConfiguration)
        {
            ExceptionUtilities.CheckArgumentNotNull(collectionWriter, "collectionWriter");
            ExceptionUtilities.CheckArgumentNotNull(testConfiguration, "testConfiguration");

            this.collectionWriter = collectionWriter;
            this.testConfiguration = testConfiguration;
        }
        /// <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");
            }

            ODataCollectionValue collectionValue = CreateODataValue(graph, collectionType, writeContext) as ODataCollectionValue;

            writer.WriteStart(new ODataCollectionStart { Name = writeContext.RootElementName });

            if (collectionValue != null)
            {
                foreach (object item in collectionValue.Items)
                {
                    writer.WriteItem(item);
                }
            }

            writer.WriteEnd();
        }
        /// <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();
        }
        /// <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 the collection payload as specified in the <paramref name="testDescriptor"/>.
        /// </summary>
        /// <param name="messageWriter">The message writer.</param>
        /// <param name="writer">The writer to write to.</param>
        /// <param name="flush">True if the stream should be flush before returning; otherwise false.</param>
        /// <param name="testDescriptor">The test descriptor specifying the collection to write.</param>
        internal static void WriteCollectionPayload(ODataMessageWriterTestWrapper messageWriter, ODataCollectionWriter writer, bool flush, CollectionWriterTestDescriptor testDescriptor)
        {
            Debug.Assert(writer != null, "writer != null");
            Debug.Assert(testDescriptor != null, "testDescriptor != null");

            object[] payloadItems = testDescriptor.PayloadItems;
            int payloadItemIndex = 0;
            foreach (CollectionWriterTestDescriptor.WriterInvocations invocation in testDescriptor.Invocations)
            {
                switch (invocation)
                {
                    case CollectionWriterTestDescriptor.WriterInvocations.StartCollection:
                        ODataCollectionStartSerializationInfo serInfo = null;
                        if (!string.IsNullOrEmpty(testDescriptor.CollectionTypeName))
                        {
                            serInfo = new ODataCollectionStartSerializationInfo();
                            serInfo.CollectionTypeName = testDescriptor.CollectionTypeName;
                        }

                        writer.WriteStart(new ODataCollectionStart { Name = testDescriptor.CollectionName, SerializationInfo = serInfo });
                        break;
                    
                    case CollectionWriterTestDescriptor.WriterInvocations.Item:
                        object payloadItem = payloadItems[payloadItemIndex];

                        ODataError error = payloadItem as ODataError;
                        if (error != null)
                        {
                            throw new InvalidOperationException("Expected payload item but found an error.");
                        }

                        writer.WriteItem(payloadItem);
                        payloadItemIndex++;
                        break;
                    
                    case CollectionWriterTestDescriptor.WriterInvocations.Error:
                        ODataAnnotatedError error2 = testDescriptor.PayloadItems[payloadItemIndex] as ODataAnnotatedError;
                        if (error2 == null)
                        {
                            throw new InvalidOperationException("Expected an error but found a payload item.");
                        }

                        messageWriter.WriteError(error2.Error, error2.IncludeDebugInformation);
                        payloadItemIndex++;
                        break;
                    
                    case CollectionWriterTestDescriptor.WriterInvocations.EndCollection:
                        writer.WriteEnd();
                        break;
                    
                    case CollectionWriterTestDescriptor.WriterInvocations.UserException:
                        throw new Exception("User code triggered an exception.");

                    default:
                        break;
                }
            }

            if (flush)
            {
                writer.Flush();
            }
        }
 private void InvokeCollectionWriterAction(ODataMessageWriterTestWrapper messageWriter, ODataCollectionWriter writer, CollectionWriterAction writerAction)
 {
     switch (writerAction)
     {
         case CollectionWriterAction.Start:
             writer.WriteStart(new ODataCollectionStart { Name = "foo" });
             break;
         case CollectionWriterAction.Item:
             writer.WriteItem(42);
             break;
         case CollectionWriterAction.End:
             writer.WriteEnd();
             break;
         case CollectionWriterAction.Error:
             messageWriter.WriteError(new ODataError(), false);
             break;
     }
 }
        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();
        }
        /// <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();
            }
        }
        private string WriteAndVerifyCollection(StreamResponseMessage responseMessage, ODataCollectionWriter odataWriter,
                                                bool hasModel, string mimeType)
        {
            var collectionStart = new ODataCollectionStart() { Name = "BackupContactInfo", Count = 12, NextPageLink = new Uri("http://localhost")};
            if (!hasModel)
            {
                collectionStart.SetSerializationInfo(new ODataCollectionStartSerializationInfo()
                {
                    CollectionTypeName = "Collection(" + NameSpace + "ContactDetails)"
                });
            }

            odataWriter.WriteStart(collectionStart);
            odataWriter.WriteItem(WritePayloadHelper.CreatePrimaryContactODataComplexValue());
            odataWriter.WriteEnd();

            Stream stream = responseMessage.GetStream();
            if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
            {
                stream.Seek(0, SeekOrigin.Begin);
                var settings = new ODataMessageReaderSettings() { BaseUri = this.ServiceUri };

                ODataMessageReader messageReader = new ODataMessageReader(responseMessage, settings, WritePayloadHelper.Model);
                ODataCollectionReader reader = messageReader.CreateODataCollectionReader(WritePayloadHelper.ContactDetailType);
                bool collectionRead = false;
                while (reader.Read())
                {
                    if (reader.State == ODataCollectionReaderState.CollectionEnd)
                    {
                        collectionRead = true;
                    }
                }

                Assert.IsTrue(collectionRead, "collectionRead");
                Assert.AreEqual(ODataCollectionReaderState.Completed, reader.State);
            }

            return WritePayloadHelper.ReadStreamContent(stream);
        }