SessionSQLServerHandler.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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 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. private void GetConnectionData (out string providerAssembly,
  132. out string cncTypeName, out string cncString)
  133. {
  134. providerAssembly = null;
  135. cncTypeName = null;
  136. cncString = null;
  137. NameValueCollection config = ConfigurationSettings.AppSettings;
  138. if (config != null) {
  139. providerAssembly = config ["StateDBProviderAssembly"];
  140. cncTypeName = config ["StateDBConnectionType"];
  141. paramPrefix = config ["StateDBParamPrefix"];
  142. }
  143. cncString = this.config.SqlConnectionString;
  144. if (providerAssembly == null || providerAssembly == String.Empty)
  145. providerAssembly = "Npgsql.dll";
  146. if (cncTypeName == null || cncTypeName == String.Empty)
  147. cncTypeName = "Npgsql.NpgsqlConnection";
  148. if (cncString == null || cncString == String.Empty)
  149. cncString = "SERVER=127.0.0.1;USER ID=monostate;PASSWORD=monostate;dbname=monostate";
  150. if (paramPrefix == null || paramPrefix == String.Empty)
  151. paramPrefix = defaultParamPrefix;
  152. }
  153. IDataReader GetReader (string id)
  154. {
  155. ((IDataParameter)selectCommand.Parameters["SessionID"]).Value = id;
  156. ((IDataParameter)selectCommand.Parameters["Expires"]).Value = DateTime.Now;
  157. ((IDataParameter)selectCommand.Parameters["AppPath"]).Value = this.AppPath;
  158. return selectCommand.ExecuteReader ();
  159. }
  160. IDataReader GetReaderWithRetry (string id)
  161. {
  162. try {
  163. return GetReader (id);
  164. } catch {
  165. }
  166. try {
  167. DisposeConnection();
  168. } catch {
  169. }
  170. InitializeConnection();
  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. ((IDataParameter)insertCommand.Parameters["SessionID"]).Value = session.SessionID;
  194. ((IDataParameter)insertCommand.Parameters["AppPath"]).Value = this.AppPath;
  195. ((IDataParameter)insertCommand.Parameters["Created"]).Value = DateTime.Now;
  196. ((IDataParameter)insertCommand.Parameters["Expires"]).Value = DateTime.Now.AddMinutes (timeout);
  197. ((IDataParameter)insertCommand.Parameters["Timeout"]).Value = timeout;
  198. ((IDataParameter)insertCommand.Parameters["StaticObjectsData"]).Value = session.StaticObjects.ToByteArray ();
  199. ((IDataParameter)insertCommand.Parameters["SessionData"]).Value = session.SessionDictionary.ToByteArray ();
  200. insertCommand.ExecuteNonQuery ();
  201. }
  202. void InsertSessionWithRetry (HttpSessionState session, int timeout)
  203. {
  204. try {
  205. InsertSession (session, timeout);
  206. return;
  207. } catch {
  208. }
  209. try {
  210. DisposeConnection ();
  211. } catch {
  212. }
  213. InitializeConnection ();
  214. InsertSession (session, timeout);
  215. }
  216. void UpdateSession (string id, int timeout, SessionDictionary dict)
  217. {
  218. ((IDataParameter)updateCommand.Parameters["SessionID"]).Value = id;
  219. ((IDataParameter)updateCommand.Parameters["Expires"]).Value = DateTime.Now.AddMinutes (timeout);
  220. ((IDataParameter)updateCommand.Parameters["Timeout"]).Value = timeout;
  221. ((IDataParameter)updateCommand.Parameters["SessionData"]).Value = dict.ToByteArray ();
  222. updateCommand.ExecuteNonQuery ();
  223. }
  224. void UpdateSessionWithRetry (string id, int timeout, SessionDictionary dict)
  225. {
  226. try {
  227. UpdateSession (id, timeout, dict);
  228. return;
  229. } catch {
  230. }
  231. try {
  232. DisposeConnection ();
  233. } catch {
  234. }
  235. InitializeConnection ();
  236. UpdateSession (id, timeout, dict);
  237. }
  238. void DeleteSession (string id)
  239. {
  240. ((IDataParameter)deleteCommand.Parameters["SessionID"]).Value = id;
  241. deleteCommand.ExecuteNonQuery ();
  242. }
  243. void DeleteSessionWithRetry (string id)
  244. {
  245. try {
  246. DeleteSession (id);
  247. return;
  248. } catch {
  249. }
  250. try {
  251. DisposeConnection ();
  252. } catch {
  253. }
  254. InitializeConnection ();
  255. DeleteSession (id);
  256. }
  257. void InitializeConnection()
  258. {
  259. cnc.Open ();
  260. selectCommand = cnc.CreateCommand ();
  261. selectCommand.CommandText = selectCommandText;
  262. selectCommand.Parameters.Add (CreateParam (selectCommand, DbType.String, "SessionID", String.Empty));
  263. selectCommand.Parameters.Add (CreateParam (selectCommand, DbType.DateTime, "Expires", DateTime.MinValue ));
  264. selectCommand.Parameters.Add (CreateParam (selectCommand, DbType.String, "AppPath", String.Empty));
  265. selectCommand.Prepare ();
  266. insertCommand = cnc.CreateCommand ();
  267. insertCommand.CommandText = insertCommandText;
  268. insertCommand.Parameters.Add (CreateParam (insertCommand, DbType.String, "SessionID", String.Empty));
  269. insertCommand.Parameters.Add (CreateParam (insertCommand, DbType.String, "AppPath", String.Empty));
  270. insertCommand.Parameters.Add (CreateParam (insertCommand, DbType.DateTime, "Created", DateTime.MinValue));
  271. insertCommand.Parameters.Add (CreateParam (insertCommand, DbType.DateTime, "Expires", DateTime.MinValue));
  272. insertCommand.Parameters.Add (CreateParam (insertCommand, DbType.Int32, "Timeout", 0));
  273. insertCommand.Parameters.Add (CreateParam (insertCommand, DbType.Binary, "StaticObjectsData",new byte[0] ));
  274. insertCommand.Parameters.Add (CreateParam (insertCommand, DbType.Binary, "SessionData",
  275. new byte[0]));
  276. insertCommand.Prepare();
  277. updateCommand = cnc.CreateCommand ();
  278. updateCommand.CommandText = updateCommandText;
  279. updateCommand.Parameters.Add (CreateParam (updateCommand, DbType.String, "SessionID", String.Empty));
  280. updateCommand.Parameters.Add (CreateParam (updateCommand, DbType.DateTime, "Expires", DateTime.MinValue));
  281. updateCommand.Parameters.Add (CreateParam (updateCommand, DbType.Int32, "Timeout", 0));
  282. updateCommand.Parameters.Add (CreateParam (updateCommand, DbType.Binary, "SessionData",
  283. new byte[0]));
  284. updateCommand.Prepare();
  285. deleteCommand = cnc.CreateCommand ();
  286. deleteCommand.CommandText = deleteCommandText;
  287. deleteCommand.Parameters.Add (CreateParam (deleteCommand, DbType.String, "SessionID", String.Empty));
  288. deleteCommand.Prepare();
  289. }
  290. void DisposeConnection()
  291. {
  292. selectCommand.Dispose();
  293. insertCommand.Dispose();
  294. updateCommand.Dispose();
  295. deleteCommand.Dispose();
  296. cnc.Close();
  297. }
  298. private IDataParameter CreateParam (IDbCommand command, DbType type,
  299. string name, object value)
  300. {
  301. IDataParameter result = command.CreateParameter ();
  302. result.DbType = type;
  303. result.ParameterName = paramPrefix + name;
  304. result.Value = value;
  305. return result;
  306. }
  307. private byte [] ReadBytes (IDataReader reader, int index)
  308. {
  309. int len = (int) reader.GetBytes (index, 0, null, 0, 0);
  310. byte [] data = new byte [len];
  311. reader.GetBytes (index, 0, data, 0, len);
  312. return data;
  313. }
  314. }
  315. }
  316. #endif