using System.Threading.Tasks;
public static void Main()
var tests = new QuestionTests();
tests.DuckDuckGoExists();
tests.NonExistentSiteDoesntExist();
tests.MethodNotAllowedSiteExists();
tests.TimeoutDoesNotExist();
Console.WriteLine("All tests passed");
public void DuckDuckGoExists()
var ddg = new Client("https://start.duckduckgo.com/", 5000);
ddg.EndpointExists().ShouldBe(true);
public void NonExistentSiteDoesntExist()
var blah = new Client("http://thissitedoesnotexist.blah/", 5000);
blah.EndpointExists().ShouldBe(false);
public void MethodNotAllowedSiteExists()
var server = new LocalHost();
var listening = server.ListenAndReturn405();
var local = new Client("http://localhost:60792/405/", 5000);
local.EndpointExists().ShouldBe(true);
public void TimeoutDoesNotExist()
var server = new LocalHost();
var listening = server.ListenAndTimeout();
var local = new Client("http://localhost:60792/timesout/", 5000);
local.EndpointExists().ShouldBe(false);
private readonly string uri;
private readonly int timeout;
public Client(string uri, int timeout)
public bool EndpointExists()
var request = HttpWebRequest.Create(uri);
request.Timeout = timeout;
var response = (HttpWebResponse) request.GetResponse();
catch (WebException connectionError) when (
connectionError.Status == WebExceptionStatus.NameResolutionFailure ||
connectionError.Status == WebExceptionStatus.Timeout)
public Task ListenAndTimeout()
var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:60792/timesout/");
return Task.Factory.StartNew(() =>
var context = listener.GetContext();
var response = context.Response;
var responseString = "<HTML><BODY>OK</BODY></HTML>";
var buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
response.StatusCode = (int)HttpStatusCode.OK;
var output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
public Task ListenAndReturn405()
var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:60792/405/");
return Task.Factory.StartNew(() =>
var context = listener.GetContext();
var response = context.Response;
var responseString = "405";
var buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
var output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);