SessionSQLServerHandler.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 * FROM ASPStateTempSessions WHERE SessionID = :SessionID";
  49. string insertCommand = "INSERT INTO ASPStateTempSessions VALUES (:SessionID, :Created, :Expires, :Timeout, :StaticObjectsData, :SessionData)";
  50. string updateCommand = "UPDATE ASPStateTempSessions SET 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, 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. return command.ExecuteReader ();
  172. }
  173. IDataReader GetReaderWithRetry (string id)
  174. {
  175. try {
  176. return GetReader (id);
  177. } catch {
  178. }
  179. try {
  180. cnc.Close ();
  181. } catch {
  182. }
  183. cnc.Open ();
  184. return GetReader (id);
  185. }
  186. private 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. dict = SessionDictionary.FromByteArray (ReadBytes (reader, reader.FieldCount-1));
  195. sobjs = HttpStaticObjectsCollection.FromByteArray (ReadBytes (reader, reader.FieldCount-2));
  196. session = new HttpSessionState (id, dict, sobjs, 100, false, config.CookieLess,
  197. SessionStateMode.SQLServer, read_only);
  198. return session;
  199. }
  200. }
  201. void InsertSession (HttpSessionState session, int timeout)
  202. {
  203. IDbCommand command = cnc.CreateCommand ();
  204. IDataParameterCollection param;
  205. command.CommandText = insertCommand;
  206. param = command.Parameters;
  207. param.Add (CreateParam (command, DbType.String, "SessionID", session.SessionID));
  208. param.Add (CreateParam (command, DbType.DateTime, "Created", DateTime.Now));
  209. param.Add (CreateParam (command, DbType.DateTime, "Expires", Tommorow ()));
  210. param.Add (CreateParam (command, DbType.Int32, "Timeout", timeout));
  211. param.Add (CreateParam (command, DbType.Binary, "StaticObjectsData",
  212. session.StaticObjects.ToByteArray ()));
  213. param.Add (CreateParam (command, DbType.Binary, "SessionData",
  214. session.SessionDictionary.ToByteArray ()));
  215. command.ExecuteNonQuery ();
  216. }
  217. void InsertSessionWithRetry (HttpSessionState session, int timeout)
  218. {
  219. try {
  220. InsertSession (session, timeout);
  221. return;
  222. } catch {
  223. }
  224. try {
  225. cnc.Close ();
  226. } catch {
  227. }
  228. cnc.Open ();
  229. InsertSession (session, timeout);
  230. }
  231. void UpdateSession (string id, SessionDictionary dict)
  232. {
  233. IDbCommand command = cnc.CreateCommand ();
  234. IDataParameterCollection param;
  235. command.CommandText = updateCommand;
  236. param = command.Parameters;
  237. param.Add (CreateParam (command, DbType.String, "SessionID", id));
  238. param.Add (CreateParam (command, DbType.Binary, "SessionData",
  239. dict.ToByteArray ()));
  240. command.ExecuteNonQuery ();
  241. }
  242. void UpdateSessionWithRetry (string id, SessionDictionary dict)
  243. {
  244. try {
  245. UpdateSession (id, dict);
  246. return;
  247. } catch {
  248. }
  249. try {
  250. cnc.Close ();
  251. } catch {
  252. }
  253. cnc.Open ();
  254. UpdateSession (id, dict);
  255. }
  256. void DeleteSession (string id)
  257. {
  258. IDbCommand command = cnc.CreateCommand ();
  259. IDataParameterCollection param;
  260. command.CommandText = deleteCommand;
  261. param = command.Parameters;
  262. param.Add (CreateParam (command, DbType.String, "SessionID", id));
  263. command.ExecuteNonQuery ();
  264. }
  265. void DeleteSessionWithRetry (string id)
  266. {
  267. try {
  268. DeleteSession (id);
  269. return;
  270. } catch {
  271. }
  272. try {
  273. cnc.Close ();
  274. } catch {
  275. }
  276. cnc.Open ();
  277. DeleteSession (id);
  278. }
  279. private IDataParameter CreateParam (IDbCommand command, DbType type,
  280. string name, object value)
  281. {
  282. IDataParameter result = command.CreateParameter ();
  283. result.DbType = type;
  284. result.ParameterName = paramPrefix + name;
  285. result.Value = value;
  286. return result;
  287. }
  288. private DateTime Tommorow ()
  289. {
  290. return DateTime.Now.AddDays (1);
  291. }
  292. private byte [] ReadBytes (IDataReader reader, int index)
  293. {
  294. int len = (int) reader.GetBytes (reader.FieldCount-1, 0, null, 0, 0);
  295. byte [] data = new byte [len];
  296. reader.GetBytes (index, 0, data, 0, len);
  297. return data;
  298. }
  299. }
  300. }