Exemple #1
0
        public void SendAsync_ExpectedDiagnosticExceptionLogging()
        {
            RemoteInvoke(() =>
            {
                bool exceptionLogged           = false;
                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.Response"))
                    {
                        Assert.NotNull(kvp.Value);
                        GetPropertyValueFromAnonymousTypeInstance <Exception>(kvp.Value, "Exception");
                        var requestStatus = GetPropertyValueFromAnonymousTypeInstance <TaskStatus>(kvp.Value, "RequestTaskStatus");
                        Assert.Equal(TaskStatus.Faulted, requestStatus);

                        exceptionLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable();
                    using (var client = new HttpClient())
                    {
                        Assert.ThrowsAsync <HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
                    }
                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    WaitForTrue(() => exceptionLogged, TimeSpan.FromSeconds(1),
                                "Exception was not logged within 1 second timeout.");
                    diagnosticListenerObserver.Disable();
                }

                return(SuccessExitCode);
            }).Dispose();
        }
        public void SendAsync_NullRequest_ThrowsArgumentNullException()
        {
            RemoteInvoke(async() =>
            {
                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(null);
                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable();

                    using (MyHandler handler = new MyHandler())
                    {
                        // Getting the Task first from the .SendAsync() call also tests
                        // that the exception comes from the async Task path.
                        Task t = handler.SendAsync(null);
                        if (PlatformDetection.IsUap)
                        {
                            await Assert.ThrowsAsync <HttpRequestException>(() => t);
                        }
                        else
                        {
                            await Assert.ThrowsAsync <ArgumentNullException>(() => t);
                        }
                    }
                }

                diagnosticListenerObserver.Disable();
                return(SuccessExitCode);
            }).Dispose();
        }
Exemple #3
0
        public void SendAsync_ExpectedDiagnosticSynchronousExceptionActivityLogging()
        {
            RemoteInvoke(useSocketsHttpHandlerString =>
            {
                bool exceptionLogged           = false;
                bool activityStopLogged        = false;
                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
                    {
                        Assert.NotNull(kvp.Value);
                        GetPropertyValueFromAnonymousTypeInstance <HttpRequestMessage>(kvp.Value, "Request");
                        var requestStatus = GetPropertyValueFromAnonymousTypeInstance <TaskStatus>(kvp.Value, "RequestTaskStatus");
                        Assert.Equal(TaskStatus.Faulted, requestStatus);

                        activityStopLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Exception"))
                    {
                        Assert.NotNull(kvp.Value);
                        GetPropertyValueFromAnonymousTypeInstance <Exception>(kvp.Value, "Exception");

                        exceptionLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable();
                    using (HttpClientHandler handler = CreateHttpClientHandler(useSocketsHttpHandlerString))
                        using (HttpClient client = new HttpClient(handler))
                        {
                            if (bool.Parse(useSocketsHttpHandlerString))
                            {
                                // Forces a synchronous exception for SocketsHttpHandler
                                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"http://{Guid.NewGuid()}.com");
                                request.Version            = new Version(0, 0);

                                Assert.ThrowsAsync <NotSupportedException>(() => client.SendAsync(request)).Wait();
                            }
                            else
                            {
                                // Forces a synchronous exception for WinHttpHandler
                                handler.UseCookies      = true;
                                handler.CookieContainer = null;

                                Assert.ThrowsAsync <InvalidOperationException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
                            }
                        }
                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1),
                                "Response with exception was not logged within 1 second timeout.");
                    Assert.True(exceptionLogged, "Exception was not logged");
                    diagnosticListenerObserver.Disable();
                }

                return(SuccessExitCode);
            }, UseSocketsHttpHandler.ToString()).Dispose();
        }
        public void SendAsync_ExpectedDiagnosticSourceLogging()
        {
            RemoteInvoke(() =>
            {
                bool requestLogged  = false;
                Guid requestGuid    = Guid.Empty;
                bool responseLogged = false;
                Guid responseGuid   = Guid.Empty;

                bool exceptionLogged           = false;
                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.Request"))
                    {
                        Assert.NotNull(kvp.Value);
                        GetPropertyValueFromAnonymousTypeInstance <HttpRequestMessage>(kvp.Value, "Request");
                        requestGuid   = GetPropertyValueFromAnonymousTypeInstance <Guid>(kvp.Value, "LoggingRequestId");
                        requestLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Response"))
                    {
                        Assert.NotNull(kvp.Value);

                        GetPropertyValueFromAnonymousTypeInstance <HttpResponseMessage>(kvp.Value, "Response");
                        responseGuid      = GetPropertyValueFromAnonymousTypeInstance <Guid>(kvp.Value, "LoggingRequestId");
                        var requestStatus = GetPropertyValueFromAnonymousTypeInstance <TaskStatus>(kvp.Value, "RequestTaskStatus");
                        Assert.Equal(TaskStatus.RanToCompletion, requestStatus);

                        responseLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Exception"))
                    {
                        exceptionLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable();
                    using (var client = new HttpClient())
                    {
                        var response = client.GetAsync(Configuration.Http.RemoteEchoServer).Result;
                    }

                    Assert.True(requestLogged, "Request was not logged.");
                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1), "Response was not logged within 1 second timeout.");
                    Assert.Equal(requestGuid, responseGuid);
                    Assert.False(exceptionLogged, "Exception was logged for successful request");
                    diagnosticListenerObserver.Disable();
                }

                return(SuccessExitCode);
            }).Dispose();
        }
Exemple #5
0
        public void SendAsync_ExpectedDiagnosticSourceNewAndDeprecatedEventsLogging()
        {
            RemoteInvoke(() =>
            {
                bool requestLogged       = false;
                bool responseLogged      = false;
                bool activityStartLogged = false;
                bool activityStopLogged  = false;

                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.Request"))
                    {
                        requestLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Response"))
                    {
                        responseLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
                    {
                        activityStartLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
                    {
                        activityStopLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable();
                    using (var client = new HttpClient())
                    {
                        client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
                    }

                    Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged.");
                    Assert.True(requestLogged, "Request was not logged.");
                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout.");
                    Assert.True(responseLogged, "Response was not logged.");
                    diagnosticListenerObserver.Disable();
                }

                return(SuccessExitCode);
            }).Dispose();
        }
        public void SendAsync_ExpectedDiagnosticSourceActivityLoggingDoesNotOverwriteHeader()
        {
            RemoteInvoke(useSocketsHttpHandlerString =>
            {
                bool activityStartLogged = false;
                bool activityStopLogged  = false;

                Activity parentActivity = new Activity("parent");
                parentActivity.AddBaggage("correlationId", Guid.NewGuid().ToString());
                parentActivity.Start();

                string customRequestIdHeader   = "|foo.bar.";
                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
                    {
                        var request = GetPropertyValueFromAnonymousTypeInstance <HttpRequestMessage>(kvp.Value, "Request");
                        request.Headers.Add("Request-Id", customRequestIdHeader);

                        activityStartLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
                    {
                        var request = GetPropertyValueFromAnonymousTypeInstance <HttpRequestMessage>(kvp.Value, "Request");
                        Assert.Single(request.Headers.GetValues("Request-Id"));
                        Assert.Equal(customRequestIdHeader, request.Headers.GetValues("Request-Id").Single());
                        activityStopLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable();
                    using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString))
                    {
                        client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
                    }

                    Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged.");

                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout.");
                    diagnosticListenerObserver.Disable();
                }

                return(SuccessExitCode);
            }, UseSocketsHttpHandler.ToString()).Dispose();
        }
Exemple #7
0
        public void SendAsync_ExpectedDiagnosticSourceUrlFilteredActivityLogging()
        {
            RemoteInvoke(() =>
            {
                bool activityStartLogged = false;
                bool activityStopLogged  = false;

                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
                    {
                        activityStartLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
                    {
                        activityStopLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable((s, r, _) =>
                    {
                        if (s.StartsWith("System.Net.Http.HttpRequestOut"))
                        {
                            var request = r as HttpRequestMessage;
                            if (request != null)
                            {
                                return(!request.RequestUri.Equals(Configuration.Http.RemoteEchoServer));
                            }
                        }
                        return(true);
                    });
                    using (var client = new HttpClient())
                    {
                        var response = client.GetAsync(Configuration.Http.RemoteEchoServer).Result;
                    }
                    Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while URL disabled.");
                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while URL disabled.");
                    diagnosticListenerObserver.Disable();
                }

                return(SuccessExitCode);
            }).Dispose();
        }
Exemple #8
0
        public void SendAsync_ExpectedDiagnosticSourceLogging()
        {
            bool requestLogged  = false;
            Guid requestGuid    = Guid.Empty;
            bool responseLogged = false;
            Guid responseGuid   = Guid.Empty;

            var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(
                kvp =>
            {
                if (kvp.Key.Equals("System.Net.Http.Request"))
                {
                    Assert.NotNull(kvp.Value);
                    GetPropertyValueFromAnonymousTypeInstance <HttpRequestMessage>(kvp.Value, "Request");
                    requestGuid = GetPropertyValueFromAnonymousTypeInstance <Guid>(kvp.Value, "LoggingRequestId");

                    requestLogged = true;
                }
                else if (kvp.Key.Equals("System.Net.Http.Response"))
                {
                    Assert.NotNull(kvp.Value);

                    GetPropertyValueFromAnonymousTypeInstance <HttpResponseMessage>(kvp.Value, "Response");
                    responseGuid = GetPropertyValueFromAnonymousTypeInstance <Guid>(kvp.Value, "LoggingRequestId");

                    responseLogged = true;
                }
            });

            using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
            {
                diagnosticListenerObserver.Enable();
                using (var client = new HttpClient())
                {
                    var response = client.GetAsync(HttpTestServers.RemoteEchoServer).Result;
                }

                Assert.True(requestLogged, "Request was not logged.");
                // Poll with a timeout since logging response is not synchronized with returning a response.
                WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1), "Response was not logged within 1 second timeout.");
                Assert.Equal(requestGuid, responseGuid);
                diagnosticListenerObserver.Disable();
            }
        }
Exemple #9
0
        public void SendAsync_ExpectedDiagnosticCancelledActivityLogging()
        {
            RemoteInvoke(() =>
            {
                bool cancelLogged = false;
                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key == "System.Net.Http.HttpRequestOut.Stop")
                    {
                        Assert.NotNull(kvp.Value);
                        GetPropertyValueFromAnonymousTypeInstance <HttpRequestMessage>(kvp.Value, "Request");
                        var status = GetPropertyValueFromAnonymousTypeInstance <TaskStatus>(kvp.Value, "RequestTaskStatus");
                        Assert.Equal(TaskStatus.Canceled, status);
                        cancelLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable();
                    using (var client = new HttpClient())
                    {
                        LoopbackServer.CreateServerAsync(async(server, url) =>
                        {
                            CancellationTokenSource tcs = new CancellationTokenSource();
                            Task request = LoopbackServer.AcceptSocketAsync(server,
                                                                            (s, stream, reader, writer) =>
                            {
                                tcs.Cancel();
                                return(LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer));
                            });
                            Task response = client.GetAsync(url, tcs.Token);
                            await Assert.ThrowsAnyAsync <Exception>(() => Task.WhenAll(response, request));
                        }).Wait();
                    }
                }
                // Poll with a timeout since logging response is not synchronized with returning a response.
                WaitForTrue(() => cancelLogged, TimeSpan.FromSeconds(1),
                            "Cancellation was not logged within 1 second timeout.");
                diagnosticListenerObserver.Disable();

                return(SuccessExitCode);
            }).Dispose();
        }
Exemple #10
0
        public void SendAsync_ExpectedDiagnosticCancelledActivityLogging()
        {
            RemoteInvoke(useSocketsHttpHandlerString =>
            {
                bool cancelLogged = false;
                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key == "System.Net.Http.HttpRequestOut.Stop")
                    {
                        Assert.NotNull(kvp.Value);
                        GetPropertyValueFromAnonymousTypeInstance <HttpRequestMessage>(kvp.Value, "Request");
                        var status = GetPropertyValueFromAnonymousTypeInstance <TaskStatus>(kvp.Value, "RequestTaskStatus");
                        Assert.Equal(TaskStatus.Canceled, status);
                        Volatile.Write(ref cancelLogged, true);
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable();
                    using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString))
                    {
                        LoopbackServer.CreateServerAsync(async(server, url) =>
                        {
                            CancellationTokenSource tcs = new CancellationTokenSource();
                            Task request = server.AcceptConnectionAsync(connection =>
                            {
                                tcs.Cancel();
                                return(connection.ReadRequestHeaderAndSendResponseAsync());
                            });
                            Task response = client.GetAsync(url, tcs.Token);
                            await Assert.ThrowsAnyAsync <Exception>(() => TestHelper.WhenAllCompletedOrAnyFailed(response, request));
                        }).Wait();
                    }
                }
                // Poll with a timeout since logging response is not synchronized with returning a response.
                WaitForTrue(() => Volatile.Read(ref cancelLogged), TimeSpan.FromSeconds(1),
                            "Cancellation was not logged within 1 second timeout.");
                diagnosticListenerObserver.Disable();

                return(SuccessExitCode);
            }, UseSocketsHttpHandler.ToString()).Dispose();
        }
Exemple #11
0
        public void SendAsync_NullRequest_ThrowsArgumentNullException()
        {
            RemoteInvoke(() =>
            {
                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(null);
                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable();

                    using (MyHandler handler = new MyHandler())
                    {
                        Assert.ThrowsAsync <ArgumentNullException>(() => handler.SendAsync(null)).Wait();
                    }
                }

                diagnosticListenerObserver.Disable();
                return(SuccessExitCode);
            }).Dispose();
        }
Exemple #12
0
        public void SendAsync_ExpectedDiagnosticExceptionOnlyActivityLogging()
        {
            RemoteInvoke(useSocketsHttpHandlerString =>
            {
                bool exceptionLogged           = false;
                bool activityLogged            = false;
                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
                    {
                        activityLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Exception"))
                    {
                        Assert.NotNull(kvp.Value);
                        GetPropertyValueFromAnonymousTypeInstance <Exception>(kvp.Value, "Exception");

                        exceptionLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.Exception"));
                    using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString))
                    {
                        Assert.ThrowsAsync <HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
                    }
                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    WaitForTrue(() => exceptionLogged, TimeSpan.FromSeconds(1),
                                "Exception was not logged within 1 second timeout.");
                    Assert.False(activityLogged, "HttpOutReq was logged when logging was disabled");
                    diagnosticListenerObserver.Disable();
                }

                return(SuccessExitCode);
            }, UseSocketsHttpHandler.ToString()).Dispose();
        }
Exemple #13
0
        public void SendAsync_ExpectedDiagnosticStopOnlyActivityLogging()
        {
            RemoteInvoke(() =>
            {
                bool activityStartLogged = false;
                bool activityStopLogged  = false;

                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
                    {
                        activityStartLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
                    {
                        Assert.NotNull(Activity.Current);
                        activityStopLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.HttpRequestOut"));
                    using (var client = new HttpClient())
                    {
                        var response = client.GetAsync(Configuration.Http.RemoteEchoServer).Result;
                    }
                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1),
                                "HttpRequestOut.Stop was not logged within 1 second timeout.");
                    Assert.False(activityStartLogged, "HttpRequestOut.Start was logged when start logging was disabled");
                    diagnosticListenerObserver.Disable();
                }

                return(SuccessExitCode);
            }).Dispose();
        }
Exemple #14
0
        public void SendAsync_ExpectedDiagnosticSourceActivityLogging()
        {
            RemoteInvoke(() =>
            {
                bool requestLogged       = false;
                bool responseLogged      = false;
                bool activityStartLogged = false;
                bool activityStopLogged  = false;
                bool exceptionLogged     = false;

                Activity parentActivity = new Activity("parent");
                parentActivity.AddBaggage("correlationId", Guid.NewGuid().ToString());
                parentActivity.AddBaggage("moreBaggage", Guid.NewGuid().ToString());
                parentActivity.AddTag("tag", "tag"); //add tag to ensure it is not injected into request
                parentActivity.Start();

                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.Request"))
                    {
                        requestLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Response"))
                    {
                        responseLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Exception"))
                    {
                        exceptionLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
                    {
                        Assert.NotNull(kvp.Value);
                        Assert.NotNull(Activity.Current);
                        Assert.Equal(parentActivity, Activity.Current.Parent);
                        GetPropertyValueFromAnonymousTypeInstance <HttpRequestMessage>(kvp.Value, "Request");

                        activityStartLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
                    {
                        Assert.NotNull(kvp.Value);
                        Assert.NotNull(Activity.Current);
                        Assert.Equal(parentActivity, Activity.Current.Parent);
                        Assert.True(Activity.Current.Duration != TimeSpan.Zero);
                        GetPropertyValueFromAnonymousTypeInstance <HttpRequestMessage>(kvp.Value, "Request");
                        GetPropertyValueFromAnonymousTypeInstance <HttpResponseMessage>(kvp.Value, "Response");
                        var requestStatus = GetPropertyValueFromAnonymousTypeInstance <TaskStatus>(kvp.Value, "RequestTaskStatus");
                        Assert.Equal(TaskStatus.RanToCompletion, requestStatus);

                        activityStopLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable();
                    using (var client = new HttpClient())
                    {
                        LoopbackServer.CreateServerAsync(async(server, url) =>
                        {
                            Task <List <string> > requestLines = LoopbackServer.AcceptSocketAsync(server,
                                                                                                  (s, stream, reader, writer) => LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer));
                            Task response = client.GetAsync(url);
                            await Task.WhenAll(response, requestLines);

                            AssertHeadersAreInjected(requestLines.Result, parentActivity);
                        }).Wait();
                    }

                    Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged.");
                    Assert.False(requestLogged, "Request was logged when Activity logging was enabled.");
                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout.");
                    Assert.False(exceptionLogged, "Exception was logged for successful request");
                    Assert.False(responseLogged, "Response was logged when Activity logging was enabled.");
                    diagnosticListenerObserver.Disable();
                }

                return(SuccessExitCode);
            }).Dispose();
        }
        public void SendAsync_ExpectedDiagnosticSynchronousExceptionActivityLogging()
        {
            if (IsCurlHandler)
            {
                // The only way to throw a synchronous exception for CurlHandler through
                // DiagnosticHandler is when the Request uri scheme is Https, and the
                // backend doesn't support SSL.
                return;
            }

            RemoteInvoke(useSocketsHttpHandlerString =>
            {
                bool exceptionLogged           = false;
                bool activityStopLogged        = false;
                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
                    {
                        Assert.NotNull(kvp.Value);
                        GetPropertyValueFromAnonymousTypeInstance <HttpRequestMessage>(kvp.Value, "Request");
                        var requestStatus = GetPropertyValueFromAnonymousTypeInstance <TaskStatus>(kvp.Value, "RequestTaskStatus");
                        Assert.Equal(TaskStatus.Faulted, requestStatus);

                        activityStopLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Exception"))
                    {
                        Assert.NotNull(kvp.Value);
                        GetPropertyValueFromAnonymousTypeInstance <Exception>(kvp.Value, "Exception");

                        exceptionLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable();
                    using (HttpClientHandler handler = CreateHttpClientHandler(useSocketsHttpHandlerString))
                        using (HttpClient client = new HttpClient(handler))
                        {
                            // Set a https proxy.
                            handler.Proxy = new WebProxy($"https://{Guid.NewGuid()}.com", false);
                            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"http://{Guid.NewGuid()}.com");

                            if (bool.Parse(useSocketsHttpHandlerString))
                            {
                                // Forces a synchronous exception for SocketsHttpHandler.
                                // SocketsHttpHandler only allow http scheme for proxies.

                                // We cannot use Assert.Throws<Exception>(() => { SendAsync(...); }) to verify the
                                // synchronous exception here, because DiagnosticsHandler SendAsync() method has async
                                // modifier, and returns Task. If the call is not awaited, the current test method will continue
                                // run before the call is completed, thus Assert.Throws() will not capture the exception.
                                // We need to wait for the Task to complete synchronously, to validate the exception.
                                Task sendTask = client.SendAsync(request);
                                Assert.True(sendTask.IsFaulted);
                                Assert.IsType <NotSupportedException>(sendTask.Exception.InnerException);
                            }
                            else
                            {
                                // Forces a synchronous exception for WinHttpHandler.
                                // WinHttpHandler will not allow (proxy != null && !UseCustomProxy).
                                handler.UseProxy = false;

                                // We cannot use Assert.Throws<Exception>(() => { SendAsync(...); }) to verify the
                                // synchronous exception here, because DiagnosticsHandler SendAsync() method has async
                                // modifier, and returns Task. If the call is not awaited, the current test method will continue
                                // run before the call is completed, thus Assert.Throws() will not capture the exception.
                                // We need to wait for the Task to complete synchronously, to validate the exception.
                                Task sendTask = client.SendAsync(request);
                                Assert.True(sendTask.IsFaulted);
                                Assert.IsType <InvalidOperationException>(sendTask.Exception.InnerException);
                            }
                        }
                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1),
                                "Response with exception was not logged within 1 second timeout.");
                    Assert.True(exceptionLogged, "Exception was not logged");
                    diagnosticListenerObserver.Disable();
                }

                return(SuccessExitCode);
            }, UseSocketsHttpHandler.ToString()).Dispose();
        }