AdoController.cs 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Data.Common;
  6. using System.Web.Mvc;
  7. using Benchmarks.Mono.AspNet.Models;
  8. namespace Benchmarks.Mono.AspNet.Controllers
  9. {
  10. public class AdoController : Controller
  11. {
  12. private DbConnection CreateConnection(string providerName)
  13. {
  14. ConnectionStringSettings connectionSettings = ConfigurationManager.ConnectionStrings[providerName];
  15. DbProviderFactory factory = DbProviderFactories.GetFactory(connectionSettings.ProviderName);
  16. DbConnection connection = factory.CreateConnection();
  17. connection.ConnectionString = connectionSettings.ConnectionString;
  18. return connection;
  19. }
  20. public ActionResult Index(string providerName, int? queries)
  21. {
  22. List<World> worlds = new List<World>(queries ?? 1);
  23. using (DbConnection connection = CreateConnection(providerName))
  24. {
  25. connection.Open();
  26. using (DbCommand command = connection.CreateCommand())
  27. {
  28. command.CommandText = "SELECT * FROM World WHERE id = @ID";
  29. Random random = new Random();
  30. for (int i = 0; i < worlds.Capacity; i++)
  31. {
  32. int randomID = random.Next(0, 10000) + 1;
  33. DbParameter parameter = command.CreateParameter();
  34. parameter.ParameterName = "@ID";
  35. parameter.Value = randomID;
  36. command.Parameters.Clear();
  37. command.Parameters.Add(parameter);
  38. using (DbDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow))
  39. {
  40. if (reader.Read())
  41. {
  42. World world = new World();
  43. world.id = reader.GetInt32(0);
  44. world.randomNumber = reader.GetInt32(1);
  45. worlds.Add(world);
  46. }
  47. }
  48. }
  49. }
  50. }
  51. return queries != null ? Json(worlds, JsonRequestBehavior.AllowGet)
  52. : Json(worlds[0], JsonRequestBehavior.AllowGet);
  53. }
  54. public ActionResult Fortunes(string providerName)
  55. {
  56. List<Fortune> fortunes = new List<Fortune>();
  57. using (DbConnection connection = CreateConnection(providerName))
  58. {
  59. connection.Open();
  60. using (DbCommand command = connection.CreateCommand())
  61. {
  62. command.CommandText = "SELECT * FROM Fortune";
  63. using (DbDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
  64. {
  65. while (reader.Read())
  66. {
  67. Fortune fortune = new Fortune
  68. {
  69. ID = reader.GetInt32(0),
  70. Message = reader.GetString(1)
  71. };
  72. fortunes.Add(fortune);
  73. }
  74. }
  75. }
  76. }
  77. fortunes.Add(new Fortune { ID = 0, Message = "Additional fortune added at request time." });
  78. fortunes.Sort();
  79. return View("Fortunes", fortunes);
  80. }
  81. }
  82. }