Ejemplo n.º 1
0
        /// <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)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(messageReaderSettings != null, "messageReaderSettings != null");

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

            if (!readingResponse && messageReaderSettings.UndeclaredPropertyBehaviorKinds != ODataUndeclaredPropertyBehaviorKinds.None)
            {
                throw new ODataException(Strings.ReaderValidationUtils_UndeclaredPropertyBehaviorKindSpecifiedOnRequest);
            }

            if (!string.IsNullOrEmpty(messageReaderSettings.ReaderBehavior.ODataTypeScheme) && !string.Equals(messageReaderSettings.ReaderBehavior.ODataTypeScheme, Atom.AtomConstants.ODataSchemeNamespace))
            {
                ODataVersionChecker.CheckCustomTypeScheme(messageReaderSettings.MaxProtocolVersion);
            }

            if (!string.IsNullOrEmpty(messageReaderSettings.ReaderBehavior.ODataNamespace) && !string.Equals(messageReaderSettings.ReaderBehavior.ODataNamespace, Atom.AtomConstants.ODataNamespace))
            {
                ODataVersionChecker.CheckCustomDataNamespace(messageReaderSettings.MaxProtocolVersion);
            }
        }
Ejemplo n.º 2
0
 internal static IEdmTypeReference ResolveAndValidateNonPrimitiveTargetType(EdmTypeKind expectedTypeKind, IEdmTypeReference expectedTypeReference, EdmTypeKind payloadTypeKind, IEdmType payloadType, string payloadTypeName, IEdmModel model, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, out SerializationTypeNameAnnotation serializationTypeNameAnnotation)
 {
     bool flag = (messageReaderSettings.ReaderBehavior.TypeResolver != null) && (payloadType != null);
     if (!flag)
     {
         ValidateTypeSupported(expectedTypeReference, version);
         if (model.IsUserModel() && ((expectedTypeReference == null) || !messageReaderSettings.DisableStrictMetadataValidation))
         {
             VerifyPayloadTypeDefined(payloadTypeName, payloadType);
         }
     }
     else
     {
         ValidateTypeSupported((payloadType == null) ? null : payloadType.ToTypeReference(true), version);
     }
     if ((payloadTypeKind != EdmTypeKind.None) && (!messageReaderSettings.DisableStrictMetadataValidation || (expectedTypeReference == null)))
     {
         ValidationUtils.ValidateTypeKind(payloadTypeKind, expectedTypeKind, payloadTypeName);
     }
     serializationTypeNameAnnotation = null;
     if (!model.IsUserModel())
     {
         return null;
     }
     if ((expectedTypeReference == null) || flag)
     {
         return ResolveAndValidateTargetTypeWithNoExpectedType(expectedTypeKind, payloadType, payloadTypeName, out serializationTypeNameAnnotation);
     }
     if (messageReaderSettings.DisableStrictMetadataValidation)
     {
         return ResolveAndValidateTargetTypeStrictValidationDisabled(expectedTypeKind, expectedTypeReference, payloadType, payloadTypeName, out serializationTypeNameAnnotation);
     }
     return ResolveAndValidateTargetTypeStrictValidationEnabled(expectedTypeKind, expectedTypeReference, payloadType, payloadTypeName, out serializationTypeNameAnnotation);
 }
Ejemplo n.º 3
0
 private static EdmTypeKind ComputeTargetTypeKind(IEdmTypeReference expectedTypeReference, bool forEntityValue, string payloadTypeName, EdmTypeKind payloadTypeKind, ODataMessageReaderSettings messageReaderSettings, Func<EdmTypeKind> typeKindFromPayloadFunc)
 {
     EdmTypeKind kind;
     bool flag = (messageReaderSettings.ReaderBehavior.TypeResolver != null) && (payloadTypeKind != EdmTypeKind.None);
     if (((expectedTypeReference != null) && !flag) && (!expectedTypeReference.IsODataPrimitiveTypeKind() || !messageReaderSettings.DisablePrimitiveTypeConversion))
     {
         kind = expectedTypeReference.TypeKind();
     }
     else if (payloadTypeKind != EdmTypeKind.None)
     {
         if (!forEntityValue)
         {
             ValidationUtils.ValidateValueTypeKind(payloadTypeKind, payloadTypeName);
         }
         kind = payloadTypeKind;
     }
     else
     {
         kind = typeKindFromPayloadFunc();
     }
     if (ShouldValidatePayloadTypeKind(messageReaderSettings, expectedTypeReference, payloadTypeKind))
     {
         ValidationUtils.ValidateTypeKind(kind, expectedTypeReference.TypeKind(), payloadTypeName);
     }
     return kind;
 }
        /// <inheritdoc/>
        public override async Task<HttpResponseMessage> ProcessBatchAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            cancellationToken.ThrowIfCancellationRequested();

            ValidateRequest(request);

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

            ODataMessageReader reader = await request.Content.GetODataMessageReaderAsync(oDataReaderSettings);
            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);
        }
Ejemplo n.º 5
0
 internal static XmlReader CreateXmlReader(Stream stream, Encoding encoding, ODataMessageReaderSettings messageReaderSettings)
 {
     XmlReaderSettings settings = CreateXmlReaderSettings(messageReaderSettings);
     if (encoding != null)
     {
         return XmlReader.Create(new StreamReader(stream, encoding), settings);
     }
     return XmlReader.Create(stream, settings);
 }
Ejemplo n.º 6
0
 internal ODataPayloadKindDetectionInfo(MediaType contentType, ODataMessageReaderSettings messageReaderSettings, IEdmModel model, IEnumerable<ODataPayloadKind> possiblePayloadKinds)
 {
     ExceptionUtils.CheckArgumentNotNull<MediaType>(contentType, "contentType");
     ExceptionUtils.CheckArgumentNotNull<ODataMessageReaderSettings>(messageReaderSettings, "readerSettings");
     ExceptionUtils.CheckArgumentNotNull<IEnumerable<ODataPayloadKind>>(possiblePayloadKinds, "possiblePayloadKinds");
     this.contentType = contentType;
     this.messageReaderSettings = messageReaderSettings;
     this.model = model;
     this.possiblePayloadKinds = possiblePayloadKinds;
 }
Ejemplo n.º 7
0
 protected ODataInputContext(ODataFormat format, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, bool readingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver)
 {
     ExceptionUtils.CheckArgumentNotNull<ODataFormat>(format, "format");
     ExceptionUtils.CheckArgumentNotNull<ODataMessageReaderSettings>(messageReaderSettings, "messageReaderSettings");
     this.format = format;
     this.messageReaderSettings = messageReaderSettings;
     this.version = version;
     this.readingResponse = readingResponse;
     this.synchronous = synchronous;
     this.model = model;
     this.urlResolver = urlResolver;
 }
        /// <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>
        /// <returns>A <see cref="ODataMessageReader"/>.</returns>
        public static async Task<ODataMessageReader> GetODataMessageReaderAsync(this HttpContent content, ODataMessageReaderSettings settings)
        {
            if (content == null)
            {
                throw Error.ArgumentNull("content");
            }

            Stream contentStream = await content.ReadAsStreamAsync();
            IODataRequestMessage oDataRequestMessage = new ODataMessageWrapper(contentStream, content.Headers);
            ODataMessageReader oDataMessageReader = new ODataMessageReader(oDataRequestMessage, settings);
            return oDataMessageReader;
        }
 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();
     }
 }
Ejemplo n.º 10
0
 internal static IEdmProperty FindDefinedProperty(string propertyName, IEdmStructuredType owningStructuredType, ODataMessageReaderSettings messageReaderSettings)
 {
     if (owningStructuredType == null)
     {
         return null;
     }
     IEdmProperty property = owningStructuredType.FindProperty(propertyName);
     if (((property == null) && owningStructuredType.IsOpen) && (messageReaderSettings.UndeclaredPropertyBehaviorKinds != ODataUndeclaredPropertyBehaviorKinds.None))
     {
         throw new ODataException(Microsoft.Data.OData.Strings.ReaderValidationUtils_UndeclaredPropertyBehaviorKindSpecifiedForOpenType(propertyName, owningStructuredType.ODataFullName()));
     }
     return property;
 }
Ejemplo n.º 11
0
 public ODataMessageReaderSettings(ODataMessageReaderSettings other)
 {
     ExceptionUtils.CheckArgumentNotNull<ODataMessageReaderSettings>(other, "other");
     this.BaseUri = other.BaseUri;
     this.CheckCharacters = other.CheckCharacters;
     this.DisableMessageStreamDisposal = other.DisableMessageStreamDisposal;
     this.DisablePrimitiveTypeConversion = other.DisablePrimitiveTypeConversion;
     this.EnableAtomMetadataReading = other.EnableAtomMetadataReading;
     this.messageQuotas = new ODataMessageQuotas(other.MessageQuotas);
     this.UndeclaredPropertyBehaviorKinds = other.UndeclaredPropertyBehaviorKinds;
     this.MaxProtocolVersion = other.MaxProtocolVersion;
     this.readerBehavior = other.ReaderBehavior;
 }
Ejemplo n.º 12
0
        /// <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>
        /// Copy constructor.
        /// </summary>
        /// <param name="other">The instance to copy.</param>
        public ODataMessageReaderSettings(ODataMessageReaderSettings other)
        {
            ExceptionUtils.CheckArgumentNotNull(other, "other");

            this.BaseUri = other.BaseUri;
            this.CheckCharacters = other.CheckCharacters;
            this.DisableMessageStreamDisposal = other.DisableMessageStreamDisposal;
            this.DisablePrimitiveTypeConversion = other.DisablePrimitiveTypeConversion;
            this.EnableAtomMetadataReading = other.EnableAtomMetadataReading;
            this.messageQuotas = new ODataMessageQuotas(other.MessageQuotas);
            this.UndeclaredPropertyBehaviorKinds = other.UndeclaredPropertyBehaviorKinds;
            this.MaxProtocolVersion = other.MaxProtocolVersion;
            this.atomFormatEntryXmlCustomizationCallback = other.atomFormatEntryXmlCustomizationCallback;

            // NOTE: reader behavior is immutable; copy by reference is ok.
            this.readerBehavior = other.ReaderBehavior;
        }
Ejemplo n.º 14
0
 private ODataMetadataInputContext(ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, bool readingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageReaderSettings, version, readingResponse, synchronous, model, urlResolver)
 {
     ExceptionUtils.CheckArgumentNotNull<ODataFormat>(format, "format");
     ExceptionUtils.CheckArgumentNotNull<ODataMessageReaderSettings>(messageReaderSettings, "messageReaderSettings");
     try
     {
         this.baseXmlReader = ODataAtomReaderUtils.CreateXmlReader(messageStream, encoding, messageReaderSettings);
         this.xmlReader = new BufferingXmlReader(this.baseXmlReader, null, messageReaderSettings.BaseUri, false, messageReaderSettings.MessageQuotas.MaxNestingDepth, messageReaderSettings.ReaderBehavior.ODataNamespace);
     }
     catch (Exception exception)
     {
         if (ExceptionUtils.IsCatchableExceptionType(exception) && (messageStream != null))
         {
             messageStream.Dispose();
         }
         throw;
     }
 }
Ejemplo n.º 15
0
 internal ODataJsonInputContext(ODataFormat format, TextReader reader, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, bool readingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageReaderSettings, version, readingResponse, synchronous, model, urlResolver)
 {
     ExceptionUtils.CheckArgumentNotNull<ODataFormat>(format, "format");
     ExceptionUtils.CheckArgumentNotNull<ODataMessageReaderSettings>(messageReaderSettings, "messageReaderSettings");
     try
     {
         this.textReader = reader;
         this.jsonReader = new BufferingJsonReader(this.textReader, base.UseServerFormatBehavior, messageReaderSettings.MessageQuotas.MaxNestingDepth);
     }
     catch (Exception exception)
     {
         if (ExceptionUtils.IsCatchableExceptionType(exception) && (reader != null))
         {
             reader.Dispose();
         }
         throw;
     }
 }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="contentType">The parsed content type as <see cref="MediaType"/>.</param>
        /// <param name="encoding">The encoding from the content type or the default encoding from <see cref="MediaType" />.</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>
        /// <param name="possiblePayloadKinds">The possible payload kinds based on content type negotiation.</param>
        internal ODataPayloadKindDetectionInfo(
            MediaType contentType,
            Encoding encoding,
            ODataMessageReaderSettings messageReaderSettings, 
            IEdmModel model, 
            IEnumerable<ODataPayloadKind> possiblePayloadKinds)
        {
            DebugUtils.CheckNoExternalCallers();
            ExceptionUtils.CheckArgumentNotNull(contentType, "contentType");
            ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "readerSettings");
            ExceptionUtils.CheckArgumentNotNull(possiblePayloadKinds, "possiblePayloadKinds");

            this.contentType = contentType;
            this.encoding = encoding;
            this.messageReaderSettings = messageReaderSettings;
            this.model = model;
            this.possiblePayloadKinds = possiblePayloadKinds;
        }
Ejemplo n.º 17
0
 private ODataRawInputContext(ODataFormat format, System.IO.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)
 {
     ExceptionUtils.CheckArgumentNotNull<ODataFormat>(format, "format");
     ExceptionUtils.CheckArgumentNotNull<ODataMessageReaderSettings>(messageReaderSettings, "messageReaderSettings");
     try
     {
         this.stream = messageStream;
         this.encoding = encoding;
         this.readerPayloadKind = readerPayloadKind;
     }
     catch (Exception exception)
     {
         if (ExceptionUtils.IsCatchableExceptionType(exception) && (messageStream != null))
         {
             messageStream.Dispose();
         }
         throw;
     }
 }
Ejemplo n.º 18
0
        /// <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="encoding">The encoding to use to read the input.</param>
        /// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
        /// <param name="version">The OData protocol version to be used for reading the payload.</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 ODataAtomInputContext(
            ODataFormat format,
            Stream messageStream,
            Encoding encoding,
            ODataMessageReaderSettings messageReaderSettings,
            ODataVersion version,
            bool readingResponse,
            bool synchronous,
            IEdmModel model,
            IODataUrlResolver urlResolver)
            : base(format, messageReaderSettings, version, readingResponse, synchronous, model, urlResolver)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(messageStream != null, "stream != null");

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

            try
            {
                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*/ this.UseServerFormatBehavior && this.Version < ODataVersion.V3,
                    messageReaderSettings.MessageQuotas.MaxNestingDepth,
                    messageReaderSettings.ReaderBehavior.ODataNamespace);
            }
            catch (Exception e)
            {
                // Dispose the message stream if we failed to create the input context.
                if (ExceptionUtils.IsCatchableExceptionType(e) && messageStream != null)
                {
                    messageStream.Dispose();
                }

                throw;
            }
        }
        /// <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="encoding">The encoding to use to read the input.</param>
        /// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
        /// <param name="version">The OData protocol version to be used for reading the payload.</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>
        private ODataMetadataInputContext(
            ODataFormat format,
            Stream messageStream,
            Encoding encoding,
            ODataMessageReaderSettings messageReaderSettings,
            ODataVersion version,
            bool readingResponse,
            bool synchronous,
            IEdmModel model,
            IODataUrlResolver urlResolver)
            : base(format, messageReaderSettings, version, readingResponse, synchronous, model, urlResolver)
        {
            Debug.Assert(messageStream != null, "stream != null");

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

            try
            {
                this.baseXmlReader = ODataAtomReaderUtils.CreateXmlReader(messageStream, encoding, messageReaderSettings);

                // We use the buffering reader here only for in-stream error detection (not for buffering).
                this.xmlReader = new BufferingXmlReader(
                    this.baseXmlReader,
                    /*parentXmlReader*/ null,
                    messageReaderSettings.BaseUri,
                    /*disableXmlBase*/ false,
                    messageReaderSettings.MessageQuotas.MaxNestingDepth,
                    messageReaderSettings.ReaderBehavior.ODataNamespace);
            }
            catch (Exception e)
            {
                // Dispose the message stream if we failed to create the input context.
                if (ExceptionUtils.IsCatchableExceptionType(e) && messageStream != null)
                {
                    messageStream.Dispose();
                }

                throw;
            }
        }
Ejemplo n.º 20
0
        /// <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)
        {
            DebugUtils.CheckNoExternalCallers();
            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);
        }
Ejemplo n.º 21
0
        /// <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="encoding">The encoding to use to read the input.</param>
        /// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
        /// <param name="version">The OData protocol version to be used for reading the payload.</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>
        /// <param name="readerPayloadKind">The <see cref="ODataPayloadKind"/> to read.</param>
        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)
        {
            DebugUtils.CheckNoExternalCallers();
            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;
            }
        }
Ejemplo n.º 22
0
        /// <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="encoding">The encoding to use to read the input.</param>
        /// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
        /// <param name="version">The OData protocol version to be used for reading the payload.</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>
        /// <param name="readerPayloadKind">The <see cref="ODataPayloadKind"/> to read.</param>
        private 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;
            }
        }
Ejemplo n.º 23
0
 internal static void CheckVersionSupported(ODataVersion version, ODataMessageReaderSettings messageReaderSettings)
 {
     if (version > messageReaderSettings.MaxProtocolVersion)
     {
         throw new ODataException(Microsoft.Data.OData.Strings.ODataVersionChecker_MaxProtocolVersionExceeded(ODataUtils.ODataVersionToString(version), ODataUtils.ODataVersionToString(messageReaderSettings.MaxProtocolVersion)));
     }
 }
        /// <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 = DefaultODataVersion;
        }
        private object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            object result;

            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;

            // If content length is 0 then return default value for this type
            if (contentHeaders == null || contentHeaders.ContentLength == 0)
            {
                result = GetDefaultValueForType(type);
            }
            else
            {
                IEdmModel model = Request.GetEdmModel();
                if (model == null)
                {
                    throw Error.InvalidOperation(SRResources.RequestMustHaveModel);
                }

                IEdmTypeReference expectedPayloadType;
                ODataDeserializer deserializer = GetDeserializer(type, Request.GetODataPath(), model, _deserializerProvider, out expectedPayloadType);
                if (deserializer == null)
                {
                    throw Error.Argument("type", SRResources.FormatterReadIsNotSupportedForType, type.FullName, GetType().FullName);
                }

                try
                {
                    ODataMessageReaderSettings oDataReaderSettings = new ODataMessageReaderSettings(MessageReaderSettings);
                    oDataReaderSettings.BaseUri = GetBaseAddress(Request);

                    IODataRequestMessage oDataRequestMessage = new ODataMessageWrapper(readStream, contentHeaders, Request.GetODataContentIdMapping());
                    ODataMessageReader oDataMessageReader = new ODataMessageReader(oDataRequestMessage, oDataReaderSettings, model);

                    Request.RegisterForDispose(oDataMessageReader);
                    ODataPath path = Request.GetODataPath();
                    ODataDeserializerContext readContext = new ODataDeserializerContext
                    {
                        Path = path,
                        Model = model,
                        Request = Request,
                        ResourceType = type,
                        ResourceEdmType = expectedPayloadType,
                        RequestContext = Request.GetRequestContext(),
                    };

                    result = deserializer.Read(oDataMessageReader, type, readContext);
                }
                catch (Exception e)
                {
                    if (formatterLogger == null)
                    {
                        throw;
                    }

                    formatterLogger.LogError(String.Empty, e);
                    result = GetDefaultValueForType(type);
                }
            }

            return result;
        }
Ejemplo n.º 26
0
 internal static void ValidateNullValue(IEdmModel model, IEdmTypeReference expectedTypeReference, ODataMessageReaderSettings messageReaderSettings, bool validateNullValue, ODataVersion version)
 {
     if (expectedTypeReference != null)
     {
         ValidateTypeSupported(expectedTypeReference, version);
         if (!messageReaderSettings.DisablePrimitiveTypeConversion || (expectedTypeReference.TypeKind() != EdmTypeKind.Primitive))
         {
             ValidateNullValueAllowed(expectedTypeReference, validateNullValue, model);
         }
     }
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Create RAW input context.
        /// </summary>
        /// <param name="format">The format for the input context.</param>
        /// <param name="message">The message to use.</param>
        /// <param name="encoding">The encoding to use.</param>
        /// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
        /// <param name="version">The OData protocol version to be used for reading the payload.</param>
        /// <param name="readingResponse">true if reading a response message; otherwise false.</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>
        /// <param name="readerPayloadKind">The <see cref="ODataPayloadKind"/> to read.</param>
        /// <returns>The newly created input context.</returns>
        internal static ODataInputContext Create(
            ODataFormat format,
            ODataMessage message,
            Encoding encoding,
            ODataMessageReaderSettings messageReaderSettings,
            ODataVersion version,
            bool readingResponse,
            IEdmModel model,
            IODataUrlResolver urlResolver,
            ODataPayloadKind readerPayloadKind)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(format == ODataFormat.RawValue || format == ODataFormat.Batch, "This method only supports the RAW value or batch format.");
            Debug.Assert(message != null, "message != null");
            Debug.Assert(messageReaderSettings != null, "messageReaderSettings != null");
            Debug.Assert(readerPayloadKind != ODataPayloadKind.Unsupported, "readerPayloadKind != ODataPayloadKind.Unsupported");

            Stream messageStream = message.GetStream();
            return new ODataRawInputContext(
                format,
                messageStream,
                encoding,
                messageReaderSettings,
                version,
                readingResponse,
                true,
                model,
                urlResolver,
                readerPayloadKind);
        }
Ejemplo n.º 28
0
 private ODataMetadataInputContext(ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, bool readingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageReaderSettings, version, readingResponse, synchronous, model, urlResolver)
 {
     ExceptionUtils.CheckArgumentNotNull <ODataFormat>(format, "format");
     ExceptionUtils.CheckArgumentNotNull <ODataMessageReaderSettings>(messageReaderSettings, "messageReaderSettings");
     try
     {
         this.baseXmlReader = ODataAtomReaderUtils.CreateXmlReader(messageStream, encoding, messageReaderSettings);
         this.xmlReader     = new BufferingXmlReader(this.baseXmlReader, null, messageReaderSettings.BaseUri, false, messageReaderSettings.MessageQuotas.MaxNestingDepth, messageReaderSettings.ReaderBehavior.ODataNamespace);
     }
     catch (Exception exception)
     {
         if (ExceptionUtils.IsCatchableExceptionType(exception) && (messageStream != null))
         {
             messageStream.Dispose();
         }
         throw;
     }
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Creates an instance of the input context for the specified format.
        /// </summary>
        /// <param name="format">The format to create the context for.</param>
        /// <param name="readerPayloadKind">The <see cref="ODataPayloadKind"/> to read.</param>
        /// <param name="message">The message to use.</param>
        /// <param name="encoding">The encoding to use.</param>
        /// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
        /// <param name="version">The OData protocol version to be used for reading the payload.</param>
        /// <param name="readingResponse">true if reading a response message; otherwise false.</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>
        /// <returns>The newly created input context.</returns>
        internal static ODataInputContext CreateInputContext(
            ODataFormat format,
            ODataPayloadKind readerPayloadKind,
            ODataMessage message,
            Encoding encoding,
            ODataMessageReaderSettings messageReaderSettings,
            ODataVersion version,
            bool readingResponse,
            IEdmModel model,
            IODataUrlResolver urlResolver)
        {
            DebugUtils.CheckNoExternalCallers();

            if (format == ODataFormat.Atom)
            {
                return(ODataAtomInputContext.Create(
                           format,
                           message,
                           encoding,
                           messageReaderSettings,
                           version,
                           readingResponse,
                           model,
                           urlResolver));
            }

            if (format == ODataFormat.VerboseJson)
            {
                return(ODataJsonInputContext.Create(
                           format,
                           message,
                           encoding,
                           messageReaderSettings,
                           version,
                           readingResponse,
                           model,
                           urlResolver));
            }

            if (format == ODataFormat.Metadata)
            {
                return(ODataMetadataInputContext.Create(
                           format,
                           message,
                           encoding,
                           messageReaderSettings,
                           version,
                           readingResponse,
                           model,
                           urlResolver));
            }

            if (format == ODataFormat.Batch || format == ODataFormat.RawValue)
            {
                return(ODataRawInputContext.Create(
                           format,
                           message,
                           encoding,
                           messageReaderSettings,
                           version,
                           readingResponse,
                           model,
                           urlResolver,
                           readerPayloadKind));
            }

            throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataInputContext_CreateInputContext_UnrecognizedFormat));
        }
Ejemplo n.º 30
0
 private ODataRawInputContext(ODataFormat format, System.IO.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)
 {
     ExceptionUtils.CheckArgumentNotNull <ODataFormat>(format, "format");
     ExceptionUtils.CheckArgumentNotNull <ODataMessageReaderSettings>(messageReaderSettings, "messageReaderSettings");
     try
     {
         this.stream            = messageStream;
         this.encoding          = encoding;
         this.readerPayloadKind = readerPayloadKind;
     }
     catch (Exception exception)
     {
         if (ExceptionUtils.IsCatchableExceptionType(exception) && (messageStream != null))
         {
             messageStream.Dispose();
         }
         throw;
     }
 }
Ejemplo n.º 31
0
 internal static Task <ODataInputContext> CreateAsync(ODataFormat format, ODataMessage message, Encoding encoding, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, bool readingResponse, IEdmModel model, IODataUrlResolver urlResolver, ODataPayloadKind readerPayloadKind)
 {
     return(message.GetStreamAsync().FollowOnSuccessWith <System.IO.Stream, ODataInputContext>(streamTask => new ODataRawInputContext(format, streamTask.Result, encoding, messageReaderSettings, version, readingResponse, false, model, urlResolver, readerPayloadKind)));
 }
Ejemplo n.º 32
0
        private static EdmTypeKind ComputeTargetTypeKind(IEdmTypeReference expectedTypeReference, bool forEntityValue, string payloadTypeName, EdmTypeKind payloadTypeKind, ODataMessageReaderSettings messageReaderSettings, Func <EdmTypeKind> typeKindFromPayloadFunc)
        {
            EdmTypeKind kind;
            bool        flag = (messageReaderSettings.ReaderBehavior.TypeResolver != null) && (payloadTypeKind != EdmTypeKind.None);

            if (((expectedTypeReference != null) && !flag) && (!expectedTypeReference.IsODataPrimitiveTypeKind() || !messageReaderSettings.DisablePrimitiveTypeConversion))
            {
                kind = expectedTypeReference.TypeKind();
            }
            else if (payloadTypeKind != EdmTypeKind.None)
            {
                if (!forEntityValue)
                {
                    ValidationUtils.ValidateValueTypeKind(payloadTypeKind, payloadTypeName);
                }
                kind = payloadTypeKind;
            }
            else
            {
                kind = typeKindFromPayloadFunc();
            }
            if (ShouldValidatePayloadTypeKind(messageReaderSettings, expectedTypeReference, payloadTypeKind))
            {
                ValidationUtils.ValidateTypeKind(kind, expectedTypeReference.TypeKind(), payloadTypeName);
            }
            return(kind);
        }
Ejemplo n.º 33
0
 internal static ODataInputContext Create(ODataFormat format, ODataMessage message, Encoding encoding, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, bool readingResponse, IEdmModel model, IODataUrlResolver urlResolver, ODataPayloadKind readerPayloadKind)
 {
     return new ODataRawInputContext(format, message.GetStream(), encoding, messageReaderSettings, version, readingResponse, true, model, urlResolver, readerPayloadKind);
 }
Ejemplo n.º 34
0
        internal static IEdmProperty ValidateValuePropertyDefined(string propertyName, IEdmStructuredType owningStructuredType, ODataMessageReaderSettings messageReaderSettings, out bool ignoreProperty)
        {
            ignoreProperty = false;
            if (owningStructuredType == null)
            {
                return(null);
            }
            IEdmProperty property = FindDefinedProperty(propertyName, owningStructuredType, messageReaderSettings);

            if ((property == null) && !owningStructuredType.IsOpen)
            {
                if (!messageReaderSettings.UndeclaredPropertyBehaviorKinds.HasFlag(ODataUndeclaredPropertyBehaviorKinds.IgnoreUndeclaredValueProperty))
                {
                    throw new ODataException(Microsoft.Data.OData.Strings.ValidationUtils_PropertyDoesNotExistOnType(propertyName, owningStructuredType.ODataFullName()));
                }
                ignoreProperty = true;
            }
            return(property);
        }
Ejemplo n.º 35
0
 public ODataMessageReader(IODataRequestMessage requestMessage, ODataMessageReaderSettings settings) : this(requestMessage, settings, null)
 {
 }
        public virtual async Task<IList<ODataBatchRequestItem>> ParseBatchRequestsAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

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

            ODataMessageReader reader = await request.Content.GetODataMessageReaderAsync(oDataReaderSettings, 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(new ChangeSetRequestItem(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;
        }
Ejemplo n.º 37
0
 internal static Task <ODataInputContext> CreateInputContextAsync(ODataFormat format, ODataPayloadKind readerPayloadKind, ODataMessage message, Encoding encoding, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, bool readingResponse, IEdmModel model, IODataUrlResolver urlResolver)
 {
     if (format == ODataFormat.Atom)
     {
         return(ODataAtomInputContext.CreateAsync(format, message, encoding, messageReaderSettings, version, readingResponse, model, urlResolver));
     }
     if (format == ODataFormat.VerboseJson)
     {
         return(ODataJsonInputContext.CreateAsync(format, message, encoding, messageReaderSettings, version, readingResponse, model, urlResolver));
     }
     if ((format != ODataFormat.Batch) && (format != ODataFormat.RawValue))
     {
         throw new ODataException(Microsoft.Data.OData.Strings.General_InternalError(InternalErrorCodes.ODataInputContext_CreateInputContext_UnrecognizedFormat));
     }
     return(ODataRawInputContext.CreateAsync(format, message, encoding, messageReaderSettings, version, readingResponse, model, urlResolver, readerPayloadKind));
 }
Ejemplo n.º 38
0
 internal static ODataInputContext Create(ODataFormat format, ODataMessage message, Encoding encoding, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, bool readingResponse, IEdmModel model, IODataUrlResolver urlResolver)
 {
     return(new ODataMetadataInputContext(format, message.GetStream(), encoding, messageReaderSettings, version, readingResponse, true, model, urlResolver));
 }
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }

            if (readStream == null)
            {
                throw Error.ArgumentNull("readStream");
            }

            if (_request == null)
            {
                throw Error.InvalidOperation(SRResources.ReadFromStreamAsyncMustHaveRequest);
            }

            return TaskHelpers.RunSynchronously<object>(() =>
            {
                object result;

                HttpContentHeaders contentHeaders = content == null ? null : content.Headers;

                // If content length is 0 then return default value for this type
                if (contentHeaders == null || contentHeaders.ContentLength == 0)
                {
                    result = GetDefaultValueForType(type);
                }
                else
                {
                    IEdmModel model = _request.GetEdmModel();
                    if (model == null)
                    {
                        throw Error.InvalidOperation(SRResources.RequestMustHaveModel);
                    }

                    Type originalType = type;
                    bool isPatchMode = TryGetInnerTypeForDelta(ref type);
                    ODataDeserializer deserializer = _deserializerProvider.GetODataDeserializer(model, type);
                    if (deserializer == null)
                    {
                        throw Error.Argument("type", SRResources.FormatterReadIsNotSupportedForType, type.FullName, GetType().FullName);
                    }

                    ODataMessageReader oDataMessageReader = null;
                    ODataMessageReaderSettings oDataReaderSettings = new ODataMessageReaderSettings
                    {
                        DisableMessageStreamDisposal = true,
                        MessageQuotas = MessageReaderQuotas,
                        BaseUri = GetBaseAddress(_request)
                    };

                    try
                    {
                        IODataRequestMessage oDataRequestMessage = new ODataMessageWrapper(readStream, contentHeaders);
                        oDataMessageReader = new ODataMessageReader(oDataRequestMessage, oDataReaderSettings, model);

                        _request.RegisterForDispose(oDataMessageReader);
                        ODataPath path = _request.GetODataPath();
                        ODataDeserializerContext readContext = new ODataDeserializerContext
                        {
                            IsPatchMode = isPatchMode,
                            Path = path,
                            Model = model,
                            Request = _request
                        };

                        if (isPatchMode)
                        {
                            readContext.PatchEntityType = originalType;
                        }

                        result = deserializer.Read(oDataMessageReader, readContext);
                    }
                    catch (Exception e)
                    {
                        if (formatterLogger == null)
                        {
                            throw;
                        }

                        formatterLogger.LogError(String.Empty, e);
                        result = GetDefaultValueForType(type);
                    }
                }

                return result;
            });
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Asynchronously create RAW input context.
        /// </summary>
        /// <param name="format">The format for the input context.</param>
        /// <param name="message">The message to use.</param>
        /// <param name="encoding">The encoding to use.</param>
        /// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
        /// <param name="version">The OData protocol version to be used for reading the payload.</param>
        /// <param name="readingResponse">true if reading a response message; otherwise false.</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>
        /// <param name="readerPayloadKind">The <see cref="ODataPayloadKind"/> to read.</param>
        /// <returns>Task which when completed returns the newly create input context.</returns>
        internal static Task<ODataInputContext> CreateAsync(
            ODataFormat format,
            ODataMessage message,
            Encoding encoding,
            ODataMessageReaderSettings messageReaderSettings,
            ODataVersion version,
            bool readingResponse,
            IEdmModel model,
            IODataUrlResolver urlResolver,
            ODataPayloadKind readerPayloadKind)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(format == ODataFormat.RawValue || format == ODataFormat.Batch, "This method only supports the RAW value or batch format.");
            Debug.Assert(message != null, "message != null");
            Debug.Assert(messageReaderSettings != null, "messageReaderSettings != null");
            Debug.Assert(readerPayloadKind != ODataPayloadKind.Unsupported, "readerPayloadKind != ODataPayloadKind.Unsupported");

            // TODO: Note that this will buffer the entire input. We need this for batch and for raw values since they
            // both use TextReader - verify that this is really what we want to do.
            return message.GetStreamAsync()
                .FollowOnSuccessWith(
                    (streamTask) => (ODataInputContext)new ODataRawInputContext(
                        format,
                        streamTask.Result,
                        encoding,
                        messageReaderSettings,
                        version,
                        readingResponse,
                        false,
                        model,
                        urlResolver,
                        readerPayloadKind));
        }
Ejemplo n.º 41
0
        internal static IEdmTypeReference ResolvePayloadTypeNameAndComputeTargetType(EdmTypeKind expectedTypeKind, IEdmType defaultPrimitivePayloadType, IEdmTypeReference expectedTypeReference, string payloadTypeName, IEdmModel model, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, Func <EdmTypeKind> typeKindFromPayloadFunc, out EdmTypeKind targetTypeKind, out SerializationTypeNameAnnotation serializationTypeNameAnnotation)
        {
            EdmTypeKind       kind;
            IEdmTypeReference reference;

            serializationTypeNameAnnotation = null;
            IEdmType payloadType = ResolvePayloadTypeName(model, expectedTypeReference, payloadTypeName, EdmTypeKind.Complex, messageReaderSettings.ReaderBehavior, version, out kind);

            targetTypeKind = ComputeTargetTypeKind(expectedTypeReference, expectedTypeKind == EdmTypeKind.Entity, payloadTypeName, kind, messageReaderSettings, typeKindFromPayloadFunc);
            if (targetTypeKind == EdmTypeKind.Primitive)
            {
                reference = ResolveAndValidatePrimitiveTargetType(expectedTypeReference, kind, payloadType, payloadTypeName, defaultPrimitivePayloadType, model, messageReaderSettings, version);
            }
            else
            {
                reference = ResolveAndValidateNonPrimitiveTargetType(targetTypeKind, expectedTypeReference, kind, payloadType, payloadTypeName, model, messageReaderSettings, version, out serializationTypeNameAnnotation);
            }
            if ((expectedTypeKind != EdmTypeKind.None) && (reference != null))
            {
                ValidationUtils.ValidateTypeKind(targetTypeKind, expectedTypeKind, payloadTypeName);
            }
            return(reference);
        }
Ejemplo n.º 42
0
 public ODataMessageReader(IODataResponseMessage responseMessage, ODataMessageReaderSettings settings) : this(responseMessage, settings, null)
 {
 }
Ejemplo n.º 43
0
        internal static IEdmNavigationProperty ValidateNavigationPropertyDefined(string propertyName, IEdmEntityType owningEntityType, ODataMessageReaderSettings messageReaderSettings)
        {
            if (owningEntityType == null)
            {
                return(null);
            }
            IEdmProperty property = ValidateLinkPropertyDefined(propertyName, owningEntityType, messageReaderSettings);

            if (property == null)
            {
                if (owningEntityType.IsOpen)
                {
                    throw new ODataException(Microsoft.Data.OData.Strings.ValidationUtils_OpenNavigationProperty(propertyName, owningEntityType.ODataFullName()));
                }
            }
            else if (property.PropertyKind != EdmPropertyKind.Navigation)
            {
                throw new ODataException(Microsoft.Data.OData.Strings.ValidationUtils_NavigationPropertyExpected(propertyName, owningEntityType.ODataFullName(), property.PropertyKind.ToString()));
            }
            return((IEdmNavigationProperty)property);
        }
Ejemplo n.º 44
0
        internal static IEdmProperty FindDefinedProperty(string propertyName, IEdmStructuredType owningStructuredType, ODataMessageReaderSettings messageReaderSettings)
        {
            if (owningStructuredType == null)
            {
                return(null);
            }
            IEdmProperty property = owningStructuredType.FindProperty(propertyName);

            if (((property == null) && owningStructuredType.IsOpen) && (messageReaderSettings.UndeclaredPropertyBehaviorKinds != ODataUndeclaredPropertyBehaviorKinds.None))
            {
                throw new ODataException(Microsoft.Data.OData.Strings.ReaderValidationUtils_UndeclaredPropertyBehaviorKindSpecifiedForOpenType(propertyName, owningStructuredType.ODataFullName()));
            }
            return(property);
        }
Ejemplo n.º 45
0
        internal static IEdmTypeReference ResolveAndValidatePrimitiveTargetType(IEdmTypeReference expectedTypeReference, EdmTypeKind payloadTypeKind, IEdmType payloadType, string payloadTypeName, IEdmType defaultPayloadType, IEdmModel model, ODataMessageReaderSettings messageReaderSettings, ODataVersion version)
        {
            bool flag = (messageReaderSettings.ReaderBehavior.TypeResolver != null) && (payloadType != null);

            if ((expectedTypeReference != null) && !flag)
            {
                ValidateTypeSupported(expectedTypeReference, version);
            }
            if ((payloadTypeKind != EdmTypeKind.None) && (messageReaderSettings.DisablePrimitiveTypeConversion || !messageReaderSettings.DisableStrictMetadataValidation))
            {
                ValidationUtils.ValidateTypeKind(payloadTypeKind, EdmTypeKind.Primitive, payloadTypeName);
            }
            if (!model.IsUserModel())
            {
                return(GetNullablePayloadTypeReference(payloadType ?? defaultPayloadType));
            }
            if (((expectedTypeReference == null) || flag) || messageReaderSettings.DisablePrimitiveTypeConversion)
            {
                return(GetNullablePayloadTypeReference(payloadType ?? defaultPayloadType));
            }
            if (!messageReaderSettings.DisableStrictMetadataValidation && ((payloadType != null) && !MetadataUtilsCommon.CanConvertPrimitiveTypeTo((IEdmPrimitiveType)payloadType, (IEdmPrimitiveType)expectedTypeReference.Definition)))
            {
                throw new ODataException(Microsoft.Data.OData.Strings.ValidationUtils_IncompatibleType(payloadTypeName, expectedTypeReference.ODataFullName()));
            }
            return(expectedTypeReference);
        }
Ejemplo n.º 46
0
 internal static Task<ODataInputContext> CreateAsync(ODataFormat format, ODataMessage message, Encoding encoding, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, bool readingResponse, IEdmModel model, IODataUrlResolver urlResolver, ODataPayloadKind readerPayloadKind)
 {
     return message.GetStreamAsync().FollowOnSuccessWith<System.IO.Stream, ODataInputContext>(streamTask => new ODataRawInputContext(format, streamTask.Result, encoding, messageReaderSettings, version, readingResponse, false, model, urlResolver, readerPayloadKind));
 }
Ejemplo n.º 47
0
        internal static IEdmTypeReference ResolveAndValidateNonPrimitiveTargetType(EdmTypeKind expectedTypeKind, IEdmTypeReference expectedTypeReference, EdmTypeKind payloadTypeKind, IEdmType payloadType, string payloadTypeName, IEdmModel model, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, out SerializationTypeNameAnnotation serializationTypeNameAnnotation)
        {
            bool flag = (messageReaderSettings.ReaderBehavior.TypeResolver != null) && (payloadType != null);

            if (!flag)
            {
                ValidateTypeSupported(expectedTypeReference, version);
                if (model.IsUserModel() && ((expectedTypeReference == null) || !messageReaderSettings.DisableStrictMetadataValidation))
                {
                    VerifyPayloadTypeDefined(payloadTypeName, payloadType);
                }
            }
            else
            {
                ValidateTypeSupported((payloadType == null) ? null : payloadType.ToTypeReference(true), version);
            }
            if ((payloadTypeKind != EdmTypeKind.None) && (!messageReaderSettings.DisableStrictMetadataValidation || (expectedTypeReference == null)))
            {
                ValidationUtils.ValidateTypeKind(payloadTypeKind, expectedTypeKind, payloadTypeName);
            }
            serializationTypeNameAnnotation = null;
            if (!model.IsUserModel())
            {
                return(null);
            }
            if ((expectedTypeReference == null) || flag)
            {
                return(ResolveAndValidateTargetTypeWithNoExpectedType(expectedTypeKind, payloadType, payloadTypeName, out serializationTypeNameAnnotation));
            }
            if (messageReaderSettings.DisableStrictMetadataValidation)
            {
                return(ResolveAndValidateTargetTypeStrictValidationDisabled(expectedTypeKind, expectedTypeReference, payloadType, payloadTypeName, out serializationTypeNameAnnotation));
            }
            return(ResolveAndValidateTargetTypeStrictValidationEnabled(expectedTypeKind, expectedTypeReference, payloadType, payloadTypeName, out serializationTypeNameAnnotation));
        }