SessionSQLServerHandler.cs 10 KB

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