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;
45 private SessionConfig config;
46 private string AppPath = String.Empty;
48 const string defaultParamPrefix = ":";
50 string selectCommandText = "SELECT timeout,staticobjectsdata,sessiondata FROM ASPStateTempSessions WHERE SessionID = :SessionID AND Expires > :Expires AND AppPath = :AppPath";
51 IDbCommand selectCommand = null;
52 string insertCommandText = "INSERT INTO ASPStateTempSessions (SessionId, AppPath, Created, expires, timeout, StaticObjectsData, SessionData) VALUES (:SessionID, :AppPath, :Created, :Expires, :Timeout, :StaticObjectsData, :SessionData)";
53 IDbCommand insertCommand = null;
54 string updateCommandText = "UPDATE ASPStateTempSessions SET expires = :Expires, timeout = :Timeout, SessionData = :SessionData WHERE SessionId = :SessionID";
55 IDbCommand updateCommand = null;
56 string deleteCommandText = "DELETE FROM ASPStateTempSessions WHERE SessionId = :SessionID";
57 IDbCommand deleteCommand = null;
59 public void Dispose ()
67 public void Init (SessionStateModule module, HttpApplication context,
70 string connectionTypeName;
71 string providerAssemblyName;
75 this.AppPath = context.Request.ApplicationPath;
77 GetConnectionData (out providerAssemblyName, out connectionTypeName, out cncString);
78 if (cncType == null) {
79 Assembly dbAssembly = Assembly.Load (providerAssemblyName);
80 cncType = dbAssembly.GetType (connectionTypeName, true);
81 if (!typeof (IDbConnection).IsAssignableFrom (cncType))
82 throw new ApplicationException ("The type '" + cncType +
83 "' does not implement IDB Connection.\n" +
84 "Check 'DbConnectionType' in server.exe.config.");
87 cnc = (IDbConnection) Activator.CreateInstance (cncType);
88 cnc.ConnectionString = cncString;
90 InitializeConnection ();
91 } catch (Exception exc) {
96 if (paramPrefix != defaultParamPrefix) {
97 ReplaceParamPrefix (ref selectCommandText);
98 ReplaceParamPrefix (ref insertCommandText);
99 ReplaceParamPrefix (ref updateCommandText);
100 ReplaceParamPrefix (ref deleteCommandText);
104 void ReplaceParamPrefix(ref string command)
106 command = command.Replace (defaultParamPrefix, paramPrefix);
109 public void UpdateHandler (HttpContext context, SessionStateModule module)
111 HttpSessionState session = context.Session;
112 if (session == null || session.IsReadOnly)
115 string id = session.SessionID;
116 if (!session._abandoned) {
117 SessionDictionary dict = session.SessionDictionary;
118 UpdateSessionWithRetry (id, session.Timeout, dict);
120 DeleteSessionWithRetry (id);
124 public HttpSessionState UpdateContext (HttpContext context, SessionStateModule module,
125 bool required, bool read_only, ref bool isNew)
130 HttpSessionState session = null;
131 string id = SessionId.Lookup (context.Request, config.CookieLess);
134 session = SelectSession (id, read_only);
139 id = SessionId.Create ();
140 session = new HttpSessionState (id, new SessionDictionary (),
141 HttpApplicationFactory.ApplicationState.SessionObjects,
143 true, config.CookieLess, SessionStateMode.SQLServer, read_only);
145 InsertSessionWithRetry (session, config.Timeout);
150 public void Touch (string sessionId, int timeout)
152 HttpContext ctx = HttpContext.Current;
156 HttpSessionState session = ctx.Session;
160 UpdateSession (sessionId, timeout, session.SessionDictionary);
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 ((IDataParameter)selectCommand.Parameters["SessionID"]).Value = id;
195 ((IDataParameter)selectCommand.Parameters["Expires"]).Value = DateTime.Now;
196 ((IDataParameter)selectCommand.Parameters["AppPath"]).Value = this.AppPath;
197 return selectCommand.ExecuteReader ();
200 IDataReader GetReaderWithRetry (string id)
203 return GetReader (id);
212 InitializeConnection();
213 return GetReader (id);
216 private HttpSessionState SelectSession (string id, bool read_only)
218 HttpSessionState session = null;
219 using (IDataReader reader = GetReaderWithRetry (id)) {
223 SessionDictionary dict;
224 HttpStaticObjectsCollection sobjs;
227 dict = SessionDictionary.FromByteArray (ReadBytes (reader, reader.FieldCount-1));
228 sobjs = HttpStaticObjectsCollection.FromByteArray (ReadBytes (reader, reader.FieldCount-2));
229 // try to support as many DBs/int types as possible
230 timeout = Convert.ToInt32 (reader.GetValue (reader.FieldCount-3));
232 session = new HttpSessionState (id, dict, sobjs, timeout, false, config.CookieLess,
233 SessionStateMode.SQLServer, read_only);
238 void InsertSession (HttpSessionState session, int timeout)
240 ((IDataParameter)insertCommand.Parameters["SessionID"]).Value = session.SessionID;
241 ((IDataParameter)insertCommand.Parameters["AppPath"]).Value = this.AppPath;
242 ((IDataParameter)insertCommand.Parameters["Created"]).Value = DateTime.Now;
243 ((IDataParameter)insertCommand.Parameters["Expires"]).Value = DateTime.Now.AddMinutes (timeout);
244 ((IDataParameter)insertCommand.Parameters["Timeout"]).Value = timeout;
245 ((IDataParameter)insertCommand.Parameters["StaticObjectsData"]).Value = session.StaticObjects.ToByteArray ();
246 ((IDataParameter)insertCommand.Parameters["SessionData"]).Value = session.SessionDictionary.ToByteArray ();
247 insertCommand.ExecuteNonQuery ();
250 void InsertSessionWithRetry (HttpSessionState session, int timeout)
253 InsertSession (session, timeout);
259 DisposeConnection ();
263 InitializeConnection ();
264 InsertSession (session, timeout);
267 void UpdateSession (string id, int timeout, SessionDictionary dict)
269 ((IDataParameter)updateCommand.Parameters["SessionID"]).Value = id;
270 ((IDataParameter)updateCommand.Parameters["Expires"]).Value = DateTime.Now.AddMinutes (timeout);
271 ((IDataParameter)updateCommand.Parameters["Timeout"]).Value = timeout;
272 ((IDataParameter)updateCommand.Parameters["SessionData"]).Value = dict.ToByteArray ();
274 updateCommand.ExecuteNonQuery ();
277 void UpdateSessionWithRetry (string id, int timeout, SessionDictionary dict)
280 UpdateSession (id, timeout, dict);
286 DisposeConnection ();
290 InitializeConnection ();
291 UpdateSession (id, timeout, dict);
294 void DeleteSession (string id)
297 ((IDataParameter)deleteCommand.Parameters["SessionID"]).Value = id;
298 deleteCommand.ExecuteNonQuery ();
301 void DeleteSessionWithRetry (string id)
310 DisposeConnection ();
314 InitializeConnection ();
318 void InitializeConnection()
321 selectCommand = cnc.CreateCommand ();
322 selectCommand.CommandText = selectCommandText;
323 selectCommand.Parameters.Add (CreateParam (selectCommand, DbType.String, "SessionID", String.Empty));
324 selectCommand.Parameters.Add (CreateParam (selectCommand, DbType.DateTime, "Expires", DateTime.MinValue ));
325 selectCommand.Parameters.Add (CreateParam (selectCommand, DbType.String, "AppPath", String.Empty));
326 selectCommand.Prepare ();
328 insertCommand = cnc.CreateCommand ();
329 insertCommand.CommandText = insertCommandText;
330 insertCommand.Parameters.Add (CreateParam (insertCommand, DbType.String, "SessionID", String.Empty));
331 insertCommand.Parameters.Add (CreateParam (insertCommand, DbType.String, "AppPath", String.Empty));
332 insertCommand.Parameters.Add (CreateParam (insertCommand, DbType.DateTime, "Created", DateTime.MinValue));
333 insertCommand.Parameters.Add (CreateParam (insertCommand, DbType.DateTime, "Expires", DateTime.MinValue));
334 insertCommand.Parameters.Add (CreateParam (insertCommand, DbType.Int32, "Timeout", 0));
335 insertCommand.Parameters.Add (CreateParam (insertCommand, DbType.Binary, "StaticObjectsData",new byte[0] ));
336 insertCommand.Parameters.Add (CreateParam (insertCommand, DbType.Binary, "SessionData",
338 insertCommand.Prepare();
340 updateCommand = cnc.CreateCommand ();
341 updateCommand.CommandText = updateCommandText;
342 updateCommand.Parameters.Add (CreateParam (updateCommand, DbType.String, "SessionID", String.Empty));
343 updateCommand.Parameters.Add (CreateParam (updateCommand, DbType.DateTime, "Expires", DateTime.MinValue));
344 updateCommand.Parameters.Add (CreateParam (updateCommand, DbType.Int32, "Timeout", 0));
345 updateCommand.Parameters.Add (CreateParam (updateCommand, DbType.Binary, "SessionData",
347 updateCommand.Prepare();
349 deleteCommand = cnc.CreateCommand ();
350 deleteCommand.CommandText = deleteCommandText;
351 deleteCommand.Parameters.Add (CreateParam (deleteCommand, DbType.String, "SessionID", String.Empty));
352 deleteCommand.Prepare();
355 void DisposeConnection()
357 selectCommand.Dispose();
358 insertCommand.Dispose();
359 updateCommand.Dispose();
360 deleteCommand.Dispose();
364 private IDataParameter CreateParam (IDbCommand command, DbType type,
365 string name, object value)
367 IDataParameter result = command.CreateParameter ();
368 result.DbType = type;
369 result.ParameterName = paramPrefix + name;
370 result.Value = value;
374 private byte [] ReadBytes (IDataReader reader, int index)
376 int len = (int) reader.GetBytes (index, 0, null, 0, 0);
377 byte [] data = new byte [len];
378 reader.GetBytes (index, 0, data, 0, len);