SessionSQLServerHandler.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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)
  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)
  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 = System.Guid.NewGuid ().ToString ();
  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 = null;
  120. MemoryStream stream = null;
  121. int len = (int) reader.GetBytes (reader.FieldCount-1, 0, null, 0, 0);
  122. byte[] data = new byte[len];
  123. reader.GetBytes (reader.FieldCount-1, 0, data, 0, len);
  124. try {
  125. stream = new MemoryStream (data);
  126. dict = SessionDictionary.Deserialize (new BinaryReader (stream));
  127. } catch {
  128. throw;
  129. } finally {
  130. if (stream != null)
  131. stream.Close ();
  132. }
  133. session = new HttpSessionState (id, dict,
  134. new HttpStaticObjectsCollection (),
  135. 100, true, false,
  136. SessionStateMode.SQLServer, false);
  137. return session;
  138. } catch {
  139. throw;
  140. }
  141. }
  142. private void InsertSession (HttpSessionState session, int timeout)
  143. {
  144. IDbCommand command = cnc.CreateCommand ();
  145. IDataParameterCollection param;
  146. string insert = "INSERT INTO ASPStateTempSessions VALUES " +
  147. "(:SessionID, :Created, :Expires, :Timeout, :SessionData)";
  148. command.CommandText = insert;
  149. param = command.Parameters;
  150. param.Add (CreateParam (command, DbType.String, ":SessionID", session.SessionID));
  151. param.Add (CreateParam (command, DbType.DateTime, ":Created", DateTime.Now));
  152. param.Add (CreateParam (command, DbType.DateTime, ":Expires", Tommorow ()));
  153. param.Add (CreateParam (command, DbType.Int32, ":Timeout", timeout));
  154. param.Add (CreateParam (command, DbType.Binary, ":SessionData",
  155. GetDictData (session.SessionDictionary)));
  156. command.ExecuteNonQuery ();
  157. }
  158. private void UpdateSession (string id, SessionDictionary dict)
  159. {
  160. IDbCommand command = cnc.CreateCommand ();
  161. IDataParameterCollection param;
  162. string update = "UPDATE ASPStateTempSessions SET " +
  163. "SessionData = :SessionData WHERE SessionId = :SessionID";
  164. command.CommandText = update;
  165. param = command.Parameters;
  166. param.Add (CreateParam (command, DbType.String, ":SessionID", id));
  167. param.Add (CreateParam (command, DbType.Binary, ":SessionData",
  168. GetDictData (dict)));
  169. command.ExecuteNonQuery ();
  170. }
  171. private IDataParameter CreateParam (IDbCommand command, DbType type,
  172. string name, object value)
  173. {
  174. IDataParameter result = command.CreateParameter ();
  175. result.DbType = type;
  176. result.ParameterName = name;
  177. result.Value = value;
  178. return result;
  179. }
  180. private byte[] GetDictData (SessionDictionary dict)
  181. {
  182. MemoryStream stream = null;
  183. try {
  184. stream = new MemoryStream ();
  185. dict.Serialize (new BinaryWriter (stream));
  186. return stream.GetBuffer ();
  187. } catch {
  188. throw;
  189. } finally {
  190. if (stream != null)
  191. stream.Close ();
  192. }
  193. }
  194. private DateTime Tommorow ()
  195. {
  196. return DateTime.Now.AddDays (1);
  197. }
  198. private string GetId (HttpContext context)
  199. {
  200. if (!config.CookieLess &&
  201. context.Request.Cookies [CookieName] != null)
  202. return context.Request.Cookies [CookieName].Value;
  203. return null;
  204. }
  205. }
  206. }