2
0

SessionSQLServerHandler.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.IO;
  31. using System.Data;
  32. using System.Reflection;
  33. using System.Configuration;
  34. using System.Collections.Specialized;
  35. namespace System.Web.SessionState {
  36. internal class SessionSQLServerHandler : ISessionHandler
  37. {
  38. private static Type cncType = null;
  39. private IDbConnection cnc = null;
  40. private SessionConfig config;
  41. public void Dispose ()
  42. {
  43. if (cnc != null) {
  44. cnc.Close ();
  45. cnc = null;
  46. }
  47. }
  48. public void Init (SessionStateModule module, HttpApplication context, SessionConfig config)
  49. {
  50. string connectionTypeName;
  51. string providerAssemblyName;
  52. string cncString;
  53. this.config = config;
  54. GetConnectionData (out providerAssemblyName, out connectionTypeName, out cncString);
  55. if (cncType == null) {
  56. Assembly dbAssembly = Assembly.Load (providerAssemblyName);
  57. cncType = dbAssembly.GetType (connectionTypeName, true);
  58. if (!typeof (IDbConnection).IsAssignableFrom (cncType))
  59. throw new ApplicationException ("The type '" + cncType +
  60. "' does not implement IDB Connection.\n" +
  61. "Check 'DbConnectionType' in server.exe.config.");
  62. }
  63. cnc = (IDbConnection) Activator.CreateInstance (cncType);
  64. cnc.ConnectionString = cncString;
  65. try {
  66. cnc.Open ();
  67. } catch (Exception exc) {
  68. cnc = null;
  69. throw exc;
  70. }
  71. }
  72. public void UpdateHandler (HttpContext context, SessionStateModule module)
  73. {
  74. HttpSessionState session = context.Session;
  75. if (session == null || session.IsReadOnly)
  76. return;
  77. string id = session.SessionID;
  78. if (!session._abandoned) {
  79. SessionDictionary dict = session.SessionDictionary;
  80. UpdateSession (id, dict);
  81. } else {
  82. DeleteSession (id);
  83. }
  84. }
  85. public HttpSessionState UpdateContext (HttpContext context, SessionStateModule module,
  86. bool required, bool read_only, ref bool isNew)
  87. {
  88. if (!required)
  89. return null;
  90. HttpSessionState session = null;
  91. string id = SessionId.Lookup (context.Request, config.CookieLess);
  92. if (id != null) {
  93. session = SelectSession (id, read_only);
  94. if (session != null)
  95. return session;
  96. }
  97. id = SessionId.Create (module.Rng);
  98. session = new HttpSessionState (id, new SessionDictionary (),
  99. HttpApplicationFactory.ApplicationState.SessionObjects, config.Timeout,
  100. true, config.CookieLess, SessionStateMode.SQLServer, read_only);
  101. InsertSession (session, config.Timeout);
  102. isNew = true;
  103. return session;
  104. }
  105. private void GetConnectionData (out string providerAssembly,
  106. out string cncTypeName, out string cncString)
  107. {
  108. providerAssembly = null;
  109. cncTypeName = null;
  110. cncString = null;
  111. NameValueCollection config = ConfigurationSettings.AppSettings as NameValueCollection;
  112. if (config != null) {
  113. foreach (string s in config.Keys) {
  114. if (0 == String.Compare ("StateDBProviderAssembly", s, true)) {
  115. providerAssembly = config [s];
  116. } else if (0 == String.Compare ("StateDBConnectionType", s, true)) {
  117. cncTypeName = config [s];
  118. }
  119. }
  120. }
  121. cncString = this.config.SqlConnectionString;
  122. if (providerAssembly == null || providerAssembly == String.Empty)
  123. providerAssembly = "Npgsql.dll";
  124. if (cncTypeName == null || cncTypeName == String.Empty)
  125. cncTypeName = "Npgsql.NpgsqlConnection";
  126. if (cncString == null || cncString == String.Empty)
  127. cncString = "SERVER=127.0.0.1;USER ID=monostate;PASSWORD=monostate;dbname=monostate";
  128. }
  129. private HttpSessionState SelectSession (string id, bool read_only)
  130. {
  131. HttpSessionState session = null;
  132. IDbCommand command = cnc.CreateCommand();
  133. IDataReader reader;
  134. string select = "SELECT * from aspstatetempsessions WHERE SessionID = :SessionID";
  135. command.CommandText = select;
  136. command.Parameters.Add (CreateParam (command, DbType.String, ":SessionID", id));
  137. try {
  138. reader = command.ExecuteReader ();
  139. if (!reader.Read ())
  140. return null;
  141. SessionDictionary dict;
  142. HttpStaticObjectsCollection sobjs;
  143. dict = SessionDictionary.FromByteArray (ReadBytes (reader, reader.FieldCount-1));
  144. sobjs = HttpStaticObjectsCollection.FromByteArray (ReadBytes (reader, reader.FieldCount-2));
  145. session = new HttpSessionState (id, dict, sobjs, 100, false, config.CookieLess,
  146. SessionStateMode.SQLServer, read_only);
  147. return session;
  148. } catch {
  149. throw;
  150. }
  151. }
  152. private void InsertSession (HttpSessionState session, int timeout)
  153. {
  154. IDbCommand command = cnc.CreateCommand ();
  155. IDataParameterCollection param;
  156. string insert = "INSERT INTO ASPStateTempSessions VALUES " +
  157. "(:SessionID, :Created, :Expires, :Timeout, :StaticObjectsData, :SessionData)";
  158. command.CommandText = insert;
  159. param = command.Parameters;
  160. param.Add (CreateParam (command, DbType.String, ":SessionID", session.SessionID));
  161. param.Add (CreateParam (command, DbType.DateTime, ":Created", DateTime.Now));
  162. param.Add (CreateParam (command, DbType.DateTime, ":Expires", Tommorow ()));
  163. param.Add (CreateParam (command, DbType.Int32, ":Timeout", timeout));
  164. param.Add (CreateParam (command, DbType.Binary, ":StaticObjectsData",
  165. session.StaticObjects.ToByteArray ()));
  166. param.Add (CreateParam (command, DbType.Binary, ":SessionData",
  167. session.SessionDictionary.ToByteArray ()));
  168. command.ExecuteNonQuery ();
  169. }
  170. private void UpdateSession (string id, SessionDictionary dict)
  171. {
  172. IDbCommand command = cnc.CreateCommand ();
  173. IDataParameterCollection param;
  174. string update = "UPDATE ASPStateTempSessions SET " +
  175. "SessionData = :SessionData WHERE SessionId = :SessionID";
  176. command.CommandText = update;
  177. param = command.Parameters;
  178. param.Add (CreateParam (command, DbType.String, ":SessionID", id));
  179. param.Add (CreateParam (command, DbType.Binary, ":SessionData",
  180. dict.ToByteArray ()));
  181. command.ExecuteNonQuery ();
  182. }
  183. private void DeleteSession (string id)
  184. {
  185. IDbCommand command = cnc.CreateCommand ();
  186. IDataParameterCollection param;
  187. string update = "DELETE FROM ASPStateTempSessions WHERE SessionId = :SessionID";
  188. command.CommandText = update;
  189. param = command.Parameters;
  190. param.Add (CreateParam (command, DbType.String, ":SessionID", id));
  191. command.ExecuteNonQuery ();
  192. }
  193. private IDataParameter CreateParam (IDbCommand command, DbType type,
  194. string name, object value)
  195. {
  196. IDataParameter result = command.CreateParameter ();
  197. result.DbType = type;
  198. result.ParameterName = name;
  199. result.Value = value;
  200. return result;
  201. }
  202. private DateTime Tommorow ()
  203. {
  204. return DateTime.Now.AddDays (1);
  205. }
  206. private byte [] ReadBytes (IDataReader reader, int index)
  207. {
  208. int len = (int) reader.GetBytes (reader.FieldCount-1, 0, null, 0, 0);
  209. byte [] data = new byte [len];
  210. reader.GetBytes (index, 0, data, 0, len);
  211. return data;
  212. }
  213. }
  214. }