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 selectCommand = "SELECT timeout,staticobjectsdata,sessiondata FROM ASPStateTempSessions WHERE SessionID = :SessionID AND Expires > :Expires AND AppPath = :AppPath";
51 string insertCommand = "INSERT INTO ASPStateTempSessions (SessionId, AppPath, Created, expires, timeout, StaticObjectsData, SessionData) VALUES (:SessionID, :AppPath, :Created, :Expires, :Timeout, :StaticObjectsData, :SessionData)";
52 string updateCommand = "UPDATE ASPStateTempSessions SET expires = :Expires, timeout = :Timeout, SessionData = :SessionData WHERE SessionId = :SessionID";
53 string deleteCommand = "DELETE FROM ASPStateTempSessions WHERE SessionId = :SessionID";
55 public void Dispose ()
63 public void Init (SessionStateModule module, HttpApplication context,
66 string connectionTypeName;
67 string providerAssemblyName;
71 this.AppPath = context.Request.ApplicationPath;
73 GetConnectionData (out providerAssemblyName, out connectionTypeName, out cncString);
74 if (cncType == null) {
75 Assembly dbAssembly = Assembly.Load (providerAssemblyName);
76 cncType = dbAssembly.GetType (connectionTypeName, true);
77 if (!typeof (IDbConnection).IsAssignableFrom (cncType))
78 throw new ApplicationException ("The type '" + cncType +
79 "' does not implement IDB Connection.\n" +
80 "Check 'DbConnectionType' in server.exe.config.");
83 cnc = (IDbConnection) Activator.CreateInstance (cncType);
84 cnc.ConnectionString = cncString;
87 } catch (Exception exc) {
92 if (paramPrefix != defaultParamPrefix) {
93 ReplaceParamPrefix (ref selectCommand);
94 ReplaceParamPrefix (ref insertCommand);
95 ReplaceParamPrefix (ref updateCommand);
96 ReplaceParamPrefix (ref deleteCommand);
100 void ReplaceParamPrefix(ref string command)
102 command = command.Replace (defaultParamPrefix, paramPrefix);
105 public void UpdateHandler (HttpContext context, SessionStateModule module)
107 HttpSessionState session = context.Session;
108 if (session == null || session.IsReadOnly)
111 string id = session.SessionID;
112 if (!session._abandoned) {
113 SessionDictionary dict = session.SessionDictionary;
114 UpdateSessionWithRetry (id, session.Timeout, dict);
116 DeleteSessionWithRetry (id);
120 public HttpSessionState UpdateContext (HttpContext context, SessionStateModule module,
121 bool required, bool read_only, ref bool isNew)
126 HttpSessionState session = null;
127 string id = SessionId.Lookup (context.Request, config.CookieLess);
130 session = SelectSession (id, read_only);
135 id = SessionId.Create ();
136 session = new HttpSessionState (id, new SessionDictionary (),
137 HttpApplicationFactory.ApplicationState.SessionObjects,
139 true, config.CookieLess, SessionStateMode.SQLServer, read_only);
141 InsertSessionWithRetry (session, config.Timeout);
146 private void GetConnectionData (out string providerAssembly,
147 out string cncTypeName, out string cncString)
149 providerAssembly = null;
153 NameValueCollection config = ConfigurationSettings.AppSettings;
154 if (config != null) {
155 providerAssembly = config ["StateDBProviderAssembly"];
156 cncTypeName = config ["StateDBConnectionType"];
157 paramPrefix = config ["StateDBParamPrefix"];
160 cncString = this.config.SqlConnectionString;
162 if (providerAssembly == null || providerAssembly == String.Empty)
163 providerAssembly = "Npgsql.dll";
165 if (cncTypeName == null || cncTypeName == String.Empty)
166 cncTypeName = "Npgsql.NpgsqlConnection";
168 if (cncString == null || cncString == String.Empty)
169 cncString = "SERVER=127.0.0.1;USER ID=monostate;PASSWORD=monostate;dbname=monostate";
171 if (paramPrefix == null || paramPrefix == String.Empty)
172 paramPrefix = defaultParamPrefix;
175 IDataReader GetReader (string id)
177 IDbCommand command = null;
178 command = cnc.CreateCommand();
179 command.CommandText = selectCommand;
180 command.Parameters.Add (CreateParam (command, DbType.String, "SessionID", id));
181 command.Parameters.Add (CreateParam (command, DbType.DateTime, "Expires", DateTime.Now ));
182 command.Parameters.Add (CreateParam (command, DbType.String, "AppPath", this.AppPath));
184 return command.ExecuteReader ();
187 IDataReader GetReaderWithRetry (string id)
190 return GetReader (id);
200 return GetReader (id);
203 private HttpSessionState SelectSession (string id, bool read_only)
205 HttpSessionState session = null;
206 using (IDataReader reader = GetReaderWithRetry (id)) {
210 SessionDictionary dict;
211 HttpStaticObjectsCollection sobjs;
214 dict = SessionDictionary.FromByteArray (ReadBytes (reader, reader.FieldCount-1));
215 sobjs = HttpStaticObjectsCollection.FromByteArray (ReadBytes (reader, reader.FieldCount-2));
216 // try to support as many DBs/int types as possible
217 timeout = Convert.ToInt32 (reader.GetValue (reader.FieldCount-3));
219 session = new HttpSessionState (id, dict, sobjs, timeout, false, config.CookieLess,
220 SessionStateMode.SQLServer, read_only);
225 void InsertSession (HttpSessionState session, int timeout)
227 IDbCommand command = cnc.CreateCommand ();
228 IDataParameterCollection param;
230 command.CommandText = insertCommand;
233 param = command.Parameters;
234 param.Add (CreateParam (command, DbType.String, "SessionID", session.SessionID));
235 param.Add (CreateParam (command, DbType.String, "AppPath", this.AppPath));
236 param.Add (CreateParam (command, DbType.DateTime, "Created", DateTime.Now));
237 param.Add (CreateParam (command, DbType.DateTime, "Expires", DateTime.Now.AddMinutes (timeout)));
238 param.Add (CreateParam (command, DbType.Int32, "Timeout", timeout));
239 param.Add (CreateParam (command, DbType.Binary, "StaticObjectsData",
240 session.StaticObjects.ToByteArray ()));
241 param.Add (CreateParam (command, DbType.Binary, "SessionData",
242 session.SessionDictionary.ToByteArray ()));
245 command.ExecuteNonQuery ();
248 void InsertSessionWithRetry (HttpSessionState session, int timeout)
251 InsertSession (session, timeout);
262 InsertSession (session, timeout);
265 void UpdateSession (string id, int timeout, SessionDictionary dict)
267 IDbCommand command = cnc.CreateCommand ();
268 IDataParameterCollection param;
270 command.CommandText = updateCommand;
272 param = command.Parameters;
273 param.Add (CreateParam (command, DbType.String, "SessionID", id));
274 param.Add (CreateParam (command, DbType.DateTime, "Expires", DateTime.Now.AddMinutes (timeout)));
275 param.Add (CreateParam (command, DbType.Int32, "Timeout", timeout));
276 param.Add (CreateParam (command, DbType.Binary, "SessionData",
277 dict.ToByteArray ()));
280 command.ExecuteNonQuery ();
283 void UpdateSessionWithRetry (string id, int timeout, SessionDictionary dict)
286 UpdateSession (id, timeout, dict);
297 UpdateSession (id, timeout, dict);
300 void DeleteSession (string id)
302 IDbCommand command = cnc.CreateCommand ();
303 IDataParameterCollection param;
305 command.CommandText = deleteCommand;
306 param = command.Parameters;
307 param.Add (CreateParam (command, DbType.String, "SessionID", id));
309 command.ExecuteNonQuery ();
312 void DeleteSessionWithRetry (string id)
329 private IDataParameter CreateParam (IDbCommand command, DbType type,
330 string name, object value)
332 IDataParameter result = command.CreateParameter ();
333 result.DbType = type;
334 result.ParameterName = paramPrefix + name;
335 result.Value = value;
339 private byte [] ReadBytes (IDataReader reader, int index)
341 int len = (int) reader.GetBytes (index, 0, null, 0, 0);
342 byte [] data = new byte [len];
343 reader.GetBytes (index, 0, data, 0, len);