SessionSQLServerHandler.cs 12 KB

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