Program.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Data.Common;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Threading;
  10. using System.Web.Script.Serialization;
  11. using MongoDB.Driver.Builders;
  12. using Benchmarks.AspNet.Models;
  13. using System.Reflection;
  14. using System.Runtime.InteropServices;
  15. namespace HttpListener
  16. {
  17. class Program
  18. {
  19. private static void RequestCallback(Object state)
  20. {
  21. HttpListenerContext context = (HttpListenerContext)state;
  22. HttpListenerRequest request = context.Request;
  23. HttpListenerResponse response = context.Response;
  24. try
  25. {
  26. string responseString = null;
  27. switch (request.Url.LocalPath)
  28. {
  29. case "/plaintext":
  30. responseString = Plaintext(response);
  31. break;
  32. case "/json":
  33. responseString = Json(response);
  34. break;
  35. case "/db":
  36. responseString = Db(request, response);
  37. break;
  38. case "/fortunes":
  39. responseString = Fortunes(request, response);
  40. break;
  41. case "/updates":
  42. responseString = Updates(request, response);
  43. break;
  44. case "/mongodbdb":
  45. responseString = MongoDBDb(request, response);
  46. break;
  47. case "/mongodbfortunes":
  48. responseString = MongoDBFortunes(request, response);
  49. break;
  50. case "/mongodbupdates":
  51. responseString = MongoDBUpdates(request, response);
  52. break;
  53. default:
  54. responseString = NotFound(response);
  55. break;
  56. }
  57. WriteResponse(response, responseString);
  58. }
  59. finally
  60. {
  61. response.Close();
  62. }
  63. }
  64. private static void WriteResponse(HttpListenerResponse response, String responseString)
  65. {
  66. response.ContentType = response.ContentType + "; charset=utf-8";
  67. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
  68. response.ContentLength64 = buffer.Length;
  69. try
  70. {
  71. response.OutputStream.Write(buffer, 0, buffer.Length);
  72. }
  73. catch (Win32Exception)
  74. {
  75. // Ignore I/O errors
  76. }
  77. }
  78. private static void Threads()
  79. {
  80. // To improve CPU utilization, increase the number of threads that the .NET thread pool expands by when
  81. // a burst of requests come in. We could do this by editing machine.config/system.web/processModel/minWorkerThreads,
  82. // but that seems too global a change, so we do it in code for just our AppPool. More info:
  83. //
  84. // http://support.microsoft.com/kb/821268
  85. // http://blogs.msdn.com/b/tmarq/archive/2007/07/21/asp-net-thread-usage-on-iis-7-0-and-6-0.aspx
  86. // http://blogs.msdn.com/b/perfworld/archive/2010/01/13/how-can-i-improve-the-performance-of-asp-net-by-adjusting-the-clr-thread-throttling-properties.aspx
  87. int newMinWorkerThreads = Convert.ToInt32(ConfigurationManager.AppSettings["minWorkerThreadsPerLogicalProcessor"]);
  88. if (newMinWorkerThreads > 0)
  89. {
  90. int minWorkerThreads, minCompletionPortThreads;
  91. ThreadPool.GetMinThreads(out minWorkerThreads, out minCompletionPortThreads);
  92. ThreadPool.SetMinThreads(Environment.ProcessorCount * newMinWorkerThreads, minCompletionPortThreads);
  93. }
  94. }
  95. static void Main(string[] args)
  96. {
  97. Threads();
  98. System.Net.HttpListener listener = new System.Net.HttpListener();
  99. // This doesn't seem to ignore all write exceptions, so in WriteResponse(), we still have a catch block.
  100. listener.IgnoreWriteExceptions = true;
  101. listener.Prefixes.Add("http://*:8080/");
  102. try
  103. {
  104. listener.Start();
  105. // Increase the HTTP.SYS backlog queue from the default of 1000 to 65535.
  106. // To verify that this works, run `netsh http show servicestate`.
  107. Network.Utils.HttpApi.SetRequestQueueLength(listener, 65535);
  108. for (;;)
  109. {
  110. HttpListenerContext context = null;
  111. try
  112. {
  113. context = listener.GetContext();
  114. ThreadPool.QueueUserWorkItem(new WaitCallback(RequestCallback), context);
  115. context = null; // ownership has been transferred to RequestCallback
  116. }
  117. catch (HttpListenerException ex)
  118. {
  119. Console.WriteLine(ex.Message);
  120. }
  121. finally
  122. {
  123. if (context != null)
  124. context.Response.Close();
  125. }
  126. }
  127. }
  128. catch (HttpListenerException ex)
  129. {
  130. Console.WriteLine(ex.Message);
  131. }
  132. finally
  133. {
  134. // Stop listening for requests.
  135. listener.Close();
  136. Console.WriteLine("Done Listening.");
  137. }
  138. }
  139. public static DbConnection CreateConnection(HttpListenerRequest request)
  140. {
  141. string providerName = request.QueryString["provider"];
  142. if (providerName == null)
  143. {
  144. throw new ApplicationException("Missing provider querystring argument");
  145. }
  146. ConnectionStringSettings connectionSettings = ConfigurationManager.ConnectionStrings[providerName];
  147. DbProviderFactory factory = DbProviderFactories.GetFactory(connectionSettings.ProviderName);
  148. DbConnection connection = factory.CreateConnection();
  149. connection.ConnectionString = connectionSettings.ConnectionString;
  150. return connection;
  151. }
  152. public static int GetQueries(HttpListenerRequest request)
  153. {
  154. int queries = 1;
  155. string queriesString = request.QueryString["queries"];
  156. if (queriesString != null)
  157. {
  158. // If this fails to parse, queries will be set to zero.
  159. int.TryParse(queriesString, out queries);
  160. queries = Math.Max(1, Math.Min(500, queries));
  161. }
  162. return queries;
  163. }
  164. private static string NotFound(HttpListenerResponse response)
  165. {
  166. response.StatusCode = (int)HttpStatusCode.NotFound;
  167. response.ContentType = "text/plain";
  168. return "not found";
  169. }
  170. private static string Plaintext(HttpListenerResponse response)
  171. {
  172. response.ContentType = "text/plain";
  173. return "Hello, World!";
  174. }
  175. private static string Json(HttpListenerResponse response)
  176. {
  177. response.ContentType = "application/json";
  178. return new JavaScriptSerializer().Serialize(new { message = "Hello, World!" });
  179. }
  180. private static string Db(HttpListenerRequest request, HttpListenerResponse response)
  181. {
  182. Random random = new Random();
  183. int queries = GetQueries(request);
  184. List<World> worlds = new List<World>(queries);
  185. using (DbConnection connection = CreateConnection(request))
  186. {
  187. connection.Open();
  188. using (DbCommand command = connection.CreateCommand())
  189. {
  190. command.CommandText = "SELECT * FROM World WHERE id = @ID";
  191. DbParameter parameter = command.CreateParameter();
  192. parameter.ParameterName = "@ID";
  193. command.Parameters.Add(parameter);
  194. for (int i = 0; i < worlds.Capacity; i++)
  195. {
  196. int randomID = random.Next(0, 10000) + 1;
  197. parameter.Value = randomID;
  198. // Don't use CommandBehavior.SingleRow because that will make the MySql provider
  199. // send two extra commands to limit the result to one row.
  200. using (DbDataReader reader = command.ExecuteReader())
  201. {
  202. if (reader.Read())
  203. {
  204. worlds.Add(new World
  205. {
  206. id = reader.GetInt32(0),
  207. randomNumber = reader.GetInt32(1)
  208. });
  209. }
  210. }
  211. }
  212. }
  213. }
  214. response.ContentType = "application/json";
  215. return new JavaScriptSerializer().Serialize(
  216. worlds.Count > 1 ? (Object)worlds : (Object)worlds[0]);
  217. }
  218. private static string Fortunes(HttpListenerRequest request, HttpListenerResponse response)
  219. {
  220. List<Fortune> fortunes = new List<Fortune>();
  221. using (DbConnection connection = CreateConnection(request))
  222. {
  223. connection.Open();
  224. using (DbCommand command = connection.CreateCommand())
  225. {
  226. command.CommandText = "SELECT * FROM Fortune";
  227. using (DbDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
  228. {
  229. while (reader.Read())
  230. {
  231. fortunes.Add(new Fortune
  232. {
  233. ID = reader.GetInt32(0),
  234. Message = reader.GetString(1)
  235. });
  236. }
  237. }
  238. }
  239. }
  240. fortunes.Add(new Fortune { ID = 0, Message = "Additional fortune added at request time." });
  241. fortunes.Sort();
  242. response.ContentType = "text/html";
  243. var template = new Fortunes { Model = fortunes };
  244. return template.TransformText();
  245. }
  246. private static string Updates(HttpListenerRequest request, HttpListenerResponse response)
  247. {
  248. Random random = new Random();
  249. List<World> worlds = new List<World>(GetQueries(request));
  250. using (DbConnection connection = CreateConnection(request))
  251. {
  252. connection.Open();
  253. using (DbCommand selectCommand = connection.CreateCommand(),
  254. updateCommand = connection.CreateCommand())
  255. {
  256. selectCommand.CommandText = "SELECT * FROM World WHERE id = @ID";
  257. updateCommand.CommandText = "UPDATE World SET randomNumber = @Number WHERE id = @ID";
  258. for (int i = 0; i < worlds.Capacity; i++)
  259. {
  260. int randomID = random.Next(0, 10000) + 1;
  261. int randomNumber = random.Next(0, 10000) + 1;
  262. DbParameter idParameter = selectCommand.CreateParameter();
  263. idParameter.ParameterName = "@ID";
  264. idParameter.Value = randomID;
  265. selectCommand.Parameters.Clear();
  266. selectCommand.Parameters.Add(idParameter);
  267. World world = null;
  268. // Don't use CommandBehavior.SingleRow because that will make the MySql provider
  269. // send two extra commands to limit the result to one row.
  270. using (DbDataReader reader = selectCommand.ExecuteReader())
  271. {
  272. if (reader.Read())
  273. {
  274. world = new World
  275. {
  276. id = reader.GetInt32(0),
  277. randomNumber = reader.GetInt32(1)
  278. };
  279. }
  280. }
  281. DbParameter idUpdateParameter = updateCommand.CreateParameter();
  282. idUpdateParameter.ParameterName = "@ID";
  283. idUpdateParameter.Value = randomID;
  284. DbParameter numberParameter = updateCommand.CreateParameter();
  285. numberParameter.ParameterName = "@Number";
  286. numberParameter.Value = randomNumber;
  287. updateCommand.Parameters.Clear();
  288. updateCommand.Parameters.Add(idUpdateParameter);
  289. updateCommand.Parameters.Add(numberParameter);
  290. updateCommand.ExecuteNonQuery();
  291. world.randomNumber = randomNumber;
  292. worlds.Add(world);
  293. }
  294. }
  295. }
  296. response.ContentType = "application/json";
  297. return new JavaScriptSerializer().Serialize(
  298. worlds.Count > 1 ? (Object)worlds : (Object)worlds[0]);
  299. }
  300. private static string MongoDBDb(HttpListenerRequest request, HttpListenerResponse response)
  301. {
  302. Random random = new Random();
  303. int queries = GetQueries(request);
  304. List<World> worlds = new List<World>(queries);
  305. Benchmarks.AspNet.Models.MongoDB db = new Benchmarks.AspNet.Models.MongoDB("MongoDB");
  306. for (int i = 0; i < worlds.Capacity; i++)
  307. {
  308. int randomID = random.Next(0, 10000) + 1;
  309. worlds.Add(db.Worlds.FindOne(Query<World>.EQ(w => w.id, randomID)));
  310. }
  311. response.ContentType = "application/json";
  312. return new JavaScriptSerializer().Serialize(
  313. worlds.Count > 1 ? (Object)worlds : (Object)worlds[0]);
  314. }
  315. private static string MongoDBFortunes(HttpListenerRequest request, HttpListenerResponse response)
  316. {
  317. Benchmarks.AspNet.Models.MongoDB db = new Benchmarks.AspNet.Models.MongoDB("MongoDB");
  318. List<Fortune> fortunes = db.Fortunes.FindAll().ToList();
  319. fortunes.Add(new Fortune { ID = 0, Message = "Additional fortune added at request time." });
  320. fortunes.Sort();
  321. response.ContentType = "text/html";
  322. var template = new Fortunes { Model = fortunes };
  323. return template.TransformText();
  324. }
  325. private static string MongoDBUpdates(HttpListenerRequest request, HttpListenerResponse response)
  326. {
  327. Random random = new Random();
  328. Benchmarks.AspNet.Models.MongoDB db = new Benchmarks.AspNet.Models.MongoDB("MongoDB");
  329. int queries = GetQueries(request);
  330. List<World> worlds = new List<World>(queries);
  331. for (int i = 0; i < worlds.Capacity; i++)
  332. {
  333. int randomID = random.Next(0, 10000) + 1;
  334. int randomNumber = random.Next(0, 10000) + 1;
  335. World world = db.Worlds.FindOne(Query<World>.EQ(w => w.id, randomID));
  336. world.randomNumber = randomNumber;
  337. worlds.Add(world);
  338. db.Worlds.Save(world);
  339. }
  340. response.ContentType = "application/json";
  341. return new JavaScriptSerializer().Serialize(
  342. worlds.Count > 1 ? (Object)worlds : (Object)worlds[0]);
  343. }
  344. }
  345. }
  346. // Adapted from:
  347. // http://stackoverflow.com/questions/15417062/changing-http-sys-kernel-queue-limit-when-using-net-httplistener
  348. namespace Network.Utils
  349. {
  350. public static class HttpApi
  351. {
  352. public static void SetRequestQueueLength(System.Net.HttpListener listener, uint len)
  353. {
  354. var listenerType = typeof(System.Net.HttpListener);
  355. var requestQueueHandleProperty = listenerType.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance).First(p => p.Name == "RequestQueueHandle");
  356. var requestQueueHandle = (CriticalHandle)requestQueueHandleProperty.GetValue(listener);
  357. var result = HttpSetRequestQueueProperty(requestQueueHandle, HTTP_SERVER_PROPERTY.HttpServerQueueLengthProperty, ref len, (uint)Marshal.SizeOf(len), 0, IntPtr.Zero);
  358. if (result != 0)
  359. {
  360. throw new HttpListenerException((int)result);
  361. }
  362. }
  363. internal enum HTTP_SERVER_PROPERTY
  364. {
  365. HttpServerAuthenticationProperty,
  366. HttpServerLoggingProperty,
  367. HttpServerQosProperty,
  368. HttpServerTimeoutsProperty,
  369. HttpServerQueueLengthProperty,
  370. HttpServerStateProperty,
  371. HttpServer503VerbosityProperty,
  372. HttpServerBindingProperty,
  373. HttpServerExtendedAuthenticationProperty,
  374. HttpServerListenEndpointProperty,
  375. HttpServerChannelBindProperty,
  376. HttpServerProtectionLevelProperty,
  377. }
  378. [DllImport("httpapi.dll", CallingConvention = CallingConvention.StdCall)]
  379. internal static extern uint HttpSetRequestQueueProperty(
  380. CriticalHandle requestQueueHandle,
  381. HTTP_SERVER_PROPERTY serverProperty,
  382. ref uint pPropertyInfo,
  383. uint propertyInfoLength,
  384. uint reserved,
  385. IntPtr pReserved);
  386. }
  387. }