public void ReadAsStream() { var ms = new MemoryStream(); ms.WriteByte(77); ms.WriteByte(55); ms.Seek(0, SeekOrigin.Begin); var sc = new StreamContent(ms); var res = sc.ReadAsStreamAsync().Result; Assert.AreEqual(77, res.ReadByte(), "#1"); }
public void ReadAsStreamAsync_ClosedInput() { var stream = new MemoryStream(new byte[] { 1 }); var content = new StreamContent(stream); Assert.IsTrue(content.LoadIntoBufferAsync().Wait(3000), "#1"); stream.Close(); var stream_read = content.ReadAsStreamAsync().Result; Assert.IsTrue(stream_read.CanSeek, "#2"); Assert.AreEqual(0, stream_read.Position, "#3"); Assert.AreEqual(1, stream_read.Length, "#4"); }
public async Task ContentReadStream_GetPropertyPartiallyConsumed_ReturnOriginalStream(bool readStreamAsync) { int consumed = 4; var source = new MockStream(new byte[10]); source.Read(new byte[consumed], 0, consumed); var content = new StreamContent(source); Stream stream = await content.ReadAsStreamAsync(readStreamAsync); Assert.False(stream.CanWrite); Assert.Equal(source.Length, stream.Length); Assert.Equal(1, source.ReadCount); Assert.Equal(consumed, stream.Position); Assert.NotSame(source, stream); }
public async Task SerialiseAndCompressContent() { TestObject testObject = new TestObject() { Id = 99 }; StreamContent result = HttpContentUtils.SerialiseToJsonAndCompress(testObject); Stream stream = await result.ReadAsStreamAsync(); TestObject deserialisedAndDecompressedContent; using (GZipStream decompressionStream = new GZipStream(stream, CompressionMode.Decompress)) { deserialisedAndDecompressedContent = await Utf8Json.JsonSerializer.DeserializeAsync <TestObject>(decompressionStream); } Assert.AreEqual(testObject.Id, deserialisedAndDecompressedContent.Id); }
public static async Task <BitmapImage> LoadGravatar(string hash) { if (hash == null) { hash = ""; } if (_gravatarCache.ContainsKey(hash)) { return(_gravatarCache[hash]); } string url = "http://s.gravatar.com/avatar/" + hash; BitmapImage bi; HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { StreamContent sc = response.Content as StreamContent; bi = new BitmapImage(); await bi.SetSourceAsync((await sc.ReadAsStreamAsync()).AsRandomAccessStream()); //because of async loading of all gravatar infos... Monitor.Enter(_gravatarCache); if (!_gravatarCache.ContainsKey(hash)) { _gravatarCache.Add(hash, bi); } Monitor.Exit(_gravatarCache); } else { bi = GravatarHelper.DefaultGravatar; } return(bi); }
public static async Task <BitmapImage> LoadAvatar(string hash) { if (_gravatarCache.ContainsKey(hash)) { return(_gravatarCache[hash]); } string url = "http://s.gravatar.com/avatar/" + hash; BitmapImage bi; HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { StreamContent sc = response.Content as StreamContent; bi = new BitmapImage(); bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; //Debug: //MemoryStream ms = new MemoryStream(await sc.ReadAsByteArrayAsync()); //bi.StreamSource = ms; bi.StreamSource = await sc.ReadAsStreamAsync(); bi.EndInit(); bi.Freeze(); _gravatarCache.Add(hash, bi); } else { bi = GravatarHelper.DefaultGravatar; } return(bi); }
static void DownloadToDocs(string url, string localFile) { try { using (HttpClient client = new HttpClient()) { client.Timeout = new TimeSpan(0, 10, 0); // 10min timeout for large file downloads StreamContent content = (StreamContent)client.GetAsync(url).Result.Content; string fname = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), localFile); Console.WriteLine("Downloading to {0}.", fname); using (FileStream output = File.Create(fname)) { content.ReadAsStreamAsync().Result.CopyTo(output); output.Close(); } } } catch (Exception e) { Console.WriteLine("Error downloading to documents folder: " + e.Message); } }
internal static async Task UploadPackage(string accessToken, string environmentName, string apiVersion, string companyId, string FileName, string packageCode) { var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); httpClient.DefaultRequestHeaders.Add("If-Match", "*"); httpClient.DefaultRequestHeaders.Add("accept-encoding", "gzip, deflate"); // PATCH https://api.businesscentral.dynamics.com/v2.0/{environment name}/api/microsoft/automation/{apiVersion}/companies({{companyId}})/configurationPackages('{SAMPLE}')/file('{SAMPLE}')/content var FileStream = new FileStream(FileName, FileMode.Open); var content = new StreamContent(FileStream); await content.ReadAsStreamAsync(); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); // content.Headers.Add("If-Match","*"); // content.Headers.Add("accept-encoding","gzip, deflate"); HttpResponseMessage response = await httpClient .PatchAsync($"https://api.businesscentral.dynamics.com/v2.1/{environmentName}/api/microsoft/automation/{apiVersion}/companies({companyId})/configurationPackages('{packageCode}')/file('{packageCode}')/content", content); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(responseBody), Formatting.Indented)); }
public async Task ContentReadStream_CheckResultProperties_ValuesRepresentReadOnlyStream(bool readStreamAsync) { byte[] data = new byte[10]; for (int i = 0; i < data.Length; i++) { data[i] = (byte)i; } var source = new MockStream(data); var content = new StreamContent(source); Stream contentReadStream = await content.ReadAsStreamAsync(readStreamAsync); // The following checks verify that the stream returned passes all read-related properties to the // underlying MockStream and throws when using write-related members. Assert.False(contentReadStream.CanWrite); Assert.True(contentReadStream.CanRead); Assert.Equal(source.Length, contentReadStream.Length); Assert.Equal(1, source.CanSeekCount); _output.WriteLine(contentReadStream.CanSeek.ToString()); Assert.Equal(2, source.CanSeekCount); contentReadStream.Position = 3; // No exception. Assert.Equal(3, contentReadStream.Position); byte byteOnIndex3 = (byte)contentReadStream.ReadByte(); Assert.Equal(data[3], byteOnIndex3); byte[] byteOnIndex4 = new byte[1]; int result = await contentReadStream.ReadAsync(byteOnIndex4, 0, 1); Assert.Equal(1, result); Assert.Equal(data[4], byteOnIndex4[0]); byte[] byteOnIndex5 = new byte[1]; Assert.Equal(1, contentReadStream.Read(byteOnIndex5, 0, 1)); Assert.Equal(data[5], byteOnIndex5[0]); byte[] byteOnIndex6 = new byte[1]; Assert.Equal(1, contentReadStream.Read(new Span <byte>(byteOnIndex6, 0, 1))); Assert.Equal(data[6], byteOnIndex6[0]); contentReadStream.ReadTimeout = 123; Assert.Equal(123, source.ReadTimeout); Assert.Equal(123, contentReadStream.ReadTimeout); Assert.Equal(0, source.CanTimeoutCount); _output.WriteLine(contentReadStream.CanTimeout.ToString()); Assert.Equal(1, source.CanTimeoutCount); Assert.Equal(0, source.SeekCount); contentReadStream.Seek(0, SeekOrigin.Begin); Assert.Equal(1, source.SeekCount); Assert.Throws <NotSupportedException>(() => { contentReadStream.WriteTimeout = 5; }); Assert.Throws <NotSupportedException>(() => contentReadStream.WriteTimeout.ToString()); Assert.Throws <NotSupportedException>(() => contentReadStream.Flush()); Assert.Throws <NotSupportedException>(() => contentReadStream.SetLength(1)); Assert.Throws <NotSupportedException>(() => contentReadStream.Write(null, 0, 0)); Assert.Throws <NotSupportedException>(() => contentReadStream.Write(new Span <byte>(Array.Empty <byte>()))); Assert.Throws <NotSupportedException>(() => contentReadStream.WriteByte(1)); Assert.Equal(0, source.DisposeCount); contentReadStream.Dispose(); Assert.Equal(1, source.DisposeCount); }
public async Task ContentReadStream_CheckResultProperties_ValuesRepresentReadOnlyStream() { byte[] data = new byte[10]; for (int i = 0; i < data.Length; i++) { data[i] = (byte)i; } var source = new MockStream(data); var content = new StreamContent(source); Stream contentReadStream = await content.ReadAsStreamAsync(); // The following checks verify that the stream returned passes all read-related properties to the // underlying MockStream and throws when using write-related members. Assert.False(contentReadStream.CanWrite); Assert.True(contentReadStream.CanRead); Assert.Equal(source.Length, contentReadStream.Length); Assert.Equal(1, source.CanSeekCount); _output.WriteLine(contentReadStream.CanSeek.ToString()); Assert.Equal(2, source.CanSeekCount); contentReadStream.Position = 3; // No exception. Assert.Equal(3, contentReadStream.Position); byte byteOnIndex3 = (byte)contentReadStream.ReadByte(); Assert.Equal(data[3], byteOnIndex3); byte[] byteOnIndex4 = new byte[1]; int result = await contentReadStream.ReadAsync(byteOnIndex4, 0, 1); Assert.Equal(1, result); Assert.Equal(data[4], byteOnIndex4[0]); byte[] byteOnIndex5 = new byte[1]; Assert.Equal(1, contentReadStream.Read(byteOnIndex5, 0, 1)); Assert.Equal(data[5], byteOnIndex5[0]); contentReadStream.ReadTimeout = 123; Assert.Equal(123, source.ReadTimeout); Assert.Equal(123, contentReadStream.ReadTimeout); Assert.Equal(0, source.CanTimeoutCount); _output.WriteLine(contentReadStream.CanTimeout.ToString()); Assert.Equal(1, source.CanTimeoutCount); Assert.Equal(0, source.SeekCount); contentReadStream.Seek(0, SeekOrigin.Begin); Assert.Equal(1, source.SeekCount); Assert.Throws<NotSupportedException>(() => { contentReadStream.WriteTimeout = 5; }); Assert.Throws<NotSupportedException>(() => contentReadStream.WriteTimeout.ToString()); Assert.Throws<NotSupportedException>(() => contentReadStream.Flush()); Assert.Throws<NotSupportedException>(() => contentReadStream.SetLength(1)); Assert.Throws<NotSupportedException>(() => contentReadStream.Write(null, 0, 0)); Assert.Throws<NotSupportedException>(() => contentReadStream.WriteByte(1)); Assert.Equal(0, source.DisposeCount); contentReadStream.Dispose(); Assert.Equal(1, source.DisposeCount); }
public async Task ContentReadStream_GetPropertyPartiallyConsumed_ReturnOriginalStream() { int consumed = 4; var source = new MockStream(new byte[10]); source.Read(new byte[consumed], 0, consumed); var content = new StreamContent(source); Stream stream = await content.ReadAsStreamAsync(); Assert.False(stream.CanWrite); Assert.Equal(source.Length, stream.Length); Assert.Equal(1, source.ReadCount); Assert.Equal(consumed, stream.Position); Assert.NotSame(source, stream); }
public async Task ContentReadStream_GetProperty_ReturnOriginalStream() { var source = new MockStream(new byte[10]); var content = new StreamContent(source); Stream stream = await content.ReadAsStreamAsync(); Assert.False(stream.CanWrite); Assert.Equal(source.Length, stream.Length); Assert.Equal(0, source.ReadCount); Assert.NotSame(source, stream); }
public async Task <IHttpActionResult> Upload() { HttpRequestMessage request = this.Request; if (!request.Content.IsMimeMultipartContent()) { return(JsonError(HttpStatusCode.BadRequest, 201, "Mime Multipart Content missing")); } var userId = User.Identity.GetUserId(); MultipartMemoryStreamProvider provider = await request.Content.ReadAsMultipartAsync(); Advisr.Domain.DbModels.File dbFile = null; var content = provider.Contents.SingleOrDefault(); if (content is StreamContent) { string fileName = content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty); string mediaType = content.Headers.ContentType.MediaType; string folder = System.Web.HttpContext.Current.Server.MapPath(Core.Constants.UploadFilesDirectory); long fileSize = 0; StreamContent streamContent = (StreamContent)content; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } try { using (IUnitOfWork unitOfWork = UnitOfWork.Create()) { dbFile = new Domain.DbModels.File(); dbFile.FileName = fileName; dbFile.ContentType = mediaType; dbFile.IsTemp = true; dbFile.CreatedDate = DateTime.Now; dbFile.CreatedById = userId; unitOfWork.FileRepository.Insert(dbFile); await unitOfWork.SaveAsync(); string filePath = Path.Combine(folder, dbFile.Id.ToString()); using (var fileStream = await streamContent.ReadAsStreamAsync()) { using (var file = File.Create(filePath)) { await fileStream.CopyToAsync(file); fileSize = fileStream.Length; } streamContent.Dispose(); } dbFile.FileSize = fileSize; unitOfWork.FileRepository.Edit(dbFile); await unitOfWork.SaveAsync(); } } catch (Exception e) { return(JsonError(HttpStatusCode.BadRequest, 202, e.Message + " " + e.StackTrace)); } } else { return(JsonError(HttpStatusCode.BadRequest, 203, "Content missing")); } var result = new { id = dbFile.Id, fileName = dbFile.FileName, fileSize = dbFile.FileSize, contentType = dbFile.ContentType, url = string.Format("{0}/get/{1}", Url.Link("Default", new { controller = "files" }), dbFile.Id) }; return(this.Ok(result)); }