2 // System.Web.SessionState.SessionSQLServerHandler
5 // Jackson Harper (jackson@ximian.com)
7 // (C) 2003 Novell, Inc. (http://www.novell.com), All rights reserved
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.Reflection;
35 using System.Configuration;
36 using System.Collections.Specialized;
37 using System.Web.Configuration;
39 namespace System.Web.SessionState {
41 internal class SessionSQLServerHandler : ISessionHandler
43 private static Type cncType = null;
44 private IDbConnection cnc = null;
46 private SessionStateSection config;
48 private SessionConfig config;
51 const string defaultParamPrefix = ":";
53 string selectCommand = "SELECT timeout,staticobjectsdata,sessiondata FROM ASPStateTempSessions WHERE SessionID = :SessionID AND Expires > :Expires";
54 string insertCommand = "INSERT INTO ASPStateTempSessions (SessionId, Created, expires, timeout, StaticObjectsData, SessionData) VALUES (:SessionID, :Created, :Expires, :Timeout, :StaticObjectsData, :SessionData)";
55 string updateCommand = "UPDATE ASPStateTempSessions SET expires = :Expires, timeout = :Timeout, SessionData = :SessionData WHERE SessionId = :SessionID";
56 string deleteCommand = "DELETE FROM ASPStateTempSessions WHERE SessionId = :SessionID";
58 public void Dispose ()
66 public void Init (SessionStateModule module, HttpApplication context,
68 SessionStateSection config
74 string connectionTypeName;
75 string providerAssemblyName;
80 GetConnectionData (out providerAssemblyName, out connectionTypeName, out cncString);
81 if (cncType == null) {
82 Assembly dbAssembly = Assembly.Load (providerAssemblyName);
83 cncType = dbAssembly.GetType (connectionTypeName, true);
84 if (!typeof (IDbConnection).IsAssignableFrom (cncType))
85 throw new ApplicationException ("The type '" + cncType +
86 "' does not implement IDB Connection.\n" +
87 "Check 'DbConnectionType' in server.exe.config.");
90 cnc = (IDbConnection) Activator.CreateInstance (cncType);
91 cnc.ConnectionString = cncString;
94 } catch (Exception exc) {
99 if (paramPrefix != defaultParamPrefix) {
100 ReplaceParamPrefix (ref selectCommand);
101 ReplaceParamPrefix (ref insertCommand);
102 ReplaceParamPrefix (ref updateCommand);
103 ReplaceParamPrefix (ref deleteCommand);
107 void ReplaceParamPrefix(ref string command)
109 command = command.Replace (defaultParamPrefix, paramPrefix);
112 public void UpdateHandler (HttpContext context, SessionStateModule module)
114 HttpSessionState session = context.Session;
115 if (session == null || session.IsReadOnly)
118 string id = session.SessionID;
119 if (!session._abandoned) {
120 SessionDictionary dict = session.SessionDictionary;
121 UpdateSessionWithRetry (id, session.Timeout, dict);
123 DeleteSessionWithRetry (id);
127 public HttpSessionState UpdateContext (HttpContext context, SessionStateModule module,
128 bool required, bool read_only, ref bool isNew)
133 HttpSessionState session = null;
134 string id = SessionId.Lookup (context.Request, config.CookieLess);
137 session = SelectSession (id, read_only);
142 id = SessionId.Create (module.Rng);
143 session = new HttpSessionState (id, new SessionDictionary (),
144 HttpApplicationFactory.ApplicationState.SessionObjects,
146 (int)config.Timeout.TotalMinutes,
150 true, config.CookieLess, SessionStateMode.SQLServer, read_only);
152 InsertSessionWithRetry (session,
154 (int)config.Timeout.TotalMinutes
163 private void GetConnectionData (out string providerAssembly,
164 out string cncTypeName, out string cncString)
166 providerAssembly = null;
170 NameValueCollection config = ConfigurationSettings.AppSettings;
171 if (config != null) {
172 providerAssembly = config ["StateDBProviderAssembly"];
173 cncTypeName = config ["StateDBConnectionType"];
174 paramPrefix = config ["StateDBParamPrefix"];
177 cncString = this.config.SqlConnectionString;
179 if (providerAssembly == null || providerAssembly == String.Empty)
180 providerAssembly = "Npgsql.dll";
182 if (cncTypeName == null || cncTypeName == String.Empty)
183 cncTypeName = "Npgsql.NpgsqlConnection";
185 if (cncString == null || cncString == String.Empty)
186 cncString = "SERVER=127.0.0.1;USER ID=monostate;PASSWORD=monostate;dbname=monostate";
188 if (paramPrefix == null || paramPrefix == String.Empty)
189 paramPrefix = defaultParamPrefix;
192 IDataReader GetReader (string id)
194 IDbCommand command = null;
195 command = cnc.CreateCommand();
196 command.CommandText = selectCommand;
197 command.Parameters.Add (CreateParam (command, DbType.String, "SessionID", id));
198 command.Parameters.Add (CreateParam (command, DbType.DateTime, "Expires", DateTime.Now ));
199 return command.ExecuteReader ();
202 IDataReader GetReaderWithRetry (string id)
205 return GetReader (id);
215 return GetReader (id);
218 private HttpSessionState SelectSession (string id, bool read_only)
220 HttpSessionState session = null;
221 using (IDataReader reader = GetReaderWithRetry (id)) {
225 SessionDictionary dict;
226 HttpStaticObjectsCollection sobjs;
229 dict = SessionDictionary.FromByteArray (ReadBytes (reader, reader.FieldCount-1));
230 sobjs = HttpStaticObjectsCollection.FromByteArray (ReadBytes (reader, reader.FieldCount-2));
231 // try to support as many DBs/int types as possible
232 timeout = Convert.ToInt32 (reader.GetValue (reader.FieldCount-3));
234 session = new HttpSessionState (id, dict, sobjs, timeout, false, config.CookieLess,
235 SessionStateMode.SQLServer, read_only);
240 void InsertSession (HttpSessionState session, int timeout)
242 IDbCommand command = cnc.CreateCommand ();
243 IDataParameterCollection param;
245 command.CommandText = insertCommand;
247 param = command.Parameters;
248 param.Add (CreateParam (command, DbType.String, "SessionID", session.SessionID));
249 param.Add (CreateParam (command, DbType.DateTime, "Created", DateTime.Now));
250 param.Add (CreateParam (command, DbType.DateTime, "Expires", DateTime.Now.AddMinutes (timeout)));
251 param.Add (CreateParam (command, DbType.Int32, "Timeout", timeout));
252 param.Add (CreateParam (command, DbType.Binary, "StaticObjectsData",
253 session.StaticObjects.ToByteArray ()));
254 param.Add (CreateParam (command, DbType.Binary, "SessionData",
255 session.SessionDictionary.ToByteArray ()));
257 command.ExecuteNonQuery ();
260 void InsertSessionWithRetry (HttpSessionState session, int timeout)
263 InsertSession (session, timeout);
274 InsertSession (session, timeout);
277 void UpdateSession (string id, int timeout, SessionDictionary dict)
279 IDbCommand command = cnc.CreateCommand ();
280 IDataParameterCollection param;
282 command.CommandText = updateCommand;
284 param = command.Parameters;
285 param.Add (CreateParam (command, DbType.String, "SessionID", id));
286 param.Add (CreateParam (command, DbType.DateTime, "Expires", DateTime.Now.AddMinutes (timeout)));
287 param.Add (CreateParam (command, DbType.Int32, "Timeout", timeout));
288 param.Add (CreateParam (command, DbType.Binary, "SessionData",
289 dict.ToByteArray ()));
291 command.ExecuteNonQuery ();
294 void UpdateSessionWithRetry (string id, int timeout, SessionDictionary dict)
297 UpdateSession (id, timeout, dict);
308 UpdateSession (id, timeout, dict);
311 void DeleteSession (string id)
313 IDbCommand command = cnc.CreateCommand ();
314 IDataParameterCollection param;
316 command.CommandText = deleteCommand;
317 param = command.Parameters;
318 param.Add (CreateParam (command, DbType.String, "SessionID", id));
319 command.ExecuteNonQuery ();
322 void DeleteSessionWithRetry (string id)
339 private IDataParameter CreateParam (IDbCommand command, DbType type,
340 string name, object value)
342 IDataParameter result = command.CreateParameter ();
343 result.DbType = type;
344 result.ParameterName = paramPrefix + name;
345 result.Value = value;
349 private byte [] ReadBytes (IDataReader reader, int index)
351 int len = (int) reader.GetBytes (index, 0, null, 0, 0);
352 byte [] data = new byte [len];
353 reader.GetBytes (index, 0, data, 0, len);