SessionSQLServerHandler.cs 10 KB

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