/// <summary> /// Constructor. /// </summary> /// <param name="format">The format for this output context.</param> /// <param name="messageStream">The message stream to write the payload to.</param> /// <param name="encoding">The encoding to use for the payload.</param> /// <param name="messageWriterSettings">Configuration settings of the OData writer.</param> /// <param name="writingResponse">true if writing a response message; otherwise false.</param> /// <param name="synchronous">true if the output should be written synchronously; false if it should be written asynchronously.</param> /// <param name="model">The model to use.</param> /// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs written to the payload.</param> internal ODataMetadataOutputContext( ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageWriterSettings, writingResponse, synchronous, model, urlResolver) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(messageStream != null, "messageStream != null"); Debug.Assert(synchronous, "Metadata output context is only supported in synchronous operations."); try { this.messageOutputStream = messageStream; this.xmlWriter = ODataAtomWriterUtils.CreateXmlWriter(messageStream, messageWriterSettings, encoding); } catch (Exception e) { // Dispose the message stream if we failed to create the output context. if (ExceptionUtils.IsCatchableExceptionType(e) && messageStream != null) { messageStream.Dispose(); } throw; } }
/// <summary> /// Returns enumeration of tasks to run to buffer the entire input stream. /// </summary> /// <returns>Enumeration of tasks to run to buffer the input stream.</returns> /// <remarks>This method relies on lazy eval of the enumerator, never enumerate through it synchronously.</remarks> private IEnumerable <Task> BufferInputStream() { while (this.inputStream != null) { Debug.Assert(this.currentBufferIndex >= -1 && this.currentBufferIndex < this.buffers.Count, "The currentBufferIndex is outside of the valid range."); DataBuffer currentBuffer = this.currentBufferIndex == -1 ? null : this.buffers[this.currentBufferIndex]; // Here we intentionally leave some memory unused (smaller than MinReadBufferSize) // in order to issue big enough read requests. This is a perf optimization. if (currentBuffer != null && currentBuffer.FreeBytes < DataBuffer.MinReadBufferSize) { currentBuffer = null; } if (currentBuffer == null) { currentBuffer = this.AddNewBuffer(); } yield return(Task.Factory.FromAsync( (asyncCallback, asyncState) => this.inputStream.BeginRead( currentBuffer.Buffer, currentBuffer.OffsetToWriteTo, currentBuffer.FreeBytes, asyncCallback, asyncState), (asyncResult) => { try { int bytesRead = this.inputStream.EndRead(asyncResult); if (bytesRead == 0) { this.inputStream = null; } else { currentBuffer.MarkBytesAsWritten(bytesRead); } } catch (Exception exception) { if (!ExceptionUtils.IsCatchableExceptionType(exception)) { throw; } this.inputStream = null; throw; } }, null)); } }
internal static Task GetTaskForSynchronousOperationReturningTask(Func <Task> synchronousOperation) { try { return(synchronousOperation()); } catch (Exception exception) { if (!ExceptionUtils.IsCatchableExceptionType(exception)) { throw; } return(GetFaultedTask(exception)); } }
internal static Task <T> GetTaskForSynchronousOperation <T>(Func <T> synchronousOperation) { try { return(GetCompletedTask <T>(synchronousOperation())); } catch (Exception exception) { if (!ExceptionUtils.IsCatchableExceptionType(exception)) { throw; } return(GetFaultedTask <T>(exception)); } }
internal static Task Iterate(this TaskFactory factory, IEnumerable <Task> source) { IEnumerator <Task> enumerator = source.GetEnumerator(); TaskCompletionSource <object> trc = new TaskCompletionSource <object>(null, factory.CreationOptions); trc.Task.ContinueWith(delegate(Task <object> _) { enumerator.Dispose(); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); Action <Task> recursiveBody = null; recursiveBody = delegate(Task antecedent) { try { if ((antecedent != null) && antecedent.IsFaulted) { trc.TrySetException(antecedent.Exception); } else if (enumerator.MoveNext()) { enumerator.Current.ContinueWith(recursiveBody).IgnoreExceptions(); } else { trc.TrySetResult(null); } } catch (Exception exception) { if (!ExceptionUtils.IsCatchableExceptionType(exception)) { throw; } OperationCanceledException exception2 = exception as OperationCanceledException; if ((exception2 != null) && (exception2.CancellationToken == factory.CancellationToken)) { trc.TrySetCanceled(); } else { trc.TrySetException(exception); } } }; factory.StartNew(delegate { recursiveBody(null); }, CancellationToken.None, TaskCreationOptions.None, factory.GetTargetScheduler()).IgnoreExceptions(); return(trc.Task); }
internal static Task GetTaskForSynchronousOperation(Action synchronousOperation) { try { synchronousOperation(); return(CompletedTask); } catch (Exception exception) { if (!ExceptionUtils.IsCatchableExceptionType(exception)) { throw; } return(GetFaultedTask(exception)); } }
/// <summary> /// Catch any exception thrown by the action passed in; in the exception case move the reader into /// state ExceptionThrown and then rethrow the exception. /// </summary> /// <typeparam name="T">The type returned from the <paramref name="action"/> to execute.</typeparam> /// <param name="action">The action to execute.</param> /// <returns>The result of executing the <paramref name="action"/>.</returns> private T InterceptException <T>(Func <T> action) { try { return(action()); } catch (Exception e) { if (ExceptionUtils.IsCatchableExceptionType(e)) { this.EnterScope(new Scope(ODataReaderState.Exception, null, null)); } throw; } }
/// <summary> /// Catch any exception thrown by the action passed in; in the exception case move the writer into /// state Exception and then rethrow the exception. /// </summary> /// <typeparam name="T">The type of the result returned from the <paramref name="action"/>.</typeparam> /// <param name="action">The action to execute.</param> /// <returns>The result of the <paramref name="action"/>.</returns> private T InterceptException <T>(Func <T> action) { try { return(action()); } catch (Exception e) { if (ExceptionUtils.IsCatchableExceptionType(e)) { this.State = ODataBatchReaderState.Exception; } throw; } }
private ODataMetadataOutputContext(ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageWriterSettings, writingResponse, synchronous, model, urlResolver) { try { this.messageOutputStream = messageStream; this.xmlWriter = ODataAtomWriterUtils.CreateXmlWriter(messageStream, messageWriterSettings, encoding); } catch (Exception exception) { if (ExceptionUtils.IsCatchableExceptionType(exception) && (messageStream != null)) { messageStream.Dispose(); } throw; } }
internal static Task FollowAlwaysWith(this Task antecedentTask, Action <Task> operation) { TaskCompletionSource <object> taskCompletionSource = new TaskCompletionSource <object>(); antecedentTask.ContinueWith(delegate(Task t) { Exception exception = null; try { operation(t); } catch (Exception exception2) { if (!ExceptionUtils.IsCatchableExceptionType(exception2)) { throw; } exception = exception2; } switch (t.Status) { case TaskStatus.RanToCompletion: if (exception == null) { taskCompletionSource.TrySetResult(null); return; } taskCompletionSource.TrySetException(exception); return; case TaskStatus.Canceled: if (exception == null) { taskCompletionSource.TrySetCanceled(); return; } taskCompletionSource.TrySetException(exception); return; case TaskStatus.Faulted: taskCompletionSource.TrySetException(t.Exception); return; } }, TaskContinuationOptions.ExecuteSynchronously).IgnoreExceptions(); return(taskCompletionSource.Task); }
private T InterceptException <T>(Func <T> action) { T local; try { local = action(); } catch (Exception exception) { if (ExceptionUtils.IsCatchableExceptionType(exception)) { this.EnterScope(new Scope(ODataReaderState.Exception, null, null)); } throw; } return(local); }
private T InterceptException <T>(Func <T> action) { T local; try { local = action(); } catch (Exception exception) { if (ExceptionUtils.IsCatchableExceptionType(exception)) { this.State = ODataBatchReaderState.Exception; } throw; } return(local); }
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; } }
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; } }
/// <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 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) { DebugUtils.CheckNoExternalCallers(); 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; } }
private IEnumerable <Task> BufferInputStream() { while (true) { if (this.inputStream == null) { yield break; } DataBuffer currentBuffer = (this.currentBufferIndex == -1) ? null : this.buffers[this.currentBufferIndex]; if ((currentBuffer != null) && (currentBuffer.FreeBytes < 0x400)) { currentBuffer = null; } if (currentBuffer == null) { currentBuffer = this.AddNewBuffer(); } yield return(Task.Factory.FromAsync((Func <AsyncCallback, object, IAsyncResult>)((asyncCallback, asyncState) => this.inputStream.BeginRead(currentBuffer.Buffer, currentBuffer.OffsetToWriteTo, currentBuffer.FreeBytes, asyncCallback, asyncState)), delegate(IAsyncResult asyncResult) { try { int count = this.inputStream.EndRead(asyncResult); if (count == 0) { this.inputStream = null; } else { currentBuffer.MarkBytesAsWritten(count); } } catch (Exception exception) { if (!ExceptionUtils.IsCatchableExceptionType(exception)) { throw; } this.inputStream = null; throw; } }, null)); } }
private static Task <TResult> FollowOnFaultWithImplementation <TResult>(Task antecedentTask, Func <Task, TResult> getTaskResult, Action <Task> operation) { TaskCompletionSource <TResult> taskCompletionSource = new TaskCompletionSource <TResult>(); antecedentTask.ContinueWith(delegate(Task t) { switch (t.Status) { case TaskStatus.RanToCompletion: taskCompletionSource.TrySetResult(getTaskResult(t)); return; case TaskStatus.Canceled: taskCompletionSource.TrySetCanceled(); break; case TaskStatus.Faulted: try { operation(t); taskCompletionSource.TrySetException(t.Exception); } catch (Exception exception) { if (!ExceptionUtils.IsCatchableExceptionType(exception)) { throw; } AggregateException exception2 = new AggregateException(new Exception[] { t.Exception, exception }); taskCompletionSource.TrySetException(exception2); } break; default: return; } }, TaskContinuationOptions.ExecuteSynchronously).IgnoreExceptions(); return(taskCompletionSource.Task); }
/// <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; } }
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); }
/// <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); } }