SessionSQLServerHandler.cs 12 KB

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