Esempio n. 1
0
        internal ODataRawInputContext(
            ODataFormat format,
            Stream messageStream,
            Encoding encoding,
            ODataMessageReaderSettings messageReaderSettings,
            bool readingResponse,
            bool synchronous,
            IEdmModel model,
            IODataUrlResolver urlResolver,
            ODataPayloadKind readerPayloadKind)
            : base(format, messageReaderSettings, readingResponse, synchronous, model, urlResolver)
        {
            Debug.Assert(messageStream != null, "stream != null");
            Debug.Assert(readerPayloadKind != ODataPayloadKind.Unsupported, "readerPayloadKind != ODataPayloadKind.Unsupported");

            ExceptionUtils.CheckArgumentNotNull(format, "format");
            ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings");

            try
            {
                this.stream = messageStream;
                this.encoding = encoding;
                this.readerPayloadKind = readerPayloadKind;
            }
            catch (Exception e)
            {
                // Dispose the message stream if we failed to create the input context.
                if (ExceptionUtils.IsCatchableExceptionType(e) && messageStream != null)
                {
                    messageStream.Dispose();
                }

                throw;
            }
        }
        public void Read_RoundTrips()
        {
            // Arrange
            IEdmModel model = CreateModel();
            var deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage requestMessage = new MockODataRequestMessage();
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings()
            {
                ODataUri = new ODataUri { ServiceRoot = new Uri("http://any/") }
            };
            settings.SetContentType(ODataFormat.Json);

            ODataMessageWriter messageWriter = new ODataMessageWriter(requestMessage, settings);
            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink { Url = new Uri("http://localhost/samplelink") });

            ODataMessageReaderSettings readSettings = new ODataMessageReaderSettings();
            ODataMessageReader messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage), readSettings, model);
            ODataDeserializerContext context = new ODataDeserializerContext
            {
                Request = new HttpRequestMessage(),
                Path = new ODataPath(new NavigationPathSegment(GetNavigationProperty(model)))
            };

            // Act
            Uri uri = deserializer.Read(messageReader, typeof(Uri), context) as Uri;

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
        public void PropertyGettersAndSettersTest()
        {
            Uri baseUri = new Uri("http://odata.org");
            Func<ODataEntry, XmlReader, Uri, XmlReader> entryAtomXmlCustomizationCallback = (entry, reader, uri) => reader;

            ODataMessageReaderSettings settings = new ODataMessageReaderSettings {
                BaseUri = baseUri,
                CheckCharacters = true,
                DisablePrimitiveTypeConversion = true,
                DisableMessageStreamDisposal = true,
                EnableAtomMetadataReading = true,
                UndeclaredPropertyBehaviorKinds = ODataUndeclaredPropertyBehaviorKinds.IgnoreUndeclaredValueProperty,
                MaxProtocolVersion = ODataVersion.V4,
                MessageQuotas = new ODataMessageQuotas {
                    MaxPartsPerBatch = 2,
                    MaxOperationsPerChangeset = 3,
                    MaxNestingDepth = 4,
                    MaxReceivedMessageSize = 5,
                },
            };

            Assert.AreEqual(baseUri, settings.BaseUri, "The BaseUri was not correctly remembered.");
            Assert.IsTrue(settings.CheckCharacters, "The CheckCharacters should be on when set.");
            Assert.IsTrue(settings.DisablePrimitiveTypeConversion, "DisablePrimitiveTypeConversion was not correctly remembered.");
            Assert.IsTrue(settings.DisableMessageStreamDisposal, "DisableMessageStreamDisposal was not correctly remembered.");
            Assert.IsTrue(settings.EnableAtomMetadataReading, "EnableAtomMetadataReading was not correctly remembered.");
            Assert.AreEqual(ODataUndeclaredPropertyBehaviorKinds.IgnoreUndeclaredValueProperty, settings.UndeclaredPropertyBehaviorKinds, "UndeclaredPropertyBehaviorKinds was not correctly remembered.");
            Assert.AreEqual(ODataVersion.V4, settings.MaxProtocolVersion, "The MaxProtocolVersion was not correctly remembered.");
            Assert.AreEqual(2, settings.MessageQuotas.MaxPartsPerBatch, "MaxPartsPerBatch should be 2");
            Assert.AreEqual(3, settings.MessageQuotas.MaxOperationsPerChangeset, "MaxOperationsPerChangeset should be 3");
            Assert.AreEqual(4, settings.MessageQuotas.MaxNestingDepth, "MaxNestingDepth should be 4");
            Assert.AreEqual(5, settings.MessageQuotas.MaxReceivedMessageSize, "MaxMessageSize should be 5");
        }
Esempio n. 4
0
 /// <summary>
 /// Detects the payload kinds supported by this format for the specified message payload.
 /// </summary>
 /// <param name="messageInfo">The context information for the message.</param>
 /// <param name="settings">Configuration settings of the OData reader.</param>
 /// <returns>The set of <see cref="ODataPayloadKind"/>s that are supported with the specified payload.</returns>
 public override IEnumerable<ODataPayloadKind> DetectPayloadKind(
     ODataMessageInfo messageInfo,
     ODataMessageReaderSettings settings)
 {
     ExceptionUtils.CheckArgumentNotNull(messageInfo, "messageInfo");
     return DetectPayloadKindImplementation(messageInfo.MediaType);
 }
        /// <summary>
        /// Specifically use to query single entry or multi entries(query with $expand)
        /// </summary>
        /// <param name="requestUri"></param>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public List<ODataEntry> QueryEntries(string requestUri, string mimeType)
        {
            List<ODataEntry> entries = new List<ODataEntry>();

            ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = baseUri };
            var requestMessage = new HttpWebRequestMessage(new Uri(baseUri.AbsoluteUri + requestUri, UriKind.Absolute));
            requestMessage.SetHeader("Accept", mimeType);
            var responseMessage = requestMessage.GetResponse();
            Assert.AreEqual(200, responseMessage.StatusCode);

            if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
            {
                using (var messageReader = new ODataMessageReader(responseMessage, readerSettings, model))
                {
                    var reader = messageReader.CreateODataEntryReader();

                    while (reader.Read())
                    {
                        if (reader.State == ODataReaderState.EntryEnd)
                        {
                            entries.Add(reader.Item as ODataEntry);
                        }
                    }
                    Assert.AreEqual(ODataReaderState.Completed, reader.State);
                }
            }
            return entries;
        }
        /// <summary>
        /// Creates a new the reader for the given response message and settings.
        /// </summary>
        /// <param name="responseMessage">The response message.</param>
        /// <param name="settings">The settings.</param>
        /// <returns>Newly created message reader.</returns>
        internal ODataMessageReader CreateReader(IODataResponseMessage responseMessage, ODataMessageReaderSettings settings)
        {
            Debug.Assert(responseMessage != null, "responseMessage != null");
            Debug.Assert(settings != null, "settings != null");

            this.responseInfo.Context.Format.ValidateCanReadResponseFormat(responseMessage);
            return new ODataMessageReader(responseMessage, settings, this.responseInfo.TypeResolver.ReaderModel);
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="format">The format used for the test.</param>
        /// <param name="messageReaderSettings">The message reader settings used for the test.</param>
        /// <param name="readerRequest">True if the test is reading a request. Otherwise false if it's reading a response.</param>
        /// <param name="synchronous">True if the test should be ran using synchronous API. Otherwise false if it should be ran using asynchronous APIs.</param>
        /// <param name="version">The OData protocol version to be used for reading the payload.</param>
        public ReaderTestConfiguration(ODataFormat format, ODataMessageReaderSettings messageReaderSettings, bool IsRequest, bool synchronous,ODataVersion version = ODataVersion.V4)
            :base(format, version, IsRequest, TestODataBehaviorKind.Default)
        {
            Debug.Assert(messageReaderSettings != null, "readerSettings != null");

            this.MessageReaderSettings = messageReaderSettings;
            this.Synchronous = synchronous;
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="messageReader">The message reader to wrap.</param>
        /// <param name="testConfiguration">The test configuration to use.</param>
        /// <remarks>
        /// This constructor is used if not special checks against a test message should be performed. 
        /// Use the constructor overload that takes a <see cref="TestMessage"/> argument to enforce checks
        /// around disposal of the message.
        /// </remarks>
        public ODataMessageReaderTestWrapper(ODataMessageReader messageReader, ODataMessageReaderSettings messageReaderSettings, ReaderTestConfiguration testConfiguration)
        {
            ExceptionUtilities.CheckArgumentNotNull(messageReader, "messageReader");
            ExceptionUtilities.CheckArgumentNotNull(testConfiguration, "testConfiguration");

            this.messageReader = messageReader;
            this.messageReaderSettings = messageReaderSettings;
            this.testConfiguration = testConfiguration;
        }
 private static ODataProperty ReadStringPropertyUnderServerKnob(string payload)
 {
     MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(payload));
     ODataMessageReaderSettings settings = new ODataMessageReaderSettings();
     settings.EnableODataServerBehavior();
     ODataAtomInputContext context = new ODataAtomInputContext(ODataFormat.Atom, memoryStream, Encoding.UTF8, settings, false /*readingResponse*/, true /*sync*/, EdmModel, null);
     var deserializer = new ODataAtomPropertyAndValueDeserializer(context);
     return deserializer.ReadTopLevelProperty(StringProperty, StringProperty.Type);
 }
        /// <inheritdoc/>
        public override async Task<HttpResponseMessage> ProcessBatchAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            ValidateRequest(request);

            ODataMessageReaderSettings oDataReaderSettings = new ODataMessageReaderSettings
            {
                DisableMessageStreamDisposal = true,
                MessageQuotas = MessageQuotas,
                BaseUri = GetBaseUri(request)
            };

            ODataMessageReader reader = await request.Content.GetODataMessageReaderAsync(oDataReaderSettings, cancellationToken);
            request.RegisterForDispose(reader);

            ODataBatchReader batchReader = reader.CreateODataBatchReader();
            List<ODataBatchResponseItem> responses = new List<ODataBatchResponseItem>();
            Guid batchId = Guid.NewGuid();
            List<IDisposable> resourcesToDispose = new List<IDisposable>();
            try
            {
                while (batchReader.Read())
                {
                    ODataBatchResponseItem responseItem = null;
                    if (batchReader.State == ODataBatchReaderState.ChangesetStart)
                    {
                        responseItem = await ExecuteChangeSetAsync(batchReader, batchId, request, cancellationToken);
                    }
                    else if (batchReader.State == ODataBatchReaderState.Operation)
                    {
                        responseItem = await ExecuteOperationAsync(batchReader, batchId, request, cancellationToken);
                    }
                    if (responseItem != null)
                    {
                        responses.Add(responseItem);
                    }
                }
            }
            catch
            {
                foreach (ODataBatchResponseItem response in responses)
                {
                    if (response != null)
                    {
                        response.Dispose();
                    }
                }
                throw;
            }

            return await CreateResponseMessageAsync(responses, request, cancellationToken);
        }
 public ODataAdapter(ISession session, string protocolVersion, HttpResponseMessage response)
     : this(session, protocolVersion)
 {
     var readerSettings = new ODataMessageReaderSettings
     {
         MessageQuotas = { MaxReceivedMessageSize = Int32.MaxValue }
     };
     using (var messageReader = new ODataMessageReader(new ODataResponseMessage(response), readerSettings))
     {
         Model = messageReader.ReadMetadataDocument();
     }
 }
 public async Task<ODataResponse> GetResponseAsync(IODataResponseMessageAsync responseMessage, bool includeResourceTypeInEntryProperties = false)
 {
     var readerSettings = new ODataMessageReaderSettings();
     readerSettings.MessageQuotas.MaxReceivedMessageSize = Int32.MaxValue;
     using (var messageReader = new ODataMessageReader(responseMessage, readerSettings, _model))
     {
         var payloadKind = messageReader.DetectPayloadKind();
         if (payloadKind.Any(x => x.PayloadKind == ODataPayloadKind.Error))
         {
             return ODataResponse.FromStatusCode(responseMessage.StatusCode);
         }
         else if (payloadKind.Any(x => x.PayloadKind == ODataPayloadKind.Value))
         {
             if (payloadKind.Any(x => x.PayloadKind == ODataPayloadKind.Collection))
             {
                 throw new NotImplementedException();
             }
             else
             {
                 var text = Utils.StreamToString(await responseMessage.GetStreamAsync());
                 return ODataResponse.FromFeed(new[] { new Dictionary<string, object>()
                 {
                     { FluentCommand.ResultLiteral, text }
                 } });
             }
         }
         else if (payloadKind.Any(x => x.PayloadKind == ODataPayloadKind.Batch))
         {
             return await ReadResponse(messageReader.CreateODataBatchReader(), includeResourceTypeInEntryProperties);
         }
         else if (payloadKind.Any(x => x.PayloadKind == ODataPayloadKind.Feed))
         {
             return ReadResponse(messageReader.CreateODataFeedReader(), includeResourceTypeInEntryProperties);
         }
         else if (payloadKind.Any(x => x.PayloadKind == ODataPayloadKind.Collection))
         {
             return ReadResponse(messageReader.CreateODataCollectionReader(), includeResourceTypeInEntryProperties);
         }
         else if (payloadKind.Any(x => x.PayloadKind == ODataPayloadKind.Property))
         {
             var property = messageReader.ReadProperty();
             return ODataResponse.FromFeed(new[] { new Dictionary<string, object>()
             {
                 { property.Name ?? FluentCommand.ResultLiteral, GetPropertyValue(property.Value) }
             } });
         }
         else
         {
             return ReadResponse(messageReader.CreateODataEntryReader(), includeResourceTypeInEntryProperties);
         }
     }
 }
Esempio n. 13
0
        /// <summary>
        /// Asynchronously parses the batch requests.
        /// </summary>
        /// <param name="request">The HTTP request that contains the batch requests.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The task object that represents this asynchronous operation.</returns>
        public override async Task<IList<ODataBatchRequestItem>> ParseBatchRequestsAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            if (this.ApiFactory == null)
            {
                throw new InvalidOperationException(Resources.BatchHandlerRequiresApiContextFactory);
            }

            Ensure.NotNull(request, "request");

            ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings
            {
                DisableMessageStreamDisposal = true,
                MessageQuotas = MessageQuotas,
                BaseUri = GetBaseUri(request)
            };

            ODataMessageReader reader =
                await request.Content.GetODataMessageReaderAsync(readerSettings, cancellationToken);
            request.RegisterForDispose(reader);

            List<ODataBatchRequestItem> requests = new List<ODataBatchRequestItem>();
            ODataBatchReader batchReader = reader.CreateODataBatchReader();
            Guid batchId = Guid.NewGuid();
            while (batchReader.Read())
            {
                if (batchReader.State == ODataBatchReaderState.ChangesetStart)
                {
                    IList<HttpRequestMessage> changeSetRequests =
                        await batchReader.ReadChangeSetRequestAsync(batchId, cancellationToken);
                    foreach (HttpRequestMessage changeSetRequest in changeSetRequests)
                    {
                        changeSetRequest.CopyBatchRequestProperties(request);
                    }

                    requests.Add(this.CreateChangeSetRequestItem(changeSetRequests));
                }
                else if (batchReader.State == ODataBatchReaderState.Operation)
                {
                    HttpRequestMessage operationRequest = await batchReader.ReadOperationRequestAsync(
                        batchId,
                        bufferContentStream: true,
                        cancellationToken: cancellationToken);
                    operationRequest.CopyBatchRequestProperties(request);
                    requests.Add(new OperationRequestItem(operationRequest));
                }
            }

            return requests;
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="messageReader">The message reader to wrap.</param>
        /// <param name="testConfiguration">The test configuration to use.</param>
        /// <param name="message">The message to read from.</param>
        /// <remarks>
        /// This constructor is used if special checks against <paramref name="message"/> should be performed. 
        /// Use the constructor overload that does not take a <see cref="TestMessage"/> argument to prevent any checks
        /// around disposal of the message.
        /// </remarks>
        public ODataMessageReaderTestWrapper(ODataMessageReader messageReader, ODataMessageReaderSettings messageReaderSettings, ReaderTestConfiguration testConfiguration, TestMessage message)
        {
            ExceptionUtilities.CheckArgumentNotNull(messageReader, "messageReader");
            ExceptionUtilities.CheckArgumentNotNull(testConfiguration, "testConfiguration");
            ExceptionUtilities.CheckArgumentNotNull(message, "message");

            this.messageReader = messageReader;
            this.messageReaderSettings = messageReaderSettings;
            this.testConfiguration = testConfiguration;
            this.message = message;

            ExceptionUtilities.Assert(this.message.TestStream == null || this.message.TestStream.DisposeCount == 0, "If the underlying message stream is a TestStream, its dispose count must be 0.");
            ExceptionUtilities.Assert(!this.message.StreamRetrieved, "GetMessage and GetMessageAsync must not be called previously on the given message.");
        }
        /// <summary>
        /// Validates that message reader settings are correct.
        /// </summary>
        /// <param name="messageReaderSettings">The message reader settings to validate.</param>
        /// <param name="readingResponse">true if the settings were specified when reading a response, false when reading a request.</param>
        internal static void ValidateMessageReaderSettings(ODataMessageReaderSettings messageReaderSettings, bool readingResponse)
        {
            Debug.Assert(messageReaderSettings != null, "messageReaderSettings != null");

            if (messageReaderSettings.BaseUri != null && !messageReaderSettings.BaseUri.IsAbsoluteUri)
            {
                throw new ODataException(Strings.ReaderValidationUtils_MessageReaderSettingsBaseUriMustBeNullOrAbsolute(UriUtils.UriToString(messageReaderSettings.BaseUri)));
            }

            if (!readingResponse && messageReaderSettings.UndeclaredPropertyBehaviorKinds != ODataUndeclaredPropertyBehaviorKinds.None)
            {
                throw new ODataException(Strings.ReaderValidationUtils_UndeclaredPropertyBehaviorKindSpecifiedOnRequest);
            }
        }
        public DisablePrimitiveTypeConversionTests()
        {
            this.model = new EdmModel();
            this.entityType = new EdmEntityType("FQ.NS", "EntityType", null, false, true);
            this.entityType.AddStructuralProperty("String", EdmPrimitiveTypeKind.String);
            this.entityType.AddStructuralProperty("Binary", EdmPrimitiveTypeKind.Binary);
            this.model.AddElement(this.entityType);
            var container = new EdmEntityContainer("FQ.NS", "Container");
            this.model.AddElement(container);
            container.AddEntitySet("Entities", this.entityType);

            this.defaultSettings = new ODataMessageReaderSettings { BaseUri = new Uri("http://serviceRoot/"), EnableAtom = true };
            this.settingsWithConversionDisabled = new ODataMessageReaderSettings(this.defaultSettings) { DisablePrimitiveTypeConversion = true, EnableAtom = true };
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="contentType">The parsed content type as <see cref="ODataMediaType"/>.</param>
        /// <param name="encoding">The encoding from the content type or the default encoding from <see cref="ODataMediaType" />.</param>
        /// <param name="messageReaderSettings">The <see cref="ODataMessageReaderSettings"/> being used for reading the message.</param>
        /// <param name="model">The <see cref="IEdmModel"/> for the payload.</param>
        internal ODataPayloadKindDetectionInfo(
            ODataMediaType contentType,
            Encoding encoding,
            ODataMessageReaderSettings messageReaderSettings, 
            IEdmModel model)
        {
            ExceptionUtils.CheckArgumentNotNull(contentType, "contentType");
            ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "readerSettings");

            this.contentType = contentType;
            this.encoding = encoding;
            this.messageReaderSettings = messageReaderSettings;
            this.model = model;
        }
 public void DefaultValuesTest()
 {
     ODataMessageReaderSettings settings = new ODataMessageReaderSettings();
     Assert.IsNull(settings.BaseUri, "BaseUri should be null by default.");
     Assert.IsFalse(settings.CheckCharacters, "The CheckCharacters should be off by default.");
     Assert.IsFalse(settings.DisablePrimitiveTypeConversion, "DisablePrimitiveTypeConversion should be false by default.");
     Assert.IsFalse(settings.DisableMessageStreamDisposal, "DisableMessageStreamDisposal should be false by default.");
     Assert.IsFalse(settings.EnableAtomMetadataReading, "EnableAtomMetadataReading should be false by default.");
     Assert.AreEqual(ODataUndeclaredPropertyBehaviorKinds.None, settings.UndeclaredPropertyBehaviorKinds, "UndeclaredPropertyBehaviorKinds should be Default by default.");
     Assert.AreEqual(ODataVersion.V4, settings.MaxProtocolVersion, "MaxProtocolVersion should be V3.");
     Assert.AreEqual(100, settings.MessageQuotas.MaxPartsPerBatch, "MaxPartsPerBatch should be int.MaxValue.");
     Assert.AreEqual(1000, settings.MessageQuotas.MaxOperationsPerChangeset, "MaxOperationsPerChangeset should be int.MaxValue.");
     Assert.AreEqual(100, settings.MessageQuotas.MaxNestingDepth, "The MaxNestingDepth should be set to 100 by default.");
     Assert.AreEqual(1024 * 1024, settings.MessageQuotas.MaxReceivedMessageSize, "The MaxMessageSize should be set to 1024 * 1024 by default.");
 }
        /// <summary>
        /// Gets the <see cref="ODataMessageReader"/> for the <see cref="HttpContent"/> stream.
        /// </summary>
        /// <param name="content">The <see cref="HttpContent"/>.</param>
        /// <param name="settings">The <see cref="ODataMessageReaderSettings"/>.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <returns>A task object that produces an <see cref="ODataMessageReader"/> when completed.</returns>
        public static async Task<ODataMessageReader> GetODataMessageReaderAsync(this HttpContent content,
            ODataMessageReaderSettings settings, CancellationToken cancellationToken)
        {
            if (content == null)
            {
                throw Error.ArgumentNull("content");
            }

            cancellationToken.ThrowIfCancellationRequested();
            Stream contentStream = await content.ReadAsStreamAsync();

            IODataRequestMessage oDataRequestMessage = new ODataMessageWrapper(contentStream, content.Headers);
            ODataMessageReader oDataMessageReader = new ODataMessageReader(oDataRequestMessage, settings);
            return oDataMessageReader;
        }
Esempio n. 20
0
 public VCardInputContext(ODataFormat format,
     Stream messageStream,
     ODataMediaType contentType,
     Encoding encoding,
     ODataMessageReaderSettings messageReaderSettings,
     bool readingResponse,
     bool synchronous,
     IEdmModel model,
     IODataUrlResolver urlResolver)
     : base(format, messageReaderSettings, readingResponse, synchronous, model, urlResolver)
 {
     this.stream = messageStream;
     this.reader = new VCardReader(new StreamReader(messageStream, encoding));
     this.throwExceptionOnDuplicatedPropertyNames = false;
 }
Esempio n. 21
0
 public override System.Threading.Tasks.Task<ODataInputContext> CreateInputContextAsync(ODataMessageInfo messageInfo, ODataMessageReaderSettings messageReaderSettings)
 {
     return messageInfo.GetMessageStreamAsync()
         .ContinueWith(
             (streamTask) => (ODataInputContext) new VCardInputContext(
                 this,
                 streamTask.Result,
                 messageInfo.MediaType,
                 messageInfo.Encoding,
                 messageReaderSettings,
                 messageInfo.IsResponse,
                 /*sync*/ false,
                 messageInfo.Model,
                 messageInfo.UrlResolver),
             TaskContinuationOptions.NotOnFaulted);
 }
Esempio n. 22
0
        /// <summary>
        /// Read the response message and perform given verifications
        /// </summary>
        /// <param name="isFeed">Whether the response has a feed</param>
        /// <param name="responseMessage">The response message</param>
        /// <param name="expectedSet">Expected IEdmEntitySet</param>
        /// <param name="expectedType">Expected IEdmEntityType</param>
        /// <param name="verifyFeed">Action to verify the feed</param>
        /// <param name="verifyEntry">Action to verify the entry</param>
        /// <param name="verifyNavigation">Action to verify the navigation</param>
        public static void ReadAndVerifyFeedEntryMessage(bool isFeed, StreamResponseMessage responseMessage,
                                   IEdmEntitySet expectedSet, IEdmEntityType expectedType,
                                   Action<ODataFeed> verifyFeed, Action<ODataEntry> verifyEntry,
                                   Action<ODataNavigationLink> verifyNavigation)
        {
            var settings = new ODataMessageReaderSettings() { BaseUri = ServiceUri };
            settings.ShouldIncludeAnnotation = s => true;
            ODataMessageReader messageReader = new ODataMessageReader(responseMessage, settings, Model);
            ODataReader reader = isFeed
                                     ? messageReader.CreateODataFeedReader(expectedSet, expectedType)
                                     : messageReader.CreateODataEntryReader(expectedSet, expectedType);
            while (reader.Read())
            {
                switch (reader.State)
                {
                    case ODataReaderState.FeedEnd:
                        {
                            if (verifyFeed != null)
                            {
                                verifyFeed((ODataFeed)reader.Item);
                            }

                            break;
                        }
                    case ODataReaderState.EntryEnd:
                        {
                            if (verifyEntry != null)
                            {
                                verifyEntry((ODataEntry)reader.Item);
                            }

                            break;
                        }
                    case ODataReaderState.NavigationLinkEnd:
                        {
                            if (verifyNavigation != null)
                            {
                                verifyNavigation((ODataNavigationLink)reader.Item);
                            }

                            break;
                        }
                }
            }

            Assert.AreEqual(ODataReaderState.Completed, reader.State);
        }
Esempio n. 23
0
        /// <summary>
        /// Creates an instance of the input context for this format.
        /// </summary>
        /// <param name="messageInfo">The context information for the message.</param>
        /// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
        /// <returns>The newly created input context.</returns>
        public override ODataInputContext CreateInputContext(
            ODataMessageInfo messageInfo,
            ODataMessageReaderSettings messageReaderSettings)
        {
            ExceptionUtils.CheckArgumentNotNull(messageInfo, "messageInfo");
            ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings");

            return new ODataMetadataInputContext(
                this,
                messageInfo.GetMessageStream(),
                messageInfo.Encoding,
                messageReaderSettings,
                messageInfo.IsResponse,
                /*synchronous*/ true,
                messageInfo.Model,
                messageInfo.UrlResolver);
        }
        /// <summary>
        /// Validates a stream reference property.
        /// </summary>
        /// <param name="streamProperty">The stream property to check.</param>
        /// <param name="structuredType">The owning type of the stream property or null if no metadata is available.</param>
        /// <param name="streamEdmProperty">The stream property defined by the model.</param>
        /// <param name="messageReaderSettings">The message reader settings being used.</param>
        internal static void ValidateStreamReferenceProperty(ODataProperty streamProperty, IEdmStructuredType structuredType, IEdmProperty streamEdmProperty, ODataMessageReaderSettings messageReaderSettings)
        {
            Debug.Assert(streamProperty != null, "streamProperty != null");

            ValidationUtils.ValidateStreamReferenceProperty(streamProperty, streamEdmProperty);

            if (structuredType != null && structuredType.IsOpen)
            {
                // If no property match was found in the metadata and an error wasn't raised, 
                // it is an open property (which is not supported for streams).
                if (streamEdmProperty == null && !messageReaderSettings.ReportUndeclaredLinkProperties)
                {
                    // Fails with the correct error message.
                    ValidationUtils.ValidateOpenPropertyValue(streamProperty.Name, streamProperty.Value);
                }
            }
        }
        public void BaseUriGetterAndSetterTest()
        {
            ODataMessageReaderSettings settings = new ODataMessageReaderSettings
            {
                BaseUri = new Uri("http://example.org/odata.svc"),
            };

            var t = settings.BaseUri.ToString();
            settings.BaseUri.ToString().Should().BeEquivalentTo("http://example.org/odata.svc/");

            settings = new ODataMessageReaderSettings()
            {
                BaseUri = new Uri("http://example.org/odata.svc/"),
            };

            settings.BaseUri.ToString().Should().BeEquivalentTo("http://example.org/odata.svc/");
        }
Esempio n. 26
0
        /// <summary>
        /// Detects the payload kinds supported by this format for the specified message payload.
        /// </summary>
        /// <param name="messageInfo">The context information for the message.</param>
        /// <param name="settings">Configuration settings of the OData reader.</param>
        /// <returns>The set of <see cref="ODataPayloadKind"/>s that are supported with the specified payload.</returns>
        public override IEnumerable<ODataPayloadKind> DetectPayloadKind(
            ODataMessageInfo messageInfo,
            ODataMessageReaderSettings settings)
        {
            ExceptionUtils.CheckArgumentNotNull(messageInfo, "messageInfo");

            // Metadata is not supported in requests!
            return messageInfo.IsResponse
                ? DetectPayloadKindImplementation(
                    messageInfo.GetMessageStream(),
                    new ODataPayloadKindDetectionInfo(
                        messageInfo.MediaType,
                        messageInfo.Encoding,
                        settings,
                        messageInfo.Model))
                : Enumerable.Empty<ODataPayloadKind>();
        }
 public async Task<ODataResponse> GetResponseAsync(IODataResponseMessageAsync responseMessage)
 {
     var readerSettings = new ODataMessageReaderSettings();
     readerSettings.MessageQuotas.MaxReceivedMessageSize = Int32.MaxValue;
     using (var messageReader = new ODataMessageReader(responseMessage, readerSettings, _model))
     {
         var payloadKind = messageReader.DetectPayloadKind();
         if (payloadKind.Any(x => x.PayloadKind == ODataPayloadKind.Error))
         {
             return ODataResponse.FromStatusCode(responseMessage.StatusCode);
         }
         else if (payloadKind.Any(x => x.PayloadKind == ODataPayloadKind.Value))
         {
             if (payloadKind.Any(x => x.PayloadKind == ODataPayloadKind.Collection))
             {
                 throw new NotImplementedException();
             }
             else
             {
                 return ODataResponse.FromValueStream(await responseMessage.GetStreamAsync());
             }
         }
         else if (payloadKind.Any(x => x.PayloadKind == ODataPayloadKind.Batch))
         {
             return await ReadResponse(messageReader.CreateODataBatchReader());
         }
         else if (payloadKind.Any(x => x.PayloadKind == ODataPayloadKind.Feed))
         {
             return ReadResponse(messageReader.CreateODataFeedReader());
         }
         else if (payloadKind.Any(x => x.PayloadKind == ODataPayloadKind.Collection))
         {
             return ReadResponse(messageReader.CreateODataCollectionReader());
         }
         else if (payloadKind.Any(x => x.PayloadKind == ODataPayloadKind.Property))
         {
             var property = messageReader.ReadProperty();
             return ODataResponse.FromProperty(property.Name, GetPropertyValue(property.Value));
         }
         else
         {
             return ReadResponse(messageReader.CreateODataEntryReader());
         }
     }
 }
        /// <summary>Initializes a new instance of the <see cref="T:Microsoft.OData.Core.ODataMessageReaderSettings" /> class.</summary>
        /// <param name="other">The other message reader settings.</param>
        public ODataMessageReaderSettings(ODataMessageReaderSettings other)
            : base(other)
        {
            ExceptionUtils.CheckArgumentNotNull(other, "other");

            this.BaseUri = other.BaseUri;
            this.DisableMessageStreamDisposal = other.DisableMessageStreamDisposal;
            this.DisablePrimitiveTypeConversion = other.DisablePrimitiveTypeConversion;
            this.UndeclaredPropertyBehaviorKinds = other.UndeclaredPropertyBehaviorKinds;
            this.MaxProtocolVersion = other.MaxProtocolVersion;

            // NOTE: reader behavior is immutable; copy by reference is ok.
            this.readerBehavior = other.ReaderBehavior;
            this.EnableAtom = other.EnableAtom;
            this.EnableFullValidation = other.EnableFullValidation;
            this.UseKeyAsSegment = other.UseKeyAsSegment;
            this.mediaTypeResolver = other.mediaTypeResolver;
            this.ODataSimplified = other.ODataSimplified;
        }
Esempio n. 29
0
        internal ODataAvroInputContext(
            ODataFormat format,
            Stream messageStream,
            ODataMediaType contentType,
            Encoding encoding,
            ODataMessageReaderSettings messageReaderSettings,
            bool readingResponse,
            bool synchronous,
            IEdmModel model,
            IODataUrlResolver urlResolver)
            : base(format, messageReaderSettings, readingResponse, synchronous, model, urlResolver)
        {
            this.stream = messageStream;

            MemoryStream st = new MemoryStream();
            stream.CopyTo(st);
            st.Seek(0, SeekOrigin.Begin);
            this.AvroReader = new AvroReader(AvroContainer.CreateGenericReader(st));
        }
Esempio n. 30
0
        // Simple demo for reading entry
        public static void ReadEntry(bool enableFullValidation)
        {
            var message = new Message()
            {
                Stream = Payloads.GetStreamFromResource("ODataSamples.Common.Payload.Entry.txt")
            };

            ODataEntry entry = null;

            var setting = new ODataMessageReaderSettings()
            {
                EnableFullValidation = enableFullValidation,
                ShouldIncludeAnnotation = _ => true,
            };

            using (var messageReader = new ODataMessageReader((IODataResponseMessage)message, setting, ExtModel.Model))
            {
                var reader = messageReader.CreateODataEntryReader(ExtModel.Person);
                while (reader.Read())
                {
                    switch (reader.State)
                    {
                        case ODataReaderState.EntryEnd:
                            entry = (ODataEntry)reader.Item;
                            break;
                    }
                }
            }

            Console.WriteLine("Id: {0}", entry.Id);
            Console.WriteLine("properties:");

            foreach (var property in entry.Properties)
            {
                Console.WriteLine("{0}:{1}", property.Name, property.Value);
            }

            Console.WriteLine("Annotations:");
            foreach (var annotation in entry.InstanceAnnotations)
            {
                Console.WriteLine("{0}:{1}", annotation.Name, annotation.Value);
            }
        }
        internal ODataRawInputContext(
            ODataFormat format,
            Stream messageStream,
            Encoding encoding,
            ODataMessageReaderSettings messageReaderSettings,
            ODataVersion version,
            bool readingResponse,
            bool synchronous,
            IEdmModel model,
            IODataUrlResolver urlResolver,
            ODataPayloadKind readerPayloadKind)
            : base(format, messageReaderSettings, version, readingResponse, synchronous, model, urlResolver)
        {
            Debug.Assert(messageStream != null, "stream != null");
            Debug.Assert(readerPayloadKind != ODataPayloadKind.Unsupported, "readerPayloadKind != ODataPayloadKind.Unsupported");

            ExceptionUtils.CheckArgumentNotNull(format, "format");
            ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings");

            try
            {
                this.stream            = messageStream;
                this.encoding          = encoding;
                this.readerPayloadKind = readerPayloadKind;
            }
            catch (Exception e)
            {
                // Dispose the message stream if we failed to create the input context.
                if (ExceptionUtils.IsCatchableExceptionType(e) && messageStream != null)
                {
                    messageStream.Dispose();
                }

                throw;
            }
        }
Esempio n. 32
0
 /// <summary>
 /// Asynchronously creates an instance of the input context for this format.
 /// </summary>
 /// <param name="messageInfo">The context information for the message.</param>
 /// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
 /// <returns>Task which when completed returned the newly created input context.</returns>
 public abstract Task <ODataInputContext> CreateInputContextAsync(ODataMessageInfo messageInfo, ODataMessageReaderSettings messageReaderSettings);
Esempio n. 33
0
 /// <summary>
 /// Asynchronously detects the payload kinds supported by this format for the specified message payload.
 /// </summary>
 /// <param name="messageInfo">The context information for the message.</param>
 /// <param name="settings">Configuration settings of the OData reader.</param>
 /// <returns>A task that when completed returns the set of <see cref="ODataPayloadKind"/>s
 /// that are supported with the specified payload.</returns>
 /// <remarks>
 /// The stream returned by GetMessageStream of <paramref name="messageInfo"/> could be used for reading for
 /// payload kind detection. Reading this stream won't affect later reading operations of payload processing.
 /// </remarks>
 public abstract Task <IEnumerable <ODataPayloadKind> > DetectPayloadKindAsync(ODataMessageInfo messageInfo, ODataMessageReaderSettings settings);
Esempio n. 34
0
 /// <summary>
 /// Creates an instance of the input context for this format.
 /// </summary>
 /// <param name="messageInfo">The context information for the message.</param>
 /// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
 /// <returns>The newly created input context.</returns>
 public abstract ODataInputContext CreateInputContext(ODataMessageInfo messageInfo, ODataMessageReaderSettings messageReaderSettings);
Esempio n. 35
0
 /// <summary>
 /// Detects the payload kinds supported by this format for the specified message payload.
 /// </summary>
 /// <param name="messageInfo">The context information for the message.</param>
 /// <param name="settings">Configuration settings of the OData reader.</param>
 /// <returns>The set of <see cref="ODataPayloadKind"/>s that are supported with the specified payload.</returns>
 /// <remarks>
 /// The stream returned by GetMessageStream of <paramref name="messageInfo"/> could be used for reading for
 /// payload kind detection. Reading this stream won't affect later reading operations of payload processing.
 /// </remarks>
 public abstract IEnumerable <ODataPayloadKind> DetectPayloadKind(ODataMessageInfo messageInfo, ODataMessageReaderSettings settings);