UpdatesHandler.cs 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Data.Common;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using System.Web;
  9. using System.Web.Script.Serialization;
  10. using Benchmarks.AspNet.Models;
  11. public class UpdatesHandler : IHttpHandler
  12. {
  13. bool IHttpHandler.IsReusable
  14. {
  15. get { return true; }
  16. }
  17. void IHttpHandler.ProcessRequest(HttpContext context)
  18. {
  19. Random random = new Random();
  20. List<World> worlds = new List<World>(Common.GetQueries(context.Request));
  21. using (DbConnection connection = Common.CreateConnection(context.Request))
  22. {
  23. connection.Open();
  24. using (DbCommand selectCommand = connection.CreateCommand(),
  25. updateCommand = connection.CreateCommand())
  26. {
  27. selectCommand.CommandText = "SELECT * FROM World WHERE id = @ID";
  28. updateCommand.CommandText = "UPDATE World SET randomNumber = @Number WHERE id = @ID";
  29. for (int i = 0; i < worlds.Capacity; i++)
  30. {
  31. int randomID = random.Next(0, 10000) + 1;
  32. int randomNumber = random.Next(0, 10000) + 1;
  33. DbParameter idParameter = selectCommand.CreateParameter();
  34. idParameter.ParameterName = "@ID";
  35. idParameter.Value = randomID;
  36. selectCommand.Parameters.Clear();
  37. selectCommand.Parameters.Add(idParameter);
  38. World world = null;
  39. // Don't use CommandBehavior.SingleRow because that will make the MySql provider
  40. // send two extra commands to limit the result to one row.
  41. using (DbDataReader reader = selectCommand.ExecuteReader())
  42. {
  43. if (reader.Read())
  44. {
  45. world = new World
  46. {
  47. id = reader.GetInt32(0),
  48. randomNumber = reader.GetInt32(1)
  49. };
  50. }
  51. }
  52. DbParameter idUpdateParameter = updateCommand.CreateParameter();
  53. idUpdateParameter.ParameterName = "@ID";
  54. idUpdateParameter.Value = randomID;
  55. DbParameter numberParameter = updateCommand.CreateParameter();
  56. numberParameter.ParameterName = "@Number";
  57. numberParameter.Value = randomNumber;
  58. updateCommand.Parameters.Clear();
  59. updateCommand.Parameters.Add(idUpdateParameter);
  60. updateCommand.Parameters.Add(numberParameter);
  61. updateCommand.ExecuteNonQuery();
  62. world.randomNumber = randomNumber;
  63. worlds.Add(world);
  64. }
  65. }
  66. }
  67. HttpResponse response = context.Response;
  68. response.ContentType = "application/json";
  69. response.Write(new JavaScriptSerializer().Serialize(
  70. worlds.Count > 1 ? (Object)worlds : (Object)worlds[0]));
  71. }
  72. }