public static Task ReadContentUsingCorrectCharacterEncodingHelper(MediaTypeFormatter formatter, string content, byte[] sourceData, string mediaType) { // Arrange MemoryStream memStream = new MemoryStream(sourceData); StringContent dummyContent = new StringContent(string.Empty); HttpContentHeaders headers = dummyContent.Headers; headers.Clear(); headers.ContentType = MediaTypeHeaderValue.Parse(mediaType); headers.ContentLength = sourceData.Length; IFormatterLogger mockFormatterLogger = new Mock <IFormatterLogger>().Object; // Act & Assert return(formatter.ReadFromStreamAsync(typeof(string), memStream, dummyContent, mockFormatterLogger).ContinueWith( (readTask) => { string result = readTask.Result as string; // Assert Assert.Equal(TaskStatus.RanToCompletion, readTask.Status); Assert.Equal(content, result); })); }
protected static async Task ReadContentUsingCorrectCharacterEncodingHelperAsync( MediaTypeFormatter formatter, string content, byte[] sourceData, string mediaType ) { // Arrange MemoryStream memStream = new MemoryStream(sourceData); StringContent dummyContent = new StringContent(string.Empty); HttpContentHeaders headers = dummyContent.Headers; headers.Clear(); headers.ContentType = MediaTypeHeaderValue.Parse(mediaType); headers.ContentLength = sourceData.Length; IFormatterLogger mockFormatterLogger = new Mock<IFormatterLogger>().Object; // Act var result = ( await formatter.ReadFromStreamAsync( typeof(string), memStream, dummyContent, mockFormatterLogger ) ) as string; // Assert Assert.Equal(content, result); }
protected async Task ReadFromStreamAsync_UsesCorrectCharacterEncodingHelper(MediaTypeFormatter formatter, string content, string formattedContent, string mediaType, string encoding, bool isDefaultEncoding) { // Arrange Encoding enc = null; if (isDefaultEncoding) { enc = formatter.SupportedEncodings.First((e) => e.WebName.Equals(encoding, StringComparison.OrdinalIgnoreCase)); } else { enc = Encoding.GetEncoding(encoding); formatter.SupportedEncodings.Add(enc); } byte[] data = enc.GetBytes(formattedContent); MemoryStream memStream = new MemoryStream(data); StringContent dummyContent = new StringContent(string.Empty); HttpContentHeaders headers = dummyContent.Headers; headers.Clear(); headers.ContentType = MediaTypeHeaderValue.Parse(mediaType); headers.ContentLength = data.Length; IFormatterLogger mockFormatterLogger = new Mock <IFormatterLogger>().Object; // Act string result = (await formatter.ReadFromStreamAsync(typeof(string), memStream, dummyContent, mockFormatterLogger)) as string; // Assert Assert.Equal(content, result); }
/// <summary> /// Returns a <see cref="Task" /> to deserialize an object of the given <paramref name="type" /> from the given /// <paramref name="readStream" /> /// </summary> /// <remarks> /// <para> /// This implementation throws a <see cref="NotSupportedException" />. Derived types should override this method if /// the formatter supports reading. /// </para> /// <para> /// An implementation of this method should NOT close <paramref name="readStream" /> upon completion. The stream /// will be closed independently when /// the <see cref="HttpContent" /> instance is disposed. /// </para> /// </remarks> /// <param name="formatter">The <see cref="MediaTypeFormatter"/> instance.</param> /// <param name="type">The type of the object to deserialize.</param> /// <param name="readStream">The <see cref="Stream" /> to read.</param> /// <param name="content">The <see cref="HttpContent" /> if available. It may be <c>null</c>.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A <see cref="Task" /> whose result will be an object of the given type.</returns> /// <exception cref="NotSupportedException">Derived types need to support reading.</exception> public static Task <object?> ReadFromStreamAsync(this MediaTypeFormatter formatter, Type type, Stream readStream, HttpContent content, CancellationToken cancellationToken = default) { if (formatter == null) { throw Error.ArgumentNull(nameof(formatter)); } return(formatter.ReadFromStreamAsync(type, readStream, content, null, cancellationToken)); }
internal static Task <object> DeserializeAsync(string json, Type type, MediaTypeFormatter formatter = null, IFormatterLogger formatterLogger = null) { formatter = formatter ?? new JsonMediaTypeFormatter(); MemoryStream ms = new MemoryStream(); byte[] bytes = Encoding.Default.GetBytes(json); ms.Write(bytes, 0, bytes.Length); ms.Flush(); ms.Position = 0; return(formatter.ReadFromStreamAsync(type, ms, content: null, formatterLogger: formatterLogger)); }
public static Task <T> ReadAsAsync <T>(this HttpContent content, MediaTypeFormatter formatter) { var tcs = new TaskCompletionSource <T>(); try { var type = typeof(T); if (!formatter.CanReadType(type)) { tcs.TrySetException(new InvalidOperationException(string.Format("formatter {0} can not read {1}", formatter, type))); } else { var contentReadTask = content.ReadAsStreamAsync(); contentReadTask.ContinueWith(t => { if (t.IsFaulted) { tcs.TrySetException(t.Exception.GetBaseException()); } else { if (t.IsCanceled) { tcs.TrySetCanceled(); } else { formatter.ReadFromStreamAsync(type, content.Headers, t.Result).ContinueWith(t2 => { if (t2.IsFaulted) { tcs.TrySetException(t2.Exception.GetBaseException()); } else if (t2.IsCanceled) { tcs.TrySetCanceled(); } else { tcs.TrySetResult((T)t2.Result); } }); } } }); } } catch (Exception ex) { tcs.TrySetException(ex); } return(tcs.Task); }
public object ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(MediaTypeFormatter formatter, Type variationType, object testData) { // Arrange HttpContent content = new StringContent(String.Empty); HttpContentHeaders contentHeaders = content.Headers; object readObj = null; // Act & Assert Assert.Stream.WriteAndRead( stream => { Assert.Task.Succeeds(formatter.WriteToStreamAsync(variationType, testData, stream, content, transportContext: null)); contentHeaders.ContentLength = stream.Length; }, stream => readObj = Assert.Task.SucceedsWithResult(formatter.ReadFromStreamAsync(variationType, stream, content, formatterLogger: null))); return(readObj); }
internal static object Deserialize(string json, Type type, MediaTypeFormatter formatter = null, IFormatterLogger formatterLogger = null) { formatter = formatter ?? new JsonMediaTypeFormatter(); MemoryStream ms = new MemoryStream(); byte[] bytes = Encoding.Default.GetBytes(json); ms.Write(bytes, 0, bytes.Length); ms.Flush(); ms.Position = 0; Task <object> readTask = formatter.ReadFromStreamAsync(type, ms, content: null, formatterLogger: formatterLogger); readTask.WaitUntilCompleted(); if (readTask.IsFaulted) { throw readTask.Exception.GetBaseException(); } return(readTask.Result); }
public async Task <object> ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(MediaTypeFormatter formatter, Type variationType, object testData) { // Arrange HttpContent content = new StringContent(String.Empty); HttpContentHeaders contentHeaders = content.Headers; object readObj = null; // Act & Assert using (MemoryStream stream = new MemoryStream()) { await formatter.WriteToStreamAsync(variationType, testData, stream, content, transportContext : null); contentHeaders.ContentLength = stream.Length; stream.Flush(); stream.Seek(0L, SeekOrigin.Begin); readObj = await formatter.ReadFromStreamAsync(variationType, stream, content, formatterLogger : null); } return(readObj); }
public static Task ReadContentUsingCorrectCharacterEncodingHelper(MediaTypeFormatter formatter, string content, string formattedContent, string mediaType, string encoding, bool isDefaultEncoding) { // Arrange Encoding enc = null; if (isDefaultEncoding) { enc = formatter.SupportedEncodings.First((e) => e.WebName.Equals(encoding, StringComparison.OrdinalIgnoreCase)); } else { enc = Encoding.GetEncoding(encoding); formatter.SupportedEncodings.Add(enc); } byte[] data = enc.GetBytes(formattedContent); MemoryStream memStream = new MemoryStream(data); StringContent dummyContent = new StringContent(string.Empty); HttpContentHeaders headers = dummyContent.Headers; headers.Clear(); headers.ContentType = MediaTypeHeaderValue.Parse(mediaType); headers.ContentLength = data.Length; IFormatterLogger mockFormatterLogger = new Mock <IFormatterLogger>().Object; // Act return(formatter.ReadFromStreamAsync(typeof(string), memStream, headers, mockFormatterLogger).ContinueWith( (readTask) => { string result = readTask.Result as string; // Assert Assert.Equal(TaskStatus.RanToCompletion, readTask.Status); Assert.Equal(content, result); })); }
private static object Read(MemoryStream ms, Type tSource, MediaTypeFormatter formatter) { bool f = formatter.CanReadType(tSource); Assert.True(f); object o = formatter.ReadFromStreamAsync(tSource, ms, content: null, formatterLogger: null).Result; Assert.True(tSource.IsAssignableFrom(o.GetType())); return o; }