SessionSQLServerHandler.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. //
  2. // System.Web.SessionState.SessionSQLServerHandler
  3. //
  4. // Author(s):
  5. // Jackson Harper ([email protected])
  6. //
  7. // (C) 2003 Novell, Inc. (http://www.novell.com), All rights reserved
  8. //
  9. using System;
  10. using System.IO;
  11. using System.Data;
  12. using System.Reflection;
  13. using System.Configuration;
  14. using System.Collections.Specialized;
  15. namespace System.Web.SessionState {
  16. internal class SessionSQLServerHandler : ISessionHandler
  17. {
  18. const string CookieName = "ASPSESSION";
  19. const int DefTimeout = 600;
  20. private Type cncType = null;
  21. private IDbConnection cnc = null;
  22. private SessionConfig config;
  23. public void Dispose ()
  24. {
  25. if (cnc != null) {
  26. cnc.Close ();
  27. cnc = null;
  28. }
  29. }
  30. public void Init (HttpApplication context, SessionConfig config)
  31. {
  32. string connectionTypeName;
  33. string providerAssemblyName;
  34. string cncString;
  35. this.config = config;
  36. GetConnectionData (out providerAssemblyName, out connectionTypeName, out cncString);
  37. if (cncType == null) {
  38. Assembly dbAssembly = Assembly.Load (providerAssemblyName);
  39. cncType = dbAssembly.GetType (connectionTypeName, true);
  40. if (!typeof (IDbConnection).IsAssignableFrom (cncType))
  41. throw new ApplicationException ("The type '" + cncType +
  42. "' does not implement IDB Connection.\n" +
  43. "Check 'DbConnectionType' in server.exe.config.");
  44. }
  45. cnc = (IDbConnection) Activator.CreateInstance (cncType);
  46. cnc.ConnectionString = cncString;
  47. try {
  48. cnc.Open ();
  49. } catch (Exception exc) {
  50. cnc = null;
  51. throw exc;
  52. }
  53. }
  54. public void UpdateHandler (HttpContext context, SessionStateModule module)
  55. {
  56. if (context.Session == null)
  57. return;
  58. string id = context.Session.SessionID;
  59. SessionDictionary dict = context.Session.SessionDictionary;
  60. UpdateSession (id, dict);
  61. }
  62. public bool UpdateContext (HttpContext context, SessionStateModule module)
  63. {
  64. HttpSessionState session = null;
  65. string id = GetId (context);
  66. if (id != null) {
  67. session = SelectSession (id);
  68. if (session != null) {
  69. context.SetSession (session);
  70. return false;
  71. }
  72. }
  73. id = SessionId.Create (module.Rng);
  74. session = new HttpSessionState (id, new SessionDictionary (),
  75. new HttpStaticObjectsCollection (), config.Timeout, true,
  76. false, SessionStateMode.SQLServer, false);
  77. InsertSession (session, config.Timeout);
  78. context.SetSession (session);
  79. context.Session.IsNewSession = true;
  80. context.Response.AppendCookie (new HttpCookie (CookieName, id));
  81. return true;
  82. }
  83. private void GetConnectionData (out string providerAssembly,
  84. out string cncTypeName, out string cncString)
  85. {
  86. providerAssembly = null;
  87. cncTypeName = null;
  88. cncString = null;
  89. NameValueCollection config = ConfigurationSettings.AppSettings as NameValueCollection;
  90. if (config != null) {
  91. foreach (string s in config.Keys) {
  92. if (0 == String.Compare ("StateDBProviderAssembly", s, true)) {
  93. providerAssembly = config [s];
  94. } else if (0 == String.Compare ("StateDBConnectionType", s, true)) {
  95. cncTypeName = config [s];
  96. }
  97. }
  98. }
  99. cncString = this.config.SqlConnectionString;
  100. if (providerAssembly == null || providerAssembly == String.Empty)
  101. providerAssembly = "Npgsql.dll";
  102. if (cncTypeName == null || cncTypeName == String.Empty)
  103. cncTypeName = "Npgsql.NpgsqlConnection";
  104. if (cncString == null || cncString == String.Empty)
  105. cncString = "SERVER=127.0.0.1;USER ID=monostate;PASSWORD=monostate;dbname=monostate";
  106. }
  107. private HttpSessionState SelectSession (string id)
  108. {
  109. HttpSessionState session = null;
  110. IDbCommand command = cnc.CreateCommand();
  111. IDataReader reader;
  112. string select = "SELECT * from aspstatetempsessions WHERE SessionID = :SessionID";
  113. command.CommandText = select;
  114. command.Parameters.Add (CreateParam (command, DbType.String, ":SessionID", id));
  115. try {
  116. reader = command.ExecuteReader ();
  117. if (!reader.Read ())
  118. return null;
  119. SessionDictionary dict;
  120. HttpStaticObjectsCollection sobjs;
  121. dict = SessionDictionary.FromByteArray (ReadBytes (reader, reader.FieldCount-1));
  122. sobjs = HttpStaticObjectsCollection.FromByteArray (ReadBytes (reader, reader.FieldCount-2));
  123. session = new HttpSessionState (id, dict, sobjs, 100, true, false,
  124. SessionStateMode.SQLServer, false);
  125. return session;
  126. } catch {
  127. throw;
  128. }
  129. }
  130. private void InsertSession (HttpSessionState session, int timeout)
  131. {
  132. IDbCommand command = cnc.CreateCommand ();
  133. IDataParameterCollection param;
  134. string insert = "INSERT INTO ASPStateTempSessions VALUES " +
  135. "(:SessionID, :Created, :Expires, :Timeout, :StaticObjectsData, :SessionData)";
  136. command.CommandText = insert;
  137. param = command.Parameters;
  138. param.Add (CreateParam (command, DbType.String, ":SessionID", session.SessionID));
  139. param.Add (CreateParam (command, DbType.DateTime, ":Created", DateTime.Now));
  140. param.Add (CreateParam (command, DbType.DateTime, ":Expires", Tommorow ()));
  141. param.Add (CreateParam (command, DbType.Int32, ":Timeout", timeout));
  142. param.Add (CreateParam (command, DbType.Binary, ":StaticObjectsData",
  143. session.StaticObjects.ToByteArray ()));
  144. param.Add (CreateParam (command, DbType.Binary, ":SessionData",
  145. session.SessionDictionary.ToByteArray ()));
  146. command.ExecuteNonQuery ();
  147. }
  148. private void UpdateSession (string id, SessionDictionary dict)
  149. {
  150. IDbCommand command = cnc.CreateCommand ();
  151. IDataParameterCollection param;
  152. string update = "UPDATE ASPStateTempSessions SET " +
  153. "SessionData = :SessionData WHERE SessionId = :SessionID";
  154. command.CommandText = update;
  155. param = command.Parameters;
  156. param.Add (CreateParam (command, DbType.String, ":SessionID", id));
  157. param.Add (CreateParam (command, DbType.Binary, ":SessionData",
  158. dict.ToByteArray ()));
  159. command.ExecuteNonQuery ();
  160. }
  161. private IDataParameter CreateParam (IDbCommand command, DbType type,
  162. string name, object value)
  163. {
  164. IDataParameter result = command.CreateParameter ();
  165. result.DbType = type;
  166. result.ParameterName = name;
  167. result.Value = value;
  168. return result;
  169. }
  170. private DateTime Tommorow ()
  171. {
  172. return DateTime.Now.AddDays (1);
  173. }
  174. private string GetId (HttpContext context)
  175. {
  176. if (!config.CookieLess &&
  177. context.Request.Cookies [CookieName] != null)
  178. return context.Request.Cookies [CookieName].Value;
  179. return null;
  180. }
  181. private byte [] ReadBytes (IDataReader reader, int index)
  182. {
  183. int len = (int) reader.GetBytes (reader.FieldCount-1, 0, null, 0, 0);
  184. byte [] data = new byte [len];
  185. reader.GetBytes (index, 0, data, 0, len);
  186. return data;
  187. }
  188. }
  189. }