public async Task RequestContentIsLoggedAsText()
        {
            var response      = new MockResponse(500);
            var mockTransport = new MockTransport(response);

            var    pipeline = new HttpPipeline(mockTransport, new [] { LoggingPolicy.Shared });
            string requestId;

            using (HttpPipelineRequest request = pipeline.CreateRequest())
            {
                request.SetRequestLine(HttpPipelineMethod.Get, new Uri("https://contoso.a.io"));
                request.Content = HttpPipelineRequestContent.Create(Encoding.UTF8.GetBytes("Hello world"));
                request.AddHeader(new HttpHeader("Content-Type", "text/json"));
                requestId = request.RequestId;

                await pipeline.SendRequestAsync(request, CancellationToken.None);
            }

            var e = _listener.SingleEventById(RequestContentTextEvent);

            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("RequestContentText", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual("Hello world", e.GetProperty <string>("content"));

            CollectionAssert.IsEmpty(_listener.EventsById(ResponseContentEvent));
        }
        private static async Task <HttpPipelineResponse> SendRequest(bool isSeekable, Action <MockResponse> setupRequest = null)
        {
            var mockResponse = new MockResponse(500);

            byte[] responseContent = Encoding.UTF8.GetBytes("Hello world");
            if (isSeekable)
            {
                mockResponse.ResponseContentStream = new MemoryStream(responseContent);
            }
            else
            {
                mockResponse.ResponseContentStream = new NonSeekableMemoryStream(responseContent);
            }
            setupRequest?.Invoke(mockResponse);

            var mockTransport = new MockTransport(mockResponse);
            var pipeline      = new HttpPipeline(mockTransport, new[] { LoggingPolicy.Shared });

            using (HttpPipelineRequest request = pipeline.CreateRequest())
            {
                request.SetRequestLine(HttpPipelineMethod.Get, new Uri("https://contoso.a.io"));

                Response response = await pipeline.SendRequestAsync(request, CancellationToken.None);

                var buffer = new byte[11];
                Assert.AreEqual(6, await response.ContentStream.ReadAsync(buffer, 5, 6));
                Assert.AreEqual(5, await response.ContentStream.ReadAsync(buffer, 6, 5));
                Assert.AreEqual(0, await response.ContentStream.ReadAsync(buffer, 0, 5));

                return(mockResponse);
            }
        }
 public void Request(HttpPipelineRequest request)
 {
     if (IsEnabled(EventLevel.Informational, EventKeywords.None))
     {
         Request(request.RequestId, request.Method.ToString().ToUpperInvariant(), request.UriBuilder.ToString(), FormatHeaders(request.Headers));
     }
 }
 public async Task RequestContentTextAsync(HttpPipelineRequest request, Encoding encoding, CancellationToken cancellationToken)
 {
     if (IsEnabled(EventLevel.Verbose, EventKeywords.None))
     {
         RequestContentText(request.RequestId, await FormatContentStringAsync(request.Content, encoding, cancellationToken));
     }
 }
        internal static void AddAuthenticationHeaders(HttpPipelineRequest request, Uri uri, HttpVerb method, ReadOnlyMemory <byte> content, byte[] secret, string credential)
        {
            string contentHash = null;

            using (var alg = SHA256.Create())
            {
                // TODO (pri 3): ToArray should nopt be called here. Instead, TryGetArray, or PipelineContent should do hashing on the fly
                contentHash = Convert.ToBase64String(alg.ComputeHash(content.ToArray()));
            }

            using (var hmac = new HMACSHA256(secret))
            {
                var host         = uri.Host;
                var pathAndQuery = uri.PathAndQuery;

                string         verb          = method.ToString().ToUpper();
                DateTimeOffset utcNow        = DateTimeOffset.UtcNow;
                var            utcNowString  = utcNow.ToString("r");
                var            stringToSign  = $"{verb}\n{pathAndQuery}\n{utcNowString};{host};{contentHash}";
                var            signature     = Convert.ToBase64String(hmac.ComputeHash(Encoding.ASCII.GetBytes(stringToSign))); // Calculate the signature
                string         signedHeaders = "date;host;x-ms-content-sha256";                                                 // Semicolon separated header names

                // TODO (pri 3): should date header writing be moved out from here?
                request.AddHeader("Date", utcNowString);
                request.AddHeader("x-ms-content-sha256", contentHash);
                request.AddHeader("Authorization", $"HMAC-SHA256 Credential={credential}, SignedHeaders={signedHeaders}, Signature={signature}");
            }
        }
Exemplo n.º 6
0
        public async Task OriginalContentStreamIsReturnedIfNotAsync()
        {
            var content = new AsyncContent()
            {
                MemoryStream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 })
            };
            var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = content
            };
            var mockHandler = new MockHttpClientHandler(httpRequestMessage => Task.FromResult(httpResponseMessage));

            var transport = new HttpClientTransport(new HttpClient(mockHandler));
            HttpPipelineRequest request = transport.CreateRequest(null);

            request.SetRequestLine(HttpPipelineMethod.Get, new Uri("http://example.com:340"));

            HttpPipelineResponse response = await ExecuteRequest(request, transport);

            byte[] data = new byte[5];

            content.CreateContentReadStreamAsyncCompletionSource.SetResult(null);
            Stream stream = response.ResponseContentStream;

            Assert.AreSame(content.MemoryStream, stream);
        }
Exemplo n.º 7
0
 protected static Task <Response> SendGetRequest(HttpPipelineTransport transport, HttpPipelinePolicy policy)
 {
     using (HttpPipelineRequest request = transport.CreateRequest(null))
     {
         request.Method = HttpPipelineMethod.Get;
         request.Uri    = new Uri("http://example.com");
         var pipeline = new HttpPipeline(transport, new [] { policy });
         return(pipeline.SendRequestAsync(request, CancellationToken.None));
     }
 }
        private static Task <Response> SendTestRequestAsync(HttpPipeline pipeline, long offset)
        {
            using (HttpPipelineRequest request = pipeline.CreateRequest())
            {
                request.SetRequestLine(HttpPipelineMethod.Get, new Uri("http://example.com"));
                request.AddHeader("Range", "bytes=" + offset);

                return(pipeline.SendRequestAsync(request, CancellationToken.None));
            }
        }
Exemplo n.º 9
0
        protected static async Task <HttpPipelineResponse> ExecuteRequest(HttpPipelineRequest request, HttpClientTransport transport)
        {
            using (var message = new HttpPipelineMessage(CancellationToken.None)
            {
                Request = request
            })
            {
                await transport.ProcessAsync(message);

                return(message.Response);
            }
        }
Exemplo n.º 10
0
        public async Task NonSeekableResponsesErrorsAreLoggedInBlocks()
        {
            var mockResponse = new MockResponse(500);

            mockResponse.ResponseContentStream = new NonSeekableMemoryStream(new byte[] { 6, 7, 8, 9, 0 });
            var mockTransport = new MockTransport(mockResponse);

            var    pipeline = new HttpPipeline(mockTransport, new [] { LoggingPolicy.Shared });
            string requestId;

            using (HttpPipelineRequest request = pipeline.CreateRequest())
            {
                request.SetRequestLine(HttpPipelineMethod.Get, new Uri("https://contoso.a.io"));
                requestId = request.RequestId;

                Response response = await pipeline.SendRequestAsync(request, CancellationToken.None);

                var buffer = new byte[10];
                Assert.AreEqual(3, await response.ContentStream.ReadAsync(buffer, 5, 3));
                Assert.AreEqual(2, await response.ContentStream.ReadAsync(buffer, 8, 2));
                Assert.AreEqual(0, await response.ContentStream.ReadAsync(buffer, 0, 5));
            }

            EventWrittenEventArgs[] errorContentEvents = _listener.EventsById(ErrorResponseContentBlockEvent).ToArray();

            Assert.AreEqual(2, errorContentEvents.Length);

            Assert.AreEqual(EventLevel.Informational, errorContentEvents[0].Level);
            Assert.AreEqual("ErrorResponseContentBlock", errorContentEvents[0].EventName);
            Assert.AreEqual(requestId, errorContentEvents[0].GetProperty <string>("requestId"));
            Assert.AreEqual(0, errorContentEvents[0].GetProperty <int>("blockNumber"));
            CollectionAssert.AreEqual(new byte[] { 6, 7, 8 }, errorContentEvents[0].GetProperty <byte[]>("content"));

            Assert.AreEqual(EventLevel.Informational, errorContentEvents[1].Level);
            Assert.AreEqual("ErrorResponseContentBlock", errorContentEvents[1].EventName);
            Assert.AreEqual(requestId, errorContentEvents[1].GetProperty <string>("requestId"));
            Assert.AreEqual(1, errorContentEvents[1].GetProperty <int>("blockNumber"));
            CollectionAssert.AreEqual(new byte[] { 9, 0 }, errorContentEvents[1].GetProperty <byte[]>("content"));

            CollectionAssert.IsEmpty(_listener.EventsById(ErrorResponseContentEvent));
        }
Exemplo n.º 11
0
        public async Task ContentStreamIsReturnedSynchronously()
        {
            var content = new AsyncContent()
            {
                MemoryStream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 })
            };
            var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = content
            };
            var mockHandler = new MockHttpClientHandler(httpRequestMessage => Task.FromResult(httpResponseMessage));

            var transport = new HttpClientTransport(new HttpClient(mockHandler));
            HttpPipelineRequest request = transport.CreateRequest(null);

            request.SetRequestLine(HttpPipelineMethod.Get, new Uri("http://example.com:340"));

            HttpPipelineResponse response = await ExecuteRequest(request, transport);

            byte[]     data      = new byte[5];
            Stream     stream    = response.ResponseContentStream;
            Task <int> firstRead = stream.ReadAsync(data, 0, 5);

            Assert.False(firstRead.IsCompleted);

            content.CreateContentReadStreamAsyncCompletionSource.SetResult(null);
            Assert.AreEqual(5, await firstRead);

            // Exercise stream features
            stream.Position = 3;
            stream.Seek(-1, SeekOrigin.Current);
            var secondReadLength = await stream.ReadAsync(data, 0, 5);

            Assert.AreEqual(3, secondReadLength);
            Assert.False(stream.CanWrite);
            Assert.True(stream.CanSeek);
            Assert.True(stream.CanRead);
            Assert.Throws <NotSupportedException>(() => stream.Write(null, 0, 0));
            Assert.Throws <NotSupportedException>(() => stream.SetLength(5));
        }
        // TODO (pri 3): do all the methods that call this accept revisions?
        static void AddOptionsHeaders(RequestOptions options, HttpPipelineRequest request)
        {
            if (options == null)
            {
                return;
            }

            if (options.ETag.IfMatch != default)
            {
                request.AddHeader(IfMatchName, $"\"{options.ETag.IfMatch}\"");
            }

            if (options.ETag.IfNoneMatch != default)
            {
                request.AddHeader(IfNoneMatch, $"\"{options.ETag.IfNoneMatch}\"");
            }

            if (options.Revision.HasValue)
            {
                var dateTime = options.Revision.Value.UtcDateTime.ToString(AcceptDateTimeFormat);
                request.AddHeader(AcceptDatetimeHeader, dateTime);
            }
        }
Exemplo n.º 13
0
        public async Task SendingRequestProducesEvents()
        {
            var response = new MockResponse(500);

            response.SetContent(new byte[] { 6, 7, 8, 9, 0 });
            response.AddHeader(new HttpHeader("Custom-Response-Header", "Improved value"));

            var mockTransport = new MockTransport(response);

            var    pipeline = new HttpPipeline(mockTransport, new [] { LoggingPolicy.Shared });
            string requestId;

            using (HttpPipelineRequest request = pipeline.CreateRequest())
            {
                request.SetRequestLine(HttpPipelineMethod.Get, new Uri("https://contoso.a.io"));
                request.AddHeader("Date", "3/26/2019");
                request.AddHeader("Custom-Header", "Value");
                request.Content = HttpPipelineRequestContent.Create(new byte[] { 1, 2, 3, 4, 5 });
                requestId       = request.RequestId;

                await pipeline.SendRequestAsync(request, CancellationToken.None);
            }

            var e = _listener.SingleEventById(RequestEvent);

            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("Request", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual("https://contoso.a.io/", e.GetProperty <string>("uri"));
            Assert.AreEqual("GET", e.GetProperty <string>("method"));
            StringAssert.Contains($"Date:3/26/2019{Environment.NewLine}", e.GetProperty <string>("headers"));
            StringAssert.Contains($"Custom-Header:Value{Environment.NewLine}", e.GetProperty <string>("headers"));

            e = _listener.SingleEventById(RequestContentEvent);
            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("RequestContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4, 5 }, e.GetProperty <byte[]>("content"));

            e = _listener.SingleEventById(ResponseEvent);
            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("Response", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual(e.GetProperty <int>("status"), 500);
            StringAssert.Contains($"Custom-Response-Header:Improved value{Environment.NewLine}", e.GetProperty <string>("headers"));

            e = _listener.SingleEventById(ResponseContentEvent);
            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("ResponseContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 6, 7, 8, 9, 0 }, e.GetProperty <byte[]>("content"));

            e = _listener.SingleEventById(ErrorResponseEvent);
            Assert.AreEqual(EventLevel.Error, e.Level);
            Assert.AreEqual("ErrorResponse", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual(e.GetProperty <int>("status"), 500);
            StringAssert.Contains($"Custom-Response-Header:Improved value{Environment.NewLine}", e.GetProperty <string>("headers"));

            e = _listener.SingleEventById(ErrorResponseContentEvent);
            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("ErrorResponseContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 6, 7, 8, 9, 0 }, e.GetProperty <byte[]>("content"));
        }
 public void RequestRetrying(HttpPipelineRequest request, int retryNumber)
 {
     RequestRetrying(request.RequestId, retryNumber);
 }
 static void AddClientRequestID(HttpPipelineRequest request)
 {
     request.AddHeader(ClientRequestIdHeader, Guid.NewGuid().ToString());
     request.AddHeader(EchoClientRequestId, "true");
 }
 public void ProcessingRequest(HttpPipelineRequest request)
 => ProcessingRequest(request.ToString());