summaryrefslogtreecommitdiffstats
path: root/src/DotNetOpenAuth.Test/Hosting/HttpHost.cs
blob: 9606cb7f1b8df2a1c8c8ed826a55a0e95c9fd508 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
namespace DotNetOpenAuth.Test.Hosting {
	using System;
	using System.Globalization;
	using System.IO;
	using System.Net;
	using System.Threading;

	class HttpHost : IDisposable {
		HttpListener listener;
		public int Port { get; private set; }
		Thread listenerThread;
		AspNetHost aspNetHost;

		HttpHost(AspNetHost aspNetHost) {
			this.aspNetHost = aspNetHost;

			Port = 59687;
			Random r = new Random();
		tryAgain:
			try {
				listener = new HttpListener();
				listener.Prefixes.Add(string.Format(CultureInfo.InvariantCulture,
					"http://localhost:{0}/", Port));
				listener.Start();
			} catch (HttpListenerException ex) {
				if (ex.Message.Contains("conflicts")) {
					Port += r.Next(1, 20);
					goto tryAgain;
				}
				throw;
			}
			listenerThread = new Thread(processRequests);
			listenerThread.Start();
		}

		public static HttpHost CreateHost(AspNetHost aspNetHost) {
			return new HttpHost(aspNetHost);
		}

		public static HttpHost CreateHost(string webDirectory) {
			return new HttpHost(AspNetHost.CreateHost(webDirectory));
		}
		void processRequests() {
			try {
				while (true) {
					var context = listener.GetContext();
					aspNetHost.BeginProcessRequest(context);
				}
			} catch (HttpListenerException) {
				// the listener is probably being shut down
			}
		}

		public Uri BaseUri {
			get { return new Uri("http://localhost:" + Port.ToString() + "/"); }
		}
		public string ProcessRequest(string url) {
			return ProcessRequest(url, null);
		}
		public string ProcessRequest(string url, string body) {
			WebRequest request = WebRequest.Create(new Uri(BaseUri, url));
			if (body != null) {
				request.Method = "POST";
				request.ContentLength = body.Length;
				using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
					sw.Write(body);
			}
			try {
				using (WebResponse response = request.GetResponse()) {
					using (StreamReader sr = new StreamReader(response.GetResponseStream()))
						return sr.ReadToEnd();
				}
			} catch (WebException ex) {
				Logger.Error("Exception in HttpHost", ex);
				using (StreamReader sr = new StreamReader(ex.Response.GetResponseStream())) {
					string streamContent = sr.ReadToEnd();
					Logger.ErrorFormat("Error content stream follows: {0}", streamContent);
				}
				throw;
			}
		}

		#region IDisposable Members

		public void Dispose() {
			listener.Close();
			listenerThread.Join(1000);
			listenerThread.Abort();
		}

		#endregion
	}
}