Ejemplo n.º 1
0
        async Task WontBufferInMemoryIfContentLengthHeaderIsSet()
        {
            var header = new HttpResponseHeader();

            header["content-length"] = "100";

            var mockResponse = new Mock <IHttpResponse>();

            mockResponse.Setup(inst => inst.Header).Returns(header);

            var mockStream = new MemoryStream();
            var body       = new HttpResponseBody(
                mockStream,
                TcpSettings.Default,
                HttpSettings.Default,
                mockResponse.Object
                );

            // Write 99 at the end
            await body.WriteAsync(new byte[] { 0x99 }, 1024);

            // Now verify that the response stream got 99 at the end,
            // as we set the content-length, data must go directly to the response stream
            // and won't buffered in memory.
            Assert.True(mockStream.ToArray().Last() == 0x99);
        }
Ejemplo n.º 2
0
        static async Task PerformWriteIntoBody(
            bool endResponseBodyByDisposingIt,
            HttpSettings httpSettings,
            MemoryStream senderData,
            Mock <IHttpResponse> mockHttpResponse,
            MemoryStream receiverData,
            int writeBufferSize = 4096)
        {
            var body = new HttpResponseBody(
                receiverData,
                TcpSettings.Default,
                httpSettings,
                mockHttpResponse.Object);

            await senderData.CopyToAsync(body, writeBufferSize);

            if (endResponseBodyByDisposingIt)
            {
                body.Dispose();
            }
            else
            {
                await body.CompleteAsync();
            }
        }
Ejemplo n.º 3
0
        async Task LogWarningIfWriteLessThanPromisedEncodingOnDisposeMethod()
        {
            // Mockup
            MockUp(10000,
                   out HttpSettings httpSettings,
                   out MemoryStream senderData,
                   out Mock <IHttpResponse> mockHttpResponse,
                   out MemoryStream receiverData,
                   out HttpResponseHeader responseHeader);
            var logger = new Mock <ILogger>();

            responseHeader["content-length"] = 10001.ToString(CultureInfo.InvariantCulture);

            // Begin test
            using (var body = new HttpResponseBody(
                       receiverData,
                       TcpSettings.Default,
                       httpSettings,
                       mockHttpResponse.Object,
                       logger.Object))
            {
                await senderData.CopyToAsync(body);
            }
            // Check logger
            logger.Verify(
                l => l.Warn(It.IsAny <string>(), It.Is <Exception>(e => e is InvalidOperationException)),
                Times.Once);
        }
Ejemplo n.º 4
0
        async Task UseChunkedEncodingWhenExplicitlySetInHeader()
        {
            // Mockup
            MockUp(2000 /* We'll send only 2000 bytes so it won't overflow
                         * the internal buffer, and won't force chunked encoder tobe used. */,
                   out HttpSettings httpSettings,
                   out MemoryStream senderData,
                   out Mock <IHttpResponse> mockHttpResponse,
                   out MemoryStream receiverData,
                   out HttpResponseHeader responseHeader);

            responseHeader[HttpKeys.TransferEncoding] = "chunked";

            // Begin test
            using (var body = new HttpResponseBody(
                       receiverData,
                       TcpSettings.Default,
                       httpSettings,
                       mockHttpResponse.Object))
            {
                await senderData.CopyToAsync(body, 4096);
            }

            // Test decode
            await VerifyReceivedChunkedMessage(senderData, receiverData);
        }
Ejemplo n.º 5
0
        public static async Task <IActionResult> Post(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "book")] HttpRequestMessage req,
            [Inject] IBookService bookservice, [Inject] IMetaDataService metaDataService, [Inject] IValidator <Book> bookValidator)
        {
            HttpResponseBody <BookModel> body = await req.GetBodyAsync <BookModel>();

            // Convert DTO to Entity.
            Book entity = Mapper.Map <Book>(body.Value);

            entity.CreatedDate = DateTime.UtcNow;
            entity.UpdatedDate = DateTime.UtcNow;

            var validationResult = bookValidator.Validate(body.Value);

            if (!validationResult.IsValid)
            {
                return(new BadRequestObjectResult(validationResult));
            }

            // Save entity in db, can also check GUID is unique or not, because GUID is not cryptographically unique, for now it is fine.
            await bookservice.InsertBookAsync(entity);

            // If we comes here, means Success
            return(new CreatedResult($"/book/{entity.BookId}", Mapper.Map <BookDTO>(entity)));
        }
Ejemplo n.º 6
0
        public static async Task <IActionResult> Patch(
            [HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = "book/{id}")] HttpRequestMessage req,
            [Inject] IBookService bookservice, [Inject] IMetaDataService metaDataService, string id, [Inject] IValidator <Book> bookValidator)
        {
            Guid bookUniqueIdentifier;

            if (!Guid.TryParse(id, out bookUniqueIdentifier))
            {
                return(new BadRequestObjectResult(new Error("400", $"Invalid book id supplied. Book id: {id}.")));
            }

            Book book = await bookservice.GetBookAsync(id);

            if (book == null)
            {
                return(new NotFoundObjectResult(new Error("404", $"Cannot find book with id {id}.")));
            }

            HttpResponseBody <JsonPatchDocument <Book> > body = await req.GetBodyAsync <JsonPatchDocument <Book> >();

            body.Value.ApplyTo(book);
            book.UpdatedDate = DateTime.UtcNow;

            var validationResult = bookValidator.Validate(book);

            if (!validationResult.IsValid)
            {
                return(new BadRequestObjectResult(validationResult));
            }
            await bookservice.UpdateBookAsync(book);

            return(new OkObjectResult("Updated"));
        }
Ejemplo n.º 7
0
        public void can_get_raw_xml_document()
        {
            var context = StubHttpContext.Empty();

            var serializer = new XmlSerializer(typeof(MyMessage));

            serializer.Serialize(context.Response.Body, new MyMessage {
                Age = 3, Name = "Declan"
            });

            context.Response.Body.Position = 0;

            var body = new HttpResponseBody(null, context);

            var root = body.ReadAsXml();

            root.DocumentElement["Name"].InnerText.ShouldBe("Declan");
        }
Ejemplo n.º 8
0
        public void can_parse_xml()
        {
            var context = StubHttpContext.Empty();

            var serializer = new XmlSerializer(typeof(MyMessage));

            serializer.Serialize(context.Response.Body, new MyMessage {
                Age = 3, Name = "Declan"
            });

            context.Response.Body.Position = 0;

            var body = new HttpResponseBody(null, context);

            var message = body.ReadAsXml <MyMessage>();

            message.Name.ShouldBe("Declan");
        }
Ejemplo n.º 9
0
        public static async Task <HttpResponseBody <T> > GetBodyAsync <T>(this HttpRequest request)
        {
            var body       = new HttpResponseBody <T>();
            var bodyString = await request.ReadAsStringAsync();

            var results = new List <ValidationResult>();

            try
            {
                body.Value   = JsonConvert.DeserializeObject <T>(bodyString);
                body.IsValid = Validator.TryValidateObject(body.Value, new ValidationContext(body.Value, null, null), results, true);
            }
            catch (System.Exception ex)
            {
                results.Add(new ValidationResult($"Invalid Json was sent: {ex.Message}"));
            }
            body.ValidationResults = results;

            return(body);
        }
Ejemplo n.º 10
0
        async Task CanUseDisposeAndCompleteTogether()
        {
            // Mockup
            MockUp(10000,
                   out HttpSettings httpSettings,
                   out MemoryStream senderData,
                   out Mock <IHttpResponse> mockHttpResponse,
                   out MemoryStream receiverData,
                   out HttpResponseHeader responseHeader);

            // Begin test
            using (var body = new HttpResponseBody(
                       receiverData,
                       TcpSettings.Default,
                       httpSettings,
                       mockHttpResponse.Object))
            {
                await senderData.CopyToAsync(body, 4096);

                await body.CompleteAsync();
            }

            await VerifyReceivedChunkedMessage(senderData, receiverData);
        }