/// <summary>
        /// Reads the headers of a part.
        /// </summary>
        /// <returns>true if the start of a changeset part was detected; otherwise false.</returns>
        internal bool ProcessPartHeader()
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(this.batchEncoding != null, "Batch encoding should have been established on first call to SkipToBoundary.");

            bool isChangeSetPart;
            ODataBatchOperationHeaders headers = this.ReadPartHeaders(out isChangeSetPart);

            if (isChangeSetPart)
            {
                // determine the changeset boundary and the changeset encoding from the content type header
                this.DetermineChangesetBoundaryAndEncoding(headers[ODataConstants.ContentTypeHeader]);

                if (this.changesetEncoding == null)
                {
                    // NOTE: No changeset encoding was specified in the changeset's content type header.
                    //       Determine the changeset encoding from the first bytes in the changeset.
                    // NOTE: We do not have to skip over the potential preamble of the encoding
                    //       because the batch reader will skip over everything (incl. the preamble)
                    //       until it finds the first changeset (or batch) boundary
                    this.changesetEncoding = this.DetectEncoding();
                }

                // Verify that we only allow single byte encodings and UTF-8 for now.
                ReaderValidationUtils.ValidateEncodingSupportedInBatch(this.changesetEncoding);
            }

            return(isChangeSetPart);
        }
 private void EnsureBatchEncoding()
 {
     if (this.batchEncoding == null)
     {
         this.batchEncoding = this.DetectEncoding();
     }
     ReaderValidationUtils.ValidateEncodingSupportedInBatch(this.batchEncoding);
 }
Example #3
0
        /// <summary>
        /// Reads the next <see cref="ODataItem"/> from the message payload.
        /// </summary>
        /// <returns>true if more items were read; otherwise false.</returns>
        private bool ReadImplementation()
        {
            bool result;

            switch (this.State)
            {
            case ODataReaderState.Start:
                result = this.ReadAtStartImplementation();
                break;

            case ODataReaderState.FeedStart:
                result = this.ReadAtFeedStartImplementation();
                break;

            case ODataReaderState.FeedEnd:
                result = this.ReadAtFeedEndImplementation();
                break;

            case ODataReaderState.EntryStart:
                this.IncreaseEntryDepth();
                result = this.ReadAtEntryStartImplementation();
                break;

            case ODataReaderState.EntryEnd:
                this.DecreaseEntryDepth();
                result = this.ReadAtEntryEndImplementation();
                break;

            case ODataReaderState.NavigationLinkStart:
                result = this.ReadAtNavigationLinkStartImplementation();
                break;

            case ODataReaderState.NavigationLinkEnd:
                result = this.ReadAtNavigationLinkEndImplementation();
                break;

            case ODataReaderState.EntityReferenceLink:
                result = this.ReadAtEntityReferenceLink();
                break;

            case ODataReaderState.Exception:        // fall through
            case ODataReaderState.Completed:
                throw new ODataException(Strings.ODataReaderCore_NoReadCallsAllowed(this.State));

            default:
                Debug.Assert(false, "Unsupported reader state " + this.State + " detected.");
                throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataReaderCore_ReadImplementation));
            }

            if ((this.State == ODataReaderState.EntryStart || this.State == ODataReaderState.EntryEnd) && this.Item != null)
            {
                ReaderValidationUtils.ValidateEntry(this.CurrentEntry);
            }

            return(result);
        }
Example #4
0
        private bool ReadImplementation()
        {
            bool flag;

            switch (this.State)
            {
            case ODataReaderState.Start:
                flag = this.ReadAtStartImplementation();
                break;

            case ODataReaderState.FeedStart:
                flag = this.ReadAtFeedStartImplementation();
                break;

            case ODataReaderState.FeedEnd:
                flag = this.ReadAtFeedEndImplementation();
                break;

            case ODataReaderState.EntryStart:
                this.IncreaseEntryDepth();
                flag = this.ReadAtEntryStartImplementation();
                break;

            case ODataReaderState.EntryEnd:
                this.DecreaseEntryDepth();
                flag = this.ReadAtEntryEndImplementation();
                break;

            case ODataReaderState.NavigationLinkStart:
                flag = this.ReadAtNavigationLinkStartImplementation();
                break;

            case ODataReaderState.NavigationLinkEnd:
                flag = this.ReadAtNavigationLinkEndImplementation();
                break;

            case ODataReaderState.EntityReferenceLink:
                flag = this.ReadAtEntityReferenceLink();
                break;

            case ODataReaderState.Exception:
            case ODataReaderState.Completed:
                throw new ODataException(Microsoft.Data.OData.Strings.ODataReaderCore_NoReadCallsAllowed(this.State));

            default:
                throw new ODataException(Microsoft.Data.OData.Strings.General_InternalError(InternalErrorCodes.ODataReaderCore_ReadImplementation));
            }
            if (((this.State == ODataReaderState.EntryStart) || (this.State == ODataReaderState.EntryEnd)) && (this.Item != null))
            {
                ReaderValidationUtils.ValidateEntry(this.CurrentEntry);
            }
            return(flag);
        }
        /// <summary>
        /// Ensure that a batch encoding exists; if not, detect it from the first couple of bytes of the stream.
        /// </summary>
        private void EnsureBatchEncoding()
        {
            // If no batch encoding is specified we detect it from the first bytes in the buffer.
            if (this.batchEncoding == null)
            {
                // NOTE: The batch encoding will only ever be null on the first call to this method which
                //       happens before the batch reader skips to the first boundary.
                this.batchEncoding = this.DetectEncoding();
            }

            // Verify that we only allow single byte encodings and UTF-8 for now.
            ReaderValidationUtils.ValidateEncodingSupportedInBatch(this.batchEncoding);
        }
Example #6
0
 public ODataMessageReader(IODataResponseMessage responseMessage, ODataMessageReaderSettings settings, IEdmModel model)
 {
     this.readerPayloadKind = ODataPayloadKind.Unsupported;
     ExceptionUtils.CheckArgumentNotNull <IODataResponseMessage>(responseMessage, "responseMessage");
     this.settings = (settings == null) ? new ODataMessageReaderSettings() : new ODataMessageReaderSettings(settings);
     ReaderValidationUtils.ValidateMessageReaderSettings(this.settings, true);
     this.readingResponse = true;
     this.message         = new ODataResponseMessage(responseMessage, false, this.settings.DisableMessageStreamDisposal, this.settings.MessageQuotas.MaxReceivedMessageSize);
     this.urlResolver     = responseMessage as IODataUrlResolver;
     this.version         = ODataUtilsInternal.GetDataServiceVersion(this.message, this.settings.MaxProtocolVersion);
     this.model           = model ?? EdmCoreModel.Instance;
     ODataVersionChecker.CheckVersionSupported(this.version, this.settings);
 }
        internal bool ProcessPartHeader()
        {
            bool flag;
            ODataBatchOperationHeaders headers = this.ReadPartHeaders(out flag);

            if (flag)
            {
                this.DetermineChangesetBoundaryAndEncoding(headers["Content-Type"]);
                if (this.changesetEncoding == null)
                {
                    this.changesetEncoding = this.DetectEncoding();
                }
                ReaderValidationUtils.ValidateEncodingSupportedInBatch(this.changesetEncoding);
            }
            return(flag);
        }
Example #8
0
        /// <summary>
        /// If an entity type name is found in the payload this method is called to apply it to the current scope.
        /// This method should be called even if the type name was not found in which case a null should be passed in.
        /// The method validates that some type will be available as the current entity type after it returns (if we are parsing using metadata).
        /// </summary>
        /// <param name="entityTypeNameFromPayload">The entity type name found in the payload or null if no type was specified in the payload.</param>
        protected void ApplyEntityTypeNameFromPayload(string entityTypeNameFromPayload)
        {
            Debug.Assert(
                this.scopes.Count > 0 && this.scopes.Peek().Item is ODataEntry,
                "Entity type can be applied only when in entry scope.");

            SerializationTypeNameAnnotation serializationTypeNameAnnotation;
            EdmTypeKind             targetTypeKind;
            IEdmEntityTypeReference targetEntityTypeReference =
                (IEdmEntityTypeReference)ReaderValidationUtils.ResolvePayloadTypeNameAndComputeTargetType(
                    EdmTypeKind.Entity,
                    /*defaultPrimitivePayloadType*/ null,
                    this.CurrentEntityType.ToTypeReference(),
                    entityTypeNameFromPayload,
                    this.inputContext.Model,
                    this.inputContext.MessageReaderSettings,
                    this.inputContext.Version,
                    () => EdmTypeKind.Entity,
                    out targetTypeKind,
                    out serializationTypeNameAnnotation);

            IEdmEntityType targetEntityType = null;
            ODataEntry     entry            = this.CurrentEntry;

            if (targetEntityTypeReference != null)
            {
                targetEntityType = targetEntityTypeReference.EntityDefinition();
                entry.TypeName   = targetEntityType.ODataFullName();

                if (serializationTypeNameAnnotation != null)
                {
                    entry.SetAnnotation(serializationTypeNameAnnotation);
                }
            }
            else if (entityTypeNameFromPayload != null)
            {
                entry.TypeName = entityTypeNameFromPayload;
            }

            // Set the current entity type since the type from payload might be more derived than
            // the expected one.
            this.CurrentEntityType = targetEntityType;
        }
Example #9
0
        protected void ApplyEntityTypeNameFromPayload(string entityTypeNameFromPayload)
        {
            SerializationTypeNameAnnotation annotation;
            EdmTypeKind             kind;
            IEdmEntityTypeReference reference = (IEdmEntityTypeReference)ReaderValidationUtils.ResolvePayloadTypeNameAndComputeTargetType(EdmTypeKind.Entity, null, this.CurrentEntityType.ToTypeReference(), entityTypeNameFromPayload, this.inputContext.Model, this.inputContext.MessageReaderSettings, this.inputContext.Version, () => EdmTypeKind.Entity, out kind, out annotation);
            IEdmEntityType          type      = null;
            ODataEntry currentEntry           = this.CurrentEntry;

            if (reference != null)
            {
                type = reference.EntityDefinition();
                currentEntry.TypeName = type.ODataFullName();
                if (annotation != null)
                {
                    currentEntry.SetAnnotation <SerializationTypeNameAnnotation>(annotation);
                }
            }
            else if (entityTypeNameFromPayload != null)
            {
                currentEntry.TypeName = entityTypeNameFromPayload;
            }
            this.CurrentEntityType = type;
        }
Example #10
0
        /// <summary>
        /// Converts a string to a primitive value.
        /// </summary>
        /// <param name="text">The string text to convert.</param>
        /// <param name="targetTypeReference">Type to convert the string to.</param>
        /// <returns>The value converted to the target type.</returns>
        /// <remarks>This method does not convert null value.</remarks>
        internal static object ConvertStringToPrimitive(string text, IEdmPrimitiveTypeReference targetTypeReference)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(text != null, "text != null");
            Debug.Assert(targetTypeReference != null, "targetTypeReference != null");

            try
            {
                EdmPrimitiveTypeKind primitiveKind = targetTypeReference.PrimitiveKind();

                switch (primitiveKind)
                {
                case EdmPrimitiveTypeKind.Binary:
                    return(Convert.FromBase64String(text));

                case EdmPrimitiveTypeKind.Boolean:
                    return(ConvertXmlBooleanValue(text));

                case EdmPrimitiveTypeKind.Byte:
                    return(XmlConvert.ToByte(text));

                case EdmPrimitiveTypeKind.DateTime:
                    return(PlatformHelper.ConvertStringToDateTime(text));

                case EdmPrimitiveTypeKind.DateTimeOffset:
                    return(PlatformHelper.ConvertStringToDateTimeOffset(text));

                case EdmPrimitiveTypeKind.Decimal:
                    return(XmlConvert.ToDecimal(text));

                case EdmPrimitiveTypeKind.Double:
                    return(XmlConvert.ToDouble(text));

                case EdmPrimitiveTypeKind.Guid:
                    return(new Guid(text));

                case EdmPrimitiveTypeKind.Int16:
                    return(XmlConvert.ToInt16(text));

                case EdmPrimitiveTypeKind.Int32:
                    return(XmlConvert.ToInt32(text));

                case EdmPrimitiveTypeKind.Int64:
                    return(XmlConvert.ToInt64(text));

                case EdmPrimitiveTypeKind.SByte:
                    return(XmlConvert.ToSByte(text));

                case EdmPrimitiveTypeKind.Single:
                    return(XmlConvert.ToSingle(text));

                case EdmPrimitiveTypeKind.String:
                    return(text);

                case EdmPrimitiveTypeKind.Time:
                    return(XmlConvert.ToTimeSpan(text));

                case EdmPrimitiveTypeKind.Stream:
                case EdmPrimitiveTypeKind.None:
                case EdmPrimitiveTypeKind.Geography:
                case EdmPrimitiveTypeKind.GeographyCollection:
                case EdmPrimitiveTypeKind.GeographyPoint:
                case EdmPrimitiveTypeKind.GeographyLineString:
                case EdmPrimitiveTypeKind.GeographyPolygon:
                case EdmPrimitiveTypeKind.GeometryCollection:
                case EdmPrimitiveTypeKind.GeographyMultiPolygon:
                case EdmPrimitiveTypeKind.GeographyMultiLineString:
                case EdmPrimitiveTypeKind.GeographyMultiPoint:
                case EdmPrimitiveTypeKind.Geometry:
                case EdmPrimitiveTypeKind.GeometryPoint:
                case EdmPrimitiveTypeKind.GeometryLineString:
                case EdmPrimitiveTypeKind.GeometryPolygon:
                case EdmPrimitiveTypeKind.GeometryMultiPolygon:
                case EdmPrimitiveTypeKind.GeometryMultiLineString:
                case EdmPrimitiveTypeKind.GeometryMultiPoint:
                default:
                    // Note that Astoria supports XElement and Binary as well, but they are serialized as string or byte[]
                    // and the metadata will actually talk about string and byte[] as well. Astoria will perform the conversion if necessary.
                    throw new ODataException(Strings.General_InternalError(InternalErrorCodes.AtomValueUtils_ConvertStringToPrimitive));
                }
            }
            catch (Exception e)
            {
                if (!ExceptionUtils.IsCatchableExceptionType(e))
                {
                    throw;
                }

                throw ReaderValidationUtils.GetPrimitiveTypeConversionException(targetTypeReference, e);
            }
        }
Example #11
0
        internal static object ConvertStringToPrimitive(string text, IEdmPrimitiveTypeReference targetTypeReference)
        {
            object obj2;

            try
            {
                switch (targetTypeReference.PrimitiveKind())
                {
                case EdmPrimitiveTypeKind.Binary:
                    return(Convert.FromBase64String(text));

                case EdmPrimitiveTypeKind.Boolean:
                    return(XmlConvert.ToBoolean(text));

                case EdmPrimitiveTypeKind.Byte:
                    return(XmlConvert.ToByte(text));

                case EdmPrimitiveTypeKind.DateTime:
                    return(Microsoft.Data.OData.PlatformHelper.ConvertStringToDateTime(text));

                case EdmPrimitiveTypeKind.DateTimeOffset:
                    return(XmlConvert.ToDateTimeOffset(text));

                case EdmPrimitiveTypeKind.Decimal:
                    return(XmlConvert.ToDecimal(text));

                case EdmPrimitiveTypeKind.Double:
                    return(XmlConvert.ToDouble(text));

                case EdmPrimitiveTypeKind.Guid:
                    return(new Guid(text));

                case EdmPrimitiveTypeKind.Int16:
                    return(XmlConvert.ToInt16(text));

                case EdmPrimitiveTypeKind.Int32:
                    return(XmlConvert.ToInt32(text));

                case EdmPrimitiveTypeKind.Int64:
                    return(XmlConvert.ToInt64(text));

                case EdmPrimitiveTypeKind.SByte:
                    return(XmlConvert.ToSByte(text));

                case EdmPrimitiveTypeKind.Single:
                    return(XmlConvert.ToSingle(text));

                case EdmPrimitiveTypeKind.String:
                    return(text);

                case EdmPrimitiveTypeKind.Time:
                    return(XmlConvert.ToTimeSpan(text));
                }
                throw new ODataException(Microsoft.Data.OData.Strings.General_InternalError(InternalErrorCodes.AtomValueUtils_ConvertStringToPrimitive));
            }
            catch (Exception exception)
            {
                if (!ExceptionUtils.IsCatchableExceptionType(exception))
                {
                    throw;
                }
                throw ReaderValidationUtils.GetPrimitiveTypeConversionException(targetTypeReference, exception);
            }
            return(obj2);
        }
Example #12
0
        protected override Task <bool> ReadAsynchronously()
        {
            Task <bool> result;

            switch (this.State)
            {
            case ODataReaderState.Start:
                result = this.ReadAtStartImplementationAsync();
                break;

            case ODataReaderState.FeedStart:
                result = this.ReadAtFeedStartImplementationAsync();
                break;

            case ODataReaderState.FeedEnd:
                result = this.ReadAtFeedEndImplementationAsync();
                break;

            case ODataReaderState.EntryStart:
                result = TaskUtils.GetTaskForSynchronousOperation(() => this.IncreaseEntryDepth())
                         .FollowOnSuccessWithTask(t => this.ReadAtEntryStartImplementationAsync());
                break;

            case ODataReaderState.EntryEnd:
                result = TaskUtils.GetTaskForSynchronousOperation(() => this.DecreaseEntryDepth())
                         .FollowOnSuccessWithTask(t => this.ReadAtEntryEndImplementationAsync());
                break;

            case ODataReaderState.NavigationLinkStart:
                result = this.ReadAtNavigationLinkStartImplementationAsync();
                break;

            case ODataReaderState.NavigationLinkEnd:
                result = this.ReadAtNavigationLinkEndImplementationAsync();
                break;

            case ODataReaderState.EntityReferenceLink:
                result = this.ReadAtEntityReferenceLinkAsync();
                break;

            case ODataReaderState.Exception:        // fall through
            case ODataReaderState.Completed:
                result = TaskUtils.GetFaultedTask <bool>(new ODataException(Strings.ODataReaderCore_NoReadCallsAllowed(this.State)));
                break;

            default:
                Debug.Assert(false, "Unsupported reader state " + this.State + " detected.");
                result = TaskUtils.GetFaultedTask <bool>(new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataReaderCoreAsync_ReadAsynchronously)));
                break;
            }

            return(result.FollowOnSuccessWith(t =>
            {
                if ((this.State == ODataReaderState.EntryStart || this.State == ODataReaderState.EntryEnd) && this.Item != null)
                {
                    ReaderValidationUtils.ValidateEntry(this.CurrentEntry);
                }

                return t.Result;
            }));
        }