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); }
/// <summary>Constructor.</summary> /// <param name="format">The format for this input context.</param> /// <param name="messageStream">The stream to read data from.</param> /// <param name="contentType">The content type of the message to read.</param> /// <param name="encoding">The encoding to use to read the input.</param> /// <param name="messageReaderSettings">Configuration settings of the OData reader.</param> /// <param name="readingResponse">true if reading a response message; otherwise false.</param> /// <param name="synchronous">true if the input should be read synchronously; false if it should be read asynchronously.</param> /// <param name="model">The model to use.</param> /// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs read from the payload.</param> internal ODataJsonLightInputContext( ODataFormat format, Stream messageStream, ODataMediaType contentType, Encoding encoding, ODataMessageReaderSettings messageReaderSettings, bool readingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : this(format, CreateTextReaderForMessageStreamConstructor(messageStream, encoding), contentType, messageReaderSettings, readingResponse, synchronous, model, urlResolver) { }
/// <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; }
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> /// 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 this.DetectPayloadKindImplementation( messageInfo.GetMessageStream(), messageInfo.IsResponse, new ODataPayloadKindDetectionInfo( messageInfo.MediaType, messageInfo.Encoding, settings, messageInfo.Model)); }
/// <summary> /// Creates a new XmlReaderSettings instance using the encoding. /// </summary> /// <param name="messageReaderSettings">Configuration settings of the OData reader.</param> /// <returns>The Xml reader settings to use for this reader.</returns> private static XmlReaderSettings CreateXmlReaderSettings(ODataMessageReaderSettings messageReaderSettings) { XmlReaderSettings settings = new XmlReaderSettings(); settings.CheckCharacters = messageReaderSettings.CheckCharacters; settings.ConformanceLevel = ConformanceLevel.Document; settings.CloseInput = true; // We do not allow DTDs - this is the default #if ORCAS settings.ProhibitDtd = true; #else settings.DtdProcessing = DtdProcessing.Prohibit; #endif return settings; }
/// <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 ODataAtomInputContext( this, messageInfo.GetMessageStream(), messageInfo.Encoding, messageReaderSettings, messageInfo.IsResponse, /*synchronous*/ true, messageInfo.Model, messageInfo.UrlResolver); }
/// <summary> /// Creates an Xml reader over the specified stream with the provided settings. /// </summary> /// <param name="stream">The stream to create the XmlReader over.</param> /// <param name="encoding">The encoding to use to read the input.</param> /// <param name="messageReaderSettings">The OData message reader settings used to control the settings of the Xml reader.</param> /// <returns>An <see cref="XmlReader"/> instance configured with the provided settings.</returns> internal static XmlReader CreateXmlReader(Stream stream, Encoding encoding, ODataMessageReaderSettings messageReaderSettings) { Debug.Assert(stream != null, "stream != null"); Debug.Assert(messageReaderSettings != null, "messageReaderSettings != null"); XmlReaderSettings xmlReaderSettings = CreateXmlReaderSettings(messageReaderSettings); if (encoding != null) { // Use the encoding from the content type if specified. // NOTE: The XmlReader will scan ahead and determine the encoding from the Xml declaration // and or the payload. Only if no encoding is specified in the Xml declaration and // the Xml reader cannot figure out the encoding from the payload, can it happen // that we need to specify the encoding explicitly (and that wrapping the stream with // a stream reader makes a difference in the first place). return XmlReader.Create(new StreamReader(stream, encoding), xmlReaderSettings); } return XmlReader.Create(stream, xmlReaderSettings); }
static ODataEntityReferenceLinkTests() { EdmModel tmpModel = new EdmModel(); EdmComplexType complexType = new EdmComplexType("TestNamespace", "TestComplexType"); complexType.AddProperty(new EdmStructuralProperty(complexType, "StringProperty", EdmCoreModel.Instance.GetString(false))); tmpModel.AddElement(complexType); EntityType = new EdmEntityType("TestNamespace", "TestEntityType"); tmpModel.AddElement(EntityType); var keyProperty = new EdmStructuralProperty(EntityType, "ID", EdmCoreModel.Instance.GetInt32(false)); EntityType.AddKeys(new IEdmStructuralProperty[] { keyProperty }); EntityType.AddProperty(keyProperty); var defaultContainer = new EdmEntityContainer("TestNamespace", "DefaultContainer_sub"); tmpModel.AddElement(defaultContainer); EntitySet = new EdmEntitySet(defaultContainer, "Customers", EntityType); defaultContainer.AddElement(EntitySet); EdmModel = TestUtils.WrapReferencedModelsToMainModel("TestNamespace", "DefaultContainer", tmpModel); MessageReaderSettingsReadAndValidateCustomInstanceAnnotations = new ODataMessageReaderSettings { ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*") }; }
internal ODataAtomInputContext( ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageReaderSettings messageReaderSettings, bool readingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageReaderSettings, readingResponse, synchronous, model, urlResolver) { Debug.Assert(messageStream != null, "stream != null"); try { ExceptionUtils.CheckArgumentNotNull(format, "format"); ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings"); // Which encoding do we use when reading XML payloads this.baseXmlReader = ODataAtomReaderUtils.CreateXmlReader(messageStream, encoding, messageReaderSettings); // For WCF DS Server behavior we need to turn off xml:base processing for V1/V2 back compat. this.xmlReader = new BufferingXmlReader( this.baseXmlReader, /*parentXmlReader*/ null, messageReaderSettings.BaseUri, /*disableXmlBase*/ false, messageReaderSettings.MessageQuotas.MaxNestingDepth); } 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 FeedWhosePropertyDefinedInReferencedModel() { ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = ServiceBaseUri }; foreach (var mimeType in mimeTypes) { var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri.AbsoluteUri + "Trucks", 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.CreateODataResourceSetReader(); ODataResource entry = null; while (reader.Read()) { if (reader.State == ODataReaderState.ResourceEnd) { entry = reader.Item as ODataResource; } else if (reader.State == ODataReaderState.ResourceSetEnd) { Assert.IsNotNull(reader.Item as ODataResourceSet); } } Assert.IsNotNull(entry.Properties.Single(p => p.Name == "Key").Value); Assert.IsNotNull(entry.TypeName, string.Format("{0}.TruckDemo.TruckType", TestModelNameSpace)); Assert.AreEqual(ODataReaderState.Completed, reader.State); } } } }
public void RequestDeltaLink() { var customersSet = Model.FindDeclaredEntitySet("Customers"); var customerType = customersSet.EntityType(); ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = ServiceBaseUri }; foreach (var mimeType in deltaMimeTypes) { var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri.AbsoluteUri + "$delta", UriKind.Absolute)); requestMessage.SetHeader("Accept", mimeType); var responseMessage = requestMessage.GetResponse(); Assert.Equal(200, responseMessage.StatusCode); if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata)) { using (var messageReader = new ODataMessageReader(responseMessage, readerSettings, Model)) { var deltaReader = messageReader.CreateODataDeltaReader(customersSet, customerType); while (deltaReader.Read()) { if (deltaReader.State == ODataDeltaReaderState.DeltaResourceEnd) { ODataResource entry = deltaReader.Item as ODataResource; } else if (deltaReader.State == ODataDeltaReaderState.DeltaResourceSetEnd) { ODataDeltaResourceSet feed = deltaReader.Item as ODataDeltaResourceSet; } } Assert.Equal(ODataDeltaReaderState.Completed, deltaReader.State); } } } }
private List <ODataEntry> QueryFeed(string requestUri, string mimeType) { List <ODataEntry> entries = new List <ODataEntry>(); ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = ServiceBaseUri }; var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri.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.CreateODataFeedReader(); while (reader.Read()) { if (reader.State == ODataReaderState.EntryEnd) { ODataEntry entry = reader.Item as ODataEntry; entries.Add(entry); } else if (reader.State == ODataReaderState.FeedEnd) { Assert.IsNotNull(reader.Item as ODataFeed); } } Assert.AreEqual(ODataReaderState.Completed, reader.State); } } return(entries); }
private void PrimitiveValueAsKeyInURL(string keySegment) { ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = this.ServiceUri }; foreach (var mimeType in mimeTypes) { var requestMessage = new Microsoft.Test.OData.Tests.Client.Common.HttpWebRequestMessage(new Uri(this.ServiceUri.AbsoluteUri + keySegment, 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, RetrieveServiceEdmModel())) { var reader = messageReader.CreateODataResourceReader(); while (reader.Read()) { if (reader.State == ODataReaderState.ResourceEnd) { var expectedKeySegment = keySegment.Substring(0, keySegment.IndexOf("(")) + "/1"; ODataResource entry = reader.Item as ODataResource; Assert.IsTrue(entry.Id.ToString().Contains(expectedKeySegment), "Expected : Entry's Id doesn't contain trailing when Key is Int64/float/double/decimal"); if (mimeType.Equals(MimeTypes.ApplicationJson + MimeTypes.ODataParameterFullMetadata)) { Assert.IsTrue(entry.EditLink.ToString().Contains(expectedKeySegment), "Expected : Entry's EditLink doesn't contain trailing when Key is Int64/float/double/decimal"); Assert.IsTrue(entry.ReadLink.ToString().Contains(expectedKeySegment), "Expected : Entry's ReadLink doesn't contain trailing when Key is Int64/float/double/decimal"); } } } Assert.AreEqual(ODataReaderState.Completed, reader.State); } } } }
public static ODataMessageReaderSettings ToReaderSettings(this ODataClientSettings settings) { var readerSettings = new ODataMessageReaderSettings(); // TODO ODataLib7 if (settings.IgnoreUnmappedProperties) { readerSettings.Validations &= ~Microsoft.OData.ValidationKinds.ThrowOnUndeclaredPropertyForNonOpenType; } readerSettings.MessageQuotas.MaxReceivedMessageSize = int.MaxValue; readerSettings.ShouldIncludeAnnotation = x => settings.IncludeAnnotationsInResults; if (!settings.ReadUntypedAsString) { readerSettings.Version = ODataVersion.V401; readerSettings.MaxProtocolVersion = ODataVersion.V401; readerSettings.ReadUntypedAsString = false; } return(readerSettings); }
public void DefaultValuesTest401() { ODataMessageReaderSettings settings = new ODataMessageReaderSettings(ODataVersion.V401); Assert.True((settings.Validations & ValidationKinds.ThrowOnDuplicatePropertyNames) != 0, "The ThrowOnDuplicatePropertyNames should be true by default"); Assert.Null(settings.BaseUri); Assert.Null(settings.ClientCustomTypeResolver); Assert.Null(settings.PrimitiveTypeResolver); Assert.True(settings.EnablePrimitiveTypeConversion, "EnablePrimitiveTypeConversion should be true by default."); Assert.True(settings.EnableMessageStreamDisposal, "EnableMessageStreamDisposal should be false by default."); Assert.False(settings.EnableCharactersCheck, "The CheckCharacters should be off by default."); Assert.False(settings.ReadUntypedAsString, "ReadUntypedAsString should be false by default for OData 4.01."); Assert.True((settings.Validations & ValidationKinds.ThrowIfTypeConflictsWithMetadata) != 0, "The ThrowIfTypeConflictsWithMetadata should be true by default"); Assert.Null(settings.ShouldIncludeAnnotation); Assert.True((settings.Validations & ValidationKinds.ThrowOnUndeclaredPropertyForNonOpenType) == 0, "ThrowOnUndeclaredPropertyForNonOpenType should be false by default for OData 4.01."); Assert.True(ODataVersion.V401 == settings.Version, "Version should be 4.01."); Assert.True(ODataVersion.V401 == settings.MaxProtocolVersion, "MaxProtocolVersion should be 4.01."); Assert.True(100 == settings.MessageQuotas.MaxPartsPerBatch, "MaxPartsPerBatch should be int.MaxValue."); Assert.True(1000 == settings.MessageQuotas.MaxOperationsPerChangeset, "MaxOperationsPerChangeset should be int.MaxValue."); Assert.True(100 == settings.MessageQuotas.MaxNestingDepth, "The MaxNestingDepth should be set to 100 by default."); Assert.True(1024 * 1024 == settings.MessageQuotas.MaxReceivedMessageSize, "The MaxMessageSize should be set to 1024 * 1024 by default."); }
private ODataItemBase ReadPayload(string payload, IEdmModel edmModel, Func <ODataMessageReader, ODataReader> createReader) { var message = new InMemoryMessage() { Stream = new MemoryStream(Encoding.UTF8.GetBytes(payload)) }; message.SetHeader("Content-Type", "application/json;odata.metadata=minimal"); ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = new Uri("http://localhost/$metadata"), EnableMessageStreamDisposal = true, Version = ODataVersion.V4, }; using (var msgReader = new ODataMessageReader((IODataResponseMessage)message, readerSettings, edmModel)) { ODataReader reader = createReader(msgReader); return(reader.ReadResourceOrResourceSet()); } }
/// <summary> /// Initializes a new instance of the <see cref="ODataMediaTypeFormatter"/> class. /// </summary> /// <param name="deserializerProvider">The <see cref="ODataDeserializerProvider"/> to use.</param> /// <param name="serializerProvider">The <see cref="ODataSerializerProvider"/> to use.</param> /// <param name="payloadKinds">The kind of payloads this formatter supports.</param> public ODataMediaTypeFormatter(ODataDeserializerProvider deserializerProvider, ODataSerializerProvider serializerProvider, IEnumerable <ODataPayloadKind> payloadKinds) { if (deserializerProvider == null) { throw Error.ArgumentNull("deserializerProvider"); } if (serializerProvider == null) { throw Error.ArgumentNull("serializerProvider"); } if (payloadKinds == null) { throw Error.ArgumentNull("payloadKinds"); } _deserializerProvider = deserializerProvider; _serializerProvider = serializerProvider; _payloadKinds = payloadKinds; // Maxing out the received message size as we depend on the hosting layer to enforce this limit. MessageWriterSettings = new ODataMessageWriterSettings { Indent = true, DisableMessageStreamDisposal = true, MessageQuotas = new ODataMessageQuotas { MaxReceivedMessageSize = Int64.MaxValue } }; MessageReaderSettings = new ODataMessageReaderSettings { DisableMessageStreamDisposal = true, MessageQuotas = new ODataMessageQuotas { MaxReceivedMessageSize = Int64.MaxValue }, }; _version = HttpRequestMessageProperties.DefaultODataVersion; }
public void QueryEntityNavigation() { ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = ServiceBaseUri }; foreach (var mimeType in mimeTypes) { var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri.AbsoluteUri + "Customers(1)/Orders", 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.CreateODataResourceSetReader(); ODataResource entry = null; while (reader.Read()) { if (reader.State == ODataReaderState.ResourceEnd) { entry = reader.Item as ODataResource; } else if (reader.State == ODataReaderState.ResourceSetEnd) { Assert.IsNotNull(reader.Item as ODataResourceSet); } } Assert.AreEqual(8, entry.Properties.Single(p => p.Name == "OrderID").Value); Assert.AreEqual(ODataReaderState.Completed, reader.State); } } } }
private void CompareMessageReaderSettings(ODataMessageReaderSettings expected, ODataMessageReaderSettings actual) { if (expected == null && actual == null) { return; } Assert.IsNotNull(expected, "expected settings cannot be null"); Assert.IsNotNull(actual, "actual settings cannot be null"); Assert.IsTrue(Uri.Compare(expected.BaseUri, actual.BaseUri, UriComponents.AbsoluteUri, UriFormat.Unescaped, StringComparison.CurrentCulture) == 0, "BaseUri does not match"); Assert.AreEqual(expected.CheckCharacters, actual.CheckCharacters, "CheckCharacters does not match"); Assert.AreEqual(expected.DisableMessageStreamDisposal, actual.DisableMessageStreamDisposal, "DisableMessageStreamDisposal does not match"); Assert.AreEqual(expected.EnableAtomMetadataReading, actual.EnableAtomMetadataReading, "EnableAtomMetadataReading does not match"); Assert.AreEqual(expected.UndeclaredPropertyBehaviorKinds, actual.UndeclaredPropertyBehaviorKinds, "UndeclaredPropertyBehaviorKinds does not match"); Assert.AreEqual(expected.MaxProtocolVersion, actual.MaxProtocolVersion, "MaxProtocolVersion does not match."); Assert.AreEqual(expected.MessageQuotas.MaxPartsPerBatch, actual.MessageQuotas.MaxPartsPerBatch, "MaxPartsPerBatch does not match"); Assert.AreEqual(expected.MessageQuotas.MaxOperationsPerChangeset, actual.MessageQuotas.MaxOperationsPerChangeset, "MaxOperationsPerChangeset does not match"); Assert.AreEqual(expected.MessageQuotas.MaxNestingDepth, actual.MessageQuotas.MaxNestingDepth, "MaxNestingDepth does not match"); Assert.AreEqual(expected.MessageQuotas.MaxReceivedMessageSize, actual.MessageQuotas.MaxReceivedMessageSize, "MaxMessageSize does not match"); Assert.AreEqual(expected.EnableAtom, actual.EnableAtom, "EnableAtom does not match"); }
public void Can_DeserializePayload_WithPrimitiveCollections_InUntypedMode(string actionName, IEdmAction expectedAction, ODataPath path) { // Arrange const string Body = @"{ ""Name"": ""Avatar"", ""Ratings"": [ 5, 5, 3, 4, 5, 5, 4, 5, 5, 4 ], ""Time"": [""01:02:03.0040000"", ""12:13:14.1150000""]}"; int[] expectedRatings = new int[] { 5, 5, 3, 4, 5, 5, 4, 5, 5, 4 }; ODataMessageWrapper message = new ODataMessageWrapper(GetStringAsStream(Body)); message.SetHeader("Content-Type", "application/json"); ODataMessageReaderSettings settings = new ODataMessageReaderSettings(); ODataMessageReader reader = new ODataMessageReader(message as IODataRequestMessage, settings, _model); ODataDeserializerContext context = new ODataDeserializerContext { Path = path, Model = _model, ResourceType = typeof(ODataUntypedActionParameters) }; // Act ODataUntypedActionParameters payload = _deserializer.Read(reader, typeof(ODataUntypedActionParameters), context) as ODataUntypedActionParameters; IEdmAction action = ODataActionPayloadDeserializer.GetAction(context); //Assert Assert.NotNull(actionName); Assert.Same(expectedAction, action); Assert.NotNull(payload); Assert.True(payload.ContainsKey("Name")); Assert.Equal("Avatar", payload["Name"]); Assert.True(payload.ContainsKey("Ratings")); IEnumerable <int> ratings = payload["Ratings"] as IEnumerable <int>; Assert.Equal(10, ratings.Count()); Assert.True(expectedRatings.Zip(ratings, (expected, actual) => expected - actual).All(diff => diff == 0)); Assert.True(payload.ContainsKey("Time")); IEnumerable <TimeOfDay> times = payload["Time"] as IEnumerable <TimeOfDay>; Assert.Equal(2, times.Count()); Assert.Equal(new[] { new TimeOfDay(1, 2, 3, 4), new TimeOfDay(12, 13, 14, 115) }, times.ToList()); }
internal ODataJsonInputContext( ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, bool readingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : this( format, CreateTextReaderForMessageStreamConstructor(messageStream, encoding), messageReaderSettings, version, readingResponse, synchronous, model, urlResolver) { DebugUtils.CheckNoExternalCallers(); }
public void QueryEntitiesSelectEnumProperty() { ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = ServiceBaseUri }; foreach (var mimeType in mimeTypes) { var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri.AbsoluteUri + "Products?$select=SkinColor,UserAccess", 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)) { List <ODataResource> entries = new List <ODataResource>(); var reader = messageReader.CreateODataResourceSetReader(); while (reader.Read()) { if (reader.State == ODataReaderState.ResourceEnd) { ODataResource entry = reader.Item as ODataResource; Assert.IsNotNull(entry); entries.Add(entry); } } Assert.AreEqual(ODataReaderState.Completed, reader.State); Assert.AreEqual(5, entries.Count); Assert.AreEqual(false, entries[0].Properties.Any(p => p.Name != "SkinColor" && p.Name != "UserAccess")); } } } }
/// <summary> /// Converts the given string <paramref name="value"/> to an ODataComplexValue or ODataCollectionValue and returns it. /// Tries in both JSON light and Verbose JSON. /// </summary> /// <remarks>Does not handle primitive values.</remarks> /// <param name="value">Value to be deserialized.</param> /// <param name="model">Model to use for verification.</param> /// <param name="typeReference">Expected type reference from deserialization. If null, verification will be skipped.</param> /// <returns>An ODataComplexValue or ODataCollectionValue that results from the deserialization of <paramref name="value"/>.</returns> internal static object ConvertFromComplexOrCollectionValue(string value, IEdmModel model, IEdmTypeReference typeReference) { ODataMessageReaderSettings settings = new ODataMessageReaderSettings(); using (StringReader reader = new StringReader(value)) { using (ODataJsonLightInputContext context = new ODataJsonLightInputContext( ODataFormat.Json, reader, new ODataMediaType(MimeConstants.MimeApplicationType, MimeConstants.MimeJsonSubType), settings, false /*readingResponse*/, true /*synchronous*/, model, null /*urlResolver*/)) { ODataJsonLightPropertyAndValueDeserializer deserializer = new ODataJsonLightPropertyAndValueDeserializer(context); // TODO: The way JSON array literals look in the URI is different that response payload with an array in it. // The fact that we have to manually setup the underlying reader shows this different in the protocol. // There is a discussion on if we should change this or not. deserializer.JsonReader.Read(); // Move to first thing object rawResult = deserializer.ReadNonEntityValue( null /*payloadTypeName*/, typeReference, null /*DuplicatePropertyNameChecker*/, null /*CollectionWithoutExpectedTypeValidator*/, true /*validateNullValue*/, false /*isTopLevelPropertyValue*/, false /*insideComplexValue*/, null /*propertyName*/); deserializer.ReadPayloadEnd(false); Debug.Assert(rawResult is ODataComplexValue || rawResult is ODataCollectionValue, "rawResult is ODataComplexValue || rawResult is ODataCollectionValue"); return rawResult; } } }
/// <summary> /// Create message reader settings for consuming responses. /// </summary> /// <returns>Newly created message reader settings.</returns> internal ODataMessageReaderSettings CreateSettings() { ODataMessageReaderSettings settings = new ODataMessageReaderSettings(); #if !DNXCORE50 if (this.responseInfo.Context.EnableAtom) { // Enable ATOM in client settings.EnableAtomSupport(); } #endif Func <IEdmType, string, IEdmType> resolveWireTypeName = this.responseInfo.TypeResolver.ResolveWireTypeName; if (this.responseInfo.Context.Format.ServiceModel != null) { resolveWireTypeName = null; } settings.EnableWcfDataServicesClientBehavior(resolveWireTypeName); settings.BaseUri = this.responseInfo.BaseUriResolver.BaseUriOrNull; settings.ODataSimplified = this.responseInfo.Context.ODataSimplified; settings.UndeclaredPropertyBehaviorKinds = ODataUndeclaredPropertyBehaviorKinds.ReportUndeclaredLinkProperty; settings.MaxProtocolVersion = CommonUtil.ConvertToODataVersion(this.responseInfo.MaxProtocolVersion); if (this.responseInfo.IgnoreMissingProperties) { settings.UndeclaredPropertyBehaviorKinds |= ODataUndeclaredPropertyBehaviorKinds.IgnoreUndeclaredValueProperty; } if (this.responseInfo.Context.UrlConventions == DataServiceUrlConventions.KeyAsSegment) { settings.UseKeyAsSegment = true; } CommonUtil.SetDefaultMessageQuotas(settings.MessageQuotas); this.responseInfo.ResponsePipeline.ExecuteReaderSettingsConfiguration(settings); return(settings); }
public void SetBehaviorTest() { ODataMessageReaderSettings settings = new ODataMessageReaderSettings(); settings.EnableWcfDataServicesClientBehavior(null); this.CompareReaderBehavior( settings, /*formatBehaviorKind*/ ODataBehaviorKind.WcfDataServicesClient, /*apiBehaviorKind*/ ODataBehaviorKind.WcfDataServicesClient, true, /*typeResolver*/ null); Func <IEdmType, string, IEdmType> customTypeResolver = (expectedType, typeName) => expectedType; settings.EnableWcfDataServicesClientBehavior(customTypeResolver); this.CompareReaderBehavior( settings, /*formatBehaviorKind*/ ODataBehaviorKind.WcfDataServicesClient, /*apiBehaviorKind*/ ODataBehaviorKind.WcfDataServicesClient, true, customTypeResolver); settings.EnableODataServerBehavior(); this.CompareReaderBehavior( settings, /*formatBehaviorKind*/ ODataBehaviorKind.ODataServer, /*apiBehaviorKind*/ ODataBehaviorKind.ODataServer, true, /*typeResolver*/ null); settings.EnableDefaultBehavior(); this.CompareReaderBehavior( settings, /*formatBehaviorKind*/ ODataBehaviorKind.Default, /*apiBehaviorKind*/ ODataBehaviorKind.Default, false, /*typeResolver*/ null); }
public void RequestDeltaLink_Containment() { var accountsSet = this.Model.FindDeclaredEntitySet("Accounts"); var accountType = accountsSet.EntityType(); var myPisNav = accountType.FindProperty("MyPaymentInstruments") as IEdmNavigationProperty; var piSet = accountsSet.FindNavigationTarget(myPisNav) as IEdmEntitySetBase; var piType = piSet.EntityType(); ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = ServiceBaseUri }; foreach (var mimeType in deltaMimeTypes) { var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri.AbsoluteUri + "$delta?$token=containment", UriKind.Absolute)); requestMessage.SetHeader("Accept", mimeType); var responseMessage = requestMessage.GetResponse(); Assert.Equal(200, responseMessage.StatusCode); if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata)) { using (var messageReader = new ODataMessageReader(responseMessage, readerSettings, Model)) { var deltaReader = messageReader.CreateODataDeltaReader(piSet, piType); while (deltaReader.Read()) { if (deltaReader.State == ODataDeltaReaderState.DeltaResourceEnd) { ODataResource entry = deltaReader.Item as ODataResource; } } Assert.Equal(ODataDeltaReaderState.Completed, deltaReader.State); } } } }
/// <summary> /// Converts the given string <paramref name="value"/> to an ODataComplexValue or ODataCollectionValue and returns it. /// Tries in both JSON light and Verbose JSON. /// </summary> /// <remarks>Does not handle primitive values.</remarks> /// <param name="value">Value to be deserialized.</param> /// <param name="model">Model to use for verification.</param> /// <param name="typeReference">Expected type reference from deserialization. If null, verification will be skipped.</param> /// <returns>An ODataComplexValue or ODataCollectionValue that results from the deserialization of <paramref name="value"/>.</returns> internal static object ConvertFromComplexOrCollectionValue(string value, IEdmModel model, IEdmTypeReference typeReference) { ODataMessageReaderSettings settings = new ODataMessageReaderSettings(); using (StringReader reader = new StringReader(value)) { using (ODataJsonLightInputContext context = new ODataJsonLightInputContext( ODataFormat.Json, reader, new ODataMediaType(MimeConstants.MimeApplicationType, MimeConstants.MimeJsonSubType), settings, false /*readingResponse*/, true /*synchronous*/, model, null /*urlResolver*/)) { ODataJsonLightPropertyAndValueDeserializer deserializer = new ODataJsonLightPropertyAndValueDeserializer(context); // TODO: The way JSON array literals look in the URI is different that response payload with an array in it. // The fact that we have to manually setup the underlying reader shows this different in the protocol. // There is a discussion on if we should change this or not. deserializer.JsonReader.Read(); // Move to first thing object rawResult = deserializer.ReadNonEntityValue( null /*payloadTypeName*/, typeReference, null /*DuplicatePropertyNameChecker*/, null /*CollectionWithoutExpectedTypeValidator*/, true /*validateNullValue*/, false /*isTopLevelPropertyValue*/, false /*insideComplexValue*/, null /*propertyName*/); deserializer.ReadPayloadEnd(false); Debug.Assert(rawResult is ODataComplexValue || rawResult is ODataCollectionValue, "rawResult is ODataComplexValue || rawResult is ODataCollectionValue"); return(rawResult); } } }
/// <summary> /// Reads an annotation's value from the annotation value notation specified on the current element. /// </summary> /// <param name="expectedTypeReference">The expected type reference of the vocabulary term from the metadata.</param> /// <param name="attributeValueNotationTypeReference">The type reference indicated by the name of the attribute used in attribute value notation. /// For example, if the attribute was called "string", this will be a reference to the string type.</param> /// <param name="attributeValueNotationAttributeName">The name of the attribute used by attribute avalue notation.</param> /// <param name="attributeValueNotationAttributeValue">The value of the attribute used by attribute value notation.</param> /// <param name="typeAttributeValue">The value of the "m:type" attribute on the annotation element.</param> /// <param name="positionedOnEmptyElement">true if the annotation element is empty, false otherwise.</param> /// <param name="model">The edm model instance.</param> /// <param name="messageReaderSettings">The message reader settings instance.</param> /// <param name="version">The payload version to read.</param> /// <returns>The primitive value represented on this element via attribute value notation.</returns> private static ODataPrimitiveValue GetValueFromAttributeValueNotation( IEdmTypeReference expectedTypeReference, IEdmPrimitiveTypeReference attributeValueNotationTypeReference, string attributeValueNotationAttributeName, string attributeValueNotationAttributeValue, string typeAttributeValue, bool positionedOnEmptyElement, IEdmModel model, ODataMessageReaderSettings messageReaderSettings, ODataVersion version) { Debug.Assert(attributeValueNotationTypeReference != null, "attributeValueNotationTypeReference != null"); if (!positionedOnEmptyElement) { // If there is content in the body of the element, throw since it's ambiguous whether we should use the value from the attribute or the element content. throw new ODataException(ODataErrorStrings.AtomInstanceAnnotation_AttributeValueNotationUsedOnNonEmptyElement(attributeValueNotationAttributeName)); } // If both m:type is present and attribute value notation is being used, they must match. // For example, if m:type is "Edm.Int32", but the "string" attribute is also present, we should throw. if (typeAttributeValue != null && !string.Equals(attributeValueNotationTypeReference.Definition.ODataFullName(), typeAttributeValue, StringComparison.Ordinal)) { throw new ODataException(ODataErrorStrings.AtomInstanceAnnotation_AttributeValueNotationUsedWithIncompatibleType(typeAttributeValue, attributeValueNotationAttributeName)); } IEdmTypeReference targetTypeReference = ReaderValidationUtils.ResolveAndValidatePrimitiveTargetType( expectedTypeReference, EdmTypeKind.Primitive, attributeValueNotationTypeReference.Definition, attributeValueNotationTypeReference.ODataFullName(), attributeValueNotationTypeReference.Definition, model, messageReaderSettings, version); return(new ODataPrimitiveValue(AtomValueUtils.ConvertStringToPrimitive(attributeValueNotationAttributeValue, targetTypeReference.AsPrimitive()))); }
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") }); var config = RoutingConfigurationFactory.CreateWithRootContainer("OData"); var request = RequestFactory.Create(config, "OData"); ODataMessageReaderSettings readSettings = new ODataMessageReaderSettings(); ODataMessageReader messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage), readSettings, model); ODataDeserializerContext context = new ODataDeserializerContext { Request = request, Path = new ODataPath(new NavigationPropertySegment(GetNavigationProperty(model), navigationSource: null)) }; // Act Uri uri = deserializer.Read(messageReader, typeof(Uri), context) as Uri; // Assert Assert.NotNull(uri); Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri); }
protected static ODataMessageReader CreateODataMessageReader(IODataResponseMessage responseMessage, ResponseInfo responseInfo, ref ODataPayloadKind payloadKind) { ODataMessageReaderSettings settings = responseInfo.ReadHelper.CreateSettings(); ODataMessageReader odataMessageReader = responseInfo.ReadHelper.CreateReader(responseMessage, settings); if (payloadKind == ODataPayloadKind.Unsupported) { var payloadKinds = odataMessageReader.DetectPayloadKind().ToList(); if (payloadKinds.Count == 0) { throw DSClient.Error.InvalidOperation(DSClient.Strings.AtomMaterializer_InvalidResponsePayload(XmlConstants.DataWebNamespace)); } // Pick the first payload kind detected by ODataLib and use that to parse the exception. // The only exception being payload with entity reference link(s). If one of the payload kinds // is reference links, then we need to give preference to reference link payloads. ODataPayloadKindDetectionResult detectionResult = payloadKinds.FirstOrDefault(k => k.PayloadKind == ODataPayloadKind.EntityReferenceLink || k.PayloadKind == ODataPayloadKind.EntityReferenceLinks); if (detectionResult == null) { detectionResult = payloadKinds.First(); } // Astoria client only supports atom, jsonlight and raw value payloads. #pragma warning disable 618 if (detectionResult.Format != ODataFormat.Atom && detectionResult.Format != ODataFormat.Json && detectionResult.Format != ODataFormat.RawValue) #pragma warning restore 618 { throw DSClient.Error.InvalidOperation(DSClient.Strings.AtomMaterializer_InvalidContentTypeEncountered(responseMessage.GetHeader(XmlConstants.HttpContentType))); } payloadKind = detectionResult.PayloadKind; } return(odataMessageReader); }
public void QueryWithFilterTime() { ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = ServiceBaseUri }; foreach (var mimeType in mimeTypes) { var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri.AbsoluteUri + "Orders?$filter=ShipTime eq 12:40:5.05", UriKind.Absolute)); requestMessage.SetHeader("Accept", mimeType); var responseMessage = requestMessage.GetResponse(); Assert.Equal(200, responseMessage.StatusCode); if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata)) { using (var messageReader = new ODataMessageReader(responseMessage, readerSettings, Model)) { var reader = messageReader.CreateODataResourceSetReader(); while (reader.Read()) { if (reader.State == ODataReaderState.ResourceEnd) { ODataResource entry = reader.Item as ODataResource; if (entry != null) { // Verify Date Property Assert.Equal(new Date(2014, 8, 31), entry.Properties.Single(p => p.Name == "ShipDate").Value); Assert.Equal(new TimeOfDay(12, 40, 5, 50), entry.Properties.Single(p => p.Name == "ShipTime").Value); } } } Assert.Equal(ODataReaderState.Completed, reader.State); } } } }
public void FeedTypeDerivedFromReferencedModel() { ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = ServiceBaseUri }; foreach (var mimeType in mimeTypes) { var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri.AbsoluteUri + "DerivedVehicleGPSSet", 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.CreateODataFeedReader(); while (reader.Read()) { if (reader.State == ODataReaderState.EntryEnd) { ODataEntry entry = reader.Item as ODataEntry; Assert.IsNotNull(entry.Properties.Single(p => p.Name == "DisplayName").Value); Assert.IsNotNull(entry.TypeName, string.Format("{0}.TruckDemo.DerivedVehicleGPSType", TestModelNameSpace)); } else if (reader.State == ODataReaderState.FeedEnd) { Assert.IsNotNull(reader.Item as ODataFeed); } } Assert.AreEqual(ODataReaderState.Completed, reader.State); } } } }
private static object ConvertResourceOrResourceSet(object oDataValue, IEdmTypeReference edmTypeReference, ODataDeserializerContext readContext) { string valueString = oDataValue as string; Contract.Assert(valueString != null); if (edmTypeReference.IsNullable && String.Equals(valueString, "null", StringComparison.Ordinal)) { return(null); } HttpRequestMessage request = readContext.Request; ODataMessageReaderSettings oDataReaderSettings = request.GetReaderSettings(); using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(valueString))) { stream.Seek(0, SeekOrigin.Begin); IODataRequestMessage oDataRequestMessage = new ODataMessageWrapper(stream, null, request.GetODataContentIdMapping()); using ( ODataMessageReader oDataMessageReader = new ODataMessageReader(oDataRequestMessage, oDataReaderSettings, readContext.Model)) { request.RegisterForDispose(oDataMessageReader); if (edmTypeReference.IsCollection()) { return(ConvertResourceSet(oDataMessageReader, edmTypeReference, readContext)); } else { return(ConvertResource(oDataMessageReader, edmTypeReference, readContext)); } } } }
internal static TableResult TableOperationPostProcess(TableResult result, TableOperation operation, RESTCommand <TableResult> cmd, HttpWebResponse resp, OperationContext ctx, TableRequestOptions options, string accountName) { if (operation.OperationType != TableOperationType.Retrieve && operation.OperationType != TableOperationType.Insert) { result.Etag = HttpResponseParsers.GetETag(resp); operation.Entity.ETag = result.Etag; } else if (operation.OperationType == TableOperationType.Insert && (!operation.EchoContent)) { if (HttpResponseParsers.GetETag(resp) != null) { result.Etag = HttpResponseParsers.GetETag(resp); operation.Entity.ETag = result.Etag; operation.Entity.Timestamp = ParseETagForTimestamp(result.Etag); } } else { // Parse entity ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings(); readerSettings.MessageQuotas = new ODataMessageQuotas() { MaxPartsPerBatch = TableConstants.TableServiceMaxResults, MaxReceivedMessageSize = TableConstants.TableServiceMaxPayload }; if (resp.ContentType.Contains(Constants.JsonNoMetadataAcceptHeaderValue)) { result.Etag = resp.Headers[Constants.HeaderConstants.EtagHeader]; ReadEntityUsingJsonParser(result, operation, cmd.ResponseStream, ctx, options); } else { ReadOdataEntity(result, operation, new HttpResponseAdapterMessage(resp, cmd.ResponseStream), ctx, readerSettings, accountName, options); } } return(result); }
public void TypeCastEntryinCycleReferencingModels() { ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = ServiceBaseUri }; foreach (var mimeType in mimeTypes) { var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri.AbsoluteUri + "VehicleGPSSetInGPS('DerivedVehicleGPSInGPSKey3')/Microsoft.OData.SampleService.Models.ModelRefDemo.TruckDemo.DerivedVehicleGPSType", UriKind.Absolute)); requestMessage.SetHeader("Accept", mimeType); var responseMessage = requestMessage.GetResponse(); Assert.Equal(200, responseMessage.StatusCode); if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata)) { using (var messageReader = new ODataMessageReader(responseMessage, readerSettings, Model)) { var reader = messageReader.CreateODataResourceReader(); while (reader.Read()) { if (reader.State == ODataReaderState.ResourceEnd) { ODataResource entry = reader.Item as ODataResource; if (entry != null & entry.TypeName.EndsWith("VehicleGPSType")) { Assert.Equal("DerivedVehicleGPSInGPSKey3", entry.Properties.Single(p => p.Name == "Key").Value); Assert.Equal("DerivedVehicleGPSInGPSDP", entry.Properties.Single(p => p.Name == "DisplayName").Value); Assert.Equal(entry.TypeName, string.Format("{0}.TruckDemo.DerivedVehicleGPSType", TestModelNameSpace)); } } } Assert.Equal(ODataReaderState.Completed, reader.State); } } } }
public void ValidServiceDocument() { var metadataMessage = new HttpWebRequestMessage(new Uri(ServiceUri + "$metadata")); metadataMessage.SetHeader("Accept", MimeTypes.ApplicationXml); var metadataMessageReader = new ODataMessageReader(metadataMessage.GetResponse()); var model = metadataMessageReader.ReadMetadataDocument(); var message = new HttpWebRequestMessage(ServiceUri); message.SetHeader("Accept", MimeTypes.ApplicationJson); ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = ServiceUri }; using (var messageReader = new ODataMessageReader(message.GetResponse(), readerSettings, model)) { var workspace = messageReader.ReadServiceDocument(); Assert.AreEqual(24, workspace.EntitySets.Count()); } }
/// <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(); HeaderDictionary headerDict = new HeaderDictionary(); foreach (var head in content.Headers) { headerDict[head.Key] = new StringValues(head.Value.ToArray()); } IODataRequestMessage oDataRequestMessage = ODataMessageWrapperHelper.Create(contentStream, headerDict /*, new MockServiceProvider()*/); ODataMessageReader oDataMessageReader = new ODataMessageReader(oDataRequestMessage, settings); return(oDataMessageReader); }
private ODataJsonLightInputContext CreateJsonLightInputContext( string payload, IEdmModel model, bool isAsync = false, bool isResponse = true) { this.messageInfo = new ODataMessageInfo { IsResponse = isResponse, MediaType = new ODataMediaType("application", "json", new KeyValuePair <string, string>("odata.streaming", "true")), IsAsync = isAsync, Model = this.model, }; this.messageReaderSettings = new ODataMessageReaderSettings(); messageReaderSettings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*"); payloadKindDetectionInfo = new ODataPayloadKindDetectionInfo(this.messageInfo, this.messageReaderSettings); return(new ODataJsonLightInputContext( new StringReader(payload), messageInfo, messageReaderSettings)); }
public ODataJsonReaderCoreUtilsTests() { var messageReaderSettings = new ODataMessageReaderSettings { MessageQuotas = new ODataMessageQuotas { MaxNestingDepth = 10 } }; var messageInfo = new ODataMessageInfo { Encoding = Encoding.UTF8, IsResponse = true, MediaType = new ODataMediaType("application", "json"), IsAsync = false, Model = EdmCoreModel.Instance, MessageStream = new MemoryStream(), Container = null }; this.inputContext = new ODataJsonLightInputContext(messageInfo, messageReaderSettings); }
public void ModelReferenceWithOrderbyOption() { ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = ServiceBaseUri }; foreach (var mimeType in mimeTypes) { var requestMessage = new HttpWebRequestMessage( new Uri(ServiceBaseUri.AbsoluteUri + "DerivedVehicleGPSSet?$orderby=DisplayName desc", 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)) { List <ODataEntry> entries = new List <ODataEntry>(); var reader = messageReader.CreateODataFeedReader(); while (reader.Read()) { if (reader.State == ODataReaderState.EntryEnd) { entries.Add(reader.Item as ODataEntry); } } Assert.AreEqual(ODataReaderState.Completed, reader.State); Assert.AreEqual("DisplayName5", entries[0].Properties.SingleOrDefault(p => p.Name == "DisplayName").Value); Assert.AreEqual("DisplayName4", entries[1].Properties.SingleOrDefault(p => p.Name == "DisplayName").Value); } } } }
static ODataJsonLightEntryAndFeedDeserializerTests() { EdmModel tmpModel = new EdmModel(); EdmComplexType complexType = new EdmComplexType("TestNamespace", "TestComplexType"); complexType.AddProperty(new EdmStructuralProperty(complexType, "StringProperty", EdmCoreModel.Instance.GetString(false))); tmpModel.AddElement(complexType); EntityType = new EdmEntityType("TestNamespace", "TestEntityType"); tmpModel.AddElement(EntityType); var keyProperty = new EdmStructuralProperty(EntityType, "ID", EdmCoreModel.Instance.GetInt32(false)); EntityType.AddKeys(new IEdmStructuralProperty[] { keyProperty }); EntityType.AddProperty(keyProperty); var defaultContainer = new EdmEntityContainer("TestNamespace", "DefaultContainer_sub"); tmpModel.AddElement(defaultContainer); EntitySet = new EdmEntitySet(defaultContainer, "TestEntitySet", EntityType); defaultContainer.AddElement(EntitySet); Action = new EdmAction("TestNamespace", "DoSomething", null, true, null); Action.AddParameter("p1", new EdmEntityTypeReference(EntityType, false)); tmpModel.AddElement(Action); ActionImport = defaultContainer.AddActionImport("DoSomething", Action); var serviceOperationFunction = new EdmFunction("TestNamespace", "ServiceOperation", EdmCoreModel.Instance.GetInt32(true)); defaultContainer.AddFunctionImport("ServiceOperation", serviceOperationFunction); tmpModel.AddElement(serviceOperationFunction); tmpModel.AddElement(new EdmTerm("custom", "DateTimeOffsetAnnotation", EdmPrimitiveTypeKind.DateTimeOffset)); tmpModel.AddElement(new EdmTerm("custom", "DateAnnotation", EdmPrimitiveTypeKind.Date)); tmpModel.AddElement(new EdmTerm("custom", "TimeOfDayAnnotation", EdmPrimitiveTypeKind.TimeOfDay)); EdmModel = TestUtils.WrapReferencedModelsToMainModel("TestNamespace", "DefaultContainer", tmpModel); MessageReaderSettingsReadAndValidateCustomInstanceAnnotations = new ODataMessageReaderSettings { ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*") }; MessageReaderSettingsIgnoreInstanceAnnotations = new ODataMessageReaderSettings(); }
/// <summary> /// Reads an ODataError from the stream and returns it for verification. /// </summary> private ODataError ReadError() { ODataError readError; var readerSettings = new ODataMessageReaderSettings { DisableMessageStreamDisposal = false }; IODataResponseMessage messageToRead = new InMemoryMessage { StatusCode = 400, Stream = this.stream }; messageToRead.SetHeader("Content-Type", "application/json;odata.metadata=minimal"); using (var reader = new ODataMessageReader(messageToRead, readerSettings, this.model)) { readError = reader.ReadError(); } return readError; }
// TODO: ATOM top level individual property testings // FlagsEnumAsComplexPropertyAsTopLevelValue_StrAsValue_StrAsTypeName // FlagsEnumAsCollectionItemAsTopLevelValue_StrAsValue_StrAsTypeName #endregion #region private methods public void ReadFromMessageReaderAndVerifyPayload(string payload, Action<ODataMessageReader> readerAction) { string contentType = "application/xml;"; var settings = new ODataMessageReaderSettings { DisableMessageStreamDisposal = false, EnableAtom = true }; // with model { IODataResponseMessage message = new InMemoryMessage() { Stream = new MemoryStream(Encoding.UTF8.GetBytes(payload)) }; message.SetHeader(ODataConstants.ContentTypeHeader, contentType); using (ODataMessageReader reader = new ODataMessageReader(message, settings, this.userModel)) { readerAction(reader); } } // without model should fail Action action = () => { IODataResponseMessage message = new InMemoryMessage() { Stream = new MemoryStream(Encoding.UTF8.GetBytes(payload)) }; message.SetHeader(ODataConstants.ContentTypeHeader, contentType); message.SetHeader(ODataConstants.ContentTypeHeader, contentType); using (ODataMessageReader reader = new ODataMessageReader(message, settings)) { readerAction(reader); } }; action.ShouldThrow<Exception>(); }
public void UnsignedIntAndTypeDefinitionRoundtripJsonLightIntegrationTest() { var model = new EdmModel(); var uint16 = new EdmTypeDefinition("MyNS", "UInt16", EdmPrimitiveTypeKind.Double); var uint16Ref = new EdmTypeDefinitionReference(uint16, false); model.AddElement(uint16); model.SetPrimitiveValueConverter(uint16Ref, UInt16ValueConverter.Instance); var uint64 = new EdmTypeDefinition("MyNS", "UInt64", EdmPrimitiveTypeKind.String); var uint64Ref = new EdmTypeDefinitionReference(uint64, false); model.AddElement(uint64); model.SetPrimitiveValueConverter(uint64Ref, UInt64ValueConverter.Instance); var guidType = new EdmTypeDefinition("MyNS", "Guid", EdmPrimitiveTypeKind.Int64); var guidRef = new EdmTypeDefinitionReference(guidType, true); model.AddElement(guidType); var personType = new EdmEntityType("MyNS", "Person"); personType.AddKeys(personType.AddStructuralProperty("ID", uint64Ref)); personType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String); personType.AddStructuralProperty("FavoriteNumber", uint16Ref); personType.AddStructuralProperty("Age", model.GetUInt32("MyNS", true)); personType.AddStructuralProperty("Guid", guidRef); personType.AddStructuralProperty("Weight", EdmPrimitiveTypeKind.Double); personType.AddStructuralProperty("Money", EdmPrimitiveTypeKind.Decimal); model.AddElement(personType); var container = new EdmEntityContainer("MyNS", "Container"); var peopleSet = container.AddEntitySet("People", personType); model.AddElement(container); var stream = new MemoryStream(); IODataResponseMessage message = new InMemoryMessage { Stream = stream }; message.StatusCode = 200; var writerSettings = new ODataMessageWriterSettings(); writerSettings.SetServiceDocumentUri(new Uri("http://host/service")); var messageWriter = new ODataMessageWriter(message, writerSettings, model); var entryWriter = messageWriter.CreateODataEntryWriter(peopleSet); var entry = new ODataEntry { TypeName = "MyNS.Person", Properties = new[] { new ODataProperty { Name = "ID", Value = UInt64.MaxValue }, new ODataProperty { Name = "Name", Value = "Foo" }, new ODataProperty { Name = "FavoriteNumber", Value = (UInt16)250 }, new ODataProperty { Name = "Age", Value = (UInt32)123 }, new ODataProperty { Name = "Guid", Value = Int64.MinValue }, new ODataProperty { Name = "Weight", Value = 123.45 }, new ODataProperty { Name = "Money", Value = Decimal.MaxValue } } }; entryWriter.WriteStart(entry); entryWriter.WriteEnd(); entryWriter.Flush(); stream.Position = 0; StreamReader reader = new StreamReader(stream); string payload = reader.ReadToEnd(); payload.Should().Be("{\"@odata.context\":\"http://host/service/$metadata#People/$entity\",\"ID\":\"18446744073709551615\",\"Name\":\"Foo\",\"FavoriteNumber\":250.0,\"Age\":123,\"Guid\":-9223372036854775808,\"Weight\":123.45,\"Money\":79228162514264337593543950335}"); stream = new MemoryStream(Encoding.Default.GetBytes(payload)); message = new InMemoryMessage { Stream = stream }; message.StatusCode = 200; var readerSettings = new ODataMessageReaderSettings(); var messageReader = new ODataMessageReader(message, readerSettings, model); var entryReader = messageReader.CreateODataEntryReader(peopleSet, personType); Assert.True(entryReader.Read()); var entryReaded = entryReader.Item as ODataEntry; var propertiesReaded = entryReaded.Properties.ToList(); var propertiesGiven = entry.Properties.ToList(); Assert.Equal(propertiesReaded.Count, propertiesGiven.Count); for (int i = 0; i < propertiesReaded.Count; ++i) { Assert.Equal(propertiesReaded[i].Name, propertiesGiven[i].Name); Assert.Equal(propertiesReaded[i].Value.GetType(), propertiesGiven[i].Value.GetType()); Assert.Equal(propertiesReaded[i].Value, propertiesGiven[i].Value); } }
public void ParsingInstanceAnnotationsInComplexValueShouldReadComplexValue() { var model = new EdmModel(); var complexType = new EdmComplexType("TestNamespace", "Address"); model.AddElement(complexType); var complexTypeRef = new EdmComplexTypeReference(complexType, false); this.messageReaderSettings = new ODataMessageReaderSettings { ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*") }; ODataJsonLightPropertyAndValueDeserializer deserializer = new ODataJsonLightPropertyAndValueDeserializer(this.CreateJsonLightInputContext("{\"@Annotation.1\":true,\"@Annotation.2\":123,\"Annotation.3\":\"annotation\"}", model)); deserializer.JsonReader.Read(); ODataComplexValue complexValue = (ODataComplexValue)deserializer.ReadNonEntityValue( /*payloadTypeName*/ null, complexTypeRef, /*duplicatePropertyNamesChecker*/ null, /*collectionValidator*/ null, /*validateNullValue*/ true, /*isTopLevelPropertyValue*/ false, /*insideComplexValue*/ false, /*propertyName*/ null); complexValue.InstanceAnnotations.Count.Should().Be(3); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(true), complexValue.InstanceAnnotations.Single(ia => ia.Name == "Annotation.1").Value); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(123), complexValue.InstanceAnnotations.Single(ia => ia.Name == "Annotation.2").Value); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue("annotation"), complexValue.InstanceAnnotations.Single(ia => ia.Name == "Annotation.3").Value); }
public void ParsingInstanceAnnotationInComplexValueShouldThrowOnReservedODataAnnotationNamesNotApplicableToComplexValues() { var model = new EdmModel(); var complexType = new EdmComplexType("TestNamespace", "Address"); model.AddElement(complexType); var complexTypeRef = new EdmComplexTypeReference(complexType, false); this.messageReaderSettings = new ODataMessageReaderSettings { ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*") }; ODataJsonLightPropertyAndValueDeserializer deserializer = new ODataJsonLightPropertyAndValueDeserializer(this.CreateJsonLightInputContext("{\"@odata.count\":\"123\"}", model)); deserializer.JsonReader.Read(); Action action = () => deserializer.ReadNonEntityValue( /*payloadTypeName*/ null, complexTypeRef, /*duplicatePropertyNamesChecker*/ null, /*collectionValidator*/ null, /*validateNullValue*/ true, /*isTopLevelPropertyValue*/ false, /*insideComplexValue*/ false, /*propertyName*/ null); action.ShouldThrow<ODataException>().WithMessage(ErrorStrings.ODataJsonLightPropertyAndValueDeserializer_UnexpectedAnnotationProperties("odata.count")); }
public void ParsingInstanceAnnotationInTopLevelPropertyShouldThrowOnReservedODataAnnotationNamesNotApplicableToProperties() { var model = this.CreateEdmModelWithEntity(); var primitiveTypeRef = ((IEdmEntityType)model.SchemaElements.First()).Properties().First().Type; this.messageReaderSettings = new ODataMessageReaderSettings { ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*") }; ODataJsonLightPropertyAndValueDeserializer deserializer = new ODataJsonLightPropertyAndValueDeserializer(this.CreateJsonLightInputContext("{\"@odata.context\":\"http://odata.org/test/$metadata#Customers(1)/Name\",\"@odata.count\":123,\"value\":\"Joe\"}", model)); Action action = () => deserializer.ReadTopLevelProperty(primitiveTypeRef); action.ShouldThrow<ODataException>().WithMessage(ErrorStrings.ODataJsonLightPropertyAndValueDeserializer_UnexpectedAnnotationProperties("odata.count")); }
public ODataJsonLightDeserializerTests() { this.edmModel = new EdmModel(); this.messageReaderSettings = new ODataMessageReaderSettings(); }
internal ODataJsonLightInputContext( ODataFormat format, TextReader reader, ODataMediaType contentType, ODataMessageReaderSettings messageReaderSettings, bool readingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageReaderSettings, readingResponse, synchronous, model, urlResolver) { Debug.Assert(reader != null, "reader != null"); Debug.Assert(contentType != null, "contentType != null"); try { ExceptionUtils.CheckArgumentNotNull(format, "format"); ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings"); } catch (ArgumentNullException) { // Dispose the message stream if we failed to create the input context. reader.Dispose(); throw; } try { this.textReader = reader; if (contentType.HasStreamingSetToTrue()) { this.jsonReader = new BufferingJsonReader( this.textReader, JsonLightConstants.ODataErrorPropertyName, messageReaderSettings.MessageQuotas.MaxNestingDepth, ODataFormat.Json, contentType.HasIeee754CompatibleSetToTrue()); } else { // If we have a non-streaming Json Light content type we need to use the re-ordering Json reader this.jsonReader = new ReorderingJsonReader(this.textReader, messageReaderSettings.MessageQuotas.MaxNestingDepth, contentType.HasIeee754CompatibleSetToTrue()); } } catch (Exception e) { // Dispose the message stream if we failed to create the input context. if (ExceptionUtils.IsCatchableExceptionType(e) && reader != null) { reader.Dispose(); } throw; } // dont know how to get MetadataDocumentUri uri here, messageReaderSettings do not have one // Uri metadataDocumentUri = messageReaderSettings..MetadataDocumentUri == null ? null : messageReaderSettings.MetadataDocumentUri.BaseUri; // the uri here is used here to create the FullMetadataLevel can pass null in this.metadataLevel = JsonLight.JsonLightMetadataLevel.Create(contentType, null, model, readingResponse); }
private static void ReadResponseEntryPayload(EdmModel userModel, string payload, EdmEntitySet entitySet, IEdmEntityType entityType, Action<ODataReader> action) { string contentType = "application/atom+xml;type=entry"; var message = new InMemoryMessage() { Stream = new MemoryStream(Encoding.UTF8.GetBytes(payload)) }; message.SetHeader("Content-Type", contentType); var readerSettings = new ODataMessageReaderSettings { DisableMessageStreamDisposal = false, EnableAtom = true }; using (var msgReader = new ODataMessageReader((IODataResponseMessage)message, readerSettings, userModel)) { var reader = msgReader.CreateODataEntryReader(entitySet, entityType); while (reader.Read()) { action(reader); } } }
private void ReadFeedPayload(string payload, Action<ODataReader> action, bool isResponse = true, ODataVersion maxProtocolVersion = ODataVersion.V4) { if (isResponse) { IODataResponseMessage message = new InMemoryMessage() { Stream = new MemoryStream(Encoding.UTF8.GetBytes(payload)), StatusCode = 200 }; message.SetHeader("Content-Type", "application/atom+xml;type=feed"); ODataMessageReaderSettings settings = new ODataMessageReaderSettings() { MaxProtocolVersion = maxProtocolVersion, EnableAtom = true }; using (var msgReader = new ODataMessageReader(message, settings)) { var reader = msgReader.CreateODataFeedReader(); while (reader.Read()) { action(reader); } } } else { IODataRequestMessage message = new InMemoryMessage() { Stream = new MemoryStream(Encoding.UTF8.GetBytes(payload)), Method = "GET" }; message.SetHeader("Content-Type", "application/atom+xml;type=feed"); ODataMessageReaderSettings settings = new ODataMessageReaderSettings() { MaxProtocolVersion = maxProtocolVersion, EnableAtom = true }; using (var msgReader = new ODataMessageReader(message, settings)) { var reader = msgReader.CreateODataFeedReader(); while (reader.Read()) { action(reader); } } } }
/// <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 override Task<ODataInputContext> CreateInputContextAsync( ODataMessageInfo messageInfo, ODataMessageReaderSettings messageReaderSettings) { ExceptionUtils.CheckArgumentNotNull(messageInfo, "message"); ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings"); return messageInfo.GetMessageStreamAsync() .FollowOnSuccessWith( (streamTask) => (ODataInputContext)new ODataAtomInputContext( this, streamTask.Result, messageInfo.Encoding, messageReaderSettings, messageInfo.IsResponse, /*synchronous*/ false, messageInfo.Model, messageInfo.UrlResolver)); }
/// <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> public override Task<IEnumerable<ODataPayloadKind>> DetectPayloadKindAsync( ODataMessageInfo messageInfo, ODataMessageReaderSettings settings) { ExceptionUtils.CheckArgumentNotNull(messageInfo, "messageInfo"); return messageInfo.GetMessageStreamAsync() .FollowOnSuccessWith( streamTask => this.DetectPayloadKindImplementation( streamTask.Result, /*readingResponse*/ messageInfo.IsResponse, /*synchronous*/ false, new ODataPayloadKindDetectionInfo( messageInfo.MediaType, messageInfo.Encoding, settings, messageInfo.Model))); }
public void ParsingInstanceAnnotationsInTopLevelPropertyShouldReadProperty() { var model = this.CreateEdmModelWithEntity(); var primitiveTypeRef = ((IEdmEntityType)model.SchemaElements.First()).Properties().First().Type; this.messageReaderSettings = new ODataMessageReaderSettings { ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*") }; ODataJsonLightPropertyAndValueDeserializer deserializer = new ODataJsonLightPropertyAndValueDeserializer(this.CreateJsonLightInputContext("{\"@odata.context\":\"http://odata.org/test/$metadata#Customers(1)/Name\",\"@Annotation.1\":true,\"@Annotation.2\":123,\"@Annotation.3\":\"annotation\",\"value\":\"Joe\"}", model)); ODataProperty property = deserializer.ReadTopLevelProperty(primitiveTypeRef); property.InstanceAnnotations.Count.Should().Be(3); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(true), property.InstanceAnnotations.Single(ia => ia.Name == "Annotation.1").Value); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue(123), property.InstanceAnnotations.Single(ia => ia.Name == "Annotation.2").Value); TestUtils.AssertODataValueAreEqual(new ODataPrimitiveValue("annotation"), property.InstanceAnnotations.Single(ia => ia.Name == "Annotation.3").Value); }
private static ODataMessageReader CreateODataMessageReader(string payload, string contentType, bool isResponse, bool shouldReadAndValidateCustomInstanceAnnotations, bool odataSimplified = false) { var stream = new MemoryStream(Encoding.UTF8.GetBytes(payload)); var readerSettings = new ODataMessageReaderSettings { DisableMessageStreamDisposal = false, EnableAtom = true, ODataSimplified = odataSimplified }; ODataMessageReader messageReader; if (isResponse) { IODataResponseMessage responseMessage = new InMemoryMessage { StatusCode = 200, Stream = stream }; responseMessage.SetHeader("Content-Type", contentType); if (shouldReadAndValidateCustomInstanceAnnotations) { responseMessage.PreferenceAppliedHeader().AnnotationFilter = "*"; } messageReader = new ODataMessageReader(responseMessage, readerSettings, Model); } else { IODataRequestMessage requestMessage = new InMemoryMessage { Method = "GET", Stream = stream }; requestMessage.SetHeader("Content-Type", contentType); readerSettings.ShouldIncludeAnnotation = shouldReadAndValidateCustomInstanceAnnotations ? ODataUtils.CreateAnnotationFilter("*") : null; messageReader = new ODataMessageReader(requestMessage, readerSettings, Model); } return messageReader; }
private void ReadEntryPayload(string payload, Action<ODataReader> action) { var message = new InMemoryMessage() { Stream = new MemoryStream(Encoding.UTF8.GetBytes(payload)) }; message.SetHeader("Content-Type", "application/atom+xml;type=entry"); ODataMessageReaderSettings settings = new ODataMessageReaderSettings { EnableAtom = true }; using (var msgReader = new ODataMessageReader((IODataResponseMessage)message, settings)) { var reader = msgReader.CreateODataEntryReader(); while (reader.Read()) { action(reader); } } }
public void ParsingInstanceAnnotationsInDisorderInComplexValueShouldPass() { var model = new EdmModel(); var complexType = new EdmComplexType("TestNamespace", "Address"); complexType.AddStructuralProperty("CountryRegion", EdmPrimitiveTypeKind.String); model.AddElement(complexType); var complexTypeRef = new EdmComplexTypeReference(complexType, false); this.messageReaderSettings = new ODataMessageReaderSettings { ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*") }; ODataJsonLightPropertyAndValueDeserializer deserializer = new ODataJsonLightPropertyAndValueDeserializer(this.CreateJsonLightInputContext("{\"@Annotation.1\":true,\"@Annotation.2\":123,\"CountryRegion\":\"China\",\"@Annotation.3\":\"annotation\"}", model)); deserializer.JsonReader.Read(); Action action = () => deserializer.ReadNonEntityValue( /*payloadTypeName*/ null, complexTypeRef, /*duplicatePropertyNamesChecker*/ null, /*collectionValidator*/ null, /*validateNullValue*/ true, /*isTopLevelPropertyValue*/ false, /*insideComplexValue*/ false, /*propertyName*/ null); action.ShouldNotThrow(); }
private ODataJsonLightServiceDocumentDeserializer CreateODataJsonServiceDocumentDeserializer(MemoryStream stream, IODataUrlResolver urlResolver = null) { ODataMessageReaderSettings settings = new ODataMessageReaderSettings(); ODataJsonLightInputContext inputContext = new ODataJsonLightInputContext(ODataFormat.Json, stream, new ODataMediaType("application", "json"), Encoding.UTF8, settings, true /*readingResponse*/, true /*sync*/, new EdmModel() /*edmModel*/, urlResolver); return new ODataJsonLightServiceDocumentDeserializer(inputContext); }
public void ParsingInstanceAnnotationsInComplexValueShouldSkipBaseOnSettings() { var model = new EdmModel(); var complexType = new EdmComplexType("TestNamespace", "Address"); model.AddElement(complexType); var complexTypeRef = new EdmComplexTypeReference(complexType, false); this.messageReaderSettings = new ODataMessageReaderSettings(); ODataJsonLightPropertyAndValueDeserializer deserializer = new ODataJsonLightPropertyAndValueDeserializer(this.CreateJsonLightInputContext("{\"@Annotation.1\":true,\"@Annotation.2\":123,\"Annotation.3\":\"annotation\"}", model)); deserializer.JsonReader.Read(); ODataComplexValue complexValue = (ODataComplexValue)deserializer.ReadNonEntityValue( /*payloadTypeName*/ null, complexTypeRef, /*duplicatePropertyNamesChecker*/ null, /*collectionValidator*/ null, /*validateNullValue*/ true, /*isTopLevelPropertyValue*/ false, /*insideComplexValue*/ false, /*propertyName*/ null); complexValue.InstanceAnnotations.Count.Should().Be(0); }