SessionSQLServerHandler.cs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. #if !NET_2_0
  30. using System;
  31. using System.IO;
  32. using System.Data;
  33. using System.Reflection;
  34. using System.Configuration;
  35. using System.Collections.Specialized;
  36. using System.Web.Configuration;
  37. namespace System.Web.SessionState {
  38. internal class SessionSQLServerHandler : ISessionHandler
  39. {
  40. private static Type cncType = null;
  41. private IDbConnection cnc = null;
  42. private SessionConfig config;
  43. const string defaultParamPrefix = ":";
  44. string paramPrefix;
  45. string selectCommand = "SELECT timeout,staticobjectsdata,sessiondata FROM ASPStateTempSessions WHERE SessionID = :SessionID AND Expires > :Expires";
  46. string insertCommand = "INSERT INTO ASPStateTempSessions (SessionId, Created, expires, timeout, StaticObjectsData, SessionData) VALUES (:SessionID, :Created, :Expires, :Timeout, :StaticObjectsData, :SessionData)";
  47. string updateCommand = "UPDATE ASPStateTempSessions SET expires = :Expires, timeout = :Timeout, SessionData = :SessionData WHERE SessionId = :SessionID";
  48. string deleteCommand = "DELETE FROM ASPStateTempSessions WHERE SessionId = :SessionID";
  49. public void Dispose ()
  50. {
  51. if (cnc != null) {
  52. cnc.Close ();
  53. cnc = null;
  54. }
  55. }
  56. public void Init (SessionStateModule module, HttpApplication context,
  57. SessionConfig config)
  58. {
  59. string connectionTypeName;
  60. string providerAssemblyName;
  61. string cncString;
  62. this.config = config;
  63. GetConnectionData (out providerAssemblyName, out connectionTypeName, out cncString);
  64. if (cncType == null) {
  65. Assembly dbAssembly = Assembly.Load (providerAssemblyName);
  66. cncType = dbAssembly.GetType (connectionTypeName, true);
  67. if (!typeof (IDbConnection).IsAssignableFrom (cncType))
  68. throw new ApplicationException ("The type '" + cncType +
  69. "' does not implement IDB Connection.\n" +
  70. "Check 'DbConnectionType' in server.exe.config.");
  71. }
  72. cnc = (IDbConnection) Activator.CreateInstance (cncType);
  73. cnc.ConnectionString = cncString;
  74. try {
  75. cnc.Open ();
  76. } catch (Exception exc) {
  77. cnc = null;
  78. throw exc;
  79. }
  80. if (paramPrefix != defaultParamPrefix) {
  81. ReplaceParamPrefix (ref selectCommand);
  82. ReplaceParamPrefix (ref insertCommand);
  83. ReplaceParamPrefix (ref updateCommand);
  84. ReplaceParamPrefix (ref deleteCommand);
  85. }
  86. }
  87. void ReplaceParamPrefix(ref string command)
  88. {
  89. command = command.Replace (defaultParamPrefix, paramPrefix);
  90. }
  91. public void UpdateHandler (HttpContext context, SessionStateModule module)
  92. {
  93. HttpSessionState session = context.Session;
  94. if (session == null || session.IsReadOnly)
  95. return;
  96. string id = session.SessionID;
  97. if (!session._abandoned) {
  98. SessionDictionary dict = session.SessionDictionary;
  99. UpdateSessionWithRetry (id, session.Timeout, dict);
  100. } else {
  101. DeleteSessionWithRetry (id);
  102. }
  103. }
  104. public HttpSessionState UpdateContext (HttpContext context, SessionStateModule module,
  105. bool required, bool read_only, ref bool isNew)
  106. {
  107. if (!required)
  108. return null;
  109. HttpSessionState session = null;
  110. string id = SessionId.Lookup (context.Request, config.CookieLess);
  111. if (id != null) {
  112. session = SelectSession (id, read_only);
  113. if (session != null)
  114. return session;
  115. }
  116. id = SessionId.Create ();
  117. session = new HttpSessionState (id, new SessionDictionary (),
  118. HttpApplicationFactory.ApplicationState.SessionObjects,
  119. config.Timeout,
  120. true, config.CookieLess, SessionStateMode.SQLServer, read_only);
  121. InsertSessionWithRetry (session, config.Timeout);
  122. isNew = true;
  123. return session;
  124. }
  125. private void GetConnectionData (out string providerAssembly,
  126. out string cncTypeName, out string cncString)
  127. {
  128. providerAssembly = null;
  129. cncTypeName = null;
  130. cncString = null;
  131. NameValueCollection config = ConfigurationSettings.AppSettings;
  132. if (config != null) {
  133. providerAssembly = config ["StateDBProviderAssembly"];
  134. cncTypeName = config ["StateDBConnectionType"];
  135. paramPrefix = config ["StateDBParamPrefix"];
  136. }
  137. cncString = this.config.SqlConnectionString;
  138. if (providerAssembly == null || providerAssembly == String.Empty)
  139. providerAssembly = "Npgsql.dll";
  140. if (cncTypeName == null || cncTypeName == String.Empty)
  141. cncTypeName = "Npgsql.NpgsqlConnection";
  142. if (cncString == null || cncString == String.Empty)
  143. cncString = "SERVER=127.0.0.1;USER ID=monostate;PASSWORD=monostate;dbname=monostate";
  144. if (paramPrefix == null || paramPrefix == String.Empty)
  145. paramPrefix = defaultParamPrefix;
  146. }
  147. IDataReader GetReader (string id)
  148. {
  149. IDbCommand command = null;
  150. command = cnc.CreateCommand();
  151. command.CommandText = selectCommand;
  152. command.Parameters.Add (CreateParam (command, DbType.String, "SessionID", id));
  153. command.Parameters.Add (CreateParam (command, DbType.DateTime, "Expires", DateTime.Now ));
  154. command.Prepare ();
  155. return command.ExecuteReader ();
  156. }
  157. IDataReader GetReaderWithRetry (string id)
  158. {
  159. try {
  160. return GetReader (id);
  161. } catch {
  162. }
  163. try {
  164. cnc.Close ();
  165. } catch {
  166. }
  167. cnc.Open ();
  168. return GetReader (id);
  169. }
  170. private HttpSessionState SelectSession (string id, bool read_only)
  171. {
  172. HttpSessionState session = null;
  173. using (IDataReader reader = GetReaderWithRetry (id)) {
  174. if (!reader.Read ())
  175. return null;
  176. SessionDictionary dict;
  177. HttpStaticObjectsCollection sobjs;
  178. int timeout;
  179. dict = SessionDictionary.FromByteArray (ReadBytes (reader, reader.FieldCount-1));
  180. sobjs = HttpStaticObjectsCollection.FromByteArray (ReadBytes (reader, reader.FieldCount-2));
  181. // try to support as many DBs/int types as possible
  182. timeout = Convert.ToInt32 (reader.GetValue (reader.FieldCount-3));
  183. session = new HttpSessionState (id, dict, sobjs, timeout, false, config.CookieLess,
  184. SessionStateMode.SQLServer, read_only);
  185. return session;
  186. }
  187. }
  188. void InsertSession (HttpSessionState session, int timeout)
  189. {
  190. IDbCommand command = cnc.CreateCommand ();
  191. IDataParameterCollection param;
  192. command.CommandText = insertCommand;
  193. param = command.Parameters;
  194. param.Add (CreateParam (command, DbType.String, "SessionID", session.SessionID));
  195. param.Add (CreateParam (command, DbType.DateTime, "Created", DateTime.Now));
  196. param.Add (CreateParam (command, DbType.DateTime, "Expires", DateTime.Now.AddMinutes (timeout)));
  197. param.Add (CreateParam (command, DbType.Int32, "Timeout", timeout));
  198. param.Add (CreateParam (command, DbType.Binary, "StaticObjectsData",
  199. session.StaticObjects.ToByteArray ()));
  200. param.Add (CreateParam (command, DbType.Binary, "SessionData",
  201. session.SessionDictionary.ToByteArray ()));
  202. command.Prepare ();
  203. command.ExecuteNonQuery ();
  204. }
  205. void InsertSessionWithRetry (HttpSessionState session, int timeout)
  206. {
  207. try {
  208. InsertSession (session, timeout);
  209. return;
  210. } catch {
  211. }
  212. try {
  213. cnc.Close ();
  214. } catch {
  215. }
  216. cnc.Open ();
  217. InsertSession (session, timeout);
  218. }
  219. void UpdateSession (string id, int timeout, SessionDictionary dict)
  220. {
  221. IDbCommand command = cnc.CreateCommand ();
  222. IDataParameterCollection param;
  223. command.CommandText = updateCommand;
  224. param = command.Parameters;
  225. param.Add (CreateParam (command, DbType.String, "SessionID", id));
  226. param.Add (CreateParam (command, DbType.DateTime, "Expires", DateTime.Now.AddMinutes (timeout)));
  227. param.Add (CreateParam (command, DbType.Int32, "Timeout", timeout));
  228. param.Add (CreateParam (command, DbType.Binary, "SessionData",
  229. dict.ToByteArray ()));
  230. command.Prepare ();
  231. command.ExecuteNonQuery ();
  232. }
  233. void UpdateSessionWithRetry (string id, int timeout, SessionDictionary dict)
  234. {
  235. try {
  236. UpdateSession (id, timeout, dict);
  237. return;
  238. } catch {
  239. }
  240. try {
  241. cnc.Close ();
  242. } catch {
  243. }
  244. cnc.Open ();
  245. UpdateSession (id, timeout, dict);
  246. }
  247. void DeleteSession (string id)
  248. {
  249. IDbCommand command = cnc.CreateCommand ();
  250. IDataParameterCollection param;
  251. command.CommandText = deleteCommand;
  252. param = command.Parameters;
  253. param.Add (CreateParam (command, DbType.String, "SessionID", id));
  254. command.Prepare ();
  255. command.ExecuteNonQuery ();
  256. }
  257. void DeleteSessionWithRetry (string id)
  258. {
  259. try {
  260. DeleteSession (id);
  261. return;
  262. } catch {
  263. }
  264. try {
  265. cnc.Close ();
  266. } catch {
  267. }
  268. cnc.Open ();
  269. DeleteSession (id);
  270. }
  271. private IDataParameter CreateParam (IDbCommand command, DbType type,
  272. string name, object value)
  273. {
  274. IDataParameter result = command.CreateParameter ();
  275. result.DbType = type;
  276. result.ParameterName = paramPrefix + name;
  277. result.Value = value;
  278. return result;
  279. }
  280. private byte [] ReadBytes (IDataReader reader, int index)
  281. {
  282. int len = (int) reader.GetBytes (index, 0, null, 0, 0);
  283. byte [] data = new byte [len];
  284. reader.GetBytes (index, 0, data, 0, len);
  285. return data;
  286. }
  287. }
  288. }
  289. #endif