SessionSQLServerHandler.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. const int DefTimeout = 600;
  39. private Type cncType = null;
  40. private IDbConnection cnc = null;
  41. private SessionConfig config;
  42. public void Dispose ()
  43. {
  44. if (cnc != null) {
  45. cnc.Close ();
  46. cnc = null;
  47. }
  48. }
  49. public void Init (SessionStateModule module, HttpApplication context, SessionConfig config)
  50. {
  51. string connectionTypeName;
  52. string providerAssemblyName;
  53. string cncString;
  54. this.config = config;
  55. GetConnectionData (out providerAssemblyName, out connectionTypeName, out cncString);
  56. if (cncType == null) {
  57. Assembly dbAssembly = Assembly.Load (providerAssemblyName);
  58. cncType = dbAssembly.GetType (connectionTypeName, true);
  59. if (!typeof (IDbConnection).IsAssignableFrom (cncType))
  60. throw new ApplicationException ("The type '" + cncType +
  61. "' does not implement IDB Connection.\n" +
  62. "Check 'DbConnectionType' in server.exe.config.");
  63. }
  64. cnc = (IDbConnection) Activator.CreateInstance (cncType);
  65. cnc.ConnectionString = cncString;
  66. try {
  67. cnc.Open ();
  68. } catch (Exception exc) {
  69. cnc = null;
  70. throw exc;
  71. }
  72. }
  73. public void UpdateHandler (HttpContext context, SessionStateModule module)
  74. {
  75. if (context.Session == null || context.Session.IsReadOnly)
  76. return;
  77. string id = context.Session.SessionID;
  78. SessionDictionary dict = context.Session.SessionDictionary;
  79. UpdateSession (id, dict);
  80. }
  81. public HttpSessionState UpdateContext (HttpContext context, SessionStateModule module,
  82. bool required, bool read_only, ref bool isNew)
  83. {
  84. if (!required)
  85. return null;
  86. HttpSessionState session = null;
  87. string id = SessionId.Lookup (context.Request, config.CookieLess);
  88. if (id != null) {
  89. session = SelectSession (id, read_only);
  90. if (session != null)
  91. return session;
  92. }
  93. id = SessionId.Create (module.Rng);
  94. session = new HttpSessionState (id, new SessionDictionary (),
  95. HttpApplicationFactory.ApplicationState.SessionObjects, config.Timeout,
  96. true, config.CookieLess, SessionStateMode.SQLServer, read_only);
  97. InsertSession (session, config.Timeout);
  98. isNew = true;
  99. return session;
  100. }
  101. private void GetConnectionData (out string providerAssembly,
  102. out string cncTypeName, out string cncString)
  103. {
  104. providerAssembly = null;
  105. cncTypeName = null;
  106. cncString = null;
  107. NameValueCollection config = ConfigurationSettings.AppSettings as NameValueCollection;
  108. if (config != null) {
  109. foreach (string s in config.Keys) {
  110. if (0 == String.Compare ("StateDBProviderAssembly", s, true)) {
  111. providerAssembly = config [s];
  112. } else if (0 == String.Compare ("StateDBConnectionType", s, true)) {
  113. cncTypeName = config [s];
  114. }
  115. }
  116. }
  117. cncString = this.config.SqlConnectionString;
  118. if (providerAssembly == null || providerAssembly == String.Empty)
  119. providerAssembly = "Npgsql.dll";
  120. if (cncTypeName == null || cncTypeName == String.Empty)
  121. cncTypeName = "Npgsql.NpgsqlConnection";
  122. if (cncString == null || cncString == String.Empty)
  123. cncString = "SERVER=127.0.0.1;USER ID=monostate;PASSWORD=monostate;dbname=monostate";
  124. }
  125. private HttpSessionState SelectSession (string id, bool read_only)
  126. {
  127. HttpSessionState session = null;
  128. IDbCommand command = cnc.CreateCommand();
  129. IDataReader reader;
  130. string select = "SELECT * from aspstatetempsessions WHERE SessionID = :SessionID";
  131. command.CommandText = select;
  132. command.Parameters.Add (CreateParam (command, DbType.String, ":SessionID", id));
  133. try {
  134. reader = command.ExecuteReader ();
  135. if (!reader.Read ())
  136. return null;
  137. SessionDictionary dict;
  138. HttpStaticObjectsCollection sobjs;
  139. dict = SessionDictionary.FromByteArray (ReadBytes (reader, reader.FieldCount-1));
  140. sobjs = HttpStaticObjectsCollection.FromByteArray (ReadBytes (reader, reader.FieldCount-2));
  141. session = new HttpSessionState (id, dict, sobjs, 100, false, config.CookieLess,
  142. SessionStateMode.SQLServer, read_only);
  143. return session;
  144. } catch {
  145. throw;
  146. }
  147. }
  148. private void InsertSession (HttpSessionState session, int timeout)
  149. {
  150. IDbCommand command = cnc.CreateCommand ();
  151. IDataParameterCollection param;
  152. string insert = "INSERT INTO ASPStateTempSessions VALUES " +
  153. "(:SessionID, :Created, :Expires, :Timeout, :StaticObjectsData, :SessionData)";
  154. command.CommandText = insert;
  155. param = command.Parameters;
  156. param.Add (CreateParam (command, DbType.String, ":SessionID", session.SessionID));
  157. param.Add (CreateParam (command, DbType.DateTime, ":Created", DateTime.Now));
  158. param.Add (CreateParam (command, DbType.DateTime, ":Expires", Tommorow ()));
  159. param.Add (CreateParam (command, DbType.Int32, ":Timeout", timeout));
  160. param.Add (CreateParam (command, DbType.Binary, ":StaticObjectsData",
  161. session.StaticObjects.ToByteArray ()));
  162. param.Add (CreateParam (command, DbType.Binary, ":SessionData",
  163. session.SessionDictionary.ToByteArray ()));
  164. command.ExecuteNonQuery ();
  165. }
  166. private void UpdateSession (string id, SessionDictionary dict)
  167. {
  168. IDbCommand command = cnc.CreateCommand ();
  169. IDataParameterCollection param;
  170. string update = "UPDATE ASPStateTempSessions SET " +
  171. "SessionData = :SessionData WHERE SessionId = :SessionID";
  172. command.CommandText = update;
  173. param = command.Parameters;
  174. param.Add (CreateParam (command, DbType.String, ":SessionID", id));
  175. param.Add (CreateParam (command, DbType.Binary, ":SessionData",
  176. dict.ToByteArray ()));
  177. command.ExecuteNonQuery ();
  178. }
  179. private IDataParameter CreateParam (IDbCommand command, DbType type,
  180. string name, object value)
  181. {
  182. IDataParameter result = command.CreateParameter ();
  183. result.DbType = type;
  184. result.ParameterName = name;
  185. result.Value = value;
  186. return result;
  187. }
  188. private DateTime Tommorow ()
  189. {
  190. return DateTime.Now.AddDays (1);
  191. }
  192. private byte [] ReadBytes (IDataReader reader, int index)
  193. {
  194. int len = (int) reader.GetBytes (reader.FieldCount-1, 0, null, 0, 0);
  195. byte [] data = new byte [len];
  196. reader.GetBytes (index, 0, data, 0, len);
  197. return data;
  198. }
  199. }
  200. }