public HttpCsvPushStreamResponse(string filename, Action<Action<string[]>> writeAction)
     : base(HttpStatusCode.OK)
 {
     Content = new PushStreamContent((outputStream, content, context) => {
         using (StreamWriter writer = new StreamWriter(outputStream, Encoding.UTF8)) {
             writeAction((values) => CsvWriter.WriteRow(writer, values));
         }
         outputStream.Close();
     });
     Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
     Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filename };
 }
Esempio n. 2
1
        public HttpResponseMessage Get(String resolution)
        {
            Trace.TraceInformation("Get");
            //var content = new PushStreamContent(PushImage);
            var content = new PushStreamContent((stream, cont, ctx) =>
            {
                Trace.TraceInformation("pushing new frame");

                long beginTime = Convert.ToInt64((DateTime.Now - epoch).TotalMilliseconds);
                long endTime = 0;

                while (true)
                {
                    endTime = _Server.GetCurrentImageEndTime();
                    if(endTime == 0)
                    {
                        endTime = Convert.ToInt64((DateTime.Now - epoch).TotalMilliseconds) + 3 * 1000;
                    }
                    MemoryStream img = _Server.GetCurrentImage(Size.Empty);

                    do
                    {
                        // wait for 25fps
                        Thread.Sleep(40);

                        img.Seek(0, SeekOrigin.Begin);
                        img.WriteTo(stream);
                        img.Flush();

                    } while (Convert.ToInt64((DateTime.Now - epoch).TotalMilliseconds) < endTime);
                }

                //stream.Close();
            });
            content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("image/jpeg");
            _content.Add(content);
            return new HttpResponseMessage()
            {
                Content = _content
            };
        }
        public void Constructor_SetsDefaultMediaType()
        {
            MockStreamAction  streamAction = new MockStreamAction();
            PushStreamContent content      = new PushStreamContent(streamAction.Action);

            Assert.Equal(MediaTypeConstants.ApplicationOctetStreamMediaType, content.Headers.ContentType);
        }
Esempio n. 4
0
        public HttpResponseMessage Fickle()
        {
            var options = new ServiceModelReflectionOptions
            {
                ControllersTypesToIgnore = new[] { this.GetType() }
            };

            var reflector = new WebApiRuntimeServiceModelReflector(options, this.Configuration, this.GetType().Assembly, Request.RequestUri.Host);
            var serviceModel = reflector.Reflect();

            var content = new PushStreamContent(
                (stream, httpContent, transportContext) =>
                {
                    using (var streamWriter = new StreamWriter(stream))
                    {
                        var writer = new FicklefileWriter(streamWriter);
                        writer.Write(serviceModel);
                    }
                },
                new MediaTypeHeaderValue("text/fickle"));

            var response = new HttpResponseMessage
            {
                Content = content
            };

            return response;
        }
        public HttpResponseMessage Put(NewClassConfiguration classConfiguration)
        {
            var generator = new Generator();

            var zipEntries = generator.Generate(classConfiguration).ToList();

            var pushStreamContent = new PushStreamContent((stream, content, context) =>
            {
                using (var zipFile = new ZipFile())
                {
                    foreach (var zipEntry in zipEntries)
                    {
                        var newStream = new MemoryStream(zipEntry.Stream.ToArray());
                        newStream.Seek(0, SeekOrigin.Begin);
                        zipFile.AddEntry(zipEntry.FileName, newStream);
                    }

                    zipFile.Save(stream);
                    stream.Close();
                }
            }, "application/zip");

            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = pushStreamContent
            };
            //response.Headers.Add("content-disposition", $"attachment; filename={classConfiguration.Name}.zip");

            return response;
        }
        public async Task PushStreamContentWithAsyncOnStreamAvailableHandler_ExceptionsInOnStreamAvailable_AreCaught()
        {
            // Arrange
            bool              faulted   = false;
            Exception         exception = new ApplicationException();
            PushStreamContent content   = new PushStreamContent(async(s, c, tc) =>
            {
                await Task.FromResult(42);
                throw exception;
            });
            MemoryStream stream = new MemoryStream();

            try
            {
                // Act
                await content.CopyToAsync(stream);
            }
            catch (ApplicationException e)
            {
                Assert.Same(exception, e);
                faulted = true;
            }

            // Assert
            Assert.True(faulted);
        }
        static async void RunClient()
        {
            // Create an HttpClient instance
            HttpClient client = new HttpClient();

            // Create a push content so that we can use XDocument.Save to a stream
            XDocument xDoc = XDocument.Load("Sample.xml", LoadOptions.None);
            PushStreamContent xDocContent = new PushStreamContent(
                (stream, content, context) =>
                {
                    // After save we close the stream to signal that we are done writing.
                    xDoc.Save(stream);
                    stream.Close();
                },
                "application/xml");

            // Send POST request to server and wait asynchronously for the response
            Uri address = new Uri(_baseAddress, "/api/book");
            HttpResponseMessage response = await client.PostAsync(address, xDocContent);

            // Ensure we get a successful response.
            response.EnsureSuccessStatusCode();

            // Read the response using XDocument as well
            Stream responseStream = await response.Content.ReadAsStreamAsync();
            XDocument xResponseDoc = XDocument.Load(responseStream);
            Console.WriteLine("Received response: {0}", xResponseDoc.ToString());
        }
        public void Constructor_SetsDefaultMediaType()
        {
            Action <Stream, HttpContent, TransportContext> streamAction = new MockStreamAction().Action;
            PushStreamContent content = new PushStreamContent(streamAction);

            Assert.Equal(MediaTypeConstants.ApplicationOctetStreamMediaType, content.Headers.ContentType);
        }
Esempio n. 9
0
        public Task SerializeToStreamAsync_CallsAction()
        {
            // Arrange
            MemoryStream      outputStream = new MemoryStream();
            MockStreamAction  streamAction = new MockStreamAction(close: true);
            PushStreamContent content      = new PushStreamContent((Action <Stream, HttpContent, TransportContext>)streamAction.Action);

            // Act
            return(content.CopyToAsync(outputStream).ContinueWith(
                       copyTask =>
            {
                // Assert
                Assert.Equal(TaskStatus.RanToCompletion, copyTask.Status);
                Assert.True(streamAction.WasInvoked);
                Assert.Same(content, streamAction.Content);
                Assert.IsType <PushStreamContent.CompleteTaskOnCloseStream>(streamAction.OutputStream);
#if NETFX_CORE
                // In portable libraries, we expect the dispose to be called because we passed close: true above
                // on netfx45, we let the HttpContent call close on the stream.
                // CompleteTaskOnCloseStream for this reason does not dispose the innerStream when close is called
                Assert.False(outputStream.CanRead);
#else
                Assert.True(outputStream.CanRead);
#endif
            }));
        }
        public void Constructor_SetsMediaType()
        {
            Action <Stream, HttpContent, TransportContext> streamAction = new MockStreamAction().Action;
            PushStreamContent content = new PushStreamContent(streamAction, MediaTypeConstants.TextXmlMediaType);

            Assert.Equal(MediaTypeConstants.TextXmlMediaType, content.Headers.ContentType);
        }
Esempio n. 11
0
        static void Main()
        {
            var user = new User();
            user.Id = 1;
            user.Email = "*****@*****.**";
            user.Image = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            user.CreatedAt = DateTime.Now;
            user.Tags = new List<string>();
            user.Tags.Add("soccer");

            var serializer = new Serializer();

            var content = new PushStreamContent((stream, httpContent, transportContext) =>
            {
                serializer.SerializeToStream(user, stream);
                stream.Close();
            });

            var client = new HttpClient();

            var response = client.PostAsync("http://localhost:19012/api/values/myItem?replace=false", content).ConfigureAwait(false).GetAwaiter().GetResult();
            response.EnsureSuccessStatusCode();

            var nextResponse = client.GetAsync("http://localhost:19012/api/values/myItem").ConfigureAwait(false).GetAwaiter().GetResult();

            var responseStream = nextResponse.Content.ReadAsStreamAsync().ConfigureAwait(false).GetAwaiter().GetResult();

            var otherUser = serializer.DeserializeFromStream<User>(responseStream);
        }
Esempio n. 12
0
        static async Task RunClient()
        {
            // Create an HttpClient instance
            HttpClient client = new HttpClient();

            // Use chunked encoding as otherwise HttpClient would try buffering the content to 
            // figure out the content length.
            client.DefaultRequestHeaders.TransferEncodingChunked = true;

            // Create a push content so that we can use XDocument.Save to a stream
            XDocument xDoc = XDocument.Load("Sample.xml", LoadOptions.None);
            PushStreamContent xDocContent = new PushStreamContent(
                (stream, content, context) =>
                {
                    // After save we close the stream to signal that we are done writing.
                    using (stream)
                    {
                        xDoc.Save(stream);
                    }
                },
                "application/xml");

            // Send POST request to server and wait asynchronously for the response
            Uri address = new Uri(_baseAddress + "/api/book");
            HttpResponseMessage response = await client.PostAsync(address, xDocContent);

            // Ensure we get a successful response.
            response.EnsureSuccessStatusCode();

            // Read the response using XDocument as well
            Stream responseStream = await response.Content.ReadAsStreamAsync();
            XDocument xResponseDoc = XDocument.Load(responseStream);
            Console.WriteLine("Received response: {0}", xResponseDoc.ToString());
        }
        public void Constructor_SetsMediaType()
        {
            MockStreamAction  streamAction = new MockStreamAction();
            PushStreamContent content      = new PushStreamContent(streamAction.Action, MediaTypeConstants.TextXmlMediaType);

            Assert.Equal(MediaTypeConstants.TextXmlMediaType, content.Headers.ContentType);
        }
 public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
 {
     var content = new PushStreamContent(async (strm, _, __) =>
     {
         using (strm)
         {
             await _blob.DownloadToStreamAsync(strm);
         }
     });
     content.Headers.ContentType = MediaTypeHeaderValue.Parse(_blob.Properties.ContentType);
     if (!String.IsNullOrEmpty(_blob.Properties.ContentEncoding))
     {
         content.Headers.ContentEncoding.Add(_blob.Properties.ContentEncoding);
     }
     if (!String.IsNullOrEmpty(_blob.Properties.ContentLanguage))
     {
         content.Headers.ContentLanguage.Add(_blob.Properties.ContentLanguage);
     }
     var response = new HttpResponseMessage(HttpStatusCode.OK)
     {
         Content = content
     };
     if (!String.IsNullOrEmpty(_blob.Properties.ETag))
     {
         response.Headers.ETag = EntityTagHeaderValue.Parse(_blob.Properties.ETag);
     }
     return Task.FromResult(response);
 }
        public Task SerializeToStreamAsync_CallsAction()
        {
            // Arrange
            MemoryStream outputStream = new MemoryStream();
            MockStreamAction streamAction = new MockStreamAction(close: true);
            PushStreamContent content = new PushStreamContent((Action<Stream, HttpContent, TransportContext>)streamAction.Action);

            // Act
            return content.CopyToAsync(outputStream).ContinueWith(
                copyTask =>
                {
                    // Assert
                    Assert.Equal(TaskStatus.RanToCompletion, copyTask.Status);
                    Assert.True(streamAction.WasInvoked);
                    Assert.Same(content, streamAction.Content);
                    Assert.IsType<PushStreamContent.CompleteTaskOnCloseStream>(streamAction.OutputStream);
#if NETFX_CORE
                    // In portable libraries, we expect the dispose to be called because we passed close: true above
                    // on netfx45, we let the HttpContent call close on the stream.
                    // CompleteTaskOnCloseStream for this reason does not dispose the innerStream when close is called
                    Assert.False(outputStream.CanRead);
#else
                    Assert.True(outputStream.CanRead);
#endif

                });
        }
		//GET CUAHSI/HydroClient/WaterOneFlowArchive/{id}
		public async Task<HttpResponseMessage> Get(string fileName, string fileExtension)
		{
			HttpResponseMessage response = new HttpResponseMessage();
		
			//Validate/initialize input parameters
			if (String.IsNullOrWhiteSpace(fileName) || String.IsNullOrWhiteSpace(fileExtension))
			{
				response.StatusCode = HttpStatusCode.BadRequest;	//Missing/invalid parameter(s) - return early
				response.ReasonPhrase = "Invalid parameter(s)";
				return response;
			}
						
			string fileNameAndExtension = String.Format("{0}.{1}", fileName, fileExtension).ToString();
			MemoryStream ms = new MemoryStream();

			bool bFound = await _ac.RetrieveBlobAsync(fileNameAndExtension, CancellationToken.None, ms);

			if (!bFound)
			{
				response.StatusCode = HttpStatusCode.NotFound;	//Blob not found -  return early
				response.ReasonPhrase = String.Format("Requested archive file: ({0}) not found.", fileNameAndExtension.ToString());
				return response;
			}

			//Blob found - stream to client...
			ms.Seek(0, SeekOrigin.Begin);
			var pushStreamContent = new PushStreamContent((stream, content, context) =>
			{
				try
				{
					ms.CopyTo(stream);
					stream.Close(); // After save we close the stream to signal that we are done writing.
					ms.Close();
				}
				catch (Exception ex)
				{
					int n = 5;

					++n;
				}
			}, "application/zip");

			response.StatusCode = HttpStatusCode.OK;
			response.Content = pushStreamContent;
			response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
			{
				FileName = fileNameAndExtension.ToString()
			};

			return response;

		}
 public HttpResponseMessage Video(string name, string ext)
 {
     ext = ".pdb";
     name = "System.Web.Http.SelfHost";
     var currentDir=  Environment.CurrentDirectory;
     var filePath = System.IO.Path.Combine(currentDir,name);
     var video = new VideoStream(name, ext);
     var response = Request.CreateResponse();
     onStreamAvailable = video.WriteToStream;
     PushStreamContent videoContent = new PushStreamContent(onStreamAvailable, new MediaTypeHeaderValue("txt/json"));
     response.Content = videoContent;
     return response;
 }
Esempio n. 18
0
 private static PushStreamContent CreateZip(string fileName, Action<ZipArchive> onZip)
 {
     var content = new PushStreamContent((outputStream, httpContent, transportContext) =>
     {
         using (var zip = new ZipArchive(new StreamWrapper(outputStream), ZipArchiveMode.Create, leaveOpen: false))
         {
             onZip(zip);
         }
     });
     content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
     content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
     content.Headers.ContentDisposition.FileName = fileName;
     return content;
 }
        public async Task SerializeToStreamAsync_CompletesTaskOnActionException()
        {
            // Arrange
            MemoryStream      outputStream = new MemoryStream();
            MockStreamAction  streamAction = new MockStreamAction(throwException: true);
            PushStreamContent content      = new PushStreamContent((Action <Stream, HttpContent, TransportContext>)streamAction.Action);

            // Act & Assert
            await Assert.ThrowsAsync <ApplicationException>(() => content.CopyToAsync(outputStream));

            Assert.True(streamAction.WasInvoked);
            Assert.IsType <PushStreamContent.CompleteTaskOnCloseStream>(streamAction.OutputStream);
            Assert.True(outputStream.CanRead);
        }
Esempio n. 20
0
        async System.Threading.Tasks.Task UploadJsonObject1Async <T>(System.Uri uri, T data)
        {
            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                System.Net.Http.PushStreamContent content = new System.Net.Http.PushStreamContent((stream, httpContent, transportContext) =>
                {
                    Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                    using (System.IO.TextWriter writer = new System.IO.StreamWriter(stream))
                    {
                        serializer.Serialize(writer, data);
                    }
                });

                System.Net.Http.HttpResponseMessage response = await client.PostAsync(uri, content);

                response.EnsureSuccessStatusCode();
            }
        }
        public async Task SerializeToStreamAsync_CallsAction()
        {
            // Arrange
            MemoryStream      outputStream = new MemoryStream();
            MockStreamAction  streamAction = new MockStreamAction(close: true);
            PushStreamContent content      = new PushStreamContent((Action <Stream, HttpContent, TransportContext>)streamAction.Action);

            // Act
            await content.CopyToAsync(outputStream);

            // Assert
            Assert.True(streamAction.WasInvoked);
            Assert.Same(content, streamAction.Content);
            Assert.IsType <PushStreamContent.CompleteTaskOnCloseStream>(streamAction.OutputStream);

            // We don't close the underlying stream
            Assert.True(outputStream.CanRead);
        }
        public Task SerializeToStreamAsync_CompletesTaskOnActionException()
        {
            // Arrange
            MemoryStream      outputStream = new MemoryStream();
            MockStreamAction  streamAction = new MockStreamAction(throwException: true);
            PushStreamContent content      = new PushStreamContent(streamAction.Action);

            // Act
            return(content.CopyToAsync(outputStream).ContinueWith(
                       copyTask =>
            {
                // Assert
                Assert.Equal(TaskStatus.Faulted, copyTask.Status);
                Assert.IsType <ApplicationException>(copyTask.Exception.GetBaseException());
                Assert.True(streamAction.WasInvoked);
                Assert.IsType <PushStreamContent.CompleteTaskOnCloseStream>(streamAction.OutputStream);
                Assert.True(outputStream.CanRead);
            }));
        }
        public Task SerializeToStreamAsync_CallsAction()
        {
            // Arrange
            MemoryStream      outputStream = new MemoryStream();
            MockStreamAction  streamAction = new MockStreamAction(close: true);
            PushStreamContent content      = new PushStreamContent(streamAction.Action);

            // Act
            return(content.CopyToAsync(outputStream).ContinueWith(
                       copyTask =>
            {
                // Assert
                Assert.Equal(TaskStatus.RanToCompletion, copyTask.Status);
                Assert.True(streamAction.WasInvoked);
                Assert.Same(content, streamAction.Content);
                Assert.IsType <PushStreamContent.CompleteTaskOnCloseStream>(streamAction.OutputStream);
                Assert.True(outputStream.CanRead);
            }));
        }
        public Task SerializeToStreamAsync_CompletesTaskOnActionException()
        {
            // Arrange
            MemoryStream outputStream = new MemoryStream();
            MockStreamAction streamAction = new MockStreamAction(throwException: true);
            PushStreamContent content = new PushStreamContent(streamAction.Action);

            // Act
            return content.CopyToAsync(outputStream).ContinueWith(
                copyTask =>
                {
                    // Assert
                    Assert.Equal(TaskStatus.Faulted, copyTask.Status);
                    Assert.IsType<ApplicationException>(copyTask.Exception.GetBaseException());
                    Assert.True(streamAction.WasInvoked);
                    Assert.IsType<PushStreamContent.CompleteTaskOnCloseStream>(streamAction.OutputStream);
                    Assert.True(outputStream.CanRead);
                });
        }
        public Task SerializeToStreamAsync_CallsAction()
        {
            // Arrange
            MemoryStream outputStream = new MemoryStream();
            MockStreamAction streamAction = new MockStreamAction(close: true);
            PushStreamContent content = new PushStreamContent(streamAction.Action);

            // Act
            return content.CopyToAsync(outputStream).ContinueWith(
                copyTask =>
                {
                    // Assert
                    Assert.Equal(TaskStatus.RanToCompletion, copyTask.Status);
                    Assert.True(streamAction.WasInvoked);
                    Assert.Same(content, streamAction.Content);
                    Assert.IsType<PushStreamContent.CompleteTaskOnCloseStream>(streamAction.OutputStream);
                    Assert.True(outputStream.CanRead);
                });
        }
        private PushStreamContent ToGeoJsonStream(List<Permit> permits, FieldChoices choice)
        {
            PushStreamContent geoJsonContent = new PushStreamContent(
                (stream, content, context) =>
                {
                    TextWriter writer = new StreamWriter(stream);
                    JsonWriter jsonWriter = new JsonTextWriter(writer);
                    jsonWriter.Formatting = Formatting.None;
                    jsonWriter.WriteStartObject();
                    jsonWriter.WritePropertyName("type");
                    jsonWriter.WriteValue("FeatureCollection");
                    jsonWriter.WritePropertyName("features");
                    jsonWriter.WriteStartArray();

                    foreach (var permit in permits)
                    {
                        jsonWriter.WriteStartObject();
                        jsonWriter.WritePropertyName("type");
                        jsonWriter.WriteValue("Feature");
                        jsonWriter.WritePropertyName("id");
                        jsonWriter.WriteValue(permit.PermitNum);
                        jsonWriter.WritePropertyName("geometry");
                        jsonWriter.WriteStartObject();
                        jsonWriter.WritePropertyName("type");
                        jsonWriter.WriteValue("Point");
                        jsonWriter.WritePropertyName("coordinates");
                        jsonWriter.WriteStartArray();
                        jsonWriter.WriteValue(permit.Longitude);
                        jsonWriter.WriteValue(permit.Latitude);
                        jsonWriter.WriteEndArray();
                        jsonWriter.WriteEndObject();

                        if ((choice & FieldChoices.Recommended) > 0)
                        {
                            // TODO Serialize required fields
                        }

                        if ((choice & FieldChoices.Optional) > 0)
                        {
                            // TODO Serialize optional fields
                        }

                        if ((choice & FieldChoices.All) > 0)
                        {
                            // TODO Serialize all
                        }

                        jsonWriter.WriteEndObject();
                    }

                    jsonWriter.WriteEndArray();
                    jsonWriter.WriteEndObject();
                    jsonWriter.Flush();
                    jsonWriter.Close();
                });

            return geoJsonContent;
        }
Esempio n. 27
0
 public static HttpContent AsHttpContent(this IWritable w, string mediaType)
 {
     var content = new PushStreamContent((s, c, tc) => Push(w, s));
     content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);
     return content;
 }
Esempio n. 28
0
        public HttpResponseMessage Pull(long id, string connection)
        {
            Database.Subscriptions.AssertOpenSubscriptionConnection(id, connection);

            var pushStreamContent = new PushStreamContent((stream, content, transportContext) => StreamToClient(id, Database.Subscriptions, stream))
            {
                Headers =
                {
                    ContentType = new MediaTypeHeaderValue("application/json")
                    {
                        CharSet = "utf-8"
                    }
                }
            };

            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = pushStreamContent
            };
        }
Esempio n. 29
0
        private async Task<Result<Stream>> CreatePlaylist_Request(string title, string description, IEnumerable<Song> songs)
        {
            string url = AppendXt("https://play.google.com/music/services/createplaylist?format=jsarray");
            Stream response;
            try
            {
                using (var streamContent = new PushStreamContent(async (stream, httpContent, transportContext) => await Task.Run(() => CreatePlaylist_BuildJson(title, description, songs, stream)), "application/x-www-form-urlencoded"))
                {
                    response = await (await http.Client.PostAsync(url, streamContent)).Content.ReadAsStreamAsync();
                }
            }
            catch (Exception e) { return new Result<Stream>(false, null, this, e); }

            return new Result<Stream>(true, response, this);
        }
 public void Constructor_SetsMediaType()
 {
     Action<Stream, HttpContent, TransportContext> streamAction = new MockStreamAction().Action;
     PushStreamContent content = new PushStreamContent(streamAction, MediaTypeConstants.TextXmlMediaType);
     Assert.Equal(MediaTypeConstants.TextXmlMediaType, content.Headers.ContentType);
 }
 public void Constructor_SetsMediaType()
 {
     MockStreamAction streamAction = new MockStreamAction();
     PushStreamContent content = new PushStreamContent(streamAction.Action, MediaTypeConstants.TextXmlMediaType);
     Assert.Equal(MediaTypeConstants.TextXmlMediaType, content.Headers.ContentType);
 }
 public void Constructor_SetsDefaultMediaType()
 {
     MockStreamAction streamAction = new MockStreamAction();
     PushStreamContent content = new PushStreamContent(streamAction.Action);
     Assert.Equal(MediaTypeConstants.ApplicationOctetStreamMediaType, content.Headers.ContentType);
 }
 public FileResultFromStream(PushStreamContent stream, string contentType)
 {
     Stream = stream;
     ContentType = contentType;
 }
 public void Constructor_SetsDefaultMediaType()
 {
     Action<Stream, HttpContent, TransportContext> streamAction = new MockStreamAction().Action;
     PushStreamContent content = new PushStreamContent(streamAction);
     Assert.Equal(MediaTypeConstants.ApplicationOctetStreamMediaType, content.Headers.ContentType);
 }
        public HttpResponseMessage GetAllFiles()
        {
            ZipFile zip = new ZipFile();
            List<IFile> files = repository.GetAll();

            for (int i = 0; i < files.Count; i++)
            {
                byte[] contents = files[i].Contents;
                zip.AddEntry("file_" + (i + 1), contents);
            }

            PushStreamContent streamContent = new PushStreamContent((outputStream, httpContent, transportContext) =>
            {
                zip.Save(outputStream);
                outputStream.Close();
            }, "application/zip");

            return CreateDownloadResponse(streamContent, "files.zip");
        }
        public async Task PushStreamContentWithAsyncOnStreamAvailableHandler_ExceptionsInOnStreamAvailable_AreCaught()
        {
            // Arrange
            bool faulted = false;
            Exception exception = new ApplicationException();
            PushStreamContent content = new PushStreamContent(async (s, c, tc) =>
            {
                await Task.FromResult(42);
                throw exception;
            });
            MemoryStream stream = new MemoryStream();

            try
            {
                // Act
                await content.CopyToAsync(stream);
            }
            catch (ApplicationException e)
            {
                Assert.Same(exception, e);
                faulted = true;
            }

            // Assert
            Assert.True(faulted);
        }
Esempio n. 37
0
        public HttpResponseMessage TurnCameraOn()
        {
            try
            {
                var video = this.videos.All().FirstOrDefault();

                var videoStream = new VideoStream(video.Data);

                var response = Request.CreateResponse();
                var header = new MediaTypeHeaderValue("video/avi");
                var streamContent = new PushStreamContent((Action<Stream, HttpContent, TransportContext>)videoStream.WriteToStream, header);
                response.Content = streamContent;

                return response;
            }
            catch (Exception e)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, e.Message);
            }
        }
Esempio n. 38
0
        public HttpResponseMessage Get(HttpRequestMessage request, string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            Guid parsedID = Guid.Parse(id);

            HttpResponseMessage response = request.CreateResponse();
            response.Headers.Add("Access-Control-Allow-Origin", "*");
            response.Headers.Add("Cache-Control", "no-cache, must-revalidate");
            var pushContent = new PushStreamContent((Stream stream, HttpContent content, TransportContext context) =>
            {
                StreamWriter streamwriter = new StreamWriter(stream);
                var client = new Client(streamwriter, id);
                lock (_clients)
                {
                    if (_clients.ContainsKey(client.id))
                        _RemoveClient(client.id);
                    bool isAdded = _clients.TryAdd(client.id, client);
                    if (isAdded)
                        ++_clientCount;
                }
                _CheckCleanUpTimer();
            }, "text/event-stream");
            response.Content = pushContent;
            return response;
        }
Esempio n. 39
0
        private static void UsePushStreamContent()
        {
            XNamespace ns = "http://schemas.microsoft.com/2003/10/Serialization/";
            var xml = new XElement(ns + "string", "Hello");

            var content = new PushStreamContent((stream, cont, ctx) =>
            {
                using (var writer = XmlWriter.Create(stream,
                    new XmlWriterSettings { CloseOutput = true }))
                // Write xml to the request stream
                { xml.WriteTo(writer); }
            });
            content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
            var client = new HttpClient();
            var response = client.PostAsync(_greetingsBaseUri, content).Result;
            response.EnsureSuccessStatusCode();
        }
Esempio n. 40
-1
 public static PushStreamContent Create(string fileName, ITracer tracer, Action<ZipArchive> onZip)
 {
     var content = new PushStreamContent((outputStream, httpContent, transportContext) =>
     {
         using (tracer.Step("ZipStreamContent.OnZip"))
         {
             try
             {
                 using (var zip = new ZipArchive(new StreamWrapper(outputStream), ZipArchiveMode.Create, leaveOpen: false))
                 {
                     onZip(zip);
                 }
             }
             catch (Exception ex)
             {
                 tracer.TraceError(ex);
                 throw;
             }
         }
     });
     content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
     content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
     content.Headers.ContentDisposition.FileName = fileName;
     return content;
 }