public void ThrottledConcurrentRequestHandler_SendRequestAsync_ThrottlesRequests()
        {
            var      mockHandler = new MockMessageHandler();
            DateTime timeToStart = DateTime.Now.AddSeconds(1);

            var requestHandler = new MockResponseHandler()
            {
                CanHandleRequest = (request) => request.Method.Method == "GET" && request.RequestUri.ToString() == "http://testsite.com/test",
                HandleRequest    = async(request) =>
                {
                    try
                    {
                        System.Diagnostics.Debug.WriteLine(System.Threading.Interlocked.Increment(ref concurrentRequests));

                        var timeToWait = timeToStart.Subtract(DateTime.Now);
                        if (timeToWait.TotalMilliseconds > 0)
                        {
                            await Task.Delay(timeToWait).ConfigureAwait(false);
                        }

                        if (concurrentRequests > 4)
                        {
                            return(new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError));
                        }
                        else
                        {
                            return(new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.NoContent));
                        }
                    }
                    finally
                    {
                        System.Threading.Interlocked.Decrement(ref concurrentRequests);
                    }
                }
            };

            mockHandler.AddDynamicResponse(requestHandler);

            var handler = new ThrottledConcurrentRequestHandler(mockHandler);

            using (var client = new System.Net.Http.HttpClient(handler))
            {
                var requests = new List <Task <System.Net.Http.HttpResponseMessage> >();
                for (int cnt = 0; cnt < 100; cnt++)
                {
                    requests.Add(client.GetAsync("http://testsite.com/test"));
                }
                Task.WaitAll(requests.ToArray());

                Assert.IsFalse((from r in requests where r.Result.StatusCode == System.Net.HttpStatusCode.InternalServerError select r).Any());
            }
        }
        public async Task ServiceUnavailableRetryHandler_SendRequestAsync_RetriesOnTooManyRequests()
        {
            var      mockHandler = new MockMessageHandler();
            DateTime timeToStart = DateTime.Now.AddSeconds(1);

            var requestHandler = new MockResponseHandler()
            {
                CanHandleRequest = (request) => request.Method.Method == "GET" && request.RequestUri.ToString() == "http://testsite.com/test",
                HandleRequest    = async(request) =>
                {
                    try
                    {
                        System.Diagnostics.Debug.WriteLine(System.Threading.Interlocked.Increment(ref requestCount));

                        var timeToWait = timeToStart.Subtract(DateTime.Now);
                        if (timeToWait.TotalMilliseconds > 0)
                        {
                            await Task.Delay(timeToWait).ConfigureAwait(false);
                        }

                        if (requestCount < 4)
                        {
                            return(new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.ServiceUnavailable));
                        }
                        else
                        {
                            return(new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.NoContent));
                        }
                    }
                    finally
                    {
                        System.Threading.Interlocked.Increment(ref requestCount);
                    }
                }
            };

            mockHandler.AddDynamicResponse(requestHandler);

            var handler = new ServiceUnavailableRetryHandler(mockHandler, 5, TimeSpan.FromMilliseconds(1000));

            using (var client = new System.Net.Http.HttpClient(handler))
            {
                var response = await client.GetAsync("http://testsite.com/test");

                Assert.AreNotEqual(System.Net.HttpStatusCode.ServiceUnavailable, response.StatusCode);
            }
        }
        public async Task MockMessageHandler_ReturnsDynamicResponse()
        {
            var requestUriString = "http://www.mytestdomain.com/Greeting";

            var handler = new MockMessageHandler();

            handler.AddDynamicResponse(
                new MockResponseHandler()
            {
                // This decides if we will handle this specific request.
                CanHandleRequest = (request) =>
                {
                    return(request.RequestUri.ToString() == requestUriString &&
                           String.Compare(request.Method.Method, "POST", true) == 0);                         // Only handle POST requests to our end test endpoint
                },

                // This actually handles the request.
                HandleRequest = async(request) =>
                {
                    // Read the text passed in the request and return it as part
                    // of our dynamic response.
                    var name       = await request.Content.ReadAsStringAsync().ConfigureAwait(false);
                    var retVal     = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK);
                    retVal.Content = new System.Net.Http.StringContent("Hello " + name);

                    return(retVal);
                }
            }
                );

            var client = new System.Net.Http.HttpClient(handler);
            var result = await client.PostAsync(requestUriString, new System.Net.Http.StringContent("Yort"));

            Assert.AreEqual(System.Net.HttpStatusCode.OK, result.StatusCode);
            Assert.AreEqual("Hello Yort", await result.Content.ReadAsStringAsync());
        }
        private static MockMessageHandler SetupOAuth2MockHandler()
        {
            var mockHandler = new MockMessageHandler();

            mockHandler.AddFixedResponse(new Uri("http://testsite.com/Token"), new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
            {
                Content = new System.Net.Http.StringContent(String.Empty, System.Text.UTF8Encoding.UTF8, MediaTypes.ApplicationJson)
            });
            var mockResponse = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Redirect)
            {
                Content = new System.Net.Http.StringContent("Normally this is a web page the user logs into, but this test is automated and skips that.", System.Text.UTF8Encoding.UTF8, MediaTypes.ApplicationJson)
            };

            mockResponse.Headers.Location = new Uri("http://testsite.com/AuthComplete?code=28770506516186843330");
            mockHandler.AddFixedResponse(new Uri("http://testsite.com/Authorize"), mockResponse);

            var tokenIssuingHandler = new MockResponseHandler();

            tokenIssuingHandler.CanHandleRequest = (request) => { return(request.Method.Method == "POST" && request.RequestUri.ToString() == "http://testsite.com/Token"); };
            tokenIssuingHandler.HandleRequest    = async(request) =>
            {
                var content = request.Content as System.Net.Http.FormUrlEncodedContent;
                if (content == null)
                {
                    return(new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.BadRequest));
                }

                var contentParams = new Dictionary <string, string>();
                var contentStr    = await content.ReadAsStringAsync().ConfigureAwait(false);

                foreach (var kvp in contentStr.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    var    parts = kvp.Split(new char[] { '=' });
                    var    key   = Uri.UnescapeDataString(parts[0]);
                    string value = null;
                    if (parts.Length > 1)
                    {
                        value = Uri.UnescapeDataString(parts[1]);
                    }

                    contentParams.Add(key, value);
                }

                var grantType = (from c in contentParams where c.Key == "grant_type" select c.Value).FirstOrDefault();

                if (grantType == OAuth2.OAuth2GrantTypes.AuthorizationCode)
                {
                    var code = (from c in contentParams where c.Key == "code" select c.Value).FirstOrDefault();

                    if (code != "28770506516186843330")
                    {
                        return(new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.BadRequest));
                    }

                    return(new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
                    {
                        Content = new System.Net.Http.StringContent("{ token_type: \"Bearer\", access_token: \"123\", expires_in: \"3600\", refresh_token: \"456\" }", System.Text.UTF8Encoding.UTF8, MediaTypes.ApplicationJson)
                    });
                }
                else if (grantType == OAuth2GrantTypes.ClientCredentials)
                {
                    if (request.Headers.Authorization.Scheme == "Basic" && request.Headers.Authorization.Parameter == "OTg3NjU0MzIxOmFiY2RlZmdoaWxtbm9wcXJzdHV2emFiYw==")
                    {
                        return(new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
                        {
                            Content = new System.Net.Http.StringContent("{ token_type: \"Bearer\", access_token: \"123\", expires_in: \"3600\", refresh_token: \"456\" }", System.Text.UTF8Encoding.UTF8, MediaTypes.ApplicationJson)
                        });
                    }
                }

                return(new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.BadRequest));
            };
            mockHandler.AddDynamicResponse(tokenIssuingHandler);

            var authCheckingHandler = new MockResponseHandler();

            authCheckingHandler.CanHandleRequest = (request) => { return(request.RequestUri.ToString() == "http://testsite.com/TestEndpoint"); };
            authCheckingHandler.HandleRequest    = (request) =>
            {
                if (request.Headers.Authorization == null || request.Headers.Authorization.Scheme != "Bearer" || request.Headers.Authorization.Parameter != "123")
                {
                    return(Task.FromResult(new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized)));
                }

                return(Task.FromResult(new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
                {
                    Content = new System.Net.Http.StringContent("Yay! You're authed.")
                }));
            };
            mockHandler.AddDynamicResponse(authCheckingHandler);
            return(mockHandler);
        }